[
  {
    "path": ".clang-format",
    "content": "---\nLanguage:        Cpp\n# BasedOnStyle:  LLVM\nAccessModifierOffset: -2\nAlignAfterOpenBracket: Align\nAlignArrayOfStructures: None\nAlignConsecutiveMacros: None\nAlignConsecutiveAssignments: None\nAlignConsecutiveBitFields: None\nAlignConsecutiveDeclarations: None\nAlignEscapedNewlines: Right\nAlignOperands:   Align\nAlignTrailingComments: true\nAllowAllArgumentsOnNextLine: true\nAllowAllConstructorInitializersOnNextLine: true\nAllowAllParametersOfDeclarationOnNextLine: true\nAllowShortEnumsOnASingleLine: true\nAllowShortBlocksOnASingleLine: Never\nAllowShortCaseLabelsOnASingleLine: false\nAllowShortFunctionsOnASingleLine: All\nAllowShortLambdasOnASingleLine: All\nAllowShortIfStatementsOnASingleLine: Never\nAllowShortLoopsOnASingleLine: false\nAlwaysBreakAfterDefinitionReturnType: None\nAlwaysBreakAfterReturnType: None\nAlwaysBreakBeforeMultilineStrings: false\nAlwaysBreakTemplateDeclarations: MultiLine\nAttributeMacros:\n  - __capability\nBinPackArguments: true\nBinPackParameters: true\nBraceWrapping:\n  AfterCaseLabel:  false\n  AfterClass:      false\n  AfterControlStatement: Never\n  AfterEnum:       false\n  AfterFunction:   false\n  AfterNamespace:  false\n  AfterObjCDeclaration: false\n  AfterStruct:     false\n  AfterUnion:      false\n  AfterExternBlock: false\n  BeforeCatch:     false\n  BeforeElse:      false\n  BeforeLambdaBody: false\n  BeforeWhile:     false\n  IndentBraces:    false\n  SplitEmptyFunction: true\n  SplitEmptyRecord: true\n  SplitEmptyNamespace: true\nBreakBeforeBinaryOperators: None\nBreakBeforeConceptDeclarations: true\nBreakBeforeBraces: Attach\nBreakBeforeInheritanceComma: false\nBreakInheritanceList: BeforeColon\nBreakBeforeTernaryOperators: true\nBreakConstructorInitializersBeforeComma: false\nBreakConstructorInitializers: BeforeColon\nBreakAfterJavaFieldAnnotations: false\nBreakStringLiterals: true\nColumnLimit:     120\nCommentPragmas:  '^ IWYU pragma:'\nCompactNamespaces: false\nConstructorInitializerAllOnOneLineOrOnePerLine: false\nConstructorInitializerIndentWidth: 4\nContinuationIndentWidth: 4\nCpp11BracedListStyle: true\nDeriveLineEnding: true\nDerivePointerAlignment: false\nDisableFormat:   false\nEmptyLineAfterAccessModifier: Never\nEmptyLineBeforeAccessModifier: LogicalBlock\nExperimentalAutoDetectBinPacking: false\nFixNamespaceComments: true\nForEachMacros:\n  - foreach\n  - Q_FOREACH\n  - BOOST_FOREACH\nIfMacros:\n  - KJ_IF_MAYBE\nIncludeBlocks:   Preserve\nIncludeCategories:\n  - Regex:           '^\"(llvm|llvm-c|clang|clang-c)/'\n    Priority:        2\n    SortPriority:    0\n    CaseSensitive:   false\n  - Regex:           '^(<|\"(gtest|gmock|isl|json)/)'\n    Priority:        3\n    SortPriority:    0\n    CaseSensitive:   false\n  - Regex:           '.*'\n    Priority:        1\n    SortPriority:    0\n    CaseSensitive:   false\nIncludeIsMainRegex: '(Test)?$'\nIncludeIsMainSourceRegex: ''\nIndentAccessModifiers: false\nIndentCaseLabels: false\nIndentCaseBlocks: false\nIndentGotoLabels: true\nIndentPPDirectives: None\nIndentExternBlock: AfterExternBlock\nIndentRequires:  false\nIndentWidth:     2\nIndentWrappedFunctionNames: false\nInsertTrailingCommas: None\nJavaScriptQuotes: Leave\nJavaScriptWrapImports: true\nKeepEmptyLinesAtTheStartOfBlocks: true\nLambdaBodyIndentation: Signature\nMacroBlockBegin: ''\nMacroBlockEnd:   ''\nMaxEmptyLinesToKeep: 1\nNamespaceIndentation: None\nObjCBinPackProtocolList: Auto\nObjCBlockIndentWidth: 2\nObjCBreakBeforeNestedBlockParam: true\nObjCSpaceAfterProperty: false\nObjCSpaceBeforeProtocolList: true\nPenaltyBreakAssignment: 2\nPenaltyBreakBeforeFirstCallParameter: 19\nPenaltyBreakComment: 300\nPenaltyBreakFirstLessLess: 120\nPenaltyBreakString: 1000\nPenaltyBreakTemplateDeclaration: 10\nPenaltyExcessCharacter: 1000000\nPenaltyReturnTypeOnItsOwnLine: 60\nPenaltyIndentedWhitespace: 0\nPointerAlignment: Right\nPPIndentWidth:   -1\nReferenceAlignment: Pointer\nReflowComments:  true\nShortNamespaceLines: 1\nSortIncludes:    CaseSensitive\nSortJavaStaticImport: Before\nSortUsingDeclarations: true\nSpaceAfterCStyleCast: false\nSpaceAfterLogicalNot: false\nSpaceAfterTemplateKeyword: true\nSpaceBeforeAssignmentOperators: true\nSpaceBeforeCaseColon: false\nSpaceBeforeCpp11BracedList: false\nSpaceBeforeCtorInitializerColon: true\nSpaceBeforeInheritanceColon: true\nSpaceBeforeParens: ControlStatements\nSpaceAroundPointerQualifiers: Default\nSpaceBeforeRangeBasedForLoopColon: true\nSpaceInEmptyBlock: false\nSpaceInEmptyParentheses: false\nSpacesBeforeTrailingComments: 1\nSpacesInAngles:  Never\nSpacesInConditionalStatement: false\nSpacesInContainerLiterals: true\nSpacesInCStyleCastParentheses: false\nSpacesInLineCommentPrefix:\n  Minimum:         1\n  Maximum:         -1\nSpacesInParentheses: false\nSpacesInSquareBrackets: false\nSpaceBeforeSquareBrackets: false\nBitFieldColonSpacing: Both\nStandard:        Latest\nStatementAttributeLikeMacros:\n  - Q_EMIT\nStatementMacros:\n  - Q_UNUSED\n  - QT_REQUIRE_VERSION\nTabWidth:        8\nUseCRLF:         false\nUseTab:          Never\nWhitespaceSensitiveMacros:\n  - STRINGIZE\n  - PP_STRINGIZE\n  - BOOST_PP_STRINGIZE\n  - NS_SWIFT_NAME\n  - CF_SWIFT_NAME\n...\n\n"
  },
  {
    "path": ".github/workflows/compile.yml",
    "content": "name: Compile Ubuntu\n\non:\n  - push\n  - pull_request\n\njobs:\n  build:\n    runs-on: ${{ matrix.os }}\n\n    strategy:\n      fail-fast: false\n\n      matrix:\n        os: [ubuntu-latest, ubuntu-24.04, ubuntu-22.04]\n\n    env:\n      BUILD_DIR: build\n      DEBIAN_FRONTEND: noninteractive\n\n    steps:\n    - uses: actions/checkout@v4\n\n    - name: Install dependencies\n      run: sudo apt-get install -y libncurses5-dev libncursesw5-dev libdrm-dev libsystemd-dev\n\n    - name: Configure CMake\n      run: cmake -S . -B $BUILD_DIR\n\n    - name: Build\n      run: cmake --build $BUILD_DIR\n\n    - name: Install\n      run: DESTDIR=\"$PWD/build/install\" cmake --build $BUILD_DIR --target install\n      \n    - name: Upload\n      uses: actions/upload-artifact@v4\n      with:\n        name: nvtop ${{ matrix.os }}\n        path: ${{ env.BUILD_DIR }}/install\n"
  },
  {
    "path": ".gitignore",
    "content": "*.o\n*ctags\nbuild/\ncmake-build*/\n.vscode\n.idea\n"
  },
  {
    "path": "AppImage/README.md",
    "content": "# Build the AppImage\n\n```bash\npodman pull ubuntu:18.04\npodman run --interactive --tty --rm --volume $PWD:/nvtop ubuntu:24.04\ncd nvtop\n./AppImage/make_appimage.sh\n```\n"
  },
  {
    "path": "AppImage/make_appimage.sh",
    "content": "#!/usr/bin/env bash\n\nexport ARCH=\"$(uname -m)\"\nexport APPIMAGE_EXTRACT_AND_RUN=1\nAPPIMAGETOOL=\"https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage\"\n\ninstall_deps() {\n\tapt-get update\n\tapt-get install -y gcc g++ cmake libncurses5-dev libncursesw5-dev libdrm-dev \\\n\t  wget file libudev-dev ninja-build cmake file desktop-file-utils\n}\n\nconfigure_nvtop() {\n\tcmake -B build -S . -DCMAKE_BUILD_TYPE=Release \\\n\t  -DUSE_LIBUDEV_OVER_LIBSYSTEMD=ON -DCMAKE_INSTALL_PREFIX=/usr\n}\n\nbuild_nvtop() {\n\tcmake --build build\n}\n\ninstall_nvtop_AppDir() {\n\tDESTDIR=$PWD/AppDir cmake --build build --target install\n}\n\nbundle_dependencies() {\n\tmkdir -p AppDir/usr/lib\n\tldd AppDir/usr/bin/nvtop | awk -F\"[> ]\" '{print $4}' \\\n\t  | xargs -I {} cp -vf {} AppDir/usr/lib\n\tcp -v /lib64/ld-linux-x86-64.so.2 AppDir\n}\n\nconfigure_appdir() {\n\tcat >> AppDir/AppRun <<- 'EOF'\n\t#!/bin/sh\n\tHERE=\"$(readlink -f \"$(dirname \"$0\")\")\"\n\texec \"$HERE/ld-linux-x86-64.so.2\" \\\n\t  --library-path \"$HERE/usr/lib\" \"$HERE\"/usr/bin/nvtop \"$@\"\n\tEOF\n\tchmod u+x AppDir/AppRun\n\tln -s usr/share/applications/nvtop.desktop AppDir\n\tln -s usr/share/icons/nvtop.svg AppDir\n\tln -s usr/share/icons/nvtop.svg AppDir/.DirIcon\n}\n\nget_appimagetool() {\n\twget -q \"$APPIMAGETOOL\" -O ./appimagetool\n\tchmod u+x ./appimagetool\n}\n\ncreate_AppImage() {\n\tinstall_deps\n\tconfigure_nvtop\n\tbuild_nvtop\n\tinstall_nvtop_AppDir\n\tbundle_dependencies\n\tconfigure_appdir\n\tget_appimagetool\n\texport VERSION=\"$(./AppDir/AppRun --version | awk '{print $NF}')\"\n\t./appimagetool -n AppDir\n}\n\ncreate_AppImage\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.18)\n\n#///////////////////////////////////////////////////////////////////#\n#                              PROJECT                              #\n#///////////////////////////////////////////////////////////////////#\n\nproject(nvtop VERSION 3.3.2\n  LANGUAGES C CXX)\n\nset(default_build_type \"Release\")\n# Default build type\nif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)\n  message(STATUS \"Setting build type to '${default_build_type}' as none was specified.\")\n  set(CMAKE_BUILD_TYPE \"${default_build_type}\" CACHE\n    STRING \"Choose the type of build.\" FORCE)\nendif()\nset_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS\n  \"Debug\" \"Release\" \"MinSizeRel\" \"RelWithDebInfo\")\nset(CMAKE_EXPORT_COMPILE_COMMANDS ON)\n\n#///////////////////////////////////////////////////////////////////#\n#                           DEPENDENCIES                            #\n#///////////////////////////////////////////////////////////////////#\n\nlist(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules ${CMAKE_CURRENT_SOURCE_DIR}/cmake)\n\nset(CURSES_NEED_NCURSES TRUE)\n# Try to find ncurses with unicode support first\nset(CURSES_NEED_WIDE TRUE)\nfind_package(Curses QUIET)\nif (NOT CURSE_FOUND)\n  # Fallback to regular ncurses library, which may also support unicode!\n  set(CURSES_NEED_WIDE FALSE)\n  find_package(Curses REQUIRED)\nendif()\n\nadd_library(ncurses INTERFACE IMPORTED)\nset_property(TARGET ncurses PROPERTY\n  INTERFACE_INCLUDE_DIRECTORIES ${CURSES_INCLUDE_DIRS})\nset_property(TARGET ncurses PROPERTY\n  INTERFACE_LINK_LIBRARIES ${CURSES_LIBRARIES})\nadd_compile_definitions(NCURSES_ENABLE_STDBOOL_H=1)\n\n#///////////////////////////////////////////////////////////////////#\n#                        COMPILATION OPTIONS                        #\n#///////////////////////////////////////////////////////////////////#\n\n# Use full RPATH on build tree\nset(CMAKE_SKIP_BUILD_RPATH FALSE)\n# Do not build with install RPATH\nset(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)\n# Set the RPATH when install\nset(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)\n# Only set RPATH if the installation directory is not a system directory\nLIST(FIND\n  CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES \"${CMAKE_INSTALL_PREFIX}/lib\"\n  isSystemDir)\nif(\"${isSystemDir}\" STREQUAL \"-1\")\n  set(CMAKE_INSTALL_RPATH \"${CMAKE_INSTALL_PREFIX}/lib\")\nelse()\n  set(CMAKE_INSTALL_RPATH \"\")\nendif()\n\nif(APPLE)\n  set(APPLE_SUPPORT_DEFAULT ON)\n  set(NVIDIA_SUPPORT_DEFAULT OFF)\n  set(AMDGPU_SUPPORT_DEFAULT OFF)\n  set(INTEL_SUPPORT_DEFAULT OFF)\n  set(MSM_SUPPORT_DEFAULT OFF)\n  set(PANFROST_SUPPORT_DEFAULT OFF)\n  set(PANTHOR_SUPPORT_DEFAULT OFF)\n  set(ASCEND_SUPPORT_DEFAULT OFF)\n  set(METAX_SUPPORT_DEFAULT OFF)\nelseif(ASCEND_SUPPORT)\n  set(APPLE_SUPPORT_DEFAULT OFF)\n  set(NVIDIA_SUPPORT_DEFAULT OFF)\n  set(AMDGPU_SUPPORT_DEFAULT OFF)\n  set(INTEL_SUPPORT_DEFAULT OFF)\n  set(MSM_SUPPORT_DEFAULT OFF)\n  set(PANFROST_SUPPORT_DEFAULT OFF)\n  set(PANTHOR_SUPPORT_DEFAULT OFF)\n  set(ASCEND_SUPPORT_DEFAULT ON)\n  set(METAX_SUPPORT_DEFAULT OFF)\nelse()\n  set(APPLE_SUPPORT_DEFAULT OFF)\n  set(NVIDIA_SUPPORT_DEFAULT ON)\n  set(AMDGPU_SUPPORT_DEFAULT ON)\n  set(INTEL_SUPPORT_DEFAULT ON)\n  set(V3D_SUPPORT_DEFAULT ON)\n  set(MSM_SUPPORT_DEFAULT ON)\n  set(PANFROST_SUPPORT_DEFAULT ON)\n  set(PANTHOR_SUPPORT_DEFAULT ON)\n  set(ASCEND_SUPPORT_DEFAULT OFF)\n  set(METAX_SUPPORT_DEFAULT ON)\nendif()\n\n# TPU and Enflame GCU support is only available on Linux\nif (CMAKE_SYSTEM_NAME STREQUAL \"Linux\")\n  # Check for libtpuinfo.so to set the default for TPU support\n  find_library(LIBTPUINFO\n    NAMES libtpuinfo.so\n    PATHS /usr/lib /usr/lib64 /usr/local/lib /usr/local/lib64\n    HINTS ${CMAKE_INSTALL_PREFIX}/lib ${CMAKE_INSTALL_PREFIX}/lib64 lib lib64\n  )\n  if (NOT LIBTPUINFO)\n    set(TPU_SUPPORT_DEFAULT OFF)\n  else()\n    set(TPU_SUPPORT_DEFAULT ON)\n  endif()\n  set(ENFLAME_SUPPORT_DEFAULT ON)\nelse()\n  set(TPU_SUPPORT_DEFAULT OFF)\n  set(ENFLAME_SUPPORT_DEFAULT OFF)\nendif()\n\n# Rockchip support is only available on Linux on arm\n# Enable Rockchip support only on ARM Linux\nif (CMAKE_SYSTEM_NAME STREQUAL \"Linux\" AND\n    (CMAKE_SYSTEM_PROCESSOR MATCHES \"armv7\" OR CMAKE_SYSTEM_PROCESSOR MATCHES \"aarch64\"))\n  set(ROCKCHIP_SUPPORT_DEFAULT ON)\nelse()\n  set(ROCKCHIP_SUPPORT_DEFAULT OFF)\nendif()\n\noption(NVIDIA_SUPPORT \"Build support for NVIDIA GPUs through libnvml\" ${NVIDIA_SUPPORT_DEFAULT})\noption(AMDGPU_SUPPORT \"Build support for AMD GPUs through amdgpu driver\" ${AMDGPU_SUPPORT_DEFAULT})\noption(INTEL_SUPPORT \"Build support for Intel GPUs through i915 or xe driver\" ${INTEL_SUPPORT_DEFAULT})\noption(MSM_SUPPORT \"Build support for Adreno GPUs through msm driver\" ${MSM_SUPPORT_DEFAULT})\noption(APPLE_SUPPORT \"Build support for Apple GPUs through Metal\" ${APPLE_SUPPORT_DEFAULT})\noption(PANFROST_SUPPORT \"Build support for Mali GPUs through panfrost driver\" ${PANFROST_SUPPORT_DEFAULT})\noption(PANTHOR_SUPPORT \"Build support for Mali GPUs through panthor driver\" ${PANTHOR_SUPPORT_DEFAULT})\noption(ASCEND_SUPPORT \"Build support for Ascend NPUs through Ascend DCMI\" ${ASCEND_SUPPORT_DEFAULT})\noption(V3D_SUPPORT \"Build support for Raspberrypi through v3d\" ${V3D_SUPPORT_DEFAULT})\noption(TPU_SUPPORT \"Build support for Google TPUs through GRPC\" ${TPU_SUPPORT_DEFAULT})\noption(ROCKCHIP_SUPPORT \"Enable support for Rockchip NPU\" ${ROCKCHIP_SUPPORT_DEFAULT})\noption(METAX_SUPPORT \"Build support for MetaX GPUs through libmxsml\" ${METAX_SUPPORT_DEFAULT})\noption(ENFLAME_SUPPORT \"Build support for Enflame GCUs through libefml\" ${ENFLAME_SUPPORT_DEFAULT})\n\nadd_subdirectory(src)\n\n#///////////////////////////////////////////////////////////////////#\n#                             INSTALL                               #\n#///////////////////////////////////////////////////////////////////#\n\nstring(TIMESTAMP TODAY_MANPAGE \"%B %Y\")\nstring(TIMESTAMP TODAY_ISO_8601 \"%Y-%m-%d\")\nconfigure_file(\n  \"${CMAKE_CURRENT_SOURCE_DIR}/manpage/nvtop.in\"\n  \"${CMAKE_CURRENT_BINARY_DIR}/manpage/nvtop\"\n  IMMEDIATE @ONLY)\nconfigure_file(\n  \"${CMAKE_CURRENT_SOURCE_DIR}/desktop/nvtop.metainfo.xml.in\"\n  \"${CMAKE_CURRENT_BINARY_DIR}/desktop/io.github.syllo.nvtop.metainfo.xml\"\n  IMMEDIATE @ONLY)\ninstall(FILES\n  \"${CMAKE_CURRENT_BINARY_DIR}/manpage/nvtop\"\n  DESTINATION share/man/man1/\n  PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ\n  RENAME nvtop.1)\ninstall(FILES\n  \"${CMAKE_CURRENT_SOURCE_DIR}/desktop/nvtop.svg\"\n  DESTINATION share/icons/hicolor/scalable/apps\n  PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)\ninstall(FILES\n  \"${CMAKE_CURRENT_SOURCE_DIR}/desktop/nvtop.desktop\"\n  DESTINATION share/applications\n  PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)\ninstall(FILES\n  \"${CMAKE_CURRENT_BINARY_DIR}/desktop/io.github.syllo.nvtop.metainfo.xml\"\n  DESTINATION share/metainfo\n  PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)\n\nconfigure_file(\n  \"${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in\"\n  \"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake\"\n  IMMEDIATE @ONLY)\nadd_custom_target(uninstall\n  COMMAND ${CMAKE_COMMAND} -P\n  ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)\n\n#///////////////////////////////////////////////////////////////////#\n#                             TESTING                               #\n#///////////////////////////////////////////////////////////////////#\n\n\nif (NOT CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n  option(BUILD_TESTING \"Build tests\" OFF)\nendif()\ninclude(CTest)\nadd_subdirectory(tests)\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "Dockerfile",
    "content": "\n# BUILD: docker build . -t nvtop\n# or use other image with: --build-arg IMAGE=nvcr.io/nvidia/cudagl:11.4.2-base-ubuntu20.04\n# or nvidia/driver:418.87.01-ubuntu18.04, nvcr.io/nvidia/cudagl:11.4.2-base-ubuntu20.04\n# USE: docker run --rm -it --gpus all --pid host nvtop\n\nARG IMAGE=nvidia/opengl:1.2-glvnd-runtime-ubuntu20.04\n\nFROM ${IMAGE} as builder\n\nENV DEBIAN_FRONTEND=noninteractive\n\nRUN apt-get update && \\\n  apt-get install -yq build-essential wget libncurses5-dev libncursesw5-dev libssl-dev \\\n  pkg-config libdrm-dev libgtest-dev libudev-dev python3-venv\n\n# Get a recent-enough CMake\nRUN python3 -m venv /.venv && \\\n    . /.venv/bin/activate && \\\n    pip install --upgrade pip && \\\n    pip install cmake\n\nCOPY . /nvtop\nWORKDIR /nvtop\nRUN mkdir -p /nvtop/build && \\\n  cd /nvtop/build && \\\n  . /.venv/bin/activate && \\\n  cmake .. && \\\n  make -j && \\\n  make install\n\n# Stage 2\nFROM ${IMAGE}\nRUN DEBIAN_FRONTEND=noninteractive apt-get update -y && apt-get install -yq libncurses5 libncursesw5 libdrm-amdgpu1 \\\n  && rm -rf /var/lib/apt/lists/*\nCOPY --from=builder /usr/local/bin/nvtop /usr/local/bin/nvtop\nCOPY --from=builder /usr/local/share/man/man1/nvtop.1 /usr/local/share/man/man1/nvtop.1\n\nENV LANG=C.UTF-8\n\nENTRYPOINT [ \"/usr/local/bin/nvtop\" ]\n"
  },
  {
    "path": "README.markdown",
    "content": "NVTOP\n=====\n\nWhat is NVTOP?\n--------------\n\nNVTOP stands for Neat Videocard TOP, a (h)top like task monitor for GPUs and\naccelerators. It can handle multiple GPUs and print information about them in a\nhtop-familiar way.\n\nCurrently supported vendors are AMD (Linux amdgpu driver), Apple (limited M1 &\nM2 support), Huawei (Ascend), Intel (Linux i915/Xe drivers), NVIDIA (Linux\nproprietary divers), Qualcomm Adreno (Linux MSM driver), Broadcom VideoCore (Linux v3d driver),\nRockchip, MetaX (MXSML driver), Enflame (Linux EFML driver).\n\nBecause a picture is worth a thousand words:\n\n![NVTOP interface](/screenshot/NVTOP_ex1.png)\n\nTable of Contents\n-----------------\n\n- [NVTOP Options and Interactive Commands](#nvtop-options-and-interactive-commands)\n  - [Interactive Setup Window](#interactive-setup-window)\n  - [Saving Preferences](#saving-preferences)\n  - [NVTOP Manual and Command line Options](#nvtop-manual-and-command-line-options)\n- [GPU Support](#gpu-support)\n  - [AMD](#amd)\n  - [Intel](#intel)\n  - [NVIDIA](#nvidia)\n  - [Adreno](#adreno)\n  - [Apple](#apple)\n  - [Ascend](#ascend) (only tested on 910B)\n  - [VideoCore](#videocore)\n  - [Rockchip](#rockchip)\n  - [MetaX](#metax)\n  - [Enflame](#enflame)\n- [Build](#build)\n- [Distribution Specific Installation Process](#distribution-specific-installation-process)\n  - [Ubuntu / Debian](#ubuntu--debian)\n    - [Ubuntu Impish (21.10) / Debian buster (stable) and more recent (stable)](#ubuntu-impish-2110-debian-buster-stable-and-more-recent)\n  - [Fedora / Red Hat / CentOS](#fedora--red-hat--centos)\n  - [OpenSUSE](#opensuse)\n  - [Arch Linux](#arch-linux)\n  - [Gentoo](#gentoo)\n  - [AppImage](#appimage)\n  - [Snap](#snap)\n  - [Conda-forge](#conda-forge)\n  - [Docker](#docker)\n- [NVTOP Build](#nvtop-build)\n- [Troubleshoot](#troubleshoot)\n- [License](#license)\n\nNVTOP Options and Interactive Commands\n--------------------------------------\n### Interactive Setup Window\n\nNVTOP has a builtin setup utility that provides a way to specialize the interface to your needs.\nSimply press ``F2`` and select the options that are the best for you.\n\n![NVTOP Setup Window](/screenshot/Nvtop-config.png)\n\n### Saving Preferences\n\nYou can save the preferences set in the setup window by pressing ``F12``.\nThe preferences will be loaded the next time you run ``nvtop``.\n\n### NVTOP Manual and Command line Options\n\nNVTOP comes with a manpage!\n```bash\nman nvtop\n```\nFor quick command line arguments help\n```bash\nnvtop -h\nnvtop --help\n```\n\nGPU Support\n-----------\n\n### AMD\n\nNVTOP supports AMD GPUs using the `amdgpu` driver through the exposed DRM and\nsysfs interface.\n\nAMD introduced the fdinfo interface in kernel 5.14 ([browse kernel\nsource](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/gpu/drm/amd/amdgpu/amdgpu_fdinfo.c?h=linux-5.14.y)).\nHence, you will need a kernel with a version greater or equal to 5.14 to see the\nprocesses using AMD GPUs.\n\nSupport for recent GPUs are regularly mainlined into the linux kernel, so please\nuse a recent-enough kernel for your GPU.\n\n### Intel\n\nNVTOP supports Intel GPUs using the `i915` or `xe` linux driver.\n\nIntel introduced the fdinfo interface in kernel 5.19 ([browse kernel\nsource](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/gpu/drm/i915/i915_drm_client.c?h=linux-5.19.y)).\nHence, you will need a kernel with a version greater or equal to 5.19 to see the\nprocesses using Intel GPUs.\n\nIntel requires CAP_PERFMON or CAP_SYS_ADMIN capabilities to access the total memory usage,\nyou can run `sudo setcap cap_perfmon=ep nvtop` to grant the necessary permissions or run nvtop as root.\n\n### NVIDIA\n\nThe *NVML library* does not support some of the queries for GPUs coming before the\nKepler microarchitecture. Anything starting at GeForce 600, GeForce 800M and\nsuccessor should work fine. For more information about supported GPUs please\ntake a look at the [NVML documentation](http://docs.nvidia.com/deploy/nvml-api/nvml-api-reference.html#nvml-api-reference).\n\n### Adreno\n\nNVTOP supports Adreno GPUs using the `msm` linux driver.\n\nmsm introduced the fdinfo interface in kernel 6.0 ([browse kernel\nsource](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/drivers/gpu/drm/msm/msm_drv.c?h=linux-6.0.y)).\nHence, you will need a kernel with a version greater or equal to 6.0 to see the\nprocesses using Adreno GPUs.\n\n### Apple\n\nNVTOP includes some initial support for Apple using Metal. This is only supported when building for Apple, and when building for Apple only this vendor is supported.\n\n**APPLE SUPPORT STATUS**\n- Apple support is still being worked on. Some bugs and limitations may apply.\n\n### Ascend\n\nNVTOP supports Ascend (testing on Altas 800 (910B)) by DCMI API (version 6.0.0).\n\nCurrently, the DCMI only supports limited APIs, missing PCIe generation, tx/rx throughput info, max power draw etc.\n\n### VideoCore\n\nNVTOP supports VideoCore (testing on raspberrypi 4B).\n\nSupports GPU frequency, temperature, utilization, per-process utilization, GPU memory usage, and H264 decoding utilization.\n\nOn non-raspberry pi os, you need to use the `linux-rpi 6.12.y` kernel and above, and ensure the presence of the `/dev/vcio` device.\n\n### Rockchip\n\nNVTOP supports Rockchip (testing on orangepi 5 plus).\n\nSupports NPU frequency, temperature, utilization.\n\n### MetaX\n\nNVTOP supports MetaX (testing on MXC500) by MXSML LIBRARY.\n\nFor more information about GPUs please take a look at the [METAX documentation](https://developer.metax-tech.com/doc/index)\n\n### Enflame\n\nNVTOP supports Enflame GCUs (testing on Enflame S60, Enflame L300 and Enflame L600) by EFML LIBRARY\n\nGCU, which refers to General Compute Unit, is a type of accelerator card that is used to perform general-purpose computing tasks just like GPGPU.\n\nBuild\n-----\n\nSeveral libraries are required in order for NVTOP to display GPU info:\n\n* The *ncurses* library driving the user interface.\n  * This makes the screen look beautiful.\n* For NVIDIA: the *NVIDIA Management Library* (*NVML*) which comes with the GPU driver.\n  * This queries the GPU for info.\n* For AMD: the libdrm library used to query AMD GPUs through the kernel driver.\n* For METAX: the *MetaX System Management Library* (*MXSML*) which comes with the GPU driver.\n  * This queries the GPU for info.\n* For Enflame: the *Enflame Management Library* (*EFML*) which comes with the GCU driver.\n\n## Distribution Specific Installation Process\n\n### Ubuntu / Debian\n\nIf your distribution provides the snap utility, follow the [snap installation process](#snap) to obtain an up-to-date version of `nvtop`.\n\nA standalone application is available as [AppImage](#appimage).\n\n#### Ubuntu Focal (20.04), Debian buster (stable) and more recent\n\n```bash\nsudo apt install nvtop\n```\n\n#### Ubuntu PPA\n\nA [PPA supporting Ubuntu 20.04 and newer](https://launchpad.net/~quentiumyt/+archive/ubuntu/nvtop) is provided by\n[Quentin Lienhardt](https://github.com/QuentiumYT) that offers an up-to-date version of `nvtop`, enabled for NVIDIA, AMD and Intel.\n\n```bash\nsudo add-apt-repository ppa:quentiumyt/nvtop\nsudo apt install nvtop\n```\n\n#### Older\n\n- AMD and Intel Dependencies\n  ```bash\n  sudo apt install libdrm-dev libsystemd-dev\n  # Ubuntu 18.04\n  sudo apt install libudev-dev\n  ```\n\n- NVIDIA Dependency\n  - NVIDIA drivers (see [Ubuntu Wiki](https://help.ubuntu.com/community/BinaryDriverHowto/Nvidia) or [Ubuntu PPA](https://launchpad.net/~graphics-drivers/+archive/ubuntu/ppa) or [Debian Wiki](https://wiki.debian.org/NvidiaGraphicsDrivers#NVIDIA_Proprietary_Driver))\n\n- NVTOP Dependencies\n  - CMake, ncurses and Git\n  ```bash\n  sudo apt install cmake libncurses5-dev libncursesw5-dev git\n  ```\n\n- NVTOP\n  - Follow the [NVTOP Build](#nvtop-build)\n\n\n### Fedora / Red Hat / CentOS\n\nA standalone application is available as [AppImage](#appimage).\n\n#### Fedora 36 and newer\n\n- ```bash\n  sudo dnf install nvtop\n  ```\n\n#### Red Hat Enterprise Linux 8 and 9\n\n- ```bash\n  sudo dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$(rpm -E %{rhel}).noarch.rpm\n  sudo dnf install nvtop\n  ```\n\n#### CentOS Stream, Rocky Linux, AlmaLinux\n\n- ```bash\n  sudo dnf install -y epel-release\n  sudo dnf install nvtop\n  ```\n\n#### Build process for Fedora / Red Hat / CentOS:\n\n- AMD and Intel Dependencies\n  ```bash\n  sudo dnf install libdrm-devel systemd-devel\n  ```\n\n- NVIDIA Dependency\n  - NVIDIA drivers, **CUDA required for nvml libraries** (see [RPM Fusion](https://rpmfusion.org/Howto/NVIDIA))\n\n- NVTOP Dependencies\n  - CMake, ncurses, C++ and Git\n  ```bash\n  sudo dnf install cmake ncurses-devel git gcc-c++\n  ```\n\n- NVTOP\n  - Follow the [NVTOP Build](#nvtop-build)\n\n### OpenSUSE\n\nA standalone application is available as an [AppImage](#appimage).\n\nBuild process for OpenSUSE:\n\n- AMD Dependency\n  ```bash\n  sudo zypper install libdrm-devel\n  ```\n\n- NVIDIA Dependency\n  - NVIDIA drivers (see [SUSE Support Database](https://en.opensuse.org/SDB:NVIDIA_drivers))\n\n- NVTOP Dependencies\n  - CMake, ncurses and Git\n    ```bash\n    sudo zypper install cmake ncurses-devel git\n    ```\n\n- NVTOP\n  - Follow the [NVTOP Build](#nvtop-build)\n\n### Arch Linux\n\n- ```bash\n  sudo pacman -S nvtop\n  ```\n\n### Gentoo\n\n- ```bash\n  sudo emerge -av nvtop\n  ```\n\n### AppImage\n\nAn AppImage is a standalone application. Just download the AppImage, make it executable and run it!\n\n- Go to the [release page](https://github.com/Syllo/nvtop/releases/latest) and download `nvtop-x86_64.AppImage`\n\n- ```bash\n  # Go to the download location ** The path may differ on your system **\n  cd $HOME/Downloads\n  # Make the AppImage executable\n  chmod u+x nvtop-x86_64.AppImage\n  # Enjoy nvtop\n  ./nvtop-x86_64.AppImage\n  ```\n\nIf you are curious how that works, please visit the [AppImage website](https://appimage.org/).\n\n### Snap\n\n- ```bash\n  snap install nvtop\n  # Add the capability to kill processes inside nvtop\n  snap connect nvtop:process-control\n  # Add the capability to inspect GPU information (fan, PCIe, power, etc)\n  snap connect nvtop:hardware-observe\n  # AMDGPU process list support (read /proc/<pid>)\n  snap connect nvtop:system-observe\n  # Temporary workaround to get per-process GPU usage (read /proc/<pid>/fdinfo)\n  snap connect nvtop:kubernetes-support\n  ```\n\nNotice: The connect commands allow\n\n### Conda-forge\n\nA [conda-forge feedstock for `nvtop`](https://github.com/conda-forge/nvtop-feedstock) is available.\n\n#### conda / mamba / miniforge\n\n```bash\nconda install --channel conda-forge nvtop\n```\n\n#### pixi\n\n```bash\npixi global install nvtop\n```\n\n### Docker\n\n- NVIDIA drivers (same as above)\n\n- [nvidia-docker](https://github.com/NVIDIA/nvidia-docker) (See [Container Toolkit Installation Guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#docker))\n\n- ```bash\n  git clone https://github.com/Syllo/nvtop.git && cd nvtop\n  sudo docker build --tag nvtop .\n  sudo docker run -it --rm --runtime=nvidia --gpus=all --pid=host nvtop\n  ```\n\n## NVTOP Build\n\n```bash\ngit clone https://github.com/Syllo/nvtop.git\nmkdir -p nvtop/build && cd nvtop/build\ncmake .. -DNVIDIA_SUPPORT=ON -DAMDGPU_SUPPORT=ON -DINTEL_SUPPORT=ON\nmake\n\n# Install globally on the system\nsudo make install\n\n# Alternatively, install without privileges at a location of your choosing\n# cmake .. -DNVIDIA_SUPPORT=ON -DAMDGPU_SUPPORT=ON -DINTEL_SUPPORT=ON -DCMAKE_INSTALL_PREFIX=/path/to/your/dir\n# make\n# make install\n```\n\nIf you use **conda** as environment manager and encounter an error while building NVTOP, try `conda deactivate` before invoking `cmake`.\n\nThe build system supports multiple build types (e.g. -DCMAKE_BUILD_TYPE=RelWithDebInfo):\n\n* Release: Binary without debug info\n* RelWithDebInfo: Binary with debug info\n* Debug: Compile with warning flags and address/undefined sanitizers enabled (for development purposes)\n\nTroubleshoot\n------------\n\n- The plot looks bad:\n  - Verify that you installed the wide character version of the ncurses library (libncurses**w**5-dev for Debian / Ubuntu), clean the build directory and restart the build process.\n- **Putty**: Tell putty not to lie about its capabilities (`$TERM`) by setting the field ``Terminal-type string`` to ``putty`` in the menu\n  ``Connection > Data > Terminal Details``.\n\nLicense\n-------\n\nNVTOP is licensed under the GPLv3 license or any later version.\nYou will find a copy of the license inside the COPYING file of the repository or\nat the GNU website <[www.gnu.org/licenses/](http://www.gnu.org/licenses/)>.\n"
  },
  {
    "path": "cmake/cmake_uninstall.cmake.in",
    "content": "if(NOT EXISTS \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\")\n  message(FATAL_ERROR\n    \"Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\")\nendif(NOT EXISTS \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\")\n\nfile(READ \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\" files)\nstring(REGEX REPLACE \"\\n\" \";\" files \"${files}\")\nforeach(file ${files})\n  message(STATUS \"Uninstalling $ENV{DESTDIR}${file}\")\n  if(IS_SYMLINK \"$ENV{DESTDIR}${file}\" OR EXISTS \"$ENV{DESTDIR}${file}\")\n    exec_program( \"@CMAKE_COMMAND@\" ARGS \"-E remove \\\"$ENV{DESTDIR}${file}\\\"\"\n      OUTPUT_VARIABLE rm_out RETURN_VALUE rm_retval)\n    if(NOT \"${rm_retval}\" STREQUAL 0)\n      message(FATAL_ERROR \"Problem when removing $ENV{DESTDIR}${file}\")\n    endif(NOT \"${rm_retval}\" STREQUAL 0)\n  else(IS_SYMLINK \"$ENV{DESTDIR}${file}\" OR EXISTS \"$ENV{DESTDIR}${file}\")\n    message(STATUS\n      \"File\n      $ENV{DESTDIR}${file}\n      does not\n      exist.\")\n  endif(IS_SYMLINK \"$ENV{DESTDIR}${file}\" OR EXISTS \"$ENV{DESTDIR}${file}\")\nendforeach(file)\n"
  },
  {
    "path": "cmake/compile-flags-helpers.cmake",
    "content": "include(CheckLinkerFlag)\n\nfunction(add_compiler_option_to_target_type TARGET BUILDTYPE VISIBILITY OPTIONS)\n  include(CheckCCompilerFlag)\n  list(APPEND OPTIONS ${ARGN})\n  foreach(COMPILE_OPTION IN LISTS OPTIONS)\n    string(REPLACE \"=\" \"-\" COMPILE_OPTION_NAME \"${COMPILE_OPTION}\")\n    check_c_compiler_flag(${COMPILE_OPTION} \"compiler_has${COMPILE_OPTION_NAME}\")\n    if (${compiler_has${COMPILE_OPTION_NAME}})\n      target_compile_options(${TARGET} ${VISIBILITY}\n        $<$<CONFIG:${BUILDTYPE}>:${COMPILE_OPTION}>)\n    endif()\n  endforeach()\nendfunction()\n\nfunction(add_compiler_option_to_all_but_target_type TARGET BUILDTYPE VISIBILITY OPTIONS)\n  include(CheckCCompilerFlag)\n  list(APPEND OPTIONS ${ARGN})\n  foreach(COMPILE_OPTION IN LISTS OPTIONS)\n    string(REPLACE \"=\" \"-\" COMPILE_OPTION_NAME \"${COMPILE_OPTION}\")\n    check_c_compiler_flag(${COMPILE_OPTION} \"compiler_has${COMPILE_OPTION_NAME}\")\n    if (${compiler_has${COMPILE_OPTION_NAME}})\n      target_compile_options(${TARGET} ${VISIBILITY}\n        $<$<NOT:$<CONFIG:${BUILDTYPE}>>:${COMPILE_OPTION}>)\n    endif()\n  endforeach()\nendfunction()\n\nfunction(add_linker_option_to_target_type TARGET BUILDTYPE VISIBILITY OPTIONS)\n  include(CheckCCompilerFlag)\n  list(APPEND OPTIONS ${ARGN})\n  foreach(LINK_OPTION IN LISTS OPTIONS)\n    string(REPLACE \",\" \"_\" LINK_OPTION_NAME \"${LINK_OPTION}\")\n    check_linker_flag(C \"${LINK_OPTION}\" \"linker_has${LINK_OPTION_NAME}\")\n    if (${linker_has${LINK_OPTION_NAME}})\n      target_link_libraries(${TARGET} ${VISIBILITY}\n        $<$<CONFIG:${BUILDTYPE}>:${LINK_OPTION}>)\n    endif()\n  endforeach()\nendfunction()\n\nfunction(add_linker_option_to_all_but_target_type TARGET BUILDTYPE VISIBILITY OPTIONS)\n  include(CheckCCompilerFlag)\n  list(APPEND OPTIONS ${ARGN})\n  foreach(LINK_OPTION IN LISTS OPTIONS)\n    string(REPLACE \",\" \"_\" LINK_OPTION_NAME \"${LINK_OPTION}\")\n    check_linker_flag(C \"${LINK_OPTION}\" \"linker_has${LINK_OPTION_NAME}\")\n    if (${linker_has${LINK_OPTION_NAME}})\n      target_link_libraries(${TARGET} ${VISIBILITY}\n        $<$<NOT:$<CONFIG:${BUILDTYPE}>>:${LINK_OPTION}>)\n    endif()\n  endforeach()\nendfunction()\n\nfunction(add_sanitizers_to_target TARGET BUILDTYPE VISIBILITY SANITIZERS)\n  list(APPEND SANITIZERS ${ARGN})\n  foreach(SAN IN LISTS SANITIZERS)\n    set(CMAKE_REQUIRED_FLAGS \"-fsanitize=${SAN}\")\n    check_c_compiler_flag(\"-fsanitize=${SAN}\" \"sanitizer-${SAN}-available\")\n    unset(CMAKE_REQUIRED_FLAGS)\n    if (${sanitizer-${SAN}-available})\n      list(APPEND AVAILABLE_SANITIZERS ${SAN})\n    endif()\n  endforeach()\n  foreach(SAN IN LISTS AVAILABLE_SANITIZERS)\n    target_compile_options(${TARGET} ${VISIBILITY} $<$<CONFIG:${BUILDTYPE}>:-fsanitize=${SAN}>)\n    target_link_libraries(${TARGET} ${VISIBILITY} $<$<CONFIG:${BUILDTYPE}>:-fsanitize=${SAN}>)\n  endforeach()\nendfunction()\n"
  },
  {
    "path": "cmake/modules/FindASan.cmake",
    "content": "# The MIT License (MIT)\n#\n# Copyright (c)\n#   2013 Matthew Arsenault\n#   2015-2016 RWTH Aachen University, Federal Republic of Germany\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\noption(SANITIZE_ADDRESS \"Enable AddressSanitizer for sanitized targets.\" Off)\n\nset(FLAG_CANDIDATES\n    # Clang 3.2+ use this version. The no-omit-frame-pointer option is optional.\n    \"-g -fsanitize=address -fno-omit-frame-pointer\"\n    \"-g -fsanitize=address\"\n\n    # Older deprecated flag for ASan\n    \"-g -faddress-sanitizer\"\n)\n\n\nif (SANITIZE_ADDRESS AND (SANITIZE_THREAD OR SANITIZE_MEMORY))\n    message(FATAL_ERROR \"AddressSanitizer is not compatible with \"\n        \"ThreadSanitizer or MemorySanitizer.\")\nendif ()\n\n\ninclude(sanitize-helpers)\n\nif (SANITIZE_ADDRESS)\n    sanitizer_check_compiler_flags(\"${FLAG_CANDIDATES}\" \"AddressSanitizer\"\n        \"ASan\")\n\n    find_program(ASan_WRAPPER \"asan-wrapper\" PATHS ${CMAKE_MODULE_PATH})\n\tmark_as_advanced(ASan_WRAPPER)\nendif ()\n\nfunction (add_sanitize_address TARGET)\n    if (NOT SANITIZE_ADDRESS)\n        return()\n    endif ()\n\n    sanitizer_add_flags(${TARGET} \"AddressSanitizer\" \"ASan\")\nendfunction ()\n"
  },
  {
    "path": "cmake/modules/FindCurses.cmake",
    "content": "# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying\n# file Copyright.txt or https://cmake.org/licensing for details.\n\n#[=======================================================================[.rst:\nFindCurses\n----------\n\nFind the curses or ncurses include file and library.\n\nResult Variables\n^^^^^^^^^^^^^^^^\n\nThis module defines the following variables:\n\n``CURSES_FOUND``\n  True if Curses is found.\n``CURSES_INCLUDE_DIRS``\n  The include directories needed to use Curses.\n``CURSES_LIBRARIES``\n  The libraries needed to use Curses.\n``CURSES_CFLAGS``\n  Parameters which ought be given to C/C++ compilers when using Curses.\n``CURSES_HAVE_CURSES_H``\n  True if curses.h is available.\n``CURSES_HAVE_NCURSES_H``\n  True if ncurses.h is available.\n``CURSES_HAVE_NCURSES_NCURSES_H``\n  True if ``ncurses/ncurses.h`` is available.\n``CURSES_HAVE_NCURSES_CURSES_H``\n  True if ``ncurses/curses.h`` is available.\n\nSet ``CURSES_NEED_NCURSES`` to ``TRUE`` before the\n``find_package(Curses)`` call if NCurses functionality is required.\nSet ``CURSES_NEED_WIDE`` to ``TRUE`` before the\n``find_package(Curses)`` call if unicode functionality is required.\n\nBackward Compatibility\n^^^^^^^^^^^^^^^^^^^^^^\n\nThe following variable are provided for backward compatibility:\n\n``CURSES_INCLUDE_DIR``\n  Path to Curses include.  Use ``CURSES_INCLUDE_DIRS`` instead.\n``CURSES_LIBRARY``\n  Path to Curses library.  Use ``CURSES_LIBRARIES`` instead.\n#]=======================================================================]\n\ninclude(CheckLibraryExists)\n\n# we don't know anything about cursesw, so only ncurses\n# may be ncursesw\nif(NOT CURSES_NEED_WIDE)\n  set(NCURSES_LIBRARY_NAME \"ncurses\")\nelse()\n  set(NCURSES_LIBRARY_NAME \"ncursesw\")\n  # Also, if we are searching for wide curses - we are actually searching\n  # for ncurses, we don't know about any other unicode version.\n  set(CURSES_NEED_NCURSES TRUE)\nendif()\n\nfind_library(CURSES_CURSES_LIBRARY NAMES curses)\n\nfind_library(CURSES_NCURSES_LIBRARY NAMES \"${NCURSES_LIBRARY_NAME}\" )\nset(CURSES_USE_NCURSES FALSE)\n\nif(CURSES_NCURSES_LIBRARY  AND ((NOT CURSES_CURSES_LIBRARY) OR CURSES_NEED_NCURSES))\n  set(CURSES_USE_NCURSES TRUE)\nendif()\n# http://cygwin.com/ml/cygwin-announce/2010-01/msg00002.html\n# cygwin ncurses stopped providing curses.h symlinks see above\n# message.  Cygwin is an ncurses package, so force ncurses on\n# cygwin if the curses.h is missing\nif(CYGWIN)\n  if (CURSES_NEED_WIDE)\n    if(NOT EXISTS /usr/include/ncursesw/curses.h)\n      set(CURSES_USE_NCURSES TRUE)\n    endif()\n  else()\n    if(NOT EXISTS /usr/include/curses.h)\n      set(CURSES_USE_NCURSES TRUE)\n    endif()\n  endif()\nendif()\n\n\n# Not sure the logic is correct here.\n# If NCurses is required, use the function wsyncup() to check if the library\n# has NCurses functionality (at least this is where it breaks on NetBSD).\n# If wsyncup is in curses, use this one.\n# If not, try to find ncurses and check if this has the symbol.\n# Once the ncurses library is found, search the ncurses.h header first, but\n# some web pages also say that even with ncurses there is not always a ncurses.h:\n# http://osdir.com/ml/gnome.apps.mc.devel/2002-06/msg00029.html\n# So at first try ncurses.h, if not found, try to find curses.h under the same\n# prefix as the library was found, if still not found, try curses.h with the\n# default search paths.\nif(CURSES_CURSES_LIBRARY  AND  CURSES_NEED_NCURSES)\n  include(CMakePushCheckState)\n  cmake_push_check_state()\n  set(CMAKE_REQUIRED_QUIET ${Curses_FIND_QUIETLY})\n  CHECK_LIBRARY_EXISTS(\"${CURSES_CURSES_LIBRARY}\"\n    wsyncup \"\" CURSES_CURSES_HAS_WSYNCUP)\n\n  if(CURSES_NCURSES_LIBRARY  AND NOT  CURSES_CURSES_HAS_WSYNCUP)\n    CHECK_LIBRARY_EXISTS(\"${CURSES_NCURSES_LIBRARY}\"\n      wsyncup \"\" CURSES_NCURSES_HAS_WSYNCUP)\n    if( CURSES_NCURSES_HAS_WSYNCUP)\n      set(CURSES_USE_NCURSES TRUE)\n    endif()\n  endif()\n  cmake_pop_check_state()\n\nendif()\n\nif(CURSES_USE_NCURSES)\n  get_filename_component(_cursesLibDir \"${CURSES_NCURSES_LIBRARY}\" PATH)\n  get_filename_component(_cursesParentDir \"${_cursesLibDir}\" PATH)\n\n  # Use CURSES_NCURSES_INCLUDE_PATH if set, for compatibility.\n  if(CURSES_NCURSES_INCLUDE_PATH)\n    if (CURSES_NEED_WIDE)\n      find_path(CURSES_INCLUDE_PATH\n        NAMES ncursesw/ncurses.h ncursesw/curses.h ncursesw.h cursesw.h\n        PATHS ${CURSES_NCURSES_INCLUDE_PATH}\n        NO_DEFAULT_PATH\n        )\n    else()\n      find_path(CURSES_INCLUDE_PATH\n        NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h\n        PATHS ${CURSES_NCURSES_INCLUDE_PATH}\n        NO_DEFAULT_PATH\n        )\n    endif()\n  endif()\n\n  if (CURSES_NEED_WIDE)\n    set(CURSES_TINFO_LIBRARY_NAME tinfow)\n    find_path(CURSES_INCLUDE_PATH\n      NAMES ncursesw/ncurses.h ncursesw/curses.h ncursesw.h cursesw.h\n      HINTS \"${_cursesParentDir}/include\"\n      )\n  else()\n    set(CURSES_TINFO_LIBRARY_NAME tinfo)\n    find_path(CURSES_INCLUDE_PATH\n      NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h\n      HINTS \"${_cursesParentDir}/include\"\n      )\n  endif()\n\n  # Previous versions of FindCurses provided these values.\n  if(NOT DEFINED CURSES_LIBRARY)\n    set(CURSES_LIBRARY \"${CURSES_NCURSES_LIBRARY}\")\n  endif()\n\n  CHECK_LIBRARY_EXISTS(\"${CURSES_NCURSES_LIBRARY}\"\n    cbreak \"\" CURSES_NCURSES_HAS_CBREAK)\n  if(NOT CURSES_NCURSES_HAS_CBREAK)\n    find_library(CURSES_EXTRA_LIBRARY \"${CURSES_TINFO_LIBRARY_NAME}\" HINTS \"${_cursesLibDir}\")\n    find_library(CURSES_EXTRA_LIBRARY \"${CURSES_TINFO_LIBRARY_NAME}\" )\n  endif()\nelse()\n  get_filename_component(_cursesLibDir \"${CURSES_CURSES_LIBRARY}\" PATH)\n  get_filename_component(_cursesParentDir \"${_cursesLibDir}\" PATH)\n\n  #We can't find anything with CURSES_NEED_WIDE because we know\n  #only about ncursesw unicode curses version\n  if(NOT CURSES_NEED_WIDE)\n    find_path(CURSES_INCLUDE_PATH\n      NAMES curses.h\n      HINTS \"${_cursesParentDir}/include\"\n      )\n  endif()\n\n  # Previous versions of FindCurses provided these values.\n  if(NOT DEFINED CURSES_CURSES_H_PATH)\n    set(CURSES_CURSES_H_PATH \"${CURSES_INCLUDE_PATH}\")\n  endif()\n  if(NOT DEFINED CURSES_LIBRARY)\n    set(CURSES_LIBRARY \"${CURSES_CURSES_LIBRARY}\")\n  endif()\nendif()\n\n# Report whether each possible header name exists in the include directory.\nif(NOT DEFINED CURSES_HAVE_NCURSES_NCURSES_H)\n  if(CURSES_NEED_WIDE)\n    if(EXISTS \"${CURSES_INCLUDE_PATH}/ncursesw/ncurses.h\")\n      set(CURSES_HAVE_NCURSES_NCURSES_H \"${CURSES_INCLUDE_PATH}/ncursesw/ncurses.h\")\n    endif()\n  elseif(EXISTS \"${CURSES_INCLUDE_PATH}/ncurses/ncurses.h\")\n    set(CURSES_HAVE_NCURSES_NCURSES_H \"${CURSES_INCLUDE_PATH}/ncurses/ncurses.h\")\n  endif()\n  if(NOT DEFINED CURSES_HAVE_NCURSES_NCURSES_H)\n    set(CURSES_HAVE_NCURSES_NCURSES_H \"CURSES_HAVE_NCURSES_NCURSES_H-NOTFOUND\")\n  endif()\nendif()\nif(NOT DEFINED CURSES_HAVE_NCURSES_CURSES_H)\n  if(CURSES_NEED_WIDE)\n    if(EXISTS \"${CURSES_INCLUDE_PATH}/ncursesw/curses.h\")\n      set(CURSES_HAVE_NCURSES_CURSES_H \"${CURSES_INCLUDE_PATH}/ncursesw/curses.h\")\n    endif()\n  elseif(EXISTS \"${CURSES_INCLUDE_PATH}/ncurses/curses.h\")\n    set(CURSES_HAVE_NCURSES_CURSES_H \"${CURSES_INCLUDE_PATH}/ncurses/curses.h\")\n  endif()\n  if(NOT DEFINED CURSES_HAVE_NCURSES_CURSES_H)\n    set(CURSES_HAVE_NCURSES_CURSES_H \"CURSES_HAVE_NCURSES_CURSES_H-NOTFOUND\")\n  endif()\nendif()\nif(NOT CURSES_NEED_WIDE)\n  #ncursesw can't be found for this paths\n  if(NOT DEFINED CURSES_HAVE_NCURSES_H)\n    if(EXISTS \"${CURSES_INCLUDE_PATH}/ncurses.h\")\n      set(CURSES_HAVE_NCURSES_H \"${CURSES_INCLUDE_PATH}/ncurses.h\")\n    else()\n      set(CURSES_HAVE_NCURSES_H \"CURSES_HAVE_NCURSES_H-NOTFOUND\")\n    endif()\n  endif()\n  if(NOT DEFINED CURSES_HAVE_CURSES_H)\n    if(EXISTS \"${CURSES_INCLUDE_PATH}/curses.h\")\n      set(CURSES_HAVE_CURSES_H \"${CURSES_INCLUDE_PATH}/curses.h\")\n    else()\n      set(CURSES_HAVE_CURSES_H \"CURSES_HAVE_CURSES_H-NOTFOUND\")\n    endif()\n  endif()\nendif()\n\nfind_library(CURSES_FORM_LIBRARY form HINTS \"${_cursesLibDir}\")\nfind_library(CURSES_FORM_LIBRARY form )\n\n# Previous versions of FindCurses provided these values.\nif(NOT DEFINED FORM_LIBRARY)\n  set(FORM_LIBRARY \"${CURSES_FORM_LIBRARY}\")\nendif()\n\n# Need to provide the *_LIBRARIES\nset(CURSES_LIBRARIES ${CURSES_LIBRARY})\n\nif(CURSES_EXTRA_LIBRARY)\n  set(CURSES_LIBRARIES ${CURSES_LIBRARIES} ${CURSES_EXTRA_LIBRARY})\nendif()\n\nif(CURSES_FORM_LIBRARY)\n  set(CURSES_LIBRARIES ${CURSES_LIBRARIES} ${CURSES_FORM_LIBRARY})\nendif()\n\n# Provide the *_INCLUDE_DIRS and *_CFLAGS results.\nset(CURSES_INCLUDE_DIRS ${CURSES_INCLUDE_PATH})\nset(CURSES_INCLUDE_DIR ${CURSES_INCLUDE_PATH}) # compatibility\n\nfind_package(PkgConfig QUIET)\nif(PKG_CONFIG_FOUND)\n  pkg_check_modules(NCURSES QUIET ${NCURSES_LIBRARY_NAME})\n  set(CURSES_CFLAGS ${NCURSES_CFLAGS_OTHER})\nendif()\n\ninclude(FindPackageHandleStandardArgs)\nFIND_PACKAGE_HANDLE_STANDARD_ARGS(Curses DEFAULT_MSG\n  CURSES_LIBRARY CURSES_INCLUDE_PATH)\n\nmark_as_advanced(\n  CURSES_INCLUDE_PATH\n  CURSES_CURSES_LIBRARY\n  CURSES_NCURSES_LIBRARY\n  CURSES_EXTRA_LIBRARY\n  CURSES_FORM_LIBRARY\n  )\n"
  },
  {
    "path": "cmake/modules/FindLibdrm.cmake",
    "content": "#.rst:\n# FindLibdrm\n# -------\n#\n# Try to find libdrm on a Unix system.\n#\n# This will define the following variables:\n#\n# ``Libdrm_FOUND``\n#     True if (the requested version of) libdrm is available\n# ``Libdrm_VERSION``\n#     The version of libdrm\n# ``Libdrm_LIBRARIES``\n#     This can be passed to target_link_libraries() instead of the ``Libdrm::Libdrm``\n#     target\n# ``Libdrm_INCLUDE_DIRS``\n#     This should be passed to target_include_directories() if the target is not\n#     used for linking\n# ``Libdrm_DEFINITIONS``\n#     This should be passed to target_compile_options() if the target is not\n#     used for linking\n#\n# If ``Libdrm_FOUND`` is TRUE, it will also define the following imported target:\n#\n# ``Libdrm::Libdrm``\n#     The libdrm library\n#\n# In general we recommend using the imported target, as it is easier to use.\n# Bear in mind, however, that if the target is in the link interface of an\n# exported library, it must be made available by the package config file.\n\n#=============================================================================\n# SPDX-FileCopyrightText: 2014 Alex Merry <alex.merry@kde.org>\n# SPDX-FileCopyrightText: 2014 Martin Gräßlin <mgraesslin@kde.org>\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#=============================================================================\n\nif(CMAKE_VERSION VERSION_LESS 2.8.12)\n    message(FATAL_ERROR \"CMake 2.8.12 is required by FindLibdrm.cmake\")\nendif()\nif(CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 2.8.12)\n    message(AUTHOR_WARNING \"Your project should require at least CMake 2.8.12 to use FindLibdrm.cmake\")\nendif()\n\nif(NOT WIN32)\n    # Use pkg-config to get the directories and then use these values\n    # in the FIND_PATH() and FIND_LIBRARY() calls\n    find_package(PkgConfig)\n    pkg_check_modules(PKG_Libdrm QUIET libdrm)\n\n    set(Libdrm_DEFINITIONS ${PKG_Libdrm_CFLAGS_OTHER})\n    set(Libdrm_VERSION ${PKG_Libdrm_VERSION})\n\n    find_path(Libdrm_INCLUDE_DIR\n        NAMES\n            xf86drm.h\n        HINTS\n            ${PKG_Libdrm_INCLUDE_DIRS}\n    )\n    find_library(Libdrm_LIBRARY\n        NAMES\n            drm\n        HINTS\n            ${PKG_Libdrm_LIBRARY_DIRS}\n    )\n\n    include(FindPackageHandleStandardArgs)\n    find_package_handle_standard_args(Libdrm\n        FOUND_VAR\n            Libdrm_FOUND\n        REQUIRED_VARS\n            Libdrm_LIBRARY\n            Libdrm_INCLUDE_DIR\n        VERSION_VAR\n            Libdrm_VERSION\n    )\n\n    if(Libdrm_FOUND AND NOT TARGET Libdrm::Libdrm)\n        add_library(Libdrm::Libdrm UNKNOWN IMPORTED)\n        set_target_properties(Libdrm::Libdrm PROPERTIES\n            IMPORTED_LOCATION \"${Libdrm_LIBRARY}\"\n            INTERFACE_COMPILE_OPTIONS \"${Libdrm_DEFINITIONS}\"\n            INTERFACE_INCLUDE_DIRECTORIES \"${Libdrm_INCLUDE_DIR}\"\n            INTERFACE_INCLUDE_DIRECTORIES \"${Libdrm_INCLUDE_DIR}/libdrm\"\n        )\n    endif()\n\n    mark_as_advanced(Libdrm_LIBRARY Libdrm_INCLUDE_DIR)\n\n    # compatibility variables\n    set(Libdrm_LIBRARIES ${Libdrm_LIBRARY})\n    set(Libdrm_INCLUDE_DIRS ${Libdrm_INCLUDE_DIR} \"${Libdrm_INCLUDE_DIR}/libdrm\")\n    set(Libdrm_VERSION_STRING ${Libdrm_VERSION})\n\nelse()\n    message(STATUS \"FindLibdrm.cmake cannot find libdrm on Windows systems.\")\n    set(Libdrm_FOUND FALSE)\nendif()\n\ninclude(FeatureSummary)\nset_package_properties(Libdrm PROPERTIES\n    URL \"https://wiki.freedesktop.org/dri/\"\n    DESCRIPTION \"Userspace interface to kernel DRM services\"\n)\n"
  },
  {
    "path": "cmake/modules/FindMSan.cmake",
    "content": "# The MIT License (MIT)\n#\n# Copyright (c)\n#   2013 Matthew Arsenault\n#   2015-2016 RWTH Aachen University, Federal Republic of Germany\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\noption(SANITIZE_MEMORY \"Enable MemorySanitizer for sanitized targets.\" Off)\n\nset(FLAG_CANDIDATES\n    \"-g -fsanitize=memory\"\n)\n\n\ninclude(sanitize-helpers)\n\nif (SANITIZE_MEMORY)\n    if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL \"Linux\")\n        message(WARNING \"MemorySanitizer disabled for target ${TARGET} because \"\n            \"MemorySanitizer is supported for Linux systems only.\")\n        set(SANITIZE_MEMORY Off CACHE BOOL\n            \"Enable MemorySanitizer for sanitized targets.\" FORCE)\n    elseif (NOT ${CMAKE_SIZEOF_VOID_P} EQUAL 8)\n        message(WARNING \"MemorySanitizer disabled for target ${TARGET} because \"\n            \"MemorySanitizer is supported for 64bit systems only.\")\n        set(SANITIZE_MEMORY Off CACHE BOOL\n            \"Enable MemorySanitizer for sanitized targets.\" FORCE)\n    else ()\n        sanitizer_check_compiler_flags(\"${FLAG_CANDIDATES}\" \"MemorySanitizer\"\n            \"MSan\")\n    endif ()\nendif ()\n\nfunction (add_sanitize_memory TARGET)\n    if (NOT SANITIZE_MEMORY)\n        return()\n    endif ()\n\n    sanitizer_add_flags(${TARGET} \"MemorySanitizer\" \"MSan\")\nendfunction ()\n"
  },
  {
    "path": "cmake/modules/FindSanitizers.cmake",
    "content": "# The MIT License (MIT)\n#\n# Copyright (c)\n#   2013 Matthew Arsenault\n#   2015-2016 RWTH Aachen University, Federal Republic of Germany\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# If any of the used compiler is a GNU compiler, add a second option to static\n# link against the sanitizers.\noption(SANITIZE_LINK_STATIC \"Try to link static against sanitizers.\" Off)\n\n\n\n\nset(FIND_QUIETLY_FLAG \"\")\nif (DEFINED Sanitizers_FIND_QUIETLY)\n    set(FIND_QUIETLY_FLAG \"QUIET\")\nendif ()\n\nfind_package(ASan ${FIND_QUIETLY_FLAG})\nfind_package(TSan ${FIND_QUIETLY_FLAG})\nfind_package(MSan ${FIND_QUIETLY_FLAG})\nfind_package(UBSan ${FIND_QUIETLY_FLAG})\n\n\n\n\nfunction(sanitizer_add_blacklist_file FILE)\n    if(NOT IS_ABSOLUTE ${FILE})\n        set(FILE \"${CMAKE_CURRENT_SOURCE_DIR}/${FILE}\")\n    endif()\n    get_filename_component(FILE \"${FILE}\" REALPATH)\n\n    sanitizer_check_compiler_flags(\"-fsanitize-blacklist=${FILE}\"\n        \"SanitizerBlacklist\" \"SanBlist\")\nendfunction()\n\nfunction(add_sanitizers ...)\n    # If no sanitizer is enabled, return immediately.\n    if (NOT (SANITIZE_ADDRESS OR SANITIZE_MEMORY OR SANITIZE_THREAD OR\n        SANITIZE_UNDEFINED))\n        return()\n    endif ()\n\n    foreach (TARGET ${ARGV})\n        # Check if this target will be compiled by exactly one compiler. Other-\n        # wise sanitizers can't be used and a warning should be printed once.\n        get_target_property(TARGET_TYPE ${TARGET} TYPE)\n        if (TARGET_TYPE STREQUAL \"INTERFACE_LIBRARY\")\n            message(WARNING \"Can't use any sanitizers for target ${TARGET}, \"\n                    \"because it is an interface library and cannot be \"\n                    \"compiled directly.\")\n            return()\n        endif ()\n        sanitizer_target_compilers(${TARGET} TARGET_COMPILER)\n        list(LENGTH TARGET_COMPILER NUM_COMPILERS)\n        if (NUM_COMPILERS GREATER 1)\n            message(WARNING \"Can't use any sanitizers for target ${TARGET}, \"\n                    \"because it will be compiled by incompatible compilers. \"\n                    \"Target will be compiled without sanitizers.\")\n            return()\n\n        # If the target is compiled by no or no known compiler, give a warning.\n        elseif (NUM_COMPILERS EQUAL 0)\n            message(WARNING \"Sanitizers for target ${TARGET} may not be\"\n                    \" usable, because it uses no or an unknown compiler. \"\n                    \"This is a false warning for targets using only \"\n\t\t    \"object lib(s) as input.\")\n        endif ()\n\n        # Add sanitizers for target.\n        add_sanitize_address(${TARGET})\n        add_sanitize_thread(${TARGET})\n        add_sanitize_memory(${TARGET})\n        add_sanitize_undefined(${TARGET})\n\tendforeach ()\nendfunction(add_sanitizers)\n"
  },
  {
    "path": "cmake/modules/FindSystemd.cmake",
    "content": "#\n# - Find systemd libraries\n#\n# SYSTEMD_INCLUDE_DIRS - where to find systemd/sd-journal.h, etc.\n# SYSTEMD_LIBRARIES    - List of libraries when using libsystemd.\n# SYSTEMD_FOUND        - True if libsystemd is found.\n# A \"systemd\" target is created when found\n\npkg_search_module(PC_SYSTEMD QUIET libsystemd)\n\nfind_path(SYSTEMD_INCLUDE_DIR\n    NAMES\n    systemd/sd-device.h\n    HINTS\n    ${PC_SYSTEMD_INCLUDE_DIRS}\n)\n\nfind_library(SYSTEMD_LIBRARY\n    NAMES\n    systemd\n    HINTS\n    ${PC_SYSTEMD_LIBRARY_DIRS}\n)\n\ninclude(FindPackageHandleStandardArgs)\nfind_package_handle_standard_args(Systemd\n    REQUIRED_VARS SYSTEMD_LIBRARY SYSTEMD_INCLUDE_DIR\n    VERSION_VAR PC_SYSTEMD_VERSION)\n\nif(SYSTEMD_FOUND)\n    set(SYSTEMD_LIBRARIES ${SYSTEMD_LIBRARY})\n    set(SYSTEMD_INCLUDE_DIRS ${SYSTEMD_INCLUDE_DIR})\n\n    add_library(systemd INTERFACE IMPORTED GLOBAL)\n    target_include_directories(systemd INTERFACE ${SYSTEMD_INCLUDE_DIRS})\n    set_target_properties(systemd PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${SYSTEMD_INCLUDE_DIRS})\n    target_link_libraries(systemd INTERFACE ${SYSTEMD_LIBRARIES})\nelse()\n    set(SYSTEMD_LIBRARIES)\n    set(SYSTEMD_INCLUDE_DIRS)\nendif()\n\nmark_as_advanced(SYSTEMD_LIBRARIES SYSTEMD_INCLUDE_DIRS)"
  },
  {
    "path": "cmake/modules/FindTSan.cmake",
    "content": "# The MIT License (MIT)\n#\n# Copyright (c)\n#   2013 Matthew Arsenault\n#   2015-2016 RWTH Aachen University, Federal Republic of Germany\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\noption(SANITIZE_THREAD \"Enable ThreadSanitizer for sanitized targets.\" Off)\n\nset(FLAG_CANDIDATES\n    \"-g -fsanitize=thread\"\n)\n\n\n# ThreadSanitizer is not compatible with MemorySanitizer.\nif (SANITIZE_THREAD AND SANITIZE_MEMORY)\n    message(FATAL_ERROR \"ThreadSanitizer is not compatible with \"\n        \"MemorySanitizer.\")\nendif ()\n\n\ninclude(sanitize-helpers)\n\nif (SANITIZE_THREAD)\n  if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL \"Linux\" AND\n      NOT ${CMAKE_SYSTEM_NAME} STREQUAL \"Darwin\")\n        message(WARNING \"ThreadSanitizer disabled for target ${TARGET} because \"\n          \"ThreadSanitizer is supported for Linux systems and macOS only.\")\n        set(SANITIZE_THREAD Off CACHE BOOL\n            \"Enable ThreadSanitizer for sanitized targets.\" FORCE)\n    elseif (NOT ${CMAKE_SIZEOF_VOID_P} EQUAL 8)\n        message(WARNING \"ThreadSanitizer disabled for target ${TARGET} because \"\n            \"ThreadSanitizer is supported for 64bit systems only.\")\n        set(SANITIZE_THREAD Off CACHE BOOL\n            \"Enable ThreadSanitizer for sanitized targets.\" FORCE)\n    else ()\n        sanitizer_check_compiler_flags(\"${FLAG_CANDIDATES}\" \"ThreadSanitizer\"\n            \"TSan\")\n    endif ()\nendif ()\n\nfunction (add_sanitize_thread TARGET)\n    if (NOT SANITIZE_THREAD)\n        return()\n    endif ()\n\n    sanitizer_add_flags(${TARGET} \"ThreadSanitizer\" \"TSan\")\nendfunction ()\n"
  },
  {
    "path": "cmake/modules/FindUBSan.cmake",
    "content": "# The MIT License (MIT)\n#\n# Copyright (c)\n#   2013 Matthew Arsenault\n#   2015-2016 RWTH Aachen University, Federal Republic of Germany\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\noption(SANITIZE_UNDEFINED\n    \"Enable UndefinedBehaviorSanitizer for sanitized targets.\" Off)\n\nset(FLAG_CANDIDATES\n    \"-g -fsanitize=undefined\"\n)\n\n\ninclude(sanitize-helpers)\n\nif (SANITIZE_UNDEFINED)\n    sanitizer_check_compiler_flags(\"${FLAG_CANDIDATES}\"\n        \"UndefinedBehaviorSanitizer\" \"UBSan\")\nendif ()\n\nfunction (add_sanitize_undefined TARGET)\n    if (NOT SANITIZE_UNDEFINED)\n        return()\n    endif ()\n\n    sanitizer_add_flags(${TARGET} \"UndefinedBehaviorSanitizer\" \"UBSan\")\nendfunction ()\n"
  },
  {
    "path": "cmake/modules/FindUDev.cmake",
    "content": "# Configure libudev environment\n#\n# UDEV_FOUND - system has a libudev\n# UDEV_INCLUDE_DIR - where to find header files\n# UDEV_LIBRARIES - the libraries to link against udev\n# UDEV_STABLE - it's true when is the version greater or equals to 143 - version when the libudev was stabilized in its API\n# An \"udev\" target is created when found\n#\n# Adapted from a version of Petr Vanek\n# copyright (c) 2011 Petr Vanek <petr@scribus.info>\n# copyright (c) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n#\n# Redistribution and use of this file is allowed according to the terms of the BSD license.\n#\n\npkg_search_module(PC_UDEV QUIET libudev)\n\nfind_path(UDEV_INCLUDE_DIR\n    NAMES\n    libudev.h\n    HINTS\n    ${PC_UDEV_INCLUDE_DIRS}\n)\n\nfind_library(UDEV_LIBRARY\n    NAMES udev\n    HINTS\n    ${PC_UDEV_LIBRARY_DIRS}\n)\ninclude(FindPackageHandleStandardArgs)\nfind_package_handle_standard_args(UDev\n    REQUIRED_VARS UDEV_LIBRARY UDEV_INCLUDE_DIR\n    VERSION_VAR PC_UDEV_VERSION)\n\nif(UDEV_FOUND)\n    if(PC_UDEV_VERSION GREATER_EQUAL \"143\")\n        set(UDEV_STABLE TRUE)\n    else()\n        set(UDEV_STABLE FALSE)\n    endif()\n\n    set(UDEV_LIBRARIES ${UDEV_LIBRARY})\n    set(UDEV_INCLUDE_DIRS ${UDEV_INCLUDE_DIR})\n\n    message(STATUS \"Libudev stable: ${UDEV_STABLE}\")\n\n    add_library(udev INTERFACE IMPORTED GLOBAL)\n    set_target_properties(udev PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${UDEV_INCLUDE_DIRS})\n    target_link_libraries(udev INTERFACE ${UDEV_LIBRARIES})\nelse()\n    set(UDEV_LIBRARIES)\n    set(UDEV_INCLUDE_DIRS)\nendif()\n\nmark_as_advanced(UDEV_LIBRARIES UDEV_INCLUDE_DIRS)"
  },
  {
    "path": "cmake/modules/asan-wrapper",
    "content": "#!/bin/sh\n\n# The MIT License (MIT)\n#\n# Copyright (c)\n#   2013 Matthew Arsenault\n#   2015-2016 RWTH Aachen University, Federal Republic of Germany\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# This script is a wrapper for AddressSanitizer. In some special cases you need\n# to preload AddressSanitizer to avoid error messages - e.g. if you're\n# preloading another library to your application. At the moment this script will\n# only do something, if we're running on a Linux platform. OSX might not be\n# affected.\n\n\n# Exit immediately, if platform is not Linux.\nif [ \"$(uname)\" != \"Linux\" ]\nthen\n    exec $@\nfi\n\n\n# Get the used libasan of the application ($1). If a libasan was found, it will\n# be prepended to LD_PRELOAD.\nlibasan=$(ldd $1 | grep libasan | sed \"s/^[[:space:]]//\" | cut -d' ' -f1)\nif [ -n \"$libasan\" ]\nthen\n    if [ -n \"$LD_PRELOAD\" ]\n    then\n        export LD_PRELOAD=\"$libasan:$LD_PRELOAD\"\n    else\n        export LD_PRELOAD=\"$libasan\"\n    fi\nfi\n\n# Execute the application.\nexec $@\n"
  },
  {
    "path": "cmake/modules/sanitize-helpers.cmake",
    "content": "# The MIT License (MIT)\n#\n# Copyright (c)\n#   2013 Matthew Arsenault\n#   2015-2016 RWTH Aachen University, Federal Republic of Germany\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Helper function to get the language of a source file.\nfunction (sanitizer_lang_of_source FILE RETURN_VAR)\n    get_filename_component(LONGEST_EXT \"${FILE}\" EXT)\n    # If extension is empty return. This can happen for extensionless headers\n    if(\"${LONGEST_EXT}\" STREQUAL \"\")\n       set(${RETURN_VAR} \"\" PARENT_SCOPE)\n       return()\n    endif()\n    # Get shortest extension as some files can have dot in their names\n    string(REGEX REPLACE \"^.*(\\\\.[^.]+)$\" \"\\\\1\" FILE_EXT ${LONGEST_EXT})\n    string(TOLOWER \"${FILE_EXT}\" FILE_EXT)\n    string(SUBSTRING \"${FILE_EXT}\" 1 -1 FILE_EXT)\n\n    get_property(ENABLED_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)\n    foreach (LANG ${ENABLED_LANGUAGES})\n        list(FIND CMAKE_${LANG}_SOURCE_FILE_EXTENSIONS \"${FILE_EXT}\" TEMP)\n        if (NOT ${TEMP} EQUAL -1)\n            set(${RETURN_VAR} \"${LANG}\" PARENT_SCOPE)\n            return()\n        endif ()\n    endforeach()\n\n    set(${RETURN_VAR} \"\" PARENT_SCOPE)\nendfunction ()\n\n\n# Helper function to get compilers used by a target.\nfunction (sanitizer_target_compilers TARGET RETURN_VAR)\n    # Check if all sources for target use the same compiler. If a target uses\n    # e.g. C and Fortran mixed and uses different compilers (e.g. clang and\n    # gfortran) this can trigger huge problems, because different compilers may\n    # use different implementations for sanitizers.\n    set(BUFFER \"\")\n    get_target_property(TSOURCES ${TARGET} SOURCES)\n    foreach (FILE ${TSOURCES})\n        # If expression was found, FILE is a generator-expression for an object\n        # library. Object libraries will be ignored.\n        string(REGEX MATCH \"TARGET_OBJECTS:([^ >]+)\" _file ${FILE})\n        if (\"${_file}\" STREQUAL \"\")\n            sanitizer_lang_of_source(${FILE} LANG)\n            if (LANG)\n                list(APPEND BUFFER ${CMAKE_${LANG}_COMPILER_ID})\n            endif ()\n        endif ()\n    endforeach ()\n\n    list(REMOVE_DUPLICATES BUFFER)\n    set(${RETURN_VAR} \"${BUFFER}\" PARENT_SCOPE)\nendfunction ()\n\n\n# Helper function to check compiler flags for language compiler.\nfunction (sanitizer_check_compiler_flag FLAG LANG VARIABLE)\n    if (${LANG} STREQUAL \"C\")\n        include(CheckCCompilerFlag)\n        check_c_compiler_flag(\"${FLAG}\" ${VARIABLE})\n\n    elseif (${LANG} STREQUAL \"CXX\")\n        include(CheckCXXCompilerFlag)\n        check_cxx_compiler_flag(\"${FLAG}\" ${VARIABLE})\n\n    elseif (${LANG} STREQUAL \"Fortran\")\n        # CheckFortranCompilerFlag was introduced in CMake 3.x. To be compatible\n        # with older Cmake versions, we will check if this module is present\n        # before we use it. Otherwise we will define Fortran coverage support as\n        # not available.\n        include(CheckFortranCompilerFlag OPTIONAL RESULT_VARIABLE INCLUDED)\n        if (INCLUDED)\n            check_fortran_compiler_flag(\"${FLAG}\" ${VARIABLE})\n        elseif (NOT CMAKE_REQUIRED_QUIET)\n            message(STATUS \"Performing Test ${VARIABLE}\")\n            message(STATUS \"Performing Test ${VARIABLE}\"\n                \" - Failed (Check not supported)\")\n        endif ()\n    endif()\nendfunction ()\n\n\n# Helper function to test compiler flags.\nfunction (sanitizer_check_compiler_flags FLAG_CANDIDATES NAME PREFIX)\n    set(CMAKE_REQUIRED_QUIET ${${PREFIX}_FIND_QUIETLY})\n\n    get_property(ENABLED_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)\n    foreach (LANG ${ENABLED_LANGUAGES})\n        # Sanitizer flags are not dependent on language, but the used compiler.\n        # So instead of searching flags foreach language, search flags foreach\n        # compiler used.\n        set(COMPILER ${CMAKE_${LANG}_COMPILER_ID})\n        if (NOT DEFINED ${PREFIX}_${COMPILER}_FLAGS)\n            foreach (FLAG ${FLAG_CANDIDATES})\n                if(NOT CMAKE_REQUIRED_QUIET)\n                    message(STATUS \"Try ${COMPILER} ${NAME} flag = [${FLAG}]\")\n                endif()\n\n                set(CMAKE_REQUIRED_FLAGS \"${FLAG}\")\n                unset(${PREFIX}_FLAG_DETECTED CACHE)\n                sanitizer_check_compiler_flag(\"${FLAG}\" ${LANG}\n                    ${PREFIX}_FLAG_DETECTED)\n\n                if (${PREFIX}_FLAG_DETECTED)\n                    # If compiler is a GNU compiler, search for static flag, if\n                    # SANITIZE_LINK_STATIC is enabled.\n                    if (SANITIZE_LINK_STATIC AND (${COMPILER} STREQUAL \"GNU\"))\n                        string(TOLOWER ${PREFIX} PREFIX_lower)\n                        sanitizer_check_compiler_flag(\n                            \"-static-lib${PREFIX_lower}\" ${LANG}\n                            ${PREFIX}_STATIC_FLAG_DETECTED)\n\n                        if (${PREFIX}_STATIC_FLAG_DETECTED)\n                            set(FLAG \"-static-lib${PREFIX_lower} ${FLAG}\")\n                        endif ()\n                    endif ()\n\n                    set(${PREFIX}_${COMPILER}_FLAGS \"${FLAG}\" CACHE STRING\n                        \"${NAME} flags for ${COMPILER} compiler.\")\n                    mark_as_advanced(${PREFIX}_${COMPILER}_FLAGS)\n                    break()\n                endif ()\n            endforeach ()\n\n            if (NOT ${PREFIX}_FLAG_DETECTED)\n                set(${PREFIX}_${COMPILER}_FLAGS \"\" CACHE STRING\n                    \"${NAME} flags for ${COMPILER} compiler.\")\n                mark_as_advanced(${PREFIX}_${COMPILER}_FLAGS)\n\n                message(WARNING \"${NAME} is not available for ${COMPILER} \"\n                        \"compiler. Targets using this compiler will be \"\n                        \"compiled without ${NAME}.\")\n            endif ()\n        endif ()\n    endforeach ()\nendfunction ()\n\n\n# Helper to assign sanitizer flags for TARGET.\nfunction (sanitizer_add_flags TARGET NAME PREFIX)\n    # Get list of compilers used by target and check, if sanitizer is available\n    # for this target. Other compiler checks like check for conflicting\n    # compilers will be done in add_sanitizers function.\n    sanitizer_target_compilers(${TARGET} TARGET_COMPILER)\n    list(LENGTH TARGET_COMPILER NUM_COMPILERS)\n    if (\"${${PREFIX}_${TARGET_COMPILER}_FLAGS}\" STREQUAL \"\")\n        return()\n    endif()\n\n    # Set compile- and link-flags for target.\n    set_property(TARGET ${TARGET} APPEND_STRING\n        PROPERTY COMPILE_FLAGS \" ${${PREFIX}_${TARGET_COMPILER}_FLAGS}\")\n    set_property(TARGET ${TARGET} APPEND_STRING\n        PROPERTY COMPILE_FLAGS \" ${SanBlist_${TARGET_COMPILER}_FLAGS}\")\n    set_property(TARGET ${TARGET} APPEND_STRING\n        PROPERTY LINK_FLAGS \" ${${PREFIX}_${TARGET_COMPILER}_FLAGS}\")\nendfunction ()\n"
  },
  {
    "path": "cmake/optimization_flags.cmake",
    "content": "set(ADDITIONAL_DEBUG_COMPILE_OPTIONS\n  \"-Wall\"\n  #\"-Wpedantic\"\n  \"-Wextra\"\n  \"-Waddress\"\n  \"-Waggressive-loop-optimizations\"\n  #\"-Wcast-qual\"\n  #\"-Wcast-align\"\n  \"-Wbad-function-cast\"\n  \"-Wmissing-declarations\"\n  \"-Wmissing-parameter-type\"\n  \"-Wmissing-prototypes\"\n  \"-Wnested-externs\"\n  \"-Wold-style-declaration\"\n  \"-Wold-style-definition\"\n  \"-Wstrict-prototypes\"\n  \"-Wpointer-sign\"\n  \"-Wdouble-promotion\"\n  \"-Wuninitialized\"\n  \"-Winit-self\"\n  \"-Wstrict-aliasing\"\n  \"-Wsuggest-attribute=const\"\n  \"-Wtrampolines\"\n  \"-Wfloat-equal\"\n  \"-Wshadow\"\n  \"-Wunsafe-loop-optimizations\"\n  \"-Wfloat-conversion\"\n  \"-Wlogical-op\"\n  \"-Wnormalized\"\n  \"-Wdisabled-optimization\"\n  \"-Whsa\"\n  #\"-Wconversion\"\n  \"-Wunused-result\"\n  \"-Werror=implicit-function-declaration\"\n  #\"-Wpadded\"\n  \"-Wformat\"\n  \"-Wformat-security\"\n  CACHE INTERNAL \"String\"\n  )\n\nset(ADDITIONAL_RELEASE_LINK_OPTIONS\n  \"-Wl,-z,relro\")\n"
  },
  {
    "path": "desktop/nvtop.desktop",
    "content": "[Desktop Entry]\nName=nvtop\nGenericName=GPU Process Monitor\nType=Application\nTerminal=true\nExec=nvtop\nIcon=nvtop\nCategories=System;Monitor;\nX-AppImage-Integrate=false\n\n"
  },
  {
    "path": "desktop/nvtop.metainfo.xml.in",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<component type=\"console-application\">\n    <id>io.github.syllo.nvtop</id>\n\n    <name>nvtop</name>\n    <summary>GPU process monitor for AMD, Intel and NVIDIA</summary>\n\n    <metadata_license>CC0-1.0</metadata_license>\n    <project_license>GPL-3.0-or-later</project_license>\n    <developer_name>Maxime Schmitt</developer_name>\n\n    <description>\n        <p>Nvtop stands for Neat Videocard TOP, a (h)top like task monitor for AMD, Intel and NVIDIA GPUs. It can handle multiple GPUs and print information about them in a htop familiar way.</p>\n    </description>\n\n    <launchable type=\"desktop-id\">nvtop.desktop</launchable>\n\n    <icon type=\"cached\">nvtop.svg</icon>\n\n    <categories>\n        <category>System</category>\n        <category>Monitor</category>\n    </categories>\n\n    <url type=\"homepage\">https://github.com/Syllo/nvtop</url>\n\n    <screenshots>\n        <screenshot type=\"default\">\n            <caption>The nvtop interface</caption>\n            <image>https://raw.githubusercontent.com/Syllo/nvtop/master/screenshot/NVTOP_ex1.png</image>\n        </screenshot>\n        <screenshot>\n            <caption>The nvtop option screen</caption>\n            <image>https://raw.githubusercontent.com/Syllo/nvtop/master/screenshot/Nvtop-config.png</image>\n        </screenshot>\n    </screenshots>\n\n    <provides>\n        <binary>nvtop</binary>\n    </provides>\n    <releases>\n    <release version=\"@nvtop_VERSION_MAJOR@.@nvtop_VERSION_MINOR@.@nvtop_VERSION_PATCH@\" date=\"@TODAY_ISO_8601@\"></release>\n    </releases>\n</component>\n"
  },
  {
    "path": "include/ascend/dcmi_interface_api.h",
    "content": "﻿/* Copyright(C) 2021-2023. Huawei Technologies Co.,Ltd. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n#ifndef __DCMI_INTERFACE_API_H__\n#define __DCMI_INTERFACE_API_H__\n\n#ifdef __cplusplus\n#if __cplusplus\nextern \"C\" {\n#endif\n#endif /* __cplusplus */\n\n#ifdef __linux__\n#define DCMIDLLEXPORT\n#else\n#define DCMIDLLEXPORT _declspec(dllexport)\n#endif\n\n#define MAX_CARD_NUM 64\n#define MAX_CHIP_NAME_LEN 32  // Maximum length of chip name\n#define TEMPLATE_NAME_LEN 32\n#define DIE_ID_COUNT 5  // Number of die ID characters\n\n#define    DCMI_UTILIZATION_RATE_DDR             1\n#define    DCMI_UTILIZATION_RATE_AICORE          2\n#define    DCMI_UTILIZATION_RATE_AICPU           3\n#define    DCMI_UTILIZATION_RATE_CTRLCPU         4\n#define    DCMI_UTILIZATION_RATE_DDR_BANDWIDTH   5\n#define    DCMI_UTILIZATION_RATE_HBM             6\n#define    DCMI_UTILIZATION_RATE_HBM_BANDWIDTH   10\n#define    DCMI_UTILIZATION_RATE_VECTORCORE      12\n\n  /*----------------------------------------------*\n* Structure description                        *\n*----------------------------------------------*/\n  struct dcmi_chip_info {\n    unsigned char chip_type[MAX_CHIP_NAME_LEN];\n    unsigned char chip_name[MAX_CHIP_NAME_LEN];\n    unsigned char chip_ver[MAX_CHIP_NAME_LEN];\n    unsigned int aicore_cnt;\n  };\n\n  struct dcmi_pcie_info_all {\n    unsigned int venderid;\n    unsigned int subvenderid;\n    unsigned int deviceid;\n    unsigned int subdeviceid;\n    int domain;\n    unsigned int bdf_busid;\n    unsigned int bdf_deviceid;\n    unsigned int bdf_funcid;\n    unsigned char reserve[32];       /* the size of dcmi_pcie_info_all is 64 */\n  };\n\n  struct dcmi_die_id {\n    unsigned int soc_die[DIE_ID_COUNT];\n  };\n\n  struct dcmi_hbm_info {\n    unsigned long long memory_size;\n    unsigned int freq;\n    unsigned long long memory_usage;\n    int temp;\n    unsigned int bandwith_util_rate;\n  };\n\n  struct dcmi_get_memory_info_stru {\n    unsigned long long memory_size;        /* unit:MB */\n    unsigned long long memory_available;   /* free + hugepages_free * hugepagesize */\n    unsigned int freq;\n    unsigned long hugepagesize;             /* unit:KB */\n    unsigned long hugepages_total;\n    unsigned long hugepages_free;\n    unsigned int utilize;                  /* ddr memory info usages */\n    unsigned char reserve[60];             /* the size of dcmi_memory_info is 96 */\n  };\n\n  enum dcmi_ip_addr_type {\n    DCMI_IPADDR_TYPE_V4 = 0, /** IPv4 */\n    DCMI_IPADDR_TYPE_V6 = 1, /** IPv6 */\n    DCMI_IPADDR_TYPE_ANY = 2 /** IPv4+IPv6 (\"dual-stack\") */\n  };\n\n  struct dcmi_ip_addr {\n    union {\n      unsigned char ip6[16];\n      unsigned char ip4[4];\n    } u_addr;\n    enum dcmi_ip_addr_type ip_type;\n  };\n\n  enum dcmi_unit_type {\n    NPU_TYPE = 0,\n    MCU_TYPE = 1,\n    CPU_TYPE = 2,\n    INVALID_TYPE = 0xFF\n  };\n\n  enum dcmi_rdfx_detect_result {\n    DCMI_RDFX_DETECT_OK = 0,\n    DCMI_RDFX_DETECT_SOCK_FAIL = 1,\n    DCMI_RDFX_DETECT_RECV_TIMEOUT = 2,\n    DCMI_RDFX_DETECT_UNREACH = 3,\n    DCMI_RDFX_DETECT_TIME_EXCEEDED = 4,\n    DCMI_RDFX_DETECT_FAULT = 5,\n    DCMI_RDFX_DETECT_INIT = 6,\n    DCMI_RDFX_DETECT_THREAD_ERR = 7,\n    DCMI_RDFX_DETECT_IP_SET = 8,\n    DCMI_RDFX_DETECT_MAX = 0xFF\n  };\n\n  enum dcmi_port_type {\n    DCMI_VNIC_PORT = 0,\n    DCMI_ROCE_PORT = 1,\n    DCMI_INVALID_PORT\n  };\n\n  enum dcmi_main_cmd {\n    DCMI_MAIN_CMD_DVPP = 0,\n    DCMI_MAIN_CMD_ISP,\n    DCMI_MAIN_CMD_TS_GROUP_NUM,\n    DCMI_MAIN_CMD_CAN,\n    DCMI_MAIN_CMD_UART,\n    DCMI_MAIN_CMD_UPGRADE,\n    DCMI_MAIN_CMD_TEMP = 50,\n    DCMI_MAIN_CMD_SVM = 51,\n    DCMI_MAIN_CMD_VDEV_MNG,\n    DCMI_MAIN_CMD_DEVICE_SHARE = 0x8001,\n    DCMI_MAIN_CMD_MAX\n  };\n\n  enum dcmi_freq_type {\n    DCMI_FREQ_DDR = 1,\n    DCMI_FREQ_CTRLCPU = 2,\n    DCMI_FREQ_HBM = 6,\n    DCMI_FREQ_AICORE_CURRENT_ = 7,\n    DCMI_FREQ_AICORE_MAX = 9,\n    DCMI_FREQ_VECTORCORE_CURRENT = 12\n  };\n\n  enum dcmi_reset_channel {\n    OUTBAND_CHANNEL = 0, // out-of-band reset\n    INBAND_CHANNEL // in-band reset\n  };\n\n  enum dcmi_boot_status {\n    DCMI_BOOT_STATUS_UNINIT = 0, // not init\n    DCMI_BOOT_STATUS_BIOS, // BIOS starting\n    DCMI_BOOT_STATUS_OS, // OS starting\n    DCMI_BOOT_STATUS_FINISH // started\n  };\n\n  enum dcmi_event_type {\n    DCMI_DMS_FAULT_EVENT = 0,\n  };\n\n  enum dcmi_die_type {\n    NDIE,\n    VDIE\n  };\n\n#define DCMI_VDEV_RES_NAME_LEN 16\n#define DCMI_VDEV_SIZE 20\n#define DCMI_VDEV_FOR_RESERVE 32\n#define DCMI_SOC_SPLIT_MAX 32\n#define DCMI_MAX_EVENT_NAME_LENGTH 256\n#define DCMI_MAX_EVENT_DATA_LENGTH 32\n#define DCMI_EVENT_FILTER_FLAG_EVENT_ID (1UL << 0)\n#define DCMI_EVENT_FILTER_FLAG_SERVERITY (1UL << 1)\n#define DCMI_EVENT_FILTER_FLAG_NODE_TYPE (1UL << 2)\n#define DCMI_MAX_EVENT_RESV_LENGTH 32\n\n  struct dcmi_base_resource {\n    unsigned long long token;\n    unsigned long long token_max;\n    unsigned long long task_timeout;\n    unsigned int vfg_id;\n    unsigned char vip_mode;\n    unsigned char reserved[DCMI_VDEV_FOR_RESERVE - 1];  /* bytes aligned */\n  };\n\n  /* total types of computing resource */\n  struct dcmi_computing_resource {\n    /* accelator resource */\n    float aic;\n    float aiv;\n    unsigned short dsa;\n    unsigned short rtsq;\n    unsigned short acsq;\n    unsigned short cdqm;\n    unsigned short c_core;\n    unsigned short ffts;\n    unsigned short sdma;\n    unsigned short pcie_dma;\n\n    /* memory resource, MB as unit */\n    unsigned long long memory_size;\n\n    /* id resource */\n    unsigned int event_id;\n    unsigned int notify_id;\n    unsigned int stream_id;\n    unsigned int model_id;\n\n    /* cpu resource */\n    unsigned short topic_schedule_aicpu;\n    unsigned short host_ctrl_cpu;\n    unsigned short host_aicpu;\n    unsigned short device_aicpu;\n    unsigned short topic_ctrl_cpu_slot;\n\n    /* vnpu resource */\n    unsigned int vdev_aicore_utilization;\n    unsigned long long vdev_memory_total;\n    unsigned long long vdev_memory_free;\n\n    unsigned char reserved[DCMI_VDEV_FOR_RESERVE-DCMI_VDEV_SIZE];\n  };\n\n  struct dcmi_media_resource {\n    /* dvpp resource */\n    float jpegd;\n    float jpege;\n    float vpc;\n    float vdec;\n    float pngd;\n    float venc;\n    unsigned char reserved[DCMI_VDEV_FOR_RESERVE];\n  };\n\n  struct dcmi_create_vdev_out {\n    unsigned int vdev_id;\n    unsigned int pcie_bus;\n    unsigned int pcie_device;\n    unsigned int pcie_func;\n    unsigned int vfg_id;\n    unsigned char reserved[DCMI_VDEV_FOR_RESERVE];\n  };\n\n  struct dcmi_create_vdev_res_stru {\n    unsigned int vdev_id;\n    unsigned int vfg_id;\n    char template_name[TEMPLATE_NAME_LEN];\n    unsigned char reserved[64];\n  };\n\n  struct dcmi_vdev_query_info {\n    char name[DCMI_VDEV_RES_NAME_LEN];\n    unsigned int status;\n    unsigned int is_container_used;\n    unsigned int vfid;\n    unsigned int vfg_id;\n    unsigned long long container_id;\n    struct dcmi_base_resource base;\n    struct dcmi_computing_resource computing;\n    struct dcmi_media_resource media;\n  };\n\n  /* for single search */\n  struct dcmi_vdev_query_stru {\n    unsigned int vdev_id;\n    struct dcmi_vdev_query_info query_info;\n  };\n\n  struct dcmi_soc_free_resource {\n    unsigned int vfg_num;\n    unsigned int vfg_bitmap;\n    struct dcmi_base_resource base;\n    struct dcmi_computing_resource computing;\n    struct dcmi_media_resource media;\n  };\n\n  struct dcmi_soc_total_resource {\n    unsigned int vdev_num;\n    unsigned int vdev_id[DCMI_SOC_SPLIT_MAX];\n    unsigned int vfg_num;\n    unsigned int vfg_bitmap;\n    struct dcmi_base_resource base;\n    struct dcmi_computing_resource computing;\n    struct dcmi_media_resource media;\n  };\n\n  struct dcmi_dms_fault_event {\n    unsigned int event_id; /* Event ID */\n    unsigned short deviceid; /* Device ID */\n    unsigned char node_type; /* Node type */\n    unsigned char node_id; /* Node ID */\n    unsigned char sub_node_type; /* Subnode type */\n    unsigned char sub_node_id; /* Subnode ID */\n    unsigned char severity; /* Event severity. 0: warning; 1: minor; 2: major; 3: critical */\n    unsigned char assertion; /* Event type. 0: fault recovery; 1: fault generation; 2: one-off event */\n    int event_serial_num; /* Alarm serial number */\n    int notify_serial_num; /* Notification serial number*/\n    /* Time when the event occurs, presenting as the number of seconds that have elapsed since the Unix epoch. */\n    unsigned long long alarm_raised_time;\n    char event_name[DCMI_MAX_EVENT_NAME_LENGTH]; /* Event description */\n    char additional_info[DCMI_MAX_EVENT_DATA_LENGTH]; /* Additional event information */\n    unsigned char resv[DCMI_MAX_EVENT_RESV_LENGTH]; /**< Reserves 32 bytes */\n  };\n\n  struct dcmi_event {\n    enum dcmi_event_type type; /* Event type */\n    union {\n      struct dcmi_dms_fault_event dms_event; /* Event content */\n    } event_t;\n  };\n\n  struct dcmi_event_filter {\n    /* It can be used to enable one or all filter criteria. The filter criteria are as follows:\n    0: disables the filter criteria.\n    DCMI_EVENT_FILTER_FLAG_EVENT_ID: receives only specified events.\n    DCMI_EVENT_FILTER_FLAG_SERVERITY: receives only the events of a specified level and higher levels.\n    DCMI_EVENT_FILTER_FLAG_NODE_TYPE: receives only events of a specified node type. */\n    unsigned long long filter_flag;\n    /* Receives a specified event. For details, see the Health Management Error Definition. */\n    unsigned int event_id;\n    /* Receives events of a specified level and higher levels. For details,\n    see the severity definition in the struct dcmi_dms_fault_event structure. */\n    unsigned char severity;\n    /* Receives only events of a specified node type. For details, see the Health Management Error Definition. */\n    unsigned char node_type;\n    unsigned char resv[DCMI_MAX_EVENT_RESV_LENGTH]; /* < Reserves 32 bytes. */\n  };\n\n  struct dcmi_proc_mem_info {\n    int proc_id;\n    // unit is byte\n    unsigned long proc_mem_usage;\n  };\n\n  struct dcmi_board_info {\n    unsigned int board_id;\n    unsigned int pcb_id;\n    unsigned int bom_id;\n    unsigned int slot_id; // slot_id indicates pcie slot ID of the chip\n  };\n\n  struct dsmi_hbm_info_stru {\n    unsigned long long memory_size;      /**< HBM total size, KB */\n    unsigned int freq;                   /**< HBM freq, MHZ */\n    unsigned long long memory_usage;     /**< HBM memory_usage, KB */\n    int temp;                            /**< HBM temperature */\n    unsigned int bandwith_util_rate;\n  };\n\n#define DCMI_VERSION_1\n#define DCMI_VERSION_2\n\n#if defined DCMI_VERSION_2\n\n  DCMIDLLEXPORT int dcmi_init(void);\n\n  DCMIDLLEXPORT int dcmi_get_card_list(int *card_num, int *card_list, int list_len);\n\n  DCMIDLLEXPORT int dcmi_get_device_num_in_card(int card_id, int *device_num);\n\n  DCMIDLLEXPORT int dcmi_get_device_id_in_card(int card_id, int *device_id_max, int *mcu_id, int *cpu_id);\n\n  DCMIDLLEXPORT int dcmi_get_device_type(int card_id, int device_id, enum dcmi_unit_type *device_type);\n\n  DCMIDLLEXPORT int dcmi_get_device_pcie_info_v2(int card_id, int device_id, struct dcmi_pcie_info_all *pcie_info);\n\n  DCMIDLLEXPORT int dcmi_get_device_chip_info(int card_id, int device_id, struct dcmi_chip_info *chip_info);\n\n  DCMIDLLEXPORT int dcmi_get_device_power_info(int card_id, int device_id, int *power);\n\n  DCMIDLLEXPORT int dcmi_get_device_health(int card_id, int device_id, unsigned int *health);\n\n  DCMIDLLEXPORT int dcmi_get_device_errorcode_v2(\n      int card_id, int device_id, int *error_count, unsigned int *error_code_list, unsigned int list_len);\n\n  DCMIDLLEXPORT int dcmi_get_device_temperature(int card_id, int device_id, int *temperature);\n\n  DCMIDLLEXPORT int dcmi_get_device_voltage(int card_id, int device_id, unsigned int *voltage);\n\n  DCMIDLLEXPORT int dcmi_get_device_frequency(\n      int card_id, int device_id, enum dcmi_freq_type input_type, unsigned int *frequency);\n\n  DCMIDLLEXPORT int dcmi_get_device_hbm_info(int card_id, int device_id, struct dcmi_hbm_info *hbm_info);\n\n  DCMIDLLEXPORT int dcmi_get_device_memory_info_v3(int card_id, int device_id,\n                                                   struct dcmi_get_memory_info_stru *memory_info);\n\n  DCMIDLLEXPORT int dcmi_get_device_utilization_rate(\n      int card_id, int device_id, int input_type, unsigned int *utilization_rate);\n\n  DCMIDLLEXPORT int dcmi_get_device_info(\n      int card_id, int device_id, enum dcmi_main_cmd main_cmd, unsigned int sub_cmd, void *buf, unsigned int *size);\n\n  DCMIDLLEXPORT int dcmi_get_device_ip(int card_id, int device_id, enum dcmi_port_type input_type, int port_id,\n                                       struct dcmi_ip_addr *ip, struct dcmi_ip_addr *mask);\n\n  DCMIDLLEXPORT int dcmi_get_device_network_health(int card_id, int device_id, enum dcmi_rdfx_detect_result *result);\n\n  DCMIDLLEXPORT int dcmi_get_device_logic_id(int *device_logic_id, int card_id, int device_id);\n\n  DCMIDLLEXPORT int dcmi_create_vdevice(int card_id, int device_id, struct dcmi_create_vdev_res_stru *vdev,\n                                        struct dcmi_create_vdev_out *out);\n\n  DCMIDLLEXPORT int dcmi_set_destroy_vdevice(int card_id, int device_id, unsigned int vdevid);\n\n  DCMIDLLEXPORT int dcmi_get_device_phyid_from_logicid(unsigned int logicid, unsigned int *phyid);\n\n  DCMIDLLEXPORT int dcmi_get_device_logicid_from_phyid(unsigned int phyid, unsigned int *logicid);\n\n  DCMIDLLEXPORT int dcmi_get_card_id_device_id_from_logicid(int *card_id, int *device_id, unsigned int device_logic_id);\n\n  DCMIDLLEXPORT int dcmi_get_card_id_device_id_from_phyid(int *card_id, int *device_id, unsigned int device_phy_id);\n\n  DCMIDLLEXPORT int dcmi_get_product_type(int card_id, int device_id, char *product_type_str, int buf_size);\n\n  DCMIDLLEXPORT int dcmi_set_device_reset(int card_id, int device_id, enum dcmi_reset_channel channel_type);\n\n  DCMIDLLEXPORT int dcmi_get_device_boot_status(int card_id, int device_id, enum dcmi_boot_status *boot_status);\n\n  DCMIDLLEXPORT int dcmi_subscribe_fault_event(int card_id, int device_id, struct dcmi_event_filter filter);\n\n  DCMIDLLEXPORT int dcmi_get_npu_work_mode(int card_id, unsigned char *work_mode);\n\n  DCMIDLLEXPORT int dcmi_get_device_die_v2(\n      int card_id, int device_id, enum dcmi_die_type input_type, struct dcmi_die_id *die_id);\n\n  DCMIDLLEXPORT int dcmi_get_device_resource_info (int card_id, int device_id, struct dcmi_proc_mem_info *proc_info,\n                                                  int *proc_num);\n\n  DCMIDLLEXPORT int dcmi_get_device_board_info (int card_id, int device_id, struct dcmi_board_info *board_info);\n\n  DCMIDLLEXPORT int dcmi_get_hbm_info(int card_id, int device_id, struct dsmi_hbm_info_stru *device_hbm_info);\n\n#endif\n\n#if defined DCMI_VERSION_1\n  /* The following interfaces are V1 version interfaces. In order to ensure the compatibility is temporarily reserved,\n* the later version will be deleted. Please switch to the V2 version interface as soon as possible */\n\n  struct dcmi_memory_info_stru {\n    unsigned long long memory_size;\n    unsigned int freq;\n    unsigned int utilize;\n  };\n\n  DCMIDLLEXPORT int dcmi_get_memory_info(int card_id, int device_id, struct dcmi_memory_info_stru *device_memory_info);\n\n  DCMIDLLEXPORT int dcmi_get_device_errorcode(\n      int card_id, int device_id, int *error_count, unsigned int *error_code, int *error_width);\n\n  DCMIDLLEXPORT int dcmi_mcu_get_power_info(int card_id, int *power);\n#endif\n\n#ifdef __cplusplus\n#if __cplusplus\n}\n#endif\n#endif /* __cplusplus */\n\n#endif /* __DCMI_INTERFACE_API_H__ */\n"
  },
  {
    "path": "include/ini.h",
    "content": "/* inih -- simple .INI file parser\n\nSPDX-License-Identifier: BSD-3-Clause\n\nCopyright (C) 2009-2020, Ben Hoyt\n\ninih is released under the New BSD license (see LICENSE.txt). Go to the project\nhome page for more info:\n\nhttps://github.com/benhoyt/inih\n\n*/\n\n#ifndef INI_H\n#define INI_H\n\n/* Make this header file easier to include in C++ code */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdio.h>\n\n/* Nonzero if ini_handler callback should accept lineno parameter. */\n#ifndef INI_HANDLER_LINENO\n#define INI_HANDLER_LINENO 0\n#endif\n\n/* Typedef for prototype of handler function. */\n#if INI_HANDLER_LINENO\ntypedef int (*ini_handler)(void* user, const char* section,\n                           const char* name, const char* value,\n                           int lineno);\n#else\ntypedef int (*ini_handler)(void* user, const char* section,\n                           const char* name, const char* value);\n#endif\n\n/* Typedef for prototype of fgets-style reader function. */\ntypedef char* (*ini_reader)(char* str, int num, void* stream);\n\n/* Parse given INI-style file. May have [section]s, name=value pairs\n   (whitespace stripped), and comments starting with ';' (semicolon). Section\n   is \"\" if name=value pair parsed before any section heading. name:value\n   pairs are also supported as a concession to Python's configparser.\n\n   For each name=value pair parsed, call handler function with given user\n   pointer as well as section, name, and value (data only valid for duration\n   of handler call). Handler should return nonzero on success, zero on error.\n\n   Returns 0 on success, line number of first error on parse error (doesn't\n   stop on first error), -1 on file open error, or -2 on memory allocation\n   error (only when INI_USE_STACK is zero).\n*/\nint ini_parse(const char* filename, ini_handler handler, void* user);\n\n/* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't\n   close the file when it's finished -- the caller must do that. */\nint ini_parse_file(FILE* file, ini_handler handler, void* user);\n\n/* Same as ini_parse(), but takes an ini_reader function pointer instead of\n   filename. Used for implementing custom or string-based I/O (see also\n   ini_parse_string). */\nint ini_parse_stream(ini_reader reader, void* stream, ini_handler handler,\n                     void* user);\n\n/* Same as ini_parse(), but takes a zero-terminated string with the INI data\ninstead of a file. Useful for parsing INI data from a network socket or\nalready in memory. */\nint ini_parse_string(const char* string, ini_handler handler, void* user);\n\n/* Nonzero to allow multi-line value parsing, in the style of Python's\n   configparser. If allowed, ini_parse() will call the handler with the same\n   name for each subsequent line parsed. */\n#ifndef INI_ALLOW_MULTILINE\n#define INI_ALLOW_MULTILINE 1\n#endif\n\n/* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of\n   the file. See https://github.com/benhoyt/inih/issues/21 */\n#ifndef INI_ALLOW_BOM\n#define INI_ALLOW_BOM 1\n#endif\n\n/* Chars that begin a start-of-line comment. Per Python configparser, allow\n   both ; and # comments at the start of a line by default. */\n#ifndef INI_START_COMMENT_PREFIXES\n#define INI_START_COMMENT_PREFIXES \";#\"\n#endif\n\n/* Nonzero to allow inline comments (with valid inline comment characters\n   specified by INI_INLINE_COMMENT_PREFIXES). Set to 0 to turn off and match\n   Python 3.2+ configparser behaviour. */\n#ifndef INI_ALLOW_INLINE_COMMENTS\n#define INI_ALLOW_INLINE_COMMENTS 1\n#endif\n#ifndef INI_INLINE_COMMENT_PREFIXES\n#define INI_INLINE_COMMENT_PREFIXES \";\"\n#endif\n\n/* Nonzero to use stack for line buffer, zero to use heap (malloc/free). */\n#ifndef INI_USE_STACK\n#define INI_USE_STACK 1\n#endif\n\n/* Maximum line length for any line in INI file (stack or heap). Note that\n   this must be 3 more than the longest line (due to '\\r', '\\n', and '\\0'). */\n#ifndef INI_MAX_LINE\n#define INI_MAX_LINE 200\n#endif\n\n/* Nonzero to allow heap line buffer to grow via realloc(), zero for a\n   fixed-size buffer of INI_MAX_LINE bytes. Only applies if INI_USE_STACK is\n   zero. */\n#ifndef INI_ALLOW_REALLOC\n#define INI_ALLOW_REALLOC 0\n#endif\n\n/* Initial size in bytes for heap line buffer. Only applies if INI_USE_STACK\n   is zero. */\n#ifndef INI_INITIAL_ALLOC\n#define INI_INITIAL_ALLOC 200\n#endif\n\n/* Stop parsing on first error (default is to keep parsing). */\n#ifndef INI_STOP_ON_FIRST_ERROR\n#define INI_STOP_ON_FIRST_ERROR 0\n#endif\n\n/* Nonzero to call the handler at the start of each new section (with\n   name and value NULL). Default is to only call the handler on\n   each name=value pair. */\n#ifndef INI_CALL_HANDLER_ON_NEW_SECTION\n#define INI_CALL_HANDLER_ON_NEW_SECTION 0\n#endif\n\n/* Nonzero to allow a name without a value (no '=' or ':' on the line) and\n   call the handler with value NULL in this case. Default is to treat\n   no-value lines as an error. */\n#ifndef INI_ALLOW_NO_VALUE\n#define INI_ALLOW_NO_VALUE 0\n#endif\n\n/* Nonzero to use custom ini_malloc, ini_free, and ini_realloc memory\n   allocation functions (INI_USE_STACK must also be 0). These functions must\n   have the same signatures as malloc/free/realloc and behave in a similar\n   way. ini_realloc is only needed if INI_ALLOW_REALLOC is set. */\n#ifndef INI_CUSTOM_ALLOCATOR\n#define INI_CUSTOM_ALLOCATOR 0\n#endif\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* INI_H */\n"
  },
  {
    "path": "include/libdrm/xe_drm.h",
    "content": "/* SPDX-License-Identifier: MIT */\n\n/* This file is required by nvtop in order to support the newest xe driver whose xe_drm.h hasn't made it to libdrm yet */\n\n/*\n * Copyright © 2023 Intel Corporation\n */\n\n#ifndef _UAPI_XE_DRM_H_\n#define _UAPI_XE_DRM_H_\n\n#include \"drm.h\"\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n/*\n * Please note that modifications to all structs defined here are\n * subject to backwards-compatibility constraints.\n * Sections in this file are organized as follows:\n *   1. IOCTL definition\n *   2. Extension definition and helper structs\n *   3. IOCTL's Query structs in the order of the Query's entries.\n *   4. The rest of IOCTL structs in the order of IOCTL declaration.\n */\n\n/**\n * DOC: Xe Device Block Diagram\n *\n * The diagram below represents a high-level simplification of a discrete\n * GPU supported by the Xe driver. It shows some device components which\n * are necessary to understand this API, as well as how their relations\n * to each other. This diagram does not represent real hardware::\n *\n *   ┌──────────────────────────────────────────────────────────────────┐\n *   │ ┌──────────────────────────────────────────────────┐ ┌─────────┐ │\n *   │ │        ┌───────────────────────┐   ┌─────┐       │ │ ┌─────┐ │ │\n *   │ │        │         VRAM0         ├───┤ ... │       │ │ │VRAM1│ │ │\n *   │ │        └───────────┬───────────┘   └─GT1─┘       │ │ └──┬──┘ │ │\n *   │ │ ┌──────────────────┴───────────────────────────┐ │ │ ┌──┴──┐ │ │\n *   │ │ │ ┌─────────────────────┐  ┌─────────────────┐ │ │ │ │     │ │ │\n *   │ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │\n *   │ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │RCS0 │ │BCS0 │ │ │ │ │ │     │ │ │\n *   │ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │\n *   │ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │\n *   │ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │VCS0 │ │VCS1 │ │ │ │ │ │     │ │ │\n *   │ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │\n *   │ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │\n *   │ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │VECS0│ │VECS1│ │ │ │ │ │ ... │ │ │\n *   │ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │\n *   │ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │\n *   │ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │CCS0 │ │CCS1 │ │ │ │ │ │     │ │ │\n *   │ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │\n *   │ │ │ └─────────DSS─────────┘  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │\n *   │ │ │                          │ │CCS2 │ │CCS3 │ │ │ │ │ │     │ │ │\n *   │ │ │ ┌─────┐ ┌─────┐ ┌─────┐  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │\n *   │ │ │ │ ... │ │ ... │ │ ... │  │                 │ │ │ │ │     │ │ │\n *   │ │ │ └─DSS─┘ └─DSS─┘ └─DSS─┘  └─────Engines─────┘ │ │ │ │     │ │ │\n *   │ │ └───────────────────────────GT0────────────────┘ │ │ └─GT2─┘ │ │\n *   │ └────────────────────────────Tile0─────────────────┘ └─ Tile1──┘ │\n *   └─────────────────────────────Device0───────┬──────────────────────┘\n *                                               │\n *                        ───────────────────────┴────────── PCI bus\n */\n\n/**\n * DOC: Xe uAPI Overview\n *\n * This section aims to describe the Xe's IOCTL entries, its structs, and other\n * Xe related uAPI such as uevents and PMU (Platform Monitoring Unit) related\n * entries and usage.\n *\n * List of supported IOCTLs:\n *  - &DRM_IOCTL_XE_DEVICE_QUERY\n *  - &DRM_IOCTL_XE_GEM_CREATE\n *  - &DRM_IOCTL_XE_GEM_MMAP_OFFSET\n *  - &DRM_IOCTL_XE_VM_CREATE\n *  - &DRM_IOCTL_XE_VM_DESTROY\n *  - &DRM_IOCTL_XE_VM_BIND\n *  - &DRM_IOCTL_XE_EXEC_QUEUE_CREATE\n *  - &DRM_IOCTL_XE_EXEC_QUEUE_DESTROY\n *  - &DRM_IOCTL_XE_EXEC_QUEUE_GET_PROPERTY\n *  - &DRM_IOCTL_XE_EXEC\n *  - &DRM_IOCTL_XE_WAIT_USER_FENCE\n *  - &DRM_IOCTL_XE_OBSERVATION\n */\n\n/*\n * xe specific ioctls.\n *\n * The device specific ioctl range is [DRM_COMMAND_BASE, DRM_COMMAND_END) ie\n * [0x40, 0xa0) (a0 is excluded). The numbers below are defined as offset\n * against DRM_COMMAND_BASE and should be between [0x0, 0x60).\n */\n#define DRM_XE_DEVICE_QUERY\t\t0x00\n#define DRM_XE_GEM_CREATE\t\t0x01\n#define DRM_XE_GEM_MMAP_OFFSET\t\t0x02\n#define DRM_XE_VM_CREATE\t\t0x03\n#define DRM_XE_VM_DESTROY\t\t0x04\n#define DRM_XE_VM_BIND\t\t\t0x05\n#define DRM_XE_EXEC_QUEUE_CREATE\t0x06\n#define DRM_XE_EXEC_QUEUE_DESTROY\t0x07\n#define DRM_XE_EXEC_QUEUE_GET_PROPERTY\t0x08\n#define DRM_XE_EXEC\t\t\t0x09\n#define DRM_XE_WAIT_USER_FENCE\t\t0x0a\n#define DRM_XE_OBSERVATION\t\t0x0b\n\n/* Must be kept compact -- no holes */\n\n#define DRM_IOCTL_XE_DEVICE_QUERY\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_XE_DEVICE_QUERY, struct drm_xe_device_query)\n#define DRM_IOCTL_XE_GEM_CREATE\t\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_XE_GEM_CREATE, struct drm_xe_gem_create)\n#define DRM_IOCTL_XE_GEM_MMAP_OFFSET\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_XE_GEM_MMAP_OFFSET, struct drm_xe_gem_mmap_offset)\n#define DRM_IOCTL_XE_VM_CREATE\t\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_XE_VM_CREATE, struct drm_xe_vm_create)\n#define DRM_IOCTL_XE_VM_DESTROY\t\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_XE_VM_DESTROY, struct drm_xe_vm_destroy)\n#define DRM_IOCTL_XE_VM_BIND\t\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_XE_VM_BIND, struct drm_xe_vm_bind)\n#define DRM_IOCTL_XE_EXEC_QUEUE_CREATE\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_XE_EXEC_QUEUE_CREATE, struct drm_xe_exec_queue_create)\n#define DRM_IOCTL_XE_EXEC_QUEUE_DESTROY\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_XE_EXEC_QUEUE_DESTROY, struct drm_xe_exec_queue_destroy)\n#define DRM_IOCTL_XE_EXEC_QUEUE_GET_PROPERTY\tDRM_IOWR(DRM_COMMAND_BASE + DRM_XE_EXEC_QUEUE_GET_PROPERTY, struct drm_xe_exec_queue_get_property)\n#define DRM_IOCTL_XE_EXEC\t\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_XE_EXEC, struct drm_xe_exec)\n#define DRM_IOCTL_XE_WAIT_USER_FENCE\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_XE_WAIT_USER_FENCE, struct drm_xe_wait_user_fence)\n#define DRM_IOCTL_XE_OBSERVATION\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_XE_OBSERVATION, struct drm_xe_observation_param)\n\n/**\n * DOC: Xe IOCTL Extensions\n *\n * Before detailing the IOCTLs and its structs, it is important to highlight\n * that every IOCTL in Xe is extensible.\n *\n * Many interfaces need to grow over time. In most cases we can simply\n * extend the struct and have userspace pass in more data. Another option,\n * as demonstrated by Vulkan's approach to providing extensions for forward\n * and backward compatibility, is to use a list of optional structs to\n * provide those extra details.\n *\n * The key advantage to using an extension chain is that it allows us to\n * redefine the interface more easily than an ever growing struct of\n * increasing complexity, and for large parts of that interface to be\n * entirely optional. The downside is more pointer chasing; chasing across\n * the __user boundary with pointers encapsulated inside u64.\n *\n * Example chaining:\n *\n * .. code-block:: C\n *\n *\tstruct drm_xe_user_extension ext3 {\n *\t\t.next_extension = 0, // end\n *\t\t.name = ...,\n *\t};\n *\tstruct drm_xe_user_extension ext2 {\n *\t\t.next_extension = (uintptr_t)&ext3,\n *\t\t.name = ...,\n *\t};\n *\tstruct drm_xe_user_extension ext1 {\n *\t\t.next_extension = (uintptr_t)&ext2,\n *\t\t.name = ...,\n *\t};\n *\n * Typically the struct drm_xe_user_extension would be embedded in some uAPI\n * struct, and in this case we would feed it the head of the chain(i.e ext1),\n * which would then apply all of the above extensions.\n*/\n\n/**\n * struct drm_xe_user_extension - Base class for defining a chain of extensions\n */\nstruct drm_xe_user_extension {\n\t/**\n\t * @next_extension:\n\t *\n\t * Pointer to the next struct drm_xe_user_extension, or zero if the end.\n\t */\n\t__u64 next_extension;\n\n\t/**\n\t * @name: Name of the extension.\n\t *\n\t * Note that the name here is just some integer.\n\t *\n\t * Also note that the name space for this is not global for the whole\n\t * driver, but rather its scope/meaning is limited to the specific piece\n\t * of uAPI which has embedded the struct drm_xe_user_extension.\n\t */\n\t__u32 name;\n\n\t/**\n\t * @pad: MBZ\n\t *\n\t * All undefined bits must be zero.\n\t */\n\t__u32 pad;\n};\n\n/**\n * struct drm_xe_ext_set_property - Generic set property extension\n *\n * A generic struct that allows any of the Xe's IOCTL to be extended\n * with a set_property operation.\n */\nstruct drm_xe_ext_set_property {\n\t/** @base: base user extension */\n\tstruct drm_xe_user_extension base;\n\n\t/** @property: property to set */\n\t__u32 property;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n\n\t/** @value: property value */\n\t__u64 value;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_engine_class_instance - instance of an engine class\n *\n * It is returned as part of the @drm_xe_engine, but it also is used as\n * the input of engine selection for both @drm_xe_exec_queue_create and\n * @drm_xe_query_engine_cycles\n *\n * The @engine_class can be:\n *  - %DRM_XE_ENGINE_CLASS_RENDER\n *  - %DRM_XE_ENGINE_CLASS_COPY\n *  - %DRM_XE_ENGINE_CLASS_VIDEO_DECODE\n *  - %DRM_XE_ENGINE_CLASS_VIDEO_ENHANCE\n *  - %DRM_XE_ENGINE_CLASS_COMPUTE\n *  - %DRM_XE_ENGINE_CLASS_VM_BIND - Kernel only classes (not actual\n *    hardware engine class). Used for creating ordered queues of VM\n *    bind operations.\n */\nstruct drm_xe_engine_class_instance {\n#define DRM_XE_ENGINE_CLASS_RENDER\t\t0\n#define DRM_XE_ENGINE_CLASS_COPY\t\t1\n#define DRM_XE_ENGINE_CLASS_VIDEO_DECODE\t2\n#define DRM_XE_ENGINE_CLASS_VIDEO_ENHANCE\t3\n#define DRM_XE_ENGINE_CLASS_COMPUTE\t\t4\n#define DRM_XE_ENGINE_CLASS_VM_BIND\t\t5\n\t/** @engine_class: engine class id */\n\t__u16 engine_class;\n\t/** @engine_instance: engine instance id */\n\t__u16 engine_instance;\n\t/** @gt_id: Unique ID of this GT within the PCI Device */\n\t__u16 gt_id;\n\t/** @pad: MBZ */\n\t__u16 pad;\n};\n\n/**\n * struct drm_xe_engine - describe hardware engine\n */\nstruct drm_xe_engine {\n\t/** @instance: The @drm_xe_engine_class_instance */\n\tstruct drm_xe_engine_class_instance instance;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[3];\n};\n\n/**\n * struct drm_xe_query_engines - describe engines\n *\n * If a query is made with a struct @drm_xe_device_query where .query\n * is equal to %DRM_XE_DEVICE_QUERY_ENGINES, then the reply uses an array of\n * struct @drm_xe_query_engines in .data.\n */\nstruct drm_xe_query_engines {\n\t/** @num_engines: number of engines returned in @engines */\n\t__u32 num_engines;\n\t/** @pad: MBZ */\n\t__u32 pad;\n\t/** @engines: The returned engines for this device */\n\tstruct drm_xe_engine engines[];\n};\n\n/**\n * enum drm_xe_memory_class - Supported memory classes.\n */\nenum drm_xe_memory_class {\n\t/** @DRM_XE_MEM_REGION_CLASS_SYSMEM: Represents system memory. */\n\tDRM_XE_MEM_REGION_CLASS_SYSMEM = 0,\n\t/**\n\t * @DRM_XE_MEM_REGION_CLASS_VRAM: On discrete platforms, this\n\t * represents the memory that is local to the device, which we\n\t * call VRAM. Not valid on integrated platforms.\n\t */\n\tDRM_XE_MEM_REGION_CLASS_VRAM\n};\n\n/**\n * struct drm_xe_mem_region - Describes some region as known to\n * the driver.\n */\nstruct drm_xe_mem_region {\n\t/**\n\t * @mem_class: The memory class describing this region.\n\t *\n\t * See enum drm_xe_memory_class for supported values.\n\t */\n\t__u16 mem_class;\n\t/**\n\t * @instance: The unique ID for this region, which serves as the\n\t * index in the placement bitmask used as argument for\n\t * &DRM_IOCTL_XE_GEM_CREATE\n\t */\n\t__u16 instance;\n\t/**\n\t * @min_page_size: Min page-size in bytes for this region.\n\t *\n\t * When the kernel allocates memory for this region, the\n\t * underlying pages will be at least @min_page_size in size.\n\t * Buffer objects with an allowable placement in this region must be\n\t * created with a size aligned to this value.\n\t * GPU virtual address mappings of (parts of) buffer objects that\n\t * may be placed in this region must also have their GPU virtual\n\t * address and range aligned to this value.\n\t * Affected IOCTLS will return %-EINVAL if alignment restrictions are\n\t * not met.\n\t */\n\t__u32 min_page_size;\n\t/**\n\t * @total_size: The usable size in bytes for this region.\n\t */\n\t__u64 total_size;\n\t/**\n\t * @used: Estimate of the memory used in bytes for this region.\n\t *\n\t * Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable\n\t * accounting.  Without this the value here will always equal\n\t * zero.\n\t */\n\t__u64 used;\n\t/**\n\t * @cpu_visible_size: How much of this region can be CPU\n\t * accessed, in bytes.\n\t *\n\t * This will always be <= @total_size, and the remainder (if\n\t * any) will not be CPU accessible. If the CPU accessible part\n\t * is smaller than @total_size then this is referred to as a\n\t * small BAR system.\n\t *\n\t * On systems without small BAR (full BAR), the probed_size will\n\t * always equal the @total_size, since all of it will be CPU\n\t * accessible.\n\t *\n\t * Note this is only tracked for DRM_XE_MEM_REGION_CLASS_VRAM\n\t * regions (for other types the value here will always equal\n\t * zero).\n\t */\n\t__u64 cpu_visible_size;\n\t/**\n\t * @cpu_visible_used: Estimate of CPU visible memory used, in\n\t * bytes.\n\t *\n\t * Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable\n\t * accounting. Without this the value here will always equal\n\t * zero.  Note this is only currently tracked for\n\t * DRM_XE_MEM_REGION_CLASS_VRAM regions (for other types the value\n\t * here will always be zero).\n\t */\n\t__u64 cpu_visible_used;\n\t/** @reserved: Reserved */\n\t__u64 reserved[6];\n};\n\n/**\n * struct drm_xe_query_mem_regions - describe memory regions\n *\n * If a query is made with a struct drm_xe_device_query where .query\n * is equal to DRM_XE_DEVICE_QUERY_MEM_REGIONS, then the reply uses\n * struct drm_xe_query_mem_regions in .data.\n */\nstruct drm_xe_query_mem_regions {\n\t/** @num_mem_regions: number of memory regions returned in @mem_regions */\n\t__u32 num_mem_regions;\n\t/** @pad: MBZ */\n\t__u32 pad;\n\t/** @mem_regions: The returned memory regions for this device */\n\tstruct drm_xe_mem_region mem_regions[];\n};\n\n/**\n * struct drm_xe_query_config - describe the device configuration\n *\n * If a query is made with a struct drm_xe_device_query where .query\n * is equal to DRM_XE_DEVICE_QUERY_CONFIG, then the reply uses\n * struct drm_xe_query_config in .data.\n *\n * The index in @info can be:\n *  - %DRM_XE_QUERY_CONFIG_REV_AND_DEVICE_ID - Device ID (lower 16 bits)\n *    and the device revision (next 8 bits)\n *  - %DRM_XE_QUERY_CONFIG_FLAGS - Flags describing the device\n *    configuration, see list below\n *\n *    - %DRM_XE_QUERY_CONFIG_FLAG_HAS_VRAM - Flag is set if the device\n *      has usable VRAM\n *  - %DRM_XE_QUERY_CONFIG_MIN_ALIGNMENT - Minimal memory alignment\n *    required by this device, typically SZ_4K or SZ_64K\n *  - %DRM_XE_QUERY_CONFIG_VA_BITS - Maximum bits of a virtual address\n *  - %DRM_XE_QUERY_CONFIG_MAX_EXEC_QUEUE_PRIORITY - Value of the highest\n *    available exec queue priority\n */\nstruct drm_xe_query_config {\n\t/** @num_params: number of parameters returned in info */\n\t__u32 num_params;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n\n#define DRM_XE_QUERY_CONFIG_REV_AND_DEVICE_ID\t0\n#define DRM_XE_QUERY_CONFIG_FLAGS\t\t\t1\n\t#define DRM_XE_QUERY_CONFIG_FLAG_HAS_VRAM\t(1 << 0)\n#define DRM_XE_QUERY_CONFIG_MIN_ALIGNMENT\t\t2\n#define DRM_XE_QUERY_CONFIG_VA_BITS\t\t\t3\n#define DRM_XE_QUERY_CONFIG_MAX_EXEC_QUEUE_PRIORITY\t4\n\t/** @info: array of elements containing the config info */\n\t__u64 info[];\n};\n\n/**\n * struct drm_xe_gt - describe an individual GT.\n *\n * To be used with drm_xe_query_gt_list, which will return a list with all the\n * existing GT individual descriptions.\n * Graphics Technology (GT) is a subset of a GPU/tile that is responsible for\n * implementing graphics and/or media operations.\n *\n * The index in @type can be:\n *  - %DRM_XE_QUERY_GT_TYPE_MAIN\n *  - %DRM_XE_QUERY_GT_TYPE_MEDIA\n */\nstruct drm_xe_gt {\n#define DRM_XE_QUERY_GT_TYPE_MAIN\t\t0\n#define DRM_XE_QUERY_GT_TYPE_MEDIA\t\t1\n\t/** @type: GT type: Main or Media */\n\t__u16 type;\n\t/** @tile_id: Tile ID where this GT lives (Information only) */\n\t__u16 tile_id;\n\t/** @gt_id: Unique ID of this GT within the PCI Device */\n\t__u16 gt_id;\n\t/** @pad: MBZ */\n\t__u16 pad[3];\n\t/** @reference_clock: A clock frequency for timestamp */\n\t__u32 reference_clock;\n\t/**\n\t * @near_mem_regions: Bit mask of instances from\n\t * drm_xe_query_mem_regions that are nearest to the current engines\n\t * of this GT.\n\t * Each index in this mask refers directly to the struct\n\t * drm_xe_query_mem_regions' instance, no assumptions should\n\t * be made about order. The type of each region is described\n\t * by struct drm_xe_query_mem_regions' mem_class.\n\t */\n\t__u64 near_mem_regions;\n\t/**\n\t * @far_mem_regions: Bit mask of instances from\n\t * drm_xe_query_mem_regions that are far from the engines of this GT.\n\t * In general, they have extra indirections when compared to the\n\t * @near_mem_regions. For a discrete device this could mean system\n\t * memory and memory living in a different tile.\n\t * Each index in this mask refers directly to the struct\n\t * drm_xe_query_mem_regions' instance, no assumptions should\n\t * be made about order. The type of each region is described\n\t * by struct drm_xe_query_mem_regions' mem_class.\n\t */\n\t__u64 far_mem_regions;\n\t/** @ip_ver_major: Graphics/media IP major version on GMD_ID platforms */\n\t__u16 ip_ver_major;\n\t/** @ip_ver_minor: Graphics/media IP minor version on GMD_ID platforms */\n\t__u16 ip_ver_minor;\n\t/** @ip_ver_rev: Graphics/media IP revision version on GMD_ID platforms */\n\t__u16 ip_ver_rev;\n\t/** @pad2: MBZ */\n\t__u16 pad2;\n\t/** @reserved: Reserved */\n\t__u64 reserved[7];\n};\n\n/**\n * struct drm_xe_query_gt_list - A list with GT description items.\n *\n * If a query is made with a struct drm_xe_device_query where .query\n * is equal to DRM_XE_DEVICE_QUERY_GT_LIST, then the reply uses struct\n * drm_xe_query_gt_list in .data.\n */\nstruct drm_xe_query_gt_list {\n\t/** @num_gt: number of GT items returned in gt_list */\n\t__u32 num_gt;\n\t/** @pad: MBZ */\n\t__u32 pad;\n\t/** @gt_list: The GT list returned for this device */\n\tstruct drm_xe_gt gt_list[];\n};\n\n/**\n * struct drm_xe_query_topology_mask - describe the topology mask of a GT\n *\n * This is the hardware topology which reflects the internal physical\n * structure of the GPU.\n *\n * If a query is made with a struct drm_xe_device_query where .query\n * is equal to DRM_XE_DEVICE_QUERY_GT_TOPOLOGY, then the reply uses\n * struct drm_xe_query_topology_mask in .data.\n *\n * The @type can be:\n *  - %DRM_XE_TOPO_DSS_GEOMETRY - To query the mask of Dual Sub Slices\n *    (DSS) available for geometry operations. For example a query response\n *    containing the following in mask:\n *    ``DSS_GEOMETRY    ff ff ff ff 00 00 00 00``\n *    means 32 DSS are available for geometry.\n *  - %DRM_XE_TOPO_DSS_COMPUTE - To query the mask of Dual Sub Slices\n *    (DSS) available for compute operations. For example a query response\n *    containing the following in mask:\n *    ``DSS_COMPUTE    ff ff ff ff 00 00 00 00``\n *    means 32 DSS are available for compute.\n *  - %DRM_XE_TOPO_L3_BANK - To query the mask of enabled L3 banks\n *  - %DRM_XE_TOPO_EU_PER_DSS - To query the mask of Execution Units (EU)\n *    available per Dual Sub Slices (DSS). For example a query response\n *    containing the following in mask:\n *    ``EU_PER_DSS    ff ff 00 00 00 00 00 00``\n *    means each DSS has 16 SIMD8 EUs. This type may be omitted if device\n *    doesn't have SIMD8 EUs.\n *  - %DRM_XE_TOPO_SIMD16_EU_PER_DSS - To query the mask of SIMD16 Execution\n *    Units (EU) available per Dual Sub Slices (DSS). For example a query\n *    response containing the following in mask:\n *    ``SIMD16_EU_PER_DSS    ff ff 00 00 00 00 00 00``\n *    means each DSS has 16 SIMD16 EUs. This type may be omitted if device\n *    doesn't have SIMD16 EUs.\n */\nstruct drm_xe_query_topology_mask {\n\t/** @gt_id: GT ID the mask is associated with */\n\t__u16 gt_id;\n\n#define DRM_XE_TOPO_DSS_GEOMETRY\t1\n#define DRM_XE_TOPO_DSS_COMPUTE\t\t2\n#define DRM_XE_TOPO_L3_BANK\t\t3\n#define DRM_XE_TOPO_EU_PER_DSS\t\t4\n#define DRM_XE_TOPO_SIMD16_EU_PER_DSS\t5\n\t/** @type: type of mask */\n\t__u16 type;\n\n\t/** @num_bytes: number of bytes in requested mask */\n\t__u32 num_bytes;\n\n\t/** @mask: little-endian mask of @num_bytes */\n\t__u8 mask[];\n};\n\n/**\n * struct drm_xe_query_engine_cycles - correlate CPU and GPU timestamps\n *\n * If a query is made with a struct drm_xe_device_query where .query is equal to\n * DRM_XE_DEVICE_QUERY_ENGINE_CYCLES, then the reply uses struct drm_xe_query_engine_cycles\n * in .data. struct drm_xe_query_engine_cycles is allocated by the user and\n * .data points to this allocated structure.\n *\n * The query returns the engine cycles, which along with GT's @reference_clock,\n * can be used to calculate the engine timestamp. In addition the\n * query returns a set of cpu timestamps that indicate when the command\n * streamer cycle count was captured.\n */\nstruct drm_xe_query_engine_cycles {\n\t/**\n\t * @eci: This is input by the user and is the engine for which command\n\t * streamer cycles is queried.\n\t */\n\tstruct drm_xe_engine_class_instance eci;\n\n\t/**\n\t * @clockid: This is input by the user and is the reference clock id for\n\t * CPU timestamp. For definition, see clock_gettime(2) and\n\t * perf_event_open(2). Supported clock ids are CLOCK_MONOTONIC,\n\t * CLOCK_MONOTONIC_RAW, CLOCK_REALTIME, CLOCK_BOOTTIME, CLOCK_TAI.\n\t */\n\t__s32 clockid;\n\n\t/** @width: Width of the engine cycle counter in bits. */\n\t__u32 width;\n\n\t/**\n\t * @engine_cycles: Engine cycles as read from its register\n\t * at 0x358 offset.\n\t */\n\t__u64 engine_cycles;\n\n\t/**\n\t * @cpu_timestamp: CPU timestamp in ns. The timestamp is captured before\n\t * reading the engine_cycles register using the reference clockid set by the\n\t * user.\n\t */\n\t__u64 cpu_timestamp;\n\n\t/**\n\t * @cpu_delta: Time delta in ns captured around reading the lower dword\n\t * of the engine_cycles register.\n\t */\n\t__u64 cpu_delta;\n};\n\n/**\n * struct drm_xe_query_uc_fw_version - query a micro-controller firmware version\n *\n * Given a uc_type this will return the branch, major, minor and patch version\n * of the micro-controller firmware.\n */\nstruct drm_xe_query_uc_fw_version {\n\t/** @uc_type: The micro-controller type to query firmware version */\n#define XE_QUERY_UC_TYPE_GUC_SUBMISSION 0\n#define XE_QUERY_UC_TYPE_HUC 1\n\t__u16 uc_type;\n\n\t/** @pad: MBZ */\n\t__u16 pad;\n\n\t/** @branch_ver: branch uc fw version */\n\t__u32 branch_ver;\n\t/** @major_ver: major uc fw version */\n\t__u32 major_ver;\n\t/** @minor_ver: minor uc fw version */\n\t__u32 minor_ver;\n\t/** @patch_ver: patch uc fw version */\n\t__u32 patch_ver;\n\n\t/** @pad2: MBZ */\n\t__u32 pad2;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved;\n};\n\n/**\n * struct drm_xe_device_query - Input of &DRM_IOCTL_XE_DEVICE_QUERY - main\n * structure to query device information\n *\n * The user selects the type of data to query among DRM_XE_DEVICE_QUERY_*\n * and sets the value in the query member. This determines the type of\n * the structure provided by the driver in data, among struct drm_xe_query_*.\n *\n * The @query can be:\n *  - %DRM_XE_DEVICE_QUERY_ENGINES\n *  - %DRM_XE_DEVICE_QUERY_MEM_REGIONS\n *  - %DRM_XE_DEVICE_QUERY_CONFIG\n *  - %DRM_XE_DEVICE_QUERY_GT_LIST\n *  - %DRM_XE_DEVICE_QUERY_HWCONFIG - Query type to retrieve the hardware\n *    configuration of the device such as information on slices, memory,\n *    caches, and so on. It is provided as a table of key / value\n *    attributes.\n *  - %DRM_XE_DEVICE_QUERY_GT_TOPOLOGY\n *  - %DRM_XE_DEVICE_QUERY_ENGINE_CYCLES\n *\n * If size is set to 0, the driver fills it with the required size for\n * the requested type of data to query. If size is equal to the required\n * size, the queried information is copied into data. If size is set to\n * a value different from 0 and different from the required size, the\n * IOCTL call returns -EINVAL.\n *\n * For example the following code snippet allows retrieving and printing\n * information about the device engines with DRM_XE_DEVICE_QUERY_ENGINES:\n *\n * .. code-block:: C\n *\n *     struct drm_xe_query_engines *engines;\n *     struct drm_xe_device_query query = {\n *         .extensions = 0,\n *         .query = DRM_XE_DEVICE_QUERY_ENGINES,\n *         .size = 0,\n *         .data = 0,\n *     };\n *     ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query);\n *     engines = malloc(query.size);\n *     query.data = (uintptr_t)engines;\n *     ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query);\n *     for (int i = 0; i < engines->num_engines; i++) {\n *         printf(\"Engine %d: %s\\n\", i,\n *             engines->engines[i].instance.engine_class ==\n *                 DRM_XE_ENGINE_CLASS_RENDER ? \"RENDER\":\n *             engines->engines[i].instance.engine_class ==\n *                 DRM_XE_ENGINE_CLASS_COPY ? \"COPY\":\n *             engines->engines[i].instance.engine_class ==\n *                 DRM_XE_ENGINE_CLASS_VIDEO_DECODE ? \"VIDEO_DECODE\":\n *             engines->engines[i].instance.engine_class ==\n *                 DRM_XE_ENGINE_CLASS_VIDEO_ENHANCE ? \"VIDEO_ENHANCE\":\n *             engines->engines[i].instance.engine_class ==\n *                 DRM_XE_ENGINE_CLASS_COMPUTE ? \"COMPUTE\":\n *             \"UNKNOWN\");\n *     }\n *     free(engines);\n */\nstruct drm_xe_device_query {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n#define DRM_XE_DEVICE_QUERY_ENGINES\t\t0\n#define DRM_XE_DEVICE_QUERY_MEM_REGIONS\t\t1\n#define DRM_XE_DEVICE_QUERY_CONFIG\t\t2\n#define DRM_XE_DEVICE_QUERY_GT_LIST\t\t3\n#define DRM_XE_DEVICE_QUERY_HWCONFIG\t\t4\n#define DRM_XE_DEVICE_QUERY_GT_TOPOLOGY\t\t5\n#define DRM_XE_DEVICE_QUERY_ENGINE_CYCLES\t6\n#define DRM_XE_DEVICE_QUERY_UC_FW_VERSION\t7\n#define DRM_XE_DEVICE_QUERY_OA_UNITS\t\t8\n\t/** @query: The type of data to query */\n\t__u32 query;\n\n\t/** @size: Size of the queried data */\n\t__u32 size;\n\n\t/** @data: Queried data is placed here */\n\t__u64 data;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_gem_create - Input of &DRM_IOCTL_XE_GEM_CREATE - A structure for\n * gem creation\n *\n * The @flags can be:\n *  - %DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING\n *  - %DRM_XE_GEM_CREATE_FLAG_SCANOUT\n *  - %DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM - When using VRAM as a\n *    possible placement, ensure that the corresponding VRAM allocation\n *    will always use the CPU accessible part of VRAM. This is important\n *    for small-bar systems (on full-bar systems this gets turned into a\n *    noop).\n *    Note1: System memory can be used as an extra placement if the kernel\n *    should spill the allocation to system memory, if space can't be made\n *    available in the CPU accessible part of VRAM (giving the same\n *    behaviour as the i915 interface, see\n *    I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS).\n *    Note2: For clear-color CCS surfaces the kernel needs to read the\n *    clear-color value stored in the buffer, and on discrete platforms we\n *    need to use VRAM for display surfaces, therefore the kernel requires\n *    setting this flag for such objects, otherwise an error is thrown on\n *    small-bar systems.\n *\n * @cpu_caching supports the following values:\n *  - %DRM_XE_GEM_CPU_CACHING_WB - Allocate the pages with write-back\n *    caching. On iGPU this can't be used for scanout surfaces. Currently\n *    not allowed for objects placed in VRAM.\n *  - %DRM_XE_GEM_CPU_CACHING_WC - Allocate the pages as write-combined. This\n *    is uncached. Scanout surfaces should likely use this. All objects\n *    that can be placed in VRAM must use this.\n */\nstruct drm_xe_gem_create {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/**\n\t * @size: Size of the object to be created, must match region\n\t * (system or vram) minimum alignment (&min_page_size).\n\t */\n\t__u64 size;\n\n\t/**\n\t * @placement: A mask of memory instances of where BO can be placed.\n\t * Each index in this mask refers directly to the struct\n\t * drm_xe_query_mem_regions' instance, no assumptions should\n\t * be made about order. The type of each region is described\n\t * by struct drm_xe_query_mem_regions' mem_class.\n\t */\n\t__u32 placement;\n\n#define DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING\t\t(1 << 0)\n#define DRM_XE_GEM_CREATE_FLAG_SCANOUT\t\t\t(1 << 1)\n#define DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM\t(1 << 2)\n\t/**\n\t * @flags: Flags, currently a mask of memory instances of where BO can\n\t * be placed\n\t */\n\t__u32 flags;\n\n\t/**\n\t * @vm_id: Attached VM, if any\n\t *\n\t * If a VM is specified, this BO must:\n\t *\n\t *  1. Only ever be bound to that VM.\n\t *  2. Cannot be exported as a PRIME fd.\n\t */\n\t__u32 vm_id;\n\n\t/**\n\t * @handle: Returned handle for the object.\n\t *\n\t * Object handles are nonzero.\n\t */\n\t__u32 handle;\n\n#define DRM_XE_GEM_CPU_CACHING_WB                      1\n#define DRM_XE_GEM_CPU_CACHING_WC                      2\n\t/**\n\t * @cpu_caching: The CPU caching mode to select for this object. If\n\t * mmaping the object the mode selected here will also be used. The\n\t * exception is when mapping system memory (including data evicted\n\t * to system) on discrete GPUs. The caching mode selected will\n\t * then be overridden to DRM_XE_GEM_CPU_CACHING_WB, and coherency\n\t * between GPU- and CPU is guaranteed. The caching mode of\n\t * existing CPU-mappings will be updated transparently to\n\t * user-space clients.\n\t */\n\t__u16 cpu_caching;\n\t/** @pad: MBZ */\n\t__u16 pad[3];\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_gem_mmap_offset - Input of &DRM_IOCTL_XE_GEM_MMAP_OFFSET\n */\nstruct drm_xe_gem_mmap_offset {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @handle: Handle for the object being mapped. */\n\t__u32 handle;\n\n\t/** @flags: Must be zero */\n\t__u32 flags;\n\n\t/** @offset: The fake offset to use for subsequent mmap call */\n\t__u64 offset;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_vm_create - Input of &DRM_IOCTL_XE_VM_CREATE\n *\n * The @flags can be:\n *  - %DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE\n *  - %DRM_XE_VM_CREATE_FLAG_LR_MODE - An LR, or Long Running VM accepts\n *    exec submissions to its exec_queues that don't have an upper time\n *    limit on the job execution time. But exec submissions to these\n *    don't allow any of the flags DRM_XE_SYNC_FLAG_SYNCOBJ,\n *    DRM_XE_SYNC_FLAG_TIMELINE_SYNCOBJ, DRM_XE_SYNC_FLAG_DMA_BUF,\n *    used as out-syncobjs, that is, together with DRM_XE_SYNC_FLAG_SIGNAL.\n *    LR VMs can be created in recoverable page-fault mode using\n *    DRM_XE_VM_CREATE_FLAG_FAULT_MODE, if the device supports it.\n *    If that flag is omitted, the UMD can not rely on the slightly\n *    different per-VM overcommit semantics that are enabled by\n *    DRM_XE_VM_CREATE_FLAG_FAULT_MODE (see below), but KMD may\n *    still enable recoverable pagefaults if supported by the device.\n *  - %DRM_XE_VM_CREATE_FLAG_FAULT_MODE - Requires also\n *    DRM_XE_VM_CREATE_FLAG_LR_MODE. It allows memory to be allocated on\n *    demand when accessed, and also allows per-VM overcommit of memory.\n *    The xe driver internally uses recoverable pagefaults to implement\n *    this.\n */\nstruct drm_xe_vm_create {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n#define DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE\t(1 << 0)\n#define DRM_XE_VM_CREATE_FLAG_LR_MODE\t        (1 << 1)\n#define DRM_XE_VM_CREATE_FLAG_FAULT_MODE\t(1 << 2)\n\t/** @flags: Flags */\n\t__u32 flags;\n\n\t/** @vm_id: Returned VM ID */\n\t__u32 vm_id;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_vm_destroy - Input of &DRM_IOCTL_XE_VM_DESTROY\n */\nstruct drm_xe_vm_destroy {\n\t/** @vm_id: VM ID */\n\t__u32 vm_id;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_vm_bind_op - run bind operations\n *\n * The @op can be:\n *  - %DRM_XE_VM_BIND_OP_MAP\n *  - %DRM_XE_VM_BIND_OP_UNMAP\n *  - %DRM_XE_VM_BIND_OP_MAP_USERPTR\n *  - %DRM_XE_VM_BIND_OP_UNMAP_ALL\n *  - %DRM_XE_VM_BIND_OP_PREFETCH\n *\n * and the @flags can be:\n *  - %DRM_XE_VM_BIND_FLAG_READONLY - Setup the page tables as read-only\n *    to ensure write protection\n *  - %DRM_XE_VM_BIND_FLAG_IMMEDIATE - On a faulting VM, do the\n *    MAP operation immediately rather than deferring the MAP to the page\n *    fault handler. This is implied on a non-faulting VM as there is no\n *    fault handler to defer to.\n *  - %DRM_XE_VM_BIND_FLAG_NULL - When the NULL flag is set, the page\n *    tables are setup with a special bit which indicates writes are\n *    dropped and all reads return zero. In the future, the NULL flags\n *    will only be valid for DRM_XE_VM_BIND_OP_MAP operations, the BO\n *    handle MBZ, and the BO offset MBZ. This flag is intended to\n *    implement VK sparse bindings.\n */\nstruct drm_xe_vm_bind_op {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/**\n\t * @obj: GEM object to operate on, MBZ for MAP_USERPTR, MBZ for UNMAP\n\t */\n\t__u32 obj;\n\n\t/**\n\t * @pat_index: The platform defined @pat_index to use for this mapping.\n\t * The index basically maps to some predefined memory attributes,\n\t * including things like caching, coherency, compression etc.  The exact\n\t * meaning of the pat_index is platform specific and defined in the\n\t * Bspec and PRMs.  When the KMD sets up the binding the index here is\n\t * encoded into the ppGTT PTE.\n\t *\n\t * For coherency the @pat_index needs to be at least 1way coherent when\n\t * drm_xe_gem_create.cpu_caching is DRM_XE_GEM_CPU_CACHING_WB. The KMD\n\t * will extract the coherency mode from the @pat_index and reject if\n\t * there is a mismatch (see note below for pre-MTL platforms).\n\t *\n\t * Note: On pre-MTL platforms there is only a caching mode and no\n\t * explicit coherency mode, but on such hardware there is always a\n\t * shared-LLC (or is dgpu) so all GT memory accesses are coherent with\n\t * CPU caches even with the caching mode set as uncached.  It's only the\n\t * display engine that is incoherent (on dgpu it must be in VRAM which\n\t * is always mapped as WC on the CPU). However to keep the uapi somewhat\n\t * consistent with newer platforms the KMD groups the different cache\n\t * levels into the following coherency buckets on all pre-MTL platforms:\n\t *\n\t *\tppGTT UC -> COH_NONE\n\t *\tppGTT WC -> COH_NONE\n\t *\tppGTT WT -> COH_NONE\n\t *\tppGTT WB -> COH_AT_LEAST_1WAY\n\t *\n\t * In practice UC/WC/WT should only ever used for scanout surfaces on\n\t * such platforms (or perhaps in general for dma-buf if shared with\n\t * another device) since it is only the display engine that is actually\n\t * incoherent.  Everything else should typically use WB given that we\n\t * have a shared-LLC.  On MTL+ this completely changes and the HW\n\t * defines the coherency mode as part of the @pat_index, where\n\t * incoherent GT access is possible.\n\t *\n\t * Note: For userptr and externally imported dma-buf the kernel expects\n\t * either 1WAY or 2WAY for the @pat_index.\n\t *\n\t * For DRM_XE_VM_BIND_FLAG_NULL bindings there are no KMD restrictions\n\t * on the @pat_index. For such mappings there is no actual memory being\n\t * mapped (the address in the PTE is invalid), so the various PAT memory\n\t * attributes likely do not apply.  Simply leaving as zero is one\n\t * option (still a valid pat_index).\n\t */\n\t__u16 pat_index;\n\n\t/** @pad: MBZ */\n\t__u16 pad;\n\n\tunion {\n\t\t/**\n\t\t * @obj_offset: Offset into the object, MBZ for CLEAR_RANGE,\n\t\t * ignored for unbind\n\t\t */\n\t\t__u64 obj_offset;\n\n\t\t/** @userptr: user pointer to bind on */\n\t\t__u64 userptr;\n\t};\n\n\t/**\n\t * @range: Number of bytes from the object to bind to addr, MBZ for UNMAP_ALL\n\t */\n\t__u64 range;\n\n\t/** @addr: Address to operate on, MBZ for UNMAP_ALL */\n\t__u64 addr;\n\n#define DRM_XE_VM_BIND_OP_MAP\t\t0x0\n#define DRM_XE_VM_BIND_OP_UNMAP\t\t0x1\n#define DRM_XE_VM_BIND_OP_MAP_USERPTR\t0x2\n#define DRM_XE_VM_BIND_OP_UNMAP_ALL\t0x3\n#define DRM_XE_VM_BIND_OP_PREFETCH\t0x4\n\t/** @op: Bind operation to perform */\n\t__u32 op;\n\n#define DRM_XE_VM_BIND_FLAG_READONLY\t(1 << 0)\n#define DRM_XE_VM_BIND_FLAG_IMMEDIATE\t(1 << 1)\n#define DRM_XE_VM_BIND_FLAG_NULL\t(1 << 2)\n#define DRM_XE_VM_BIND_FLAG_DUMPABLE\t(1 << 3)\n\t/** @flags: Bind flags */\n\t__u32 flags;\n\n\t/**\n\t * @prefetch_mem_region_instance: Memory region to prefetch VMA to.\n\t * It is a region instance, not a mask.\n\t * To be used only with %DRM_XE_VM_BIND_OP_PREFETCH operation.\n\t */\n\t__u32 prefetch_mem_region_instance;\n\n\t/** @pad2: MBZ */\n\t__u32 pad2;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[3];\n};\n\n/**\n * struct drm_xe_vm_bind - Input of &DRM_IOCTL_XE_VM_BIND\n *\n * Below is an example of a minimal use of @drm_xe_vm_bind to\n * asynchronously bind the buffer `data` at address `BIND_ADDRESS` to\n * illustrate `userptr`. It can be synchronized by using the example\n * provided for @drm_xe_sync.\n *\n * .. code-block:: C\n *\n *     data = aligned_alloc(ALIGNMENT, BO_SIZE);\n *     struct drm_xe_vm_bind bind = {\n *         .vm_id = vm,\n *         .num_binds = 1,\n *         .bind.obj = 0,\n *         .bind.obj_offset = to_user_pointer(data),\n *         .bind.range = BO_SIZE,\n *         .bind.addr = BIND_ADDRESS,\n *         .bind.op = DRM_XE_VM_BIND_OP_MAP_USERPTR,\n *         .bind.flags = 0,\n *         .num_syncs = 1,\n *         .syncs = &sync,\n *         .exec_queue_id = 0,\n *     };\n *     ioctl(fd, DRM_IOCTL_XE_VM_BIND, &bind);\n *\n */\nstruct drm_xe_vm_bind {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @vm_id: The ID of the VM to bind to */\n\t__u32 vm_id;\n\n\t/**\n\t * @exec_queue_id: exec_queue_id, must be of class DRM_XE_ENGINE_CLASS_VM_BIND\n\t * and exec queue must have same vm_id. If zero, the default VM bind engine\n\t * is used.\n\t */\n\t__u32 exec_queue_id;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n\n\t/** @num_binds: number of binds in this IOCTL */\n\t__u32 num_binds;\n\n\tunion {\n\t\t/** @bind: used if num_binds == 1 */\n\t\tstruct drm_xe_vm_bind_op bind;\n\n\t\t/**\n\t\t * @vector_of_binds: userptr to array of struct\n\t\t * drm_xe_vm_bind_op if num_binds > 1\n\t\t */\n\t\t__u64 vector_of_binds;\n\t};\n\n\t/** @pad2: MBZ */\n\t__u32 pad2;\n\n\t/** @num_syncs: amount of syncs to wait on */\n\t__u32 num_syncs;\n\n\t/** @syncs: pointer to struct drm_xe_sync array */\n\t__u64 syncs;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_exec_queue_create - Input of &DRM_IOCTL_XE_EXEC_QUEUE_CREATE\n *\n * The example below shows how to use @drm_xe_exec_queue_create to create\n * a simple exec_queue (no parallel submission) of class\n * &DRM_XE_ENGINE_CLASS_RENDER.\n *\n * .. code-block:: C\n *\n *     struct drm_xe_engine_class_instance instance = {\n *         .engine_class = DRM_XE_ENGINE_CLASS_RENDER,\n *     };\n *     struct drm_xe_exec_queue_create exec_queue_create = {\n *          .extensions = 0,\n *          .vm_id = vm,\n *          .num_bb_per_exec = 1,\n *          .num_eng_per_bb = 1,\n *          .instances = to_user_pointer(&instance),\n *     };\n *     ioctl(fd, DRM_IOCTL_XE_EXEC_QUEUE_CREATE, &exec_queue_create);\n *\n */\nstruct drm_xe_exec_queue_create {\n#define DRM_XE_EXEC_QUEUE_EXTENSION_SET_PROPERTY\t\t0\n#define   DRM_XE_EXEC_QUEUE_SET_PROPERTY_PRIORITY\t\t0\n#define   DRM_XE_EXEC_QUEUE_SET_PROPERTY_TIMESLICE\t\t1\n\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @width: submission width (number BB per exec) for this exec queue */\n\t__u16 width;\n\n\t/** @num_placements: number of valid placements for this exec queue */\n\t__u16 num_placements;\n\n\t/** @vm_id: VM to use for this exec queue */\n\t__u32 vm_id;\n\n\t/** @flags: MBZ */\n\t__u32 flags;\n\n\t/** @exec_queue_id: Returned exec queue ID */\n\t__u32 exec_queue_id;\n\n\t/**\n\t * @instances: user pointer to a 2-d array of struct\n\t * drm_xe_engine_class_instance\n\t *\n\t * length = width (i) * num_placements (j)\n\t * index = j + i * width\n\t */\n\t__u64 instances;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_exec_queue_destroy - Input of &DRM_IOCTL_XE_EXEC_QUEUE_DESTROY\n */\nstruct drm_xe_exec_queue_destroy {\n\t/** @exec_queue_id: Exec queue ID */\n\t__u32 exec_queue_id;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_exec_queue_get_property - Input of &DRM_IOCTL_XE_EXEC_QUEUE_GET_PROPERTY\n *\n * The @property can be:\n *  - %DRM_XE_EXEC_QUEUE_GET_PROPERTY_BAN\n */\nstruct drm_xe_exec_queue_get_property {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @exec_queue_id: Exec queue ID */\n\t__u32 exec_queue_id;\n\n#define DRM_XE_EXEC_QUEUE_GET_PROPERTY_BAN\t0\n\t/** @property: property to get */\n\t__u32 property;\n\n\t/** @value: property value */\n\t__u64 value;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_sync - sync object\n *\n * The @type can be:\n *  - %DRM_XE_SYNC_TYPE_SYNCOBJ\n *  - %DRM_XE_SYNC_TYPE_TIMELINE_SYNCOBJ\n *  - %DRM_XE_SYNC_TYPE_USER_FENCE\n *\n * and the @flags can be:\n *  - %DRM_XE_SYNC_FLAG_SIGNAL\n *\n * A minimal use of @drm_xe_sync looks like this:\n *\n * .. code-block:: C\n *\n *     struct drm_xe_sync sync = {\n *         .flags = DRM_XE_SYNC_FLAG_SIGNAL,\n *         .type = DRM_XE_SYNC_TYPE_SYNCOBJ,\n *     };\n *     struct drm_syncobj_create syncobj_create = { 0 };\n *     ioctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &syncobj_create);\n *     sync.handle = syncobj_create.handle;\n *         ...\n *         use of &sync in drm_xe_exec or drm_xe_vm_bind\n *         ...\n *     struct drm_syncobj_wait wait = {\n *         .handles = &sync.handle,\n *         .timeout_nsec = INT64_MAX,\n *         .count_handles = 1,\n *         .flags = 0,\n *         .first_signaled = 0,\n *         .pad = 0,\n *     };\n *     ioctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &wait);\n */\nstruct drm_xe_sync {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n#define DRM_XE_SYNC_TYPE_SYNCOBJ\t\t0x0\n#define DRM_XE_SYNC_TYPE_TIMELINE_SYNCOBJ\t0x1\n#define DRM_XE_SYNC_TYPE_USER_FENCE\t\t0x2\n\t/** @type: Type of the this sync object */\n\t__u32 type;\n\n#define DRM_XE_SYNC_FLAG_SIGNAL\t(1 << 0)\n\t/** @flags: Sync Flags */\n\t__u32 flags;\n\n\tunion {\n\t\t/** @handle: Handle for the object */\n\t\t__u32 handle;\n\n\t\t/**\n\t\t * @addr: Address of user fence. When sync is passed in via exec\n\t\t * IOCTL this is a GPU address in the VM. When sync passed in via\n\t\t * VM bind IOCTL this is a user pointer. In either case, it is\n\t\t * the users responsibility that this address is present and\n\t\t * mapped when the user fence is signalled. Must be qword\n\t\t * aligned.\n\t\t */\n\t\t__u64 addr;\n\t};\n\n\t/**\n\t * @timeline_value: Input for the timeline sync object. Needs to be\n\t * different than 0 when used with %DRM_XE_SYNC_FLAG_TIMELINE_SYNCOBJ.\n\t */\n\t__u64 timeline_value;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_exec - Input of &DRM_IOCTL_XE_EXEC\n *\n * This is an example to use @drm_xe_exec for execution of the object\n * at BIND_ADDRESS (see example in @drm_xe_vm_bind) by an exec_queue\n * (see example in @drm_xe_exec_queue_create). It can be synchronized\n * by using the example provided for @drm_xe_sync.\n *\n * .. code-block:: C\n *\n *     struct drm_xe_exec exec = {\n *         .exec_queue_id = exec_queue,\n *         .syncs = &sync,\n *         .num_syncs = 1,\n *         .address = BIND_ADDRESS,\n *         .num_batch_buffer = 1,\n *     };\n *     ioctl(fd, DRM_IOCTL_XE_EXEC, &exec);\n *\n */\nstruct drm_xe_exec {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @exec_queue_id: Exec queue ID for the batch buffer */\n\t__u32 exec_queue_id;\n\n\t/** @num_syncs: Amount of struct drm_xe_sync in array. */\n\t__u32 num_syncs;\n\n\t/** @syncs: Pointer to struct drm_xe_sync array. */\n\t__u64 syncs;\n\n\t/**\n\t * @address: address of batch buffer if num_batch_buffer == 1 or an\n\t * array of batch buffer addresses\n\t */\n\t__u64 address;\n\n\t/**\n\t * @num_batch_buffer: number of batch buffer in this exec, must match\n\t * the width of the engine\n\t */\n\t__u16 num_batch_buffer;\n\n\t/** @pad: MBZ */\n\t__u16 pad[3];\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * struct drm_xe_wait_user_fence - Input of &DRM_IOCTL_XE_WAIT_USER_FENCE\n *\n * Wait on user fence, XE will wake-up on every HW engine interrupt in the\n * instances list and check if user fence is complete::\n *\n *\t(*addr & MASK) OP (VALUE & MASK)\n *\n * Returns to user on user fence completion or timeout.\n *\n * The @op can be:\n *  - %DRM_XE_UFENCE_WAIT_OP_EQ\n *  - %DRM_XE_UFENCE_WAIT_OP_NEQ\n *  - %DRM_XE_UFENCE_WAIT_OP_GT\n *  - %DRM_XE_UFENCE_WAIT_OP_GTE\n *  - %DRM_XE_UFENCE_WAIT_OP_LT\n *  - %DRM_XE_UFENCE_WAIT_OP_LTE\n *\n * and the @flags can be:\n *  - %DRM_XE_UFENCE_WAIT_FLAG_ABSTIME\n *  - %DRM_XE_UFENCE_WAIT_FLAG_SOFT_OP\n *\n * The @mask values can be for example:\n *  - 0xffu for u8\n *  - 0xffffu for u16\n *  - 0xffffffffu for u32\n *  - 0xffffffffffffffffu for u64\n */\nstruct drm_xe_wait_user_fence {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/**\n\t * @addr: user pointer address to wait on, must qword aligned\n\t */\n\t__u64 addr;\n\n#define DRM_XE_UFENCE_WAIT_OP_EQ\t0x0\n#define DRM_XE_UFENCE_WAIT_OP_NEQ\t0x1\n#define DRM_XE_UFENCE_WAIT_OP_GT\t0x2\n#define DRM_XE_UFENCE_WAIT_OP_GTE\t0x3\n#define DRM_XE_UFENCE_WAIT_OP_LT\t0x4\n#define DRM_XE_UFENCE_WAIT_OP_LTE\t0x5\n\t/** @op: wait operation (type of comparison) */\n\t__u16 op;\n\n#define DRM_XE_UFENCE_WAIT_FLAG_ABSTIME\t(1 << 0)\n\t/** @flags: wait flags */\n\t__u16 flags;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n\n\t/** @value: compare value */\n\t__u64 value;\n\n\t/** @mask: comparison mask */\n\t__u64 mask;\n\n\t/**\n\t * @timeout: how long to wait before bailing, value in nanoseconds.\n\t * Without DRM_XE_UFENCE_WAIT_FLAG_ABSTIME flag set (relative timeout)\n\t * it contains timeout expressed in nanoseconds to wait (fence will\n\t * expire at now() + timeout).\n\t * When DRM_XE_UFENCE_WAIT_FLAG_ABSTIME flat is set (absolute timeout) wait\n\t * will end at timeout (uses system MONOTONIC_CLOCK).\n\t * Passing negative timeout leads to neverending wait.\n\t *\n\t * On relative timeout this value is updated with timeout left\n\t * (for restarting the call in case of signal delivery).\n\t * On absolute timeout this value stays intact (restarted call still\n\t * expire at the same point of time).\n\t */\n\t__s64 timeout;\n\n\t/** @exec_queue_id: exec_queue_id returned from xe_exec_queue_create_ioctl */\n\t__u32 exec_queue_id;\n\n\t/** @pad2: MBZ */\n\t__u32 pad2;\n\n\t/** @reserved: Reserved */\n\t__u64 reserved[2];\n};\n\n/**\n * enum drm_xe_observation_type - Observation stream types\n */\nenum drm_xe_observation_type {\n\t/** @DRM_XE_OBSERVATION_TYPE_OA: OA observation stream type */\n\tDRM_XE_OBSERVATION_TYPE_OA,\n};\n\n/**\n * enum drm_xe_observation_op - Observation stream ops\n */\nenum drm_xe_observation_op {\n\t/** @DRM_XE_OBSERVATION_OP_STREAM_OPEN: Open an observation stream */\n\tDRM_XE_OBSERVATION_OP_STREAM_OPEN,\n\n\t/** @DRM_XE_OBSERVATION_OP_ADD_CONFIG: Add observation stream config */\n\tDRM_XE_OBSERVATION_OP_ADD_CONFIG,\n\n\t/** @DRM_XE_OBSERVATION_OP_REMOVE_CONFIG: Remove observation stream config */\n\tDRM_XE_OBSERVATION_OP_REMOVE_CONFIG,\n};\n\n/**\n * struct drm_xe_observation_param - Input of &DRM_XE_OBSERVATION\n *\n * The observation layer enables multiplexing observation streams of\n * multiple types. The actual params for a particular stream operation are\n * supplied via the @param pointer (use __copy_from_user to get these\n * params).\n */\nstruct drm_xe_observation_param {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\t/** @observation_type: observation stream type, of enum @drm_xe_observation_type */\n\t__u64 observation_type;\n\t/** @observation_op: observation stream op, of enum @drm_xe_observation_op */\n\t__u64 observation_op;\n\t/** @param: Pointer to actual stream params */\n\t__u64 param;\n};\n\n/**\n * enum drm_xe_observation_ioctls - Observation stream fd ioctl's\n *\n * Information exchanged between userspace and kernel for observation fd\n * ioctl's is stream type specific\n */\nenum drm_xe_observation_ioctls {\n\t/** @DRM_XE_OBSERVATION_IOCTL_ENABLE: Enable data capture for an observation stream */\n\tDRM_XE_OBSERVATION_IOCTL_ENABLE = _IO('i', 0x0),\n\n\t/** @DRM_XE_OBSERVATION_IOCTL_DISABLE: Disable data capture for a observation stream */\n\tDRM_XE_OBSERVATION_IOCTL_DISABLE = _IO('i', 0x1),\n\n\t/** @DRM_XE_OBSERVATION_IOCTL_CONFIG: Change observation stream configuration */\n\tDRM_XE_OBSERVATION_IOCTL_CONFIG = _IO('i', 0x2),\n\n\t/** @DRM_XE_OBSERVATION_IOCTL_STATUS: Return observation stream status */\n\tDRM_XE_OBSERVATION_IOCTL_STATUS = _IO('i', 0x3),\n\n\t/** @DRM_XE_OBSERVATION_IOCTL_INFO: Return observation stream info */\n\tDRM_XE_OBSERVATION_IOCTL_INFO = _IO('i', 0x4),\n};\n\n/**\n * enum drm_xe_oa_unit_type - OA unit types\n */\nenum drm_xe_oa_unit_type {\n\t/**\n\t * @DRM_XE_OA_UNIT_TYPE_OAG: OAG OA unit. OAR/OAC are considered\n\t * sub-types of OAG. For OAR/OAC, use OAG.\n\t */\n\tDRM_XE_OA_UNIT_TYPE_OAG,\n\n\t/** @DRM_XE_OA_UNIT_TYPE_OAM: OAM OA unit */\n\tDRM_XE_OA_UNIT_TYPE_OAM,\n};\n\n/**\n * struct drm_xe_oa_unit - describe OA unit\n */\nstruct drm_xe_oa_unit {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @oa_unit_id: OA unit ID */\n\t__u32 oa_unit_id;\n\n\t/** @oa_unit_type: OA unit type of @drm_xe_oa_unit_type */\n\t__u32 oa_unit_type;\n\n\t/** @capabilities: OA capabilities bit-mask */\n\t__u64 capabilities;\n#define DRM_XE_OA_CAPS_BASE\t\t(1 << 0)\n\n\t/** @oa_timestamp_freq: OA timestamp freq */\n\t__u64 oa_timestamp_freq;\n\n\t/** @reserved: MBZ */\n\t__u64 reserved[4];\n\n\t/** @num_engines: number of engines in @eci array */\n\t__u64 num_engines;\n\n\t/** @eci: engines attached to this OA unit */\n\tstruct drm_xe_engine_class_instance eci[];\n};\n\n/**\n * struct drm_xe_query_oa_units - describe OA units\n *\n * If a query is made with a struct drm_xe_device_query where .query\n * is equal to DRM_XE_DEVICE_QUERY_OA_UNITS, then the reply uses struct\n * drm_xe_query_oa_units in .data.\n *\n * OA unit properties for all OA units can be accessed using a code block\n * such as the one below:\n *\n * .. code-block:: C\n *\n *\tstruct drm_xe_query_oa_units *qoa;\n *\tstruct drm_xe_oa_unit *oau;\n *\tu8 *poau;\n *\n *\t// malloc qoa and issue DRM_XE_DEVICE_QUERY_OA_UNITS. Then:\n *\tpoau = (u8 *)&qoa->oa_units[0];\n *\tfor (int i = 0; i < qoa->num_oa_units; i++) {\n *\t\toau = (struct drm_xe_oa_unit *)poau;\n *\t\t// Access 'struct drm_xe_oa_unit' fields here\n *\t\tpoau += sizeof(*oau) + oau->num_engines * sizeof(oau->eci[0]);\n *\t}\n */\nstruct drm_xe_query_oa_units {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\t/** @num_oa_units: number of OA units returned in oau[] */\n\t__u32 num_oa_units;\n\t/** @pad: MBZ */\n\t__u32 pad;\n\t/**\n\t * @oa_units: struct @drm_xe_oa_unit array returned for this device.\n\t * Written below as a u64 array to avoid problems with nested flexible\n\t * arrays with some compilers\n\t */\n\t__u64 oa_units[];\n};\n\n/**\n * enum drm_xe_oa_format_type - OA format types as specified in PRM/Bspec\n * 52198/60942\n */\nenum drm_xe_oa_format_type {\n\t/** @DRM_XE_OA_FMT_TYPE_OAG: OAG report format */\n\tDRM_XE_OA_FMT_TYPE_OAG,\n\t/** @DRM_XE_OA_FMT_TYPE_OAR: OAR report format */\n\tDRM_XE_OA_FMT_TYPE_OAR,\n\t/** @DRM_XE_OA_FMT_TYPE_OAM: OAM report format */\n\tDRM_XE_OA_FMT_TYPE_OAM,\n\t/** @DRM_XE_OA_FMT_TYPE_OAC: OAC report format */\n\tDRM_XE_OA_FMT_TYPE_OAC,\n\t/** @DRM_XE_OA_FMT_TYPE_OAM_MPEC: OAM SAMEDIA or OAM MPEC report format */\n\tDRM_XE_OA_FMT_TYPE_OAM_MPEC,\n\t/** @DRM_XE_OA_FMT_TYPE_PEC: PEC report format */\n\tDRM_XE_OA_FMT_TYPE_PEC,\n};\n\n/**\n * enum drm_xe_oa_property_id - OA stream property id's\n *\n * Stream params are specified as a chain of @drm_xe_ext_set_property\n * struct's, with @property values from enum @drm_xe_oa_property_id and\n * @drm_xe_user_extension base.name set to @DRM_XE_OA_EXTENSION_SET_PROPERTY.\n * @param field in struct @drm_xe_observation_param points to the first\n * @drm_xe_ext_set_property struct.\n *\n * Exactly the same mechanism is also used for stream reconfiguration using the\n * @DRM_XE_OBSERVATION_IOCTL_CONFIG observation stream fd ioctl, though only a\n * subset of properties below can be specified for stream reconfiguration.\n */\nenum drm_xe_oa_property_id {\n#define DRM_XE_OA_EXTENSION_SET_PROPERTY\t0\n\t/**\n\t * @DRM_XE_OA_PROPERTY_OA_UNIT_ID: ID of the OA unit on which to open\n\t * the OA stream, see @oa_unit_id in 'struct\n\t * drm_xe_query_oa_units'. Defaults to 0 if not provided.\n\t */\n\tDRM_XE_OA_PROPERTY_OA_UNIT_ID = 1,\n\n\t/**\n\t * @DRM_XE_OA_PROPERTY_SAMPLE_OA: A value of 1 requests inclusion of raw\n\t * OA unit reports or stream samples in a global buffer attached to an\n\t * OA unit.\n\t */\n\tDRM_XE_OA_PROPERTY_SAMPLE_OA,\n\n\t/**\n\t * @DRM_XE_OA_PROPERTY_OA_METRIC_SET: OA metrics defining contents of OA\n\t * reports, previously added via @DRM_XE_OBSERVATION_OP_ADD_CONFIG.\n\t */\n\tDRM_XE_OA_PROPERTY_OA_METRIC_SET,\n\n\t/** @DRM_XE_OA_PROPERTY_OA_FORMAT: OA counter report format */\n\tDRM_XE_OA_PROPERTY_OA_FORMAT,\n\t/*\n\t * OA_FORMAT's are specified the same way as in PRM/Bspec 52198/60942,\n\t * in terms of the following quantities: a. enum @drm_xe_oa_format_type\n\t * b. Counter select c. Counter size and d. BC report. Also refer to the\n\t * oa_formats array in drivers/gpu/drm/xe/xe_oa.c.\n\t */\n#define DRM_XE_OA_FORMAT_MASK_FMT_TYPE\t\t(0xffu << 0)\n#define DRM_XE_OA_FORMAT_MASK_COUNTER_SEL\t(0xffu << 8)\n#define DRM_XE_OA_FORMAT_MASK_COUNTER_SIZE\t(0xffu << 16)\n#define DRM_XE_OA_FORMAT_MASK_BC_REPORT\t\t(0xffu << 24)\n\n\t/**\n\t * @DRM_XE_OA_PROPERTY_OA_PERIOD_EXPONENT: Requests periodic OA unit\n\t * sampling with sampling frequency proportional to 2^(period_exponent + 1)\n\t */\n\tDRM_XE_OA_PROPERTY_OA_PERIOD_EXPONENT,\n\n\t/**\n\t * @DRM_XE_OA_PROPERTY_OA_DISABLED: A value of 1 will open the OA\n\t * stream in a DISABLED state (see @DRM_XE_OBSERVATION_IOCTL_ENABLE).\n\t */\n\tDRM_XE_OA_PROPERTY_OA_DISABLED,\n\n\t/**\n\t * @DRM_XE_OA_PROPERTY_EXEC_QUEUE_ID: Open the stream for a specific\n\t * @exec_queue_id. OA queries can be executed on this exec queue.\n\t */\n\tDRM_XE_OA_PROPERTY_EXEC_QUEUE_ID,\n\n\t/**\n\t * @DRM_XE_OA_PROPERTY_OA_ENGINE_INSTANCE: Optional engine instance to\n\t * pass along with @DRM_XE_OA_PROPERTY_EXEC_QUEUE_ID or will default to 0.\n\t */\n\tDRM_XE_OA_PROPERTY_OA_ENGINE_INSTANCE,\n\n\t/**\n\t * @DRM_XE_OA_PROPERTY_NO_PREEMPT: Allow preemption and timeslicing\n\t * to be disabled for the stream exec queue.\n\t */\n\tDRM_XE_OA_PROPERTY_NO_PREEMPT,\n};\n\n/**\n * struct drm_xe_oa_config - OA metric configuration\n *\n * Multiple OA configs can be added using @DRM_XE_OBSERVATION_OP_ADD_CONFIG. A\n * particular config can be specified when opening an OA stream using\n * @DRM_XE_OA_PROPERTY_OA_METRIC_SET property.\n */\nstruct drm_xe_oa_config {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @uuid: String formatted like \"%\\08x-%\\04x-%\\04x-%\\04x-%\\012x\" */\n\tchar uuid[36];\n\n\t/** @n_regs: Number of regs in @regs_ptr */\n\t__u32 n_regs;\n\n\t/**\n\t * @regs_ptr: Pointer to (register address, value) pairs for OA config\n\t * registers. Expected length of buffer is: (2 * sizeof(u32) * @n_regs).\n\t */\n\t__u64 regs_ptr;\n};\n\n/**\n * struct drm_xe_oa_stream_status - OA stream status returned from\n * @DRM_XE_OBSERVATION_IOCTL_STATUS observation stream fd ioctl. Userspace can\n * call the ioctl to query stream status in response to EIO errno from\n * observation fd read().\n */\nstruct drm_xe_oa_stream_status {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @oa_status: OA stream status (see Bspec 46717/61226) */\n\t__u64 oa_status;\n#define DRM_XE_OASTATUS_MMIO_TRG_Q_FULL\t\t(1 << 3)\n#define DRM_XE_OASTATUS_COUNTER_OVERFLOW\t(1 << 2)\n#define DRM_XE_OASTATUS_BUFFER_OVERFLOW\t\t(1 << 1)\n#define DRM_XE_OASTATUS_REPORT_LOST\t\t(1 << 0)\n\n\t/** @reserved: reserved for future use */\n\t__u64 reserved[3];\n};\n\n/**\n * struct drm_xe_oa_stream_info - OA stream info returned from\n * @DRM_XE_OBSERVATION_IOCTL_INFO observation stream fd ioctl\n */\nstruct drm_xe_oa_stream_info {\n\t/** @extensions: Pointer to the first extension struct, if any */\n\t__u64 extensions;\n\n\t/** @oa_buf_size: OA buffer size */\n\t__u64 oa_buf_size;\n\n\t/** @reserved: reserved for future use */\n\t__u64 reserved[3];\n};\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif /* _UAPI_XE_DRM_H_ */\n"
  },
  {
    "path": "include/list.h",
    "content": "/*\n * Copyright (C) 2002 Free Software Foundation, Inc.\n * (originally part of the GNU C Library)\n * Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.\n *\n * Copyright (C) 2009 Pierre-Marc Fournier\n * Conversion to RCU list.\n * Copyright (C) 2010 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n */\n\n#ifndef _LIST_H\n#define _LIST_H\t1\n\n#include <stddef.h>\n\n/*\n * container_of - Get the address of an object containing a field.\n *\n * @ptr: pointer to the field.\n * @type: type of the object.\n * @member: name of the field within the object.\n */\n#define container_of(ptr, type, member)\t\t\t\t\t\\\n\t__extension__\t\t\t\t\t\t\t\\\n\t({\t\t\t\t\t\t\t\t\\\n\t\tconst __typeof__(((type *) NULL)->member) * __ptr = (ptr); \\\n\t\t(type *)((char *)__ptr - offsetof(type, member));\t\\\n\t})\n\n/*\n * The definitions of this file are adopted from those which can be\n * found in the Linux kernel headers to enable people familiar with the\n * latter find their way in these sources as well.\n */\n\n/* Basic type for the double-link list. */\nstruct list_head {\n\tstruct list_head *next, *prev;\n};\n\n/* Define a variable with the head and tail of the list. */\n#define LIST_HEAD(name) \\\n\tstruct list_head name = { &(name), &(name) }\n\n/* Initialize a new list head. */\n#define INIT_LIST_HEAD(ptr) \\\n\t(ptr)->next = (ptr)->prev = (ptr)\n\n#define LIST_HEAD_INIT(name) { .next = &(name), .prev = &(name) }\n\n/* Add new element at the head of the list. */\nstatic inline\nvoid list_add(struct list_head *newp, struct list_head *head)\n{\n\thead->next->prev = newp;\n\tnewp->next = head->next;\n\tnewp->prev = head;\n\thead->next = newp;\n}\n\n/* Add new element at the tail of the list. */\nstatic inline\nvoid list_add_tail(struct list_head *newp, struct list_head *head)\n{\n\thead->prev->next = newp;\n\tnewp->next = head;\n\tnewp->prev = head->prev;\n\thead->prev = newp;\n}\n\n/* Remove element from list. */\nstatic inline\nvoid __list_del(struct list_head *prev, struct list_head *next)\n{\n\tnext->prev = prev;\n\tprev->next = next;\n}\n\n/* Remove element from list. */\nstatic inline\nvoid list_del(struct list_head *elem)\n{\n\t__list_del(elem->prev, elem->next);\n}\n\n/* Remove element from list, initializing the element's list pointers. */\nstatic inline\nvoid list_del_init(struct list_head *elem)\n{\n\tlist_del(elem);\n\tINIT_LIST_HEAD(elem);\n}\n\n/* Delete from list, add to another list as head. */\nstatic inline\nvoid list_move(struct list_head *elem, struct list_head *head)\n{\n\t__list_del(elem->prev, elem->next);\n\tlist_add(elem, head);\n}\n\n/* Delete from list, add to another list as tail. */\nstatic inline\nvoid list_move_tail(struct list_head *elem, struct list_head *head)\n{\n\t__list_del(elem->prev, elem->next);\n\tlist_add_tail(elem, head);\n}\n\n/* Replace an old entry. */\nstatic inline\nvoid list_replace(struct list_head *old, struct list_head *_new)\n{\n\t_new->next = old->next;\n\t_new->prev = old->prev;\n\t_new->prev->next = _new;\n\t_new->next->prev = _new;\n}\n\n/* Join two lists. */\nstatic inline\nvoid list_splice(struct list_head *add, struct list_head *head)\n{\n\t/* Do nothing if the list which gets added is empty. */\n\tif (add != add->next) {\n\t\tadd->next->prev = head;\n\t\tadd->prev->next = head->next;\n\t\thead->next->prev = add->prev;\n\t\thead->next = add->next;\n\t}\n}\n\n/* Get typed element from list at a given position. */\n#define list_entry(ptr, type, member) \tcontainer_of(ptr, type, member)\n\n\n/* Get first entry from a list. */\n#define list_first_entry(ptr, type, member) \\\n\tlist_entry((ptr)->next, type, member)\n\n/* Iterate forward over the elements of the list. */\n#define list_for_each(pos, head) \\\n\tfor (pos = (head)->next; (pos) != (head); pos = (pos)->next)\n\n/*\n * Iterate forward over the elements list. The list elements can be\n * removed from the list while doing this.\n */\n#define list_for_each_safe(pos, p, head) \\\n\tfor (pos = (head)->next, p = (pos)->next; \\\n\t\t(pos) != (head); \\\n\t\tpos = (p), p = (pos)->next)\n\n/* Iterate backward over the elements of the list. */\n#define list_for_each_prev(pos, head) \\\n\tfor (pos = (head)->prev; (pos) != (head); pos = (pos)->prev)\n\n/*\n * Iterate backwards over the elements list. The list elements can be\n * removed from the list while doing this.\n */\n#define list_for_each_prev_safe(pos, p, head) \\\n\tfor (pos = (head)->prev, p = (pos)->prev; \\\n\t\t(pos) != (head); \\\n\t\tpos = (p), p = (pos)->prev)\n\n#define list_for_each_entry(pos, head, member) \\\n\tfor (pos = list_entry((head)->next, __typeof__(*(pos)), member); \\\n\t\t&(pos)->member != (head); \\\n\t\tpos = list_entry((pos)->member.next, __typeof__(*(pos)), member))\n\n#define list_for_each_entry_reverse(pos, head, member) \\\n\tfor (pos = list_entry((head)->prev, __typeof__(*(pos)), member); \\\n\t\t&(pos)->member != (head); \\\n\t\tpos = list_entry((pos)->member.prev, __typeof__(*(pos)), member))\n\n#define list_for_each_entry_safe(pos, p, head, member) \\\n\tfor (pos = list_entry((head)->next, __typeof__(*(pos)), member), \\\n\t\t\tp = list_entry((pos)->member.next, __typeof__(*(pos)), member); \\\n\t\t&(pos)->member != (head); \\\n\t\tpos = (p), p = list_entry((pos)->member.next, __typeof__(*(pos)), member))\n\n#define list_for_each_entry_reverse_safe(pos, p, head, member)                                                         \\\n  for (pos = list_entry((head)->prev, __typeof__(*(pos)), member),                                                     \\\n      p = list_entry((pos)->member.prev, __typeof__(*(pos)), member);                                                  \\\n       &(pos)->member != (head); pos = (p), p = list_entry((pos)->member.prev, __typeof__(*(pos)), member))\n\n/*\n * Same as list_for_each_entry_safe, but starts from \"pos\" which should\n * point to an entry within the list.\n */\n#define list_for_each_entry_safe_from(pos, p, head, member) \\\n        for (p = list_entry((pos)->member.next, __typeof__(*(pos)), member); \\\n                &(pos)->member != (head); \\\n                pos = (p), p = list_entry((pos)->member.next, __typeof__(*(pos)), member))\n\nstatic inline\nint list_empty(struct list_head *head)\n{\n\treturn head == head->next;\n}\n\nstatic inline\nvoid list_replace_init(struct list_head *old,\n\t\tstruct list_head *_new)\n{\n\tstruct list_head *head = old->next;\n\n\tlist_del(old);\n\tlist_add_tail(_new, head);\n\tINIT_LIST_HEAD(old);\n}\n\n#endif\t/* _LIST_H */\n"
  },
  {
    "path": "include/nvtop/common.h",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef NVTOP_COMMON_H__\n#define NVTOP_COMMON_H__\n\n#if !defined(HAS_REALLOCARRAY)\n\n#include <errno.h>\n#include <stdlib.h>\n\n#undef reallocarray\n\n// Reallocarray from musl libc (https://git.musl-libc.org/cgit/musl/tree/src/malloc/reallocarray.c)\nstatic void *nvtop_reallocarray__(void *ptr, size_t nmemb, size_t size) {\n  if (size && nmemb > -1 / size) {\n    errno = ENOMEM;\n    return NULL;\n  }\n  return realloc(ptr, nmemb * size);\n}\n#define reallocarray(ptr, nmemb, size) nvtop_reallocarray__(ptr, nmemb, size)\n\n#endif // !defined(HAS_REALLOCARRAY)\n\n// Increment for the number of tracked processes\n// 16 has been experimentally selected for being small while avoiding multiple allocations in most common cases\n#define COMMON_PROCESS_LINEAR_REALLOC_INC 16\n\n#define MAX_LINES_PER_PLOT 4\n\n// Helper macro to stringify an integer\n#define QUOTE(x) #x\n#define EXPAND_AND_QUOTE(x) QUOTE(x)\n\n#endif // NVTOP_COMMON_H__\n"
  },
  {
    "path": "include/nvtop/device_discovery.h",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef NVTOP_DEVICE_DISCOVERY_H__\n#define NVTOP_DEVICE_DISCOVERY_H__\n\n// Devices\ntypedef struct nvtop_device nvtop_device;\n\nnvtop_device *nvtop_device_ref(nvtop_device *device);\nnvtop_device *nvtop_device_unref(nvtop_device *device);\n\nint nvtop_device_new_from_syspath(nvtop_device **ret, const char *syspath);\nint nvtop_device_get_parent(nvtop_device *child, nvtop_device **parent);\nint nvtop_device_get_driver(nvtop_device *device, const char **driver);\nint nvtop_device_get_devname(nvtop_device *device, const char **devname);\nint nvtop_device_get_property_value(nvtop_device *device, const char *key, const char **value);\nint nvtop_device_get_sysattr_value(nvtop_device *device, const char *sysattr, const char **value);\nint nvtop_device_get_syspath(nvtop_device *device, const char **sysPath);\n\n// Devices enumerator\ntypedef struct nvtop_device_enumerator nvtop_device_enumerator;\n\nint nvtop_enumerator_new(nvtop_device_enumerator **enumerator);\nnvtop_device_enumerator *nvtop_enumerator_ref(nvtop_device_enumerator *enumerator);\nnvtop_device_enumerator *nvtop_enumerator_unref(nvtop_device_enumerator *enumerator);\n\nint nvtop_device_enumerator_add_match_subsystem(nvtop_device_enumerator *enumerator, const char *subsystem, int match);\nint nvtop_device_enumerator_add_match_property(nvtop_device_enumerator *enumerator, const char *property,\n                                               const char *value);\nint nvtop_device_enumerator_add_match_parent(nvtop_device_enumerator *enumerator, nvtop_device *parent);\n\nnvtop_device *nvtop_enumerator_get_device_first(nvtop_device_enumerator *enumerator);\nnvtop_device *nvtop_enumerator_get_device_next(nvtop_device_enumerator *enumerator);\n\ntypedef struct {\n  unsigned width;\n  unsigned speed;\n} nvtop_pcie_link;\n\nint nvtop_device_maximum_pcie_link(nvtop_device *dev, nvtop_pcie_link *pcie_info);\nint nvtop_device_current_pcie_link(nvtop_device *dev, nvtop_pcie_link *pcie_info);\n\nnvtop_device *nvtop_device_get_hwmon(nvtop_device *dev);\n\n#endif // NVTOP_DEVICE_DISCOVERY_H__\n"
  },
  {
    "path": "include/nvtop/extract_gpuinfo.h",
    "content": "/*\n *\n * Copyright (C) 2017-2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef EXTRACT_GPUINFO_H_\n#define EXTRACT_GPUINFO_H_\n\n#include \"nvtop/extract_gpuinfo_common.h\"\n\n#include <stdbool.h>\n\nbool gpuinfo_init_info_extraction(unsigned *total_dev_count, struct list_head *devices);\n\nbool gpuinfo_shutdown_info_extraction(struct list_head *devices);\n\nbool gpuinfo_populate_static_infos(struct list_head *devices);\n\nbool gpuinfo_refresh_dynamic_info(struct list_head *devices);\n\nbool gpuinfo_fix_dynamic_info_from_process_info(struct list_head *devices);\n\nbool gpuinfo_refresh_processes(struct list_head *devices);\n\nbool gpuinfo_utilisation_rate(struct list_head *devices);\n\nvoid gpuinfo_clean(struct list_head *devices);\n\nvoid gpuinfo_clear_cache(void);\n\n#endif // EXTRACT_GPUINFO_H_\n"
  },
  {
    "path": "include/nvtop/extract_gpuinfo_common.h",
    "content": "/*\n *\n * Copyright (C) 2021-2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef EXTRACT_GPUINFO_COMMON_H__\n#define EXTRACT_GPUINFO_COMMON_H__\n\n#include <limits.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <sys/types.h>\n\n#include \"list.h\"\n\n#define STRINGIFY(x) STRINGIFY_HELPER_(x)\n#define STRINGIFY_HELPER_(x) #x\n\n#define IS_VALID(x, y) ((y)[(x) / CHAR_BIT] & (1 << ((x) % CHAR_BIT)))\n#define SET_VALID(x, y) ((y)[(x) / CHAR_BIT] |= (1 << ((x) % CHAR_BIT)))\n#define RESET_VALID(x, y) ((y)[(x) / CHAR_BIT] &= ~(1 << ((x) % CHAR_BIT)))\n#define RESET_ALL(y) memset(y, 0, sizeof(y))\n\n#define SET_VALUE(structPtr, field, value, prefix)                                                                     \\\n  do {                                                                                                                 \\\n    (structPtr)->field = (value);                                                                                      \\\n    SET_VALID(prefix##field##_valid, (structPtr)->valid);                                                              \\\n  } while (0)\n#define INVALIDATE_VALUE(structPtr, field, prefix)                                                                     \\\n  do {                                                                                                                 \\\n    RESET_VALID(prefix##field##_valid, (structPtr)->valid);                                                            \\\n  } while (0)\n#define VALUE_IS_VALID(structPtr, field, prefix) IS_VALID(prefix##field##_valid, (structPtr)->valid)\n\n#define SET_GPUINFO_STATIC(structPtr, field, value) SET_VALUE(structPtr, field, value, gpuinfo_)\n#define RESET_GPUINFO_STATIC(structPtr, field) INVALIDATE_VALUE(structPtr, field, gpuinfo_)\n#define GPUINFO_STATIC_FIELD_VALID(structPtr, field) VALUE_IS_VALID(structPtr, field, gpuinfo_)\nenum gpuinfo_static_info_valid {\n  gpuinfo_device_name_valid = 0,\n  gpuinfo_max_pcie_gen_valid,\n  gpuinfo_max_pcie_link_width_valid,\n  gpuinfo_temperature_shutdown_threshold_valid,\n  gpuinfo_temperature_slowdown_threshold_valid,\n  gpuinfo_n_shared_cores_valid,\n  gpuinfo_l2cache_size_valid,\n  gpuinfo_n_exec_engines_valid,\n  gpuinfo_engine_count_valid,\n  gpuinfo_static_info_count,\n};\n\n#define MAX_DEVICE_NAME 128\n\nstruct gpuinfo_static_info {\n  char device_name[MAX_DEVICE_NAME];\n  unsigned max_pcie_gen;\n  unsigned max_pcie_link_width;\n  unsigned temperature_shutdown_threshold;\n  unsigned temperature_slowdown_threshold;\n  unsigned n_shared_cores;\n  unsigned l2cache_size;\n  unsigned n_exec_engines;\n  unsigned engine_count;\n  bool integrated_graphics;\n  bool encode_decode_shared;\n  unsigned char valid[(gpuinfo_static_info_count + CHAR_BIT - 1) / CHAR_BIT];\n};\n\n#define SET_GPUINFO_DYNAMIC(structPtr, field, value) SET_VALUE(structPtr, field, value, gpuinfo_)\n#define RESET_GPUINFO_DYNAMIC(structPtr, field) INVALIDATE_VALUE(structPtr, field, gpuinfo_)\n#define GPUINFO_DYNAMIC_FIELD_VALID(structPtr, field) VALUE_IS_VALID(structPtr, field, gpuinfo_)\nenum gpuinfo_dynamic_info_valid {\n  gpuinfo_gpu_clock_speed_valid = 0,\n  gpuinfo_gpu_clock_speed_max_valid,\n  gpuinfo_mem_clock_speed_valid,\n  gpuinfo_mem_clock_speed_max_valid,\n  gpuinfo_gpu_util_rate_valid,\n  gpuinfo_mem_util_rate_valid,\n  gpuinfo_encoder_rate_valid,\n  gpuinfo_decoder_rate_valid,\n  gpuinfo_total_memory_valid,\n  gpuinfo_free_memory_valid,\n  gpuinfo_used_memory_valid,\n  gpuinfo_pcie_link_gen_valid,\n  gpuinfo_pcie_link_width_valid,\n  gpuinfo_pcie_rx_valid,\n  gpuinfo_pcie_tx_valid,\n  gpuinfo_fan_speed_valid,\n  gpuinfo_fan_rpm_valid,\n  gpuinfo_gpu_temp_valid,\n  gpuinfo_power_draw_valid,\n  gpuinfo_power_draw_max_valid,\n  gpuinfo_effective_load_rate_valid,\n  gpuinfo_multi_instance_mode_valid,\n  gpuinfo_dynamic_info_count,\n};\n\nstruct gpuinfo_dynamic_info {\n  unsigned int gpu_clock_speed;     // Device clock speed in MHz\n  unsigned int gpu_clock_speed_max; // Maximum clock speed in MHz\n  unsigned int mem_clock_speed;     // Device clock speed in MHz\n  unsigned int mem_clock_speed_max; // Maximum clock speed in MHz\n  unsigned int gpu_util_rate;       // GPU utilization rate in %\n  unsigned int mem_util_rate;       // MEM utilization rate in %\n  unsigned int effective_load_rate; // Effective load rate in %\n  unsigned int encoder_rate;        // Encoder utilization rate in %\n  unsigned int decoder_rate;        // Decoder utilization rate in %\n  unsigned long long total_memory;  // Total memory (bytes)\n  unsigned long long free_memory;   // Unallocated memory (bytes)\n  unsigned long long used_memory;   // Allocated memory (bytes)\n  unsigned int pcie_link_gen;       // PCIe link generation used\n  unsigned int pcie_link_width;     // PCIe line width used\n  unsigned int pcie_rx;             // PCIe throughput in KB/s\n  unsigned int pcie_tx;             // PCIe throughput in KB/s\n  unsigned int fan_speed;           // Fan speed percentage\n  unsigned int fan_rpm;             // Fan speed RPM\n  unsigned int gpu_temp;            // GPU temperature °celsius\n  unsigned int power_draw;          // Power usage in milliwatts\n  unsigned int power_draw_max;      // Max power usage in milliwatts\n  bool multi_instance_mode;          // True if the GPU is in multi-instance mode\n  unsigned char valid[(gpuinfo_dynamic_info_count + CHAR_BIT - 1) / CHAR_BIT];\n};\n\nenum gpu_process_type {\n  gpu_process_unknown = 0,\n  gpu_process_graphical = 1,\n  gpu_process_compute = 2,\n  gpu_process_graphical_compute = 3,\n  gpu_process_type_count,\n};\n\n#define SET_GPUINFO_PROCESS(structPtr, field, value) SET_VALUE(structPtr, field, value, gpuinfo_process_)\n#define RESET_GPUINFO_PROCESS(structPtr, field) INVALIDATE_VALUE(structPtr, field, gpuinfo_process_)\n#define GPUINFO_PROCESS_FIELD_VALID(structPtr, field) VALUE_IS_VALID(structPtr, field, gpuinfo_process_)\nenum gpuinfo_process_info_valid {\n  gpuinfo_process_cmdline_valid,\n  gpuinfo_process_user_name_valid,\n  gpuinfo_process_gfx_engine_used_valid,\n  gpuinfo_process_compute_engine_used_valid,\n  gpuinfo_process_enc_engine_used_valid,\n  gpuinfo_process_dec_engine_used_valid,\n  gpuinfo_process_gpu_usage_valid,\n  gpuinfo_process_encode_usage_valid,\n  gpuinfo_process_decode_usage_valid,\n  gpuinfo_process_gpu_memory_usage_valid,\n  gpuinfo_process_gpu_memory_percentage_valid,\n  gpuinfo_process_cpu_usage_valid,\n  gpuinfo_process_cpu_memory_virt_valid,\n  gpuinfo_process_cpu_memory_res_valid,\n  gpuinfo_process_gpu_cycles_valid,\n  gpuinfo_process_sample_delta_valid,\n  gpuinfo_process_info_count\n};\n\nstruct gpu_process {\n  enum gpu_process_type type;\n  pid_t pid;                           // Process ID\n  char *cmdline;                       // Process User Name\n  char *user_name;                     // Process User Name\n  uint64_t sample_delta;               // Time spent between two successive samples\n  uint64_t gfx_engine_used;            // Time in nanoseconds this process spent using the GPU gfx\n  uint64_t compute_engine_used;        // Time in nanoseconds this process spent using the GPU compute\n  uint64_t enc_engine_used;            // Time in nanoseconds this process spent using the GPU encoder\n  uint64_t dec_engine_used;            // Time in nanoseconds this process spent using the GPU decoder\n  uint64_t gpu_cycles;                 // Number of GPU cycles spent in the GPU gfx engine\n  unsigned gpu_usage;                  // Percentage of GPU used by the process\n  unsigned encode_usage;               // Percentage of GPU encoder used by the process\n  unsigned decode_usage;               // Percentage of GPU decoder used by the process\n  unsigned long long gpu_memory_usage; // Memory used by the process\n  unsigned gpu_memory_percentage;      // Percentage of the total device memory\n                                       // consumed by the process\n  unsigned cpu_usage;\n  unsigned long cpu_memory_virt;\n  unsigned long cpu_memory_res;\n  unsigned char valid[(gpuinfo_process_info_count + CHAR_BIT - 1) / CHAR_BIT];\n};\n\nstruct gpu_info;\n\nstruct gpu_vendor {\n  struct list_head list;\n\n  bool (*init)(void);\n  void (*shutdown)(void);\n\n  const char *(*last_error_string)(void);\n\n  bool (*get_device_handles)(struct list_head *devices, unsigned *count);\n\n  void (*populate_static_info)(struct gpu_info *gpu_info);\n  void (*refresh_dynamic_info)(struct gpu_info *gpu_info);\n  void (*refresh_utilisation_rate)(struct gpu_info *gpu_info);\n\n  void (*refresh_running_processes)(struct gpu_info *gpu_info);\n  char *name;\n};\n\n#define PDEV_LEN 16\nstruct gpu_info {\n  struct list_head list;\n  struct gpu_vendor *vendor;\n  struct gpuinfo_static_info static_info;\n  struct gpuinfo_dynamic_info dynamic_info;\n  unsigned processes_count;\n  struct gpu_process *processes;\n  unsigned processes_array_size;\n  char pdev[PDEV_LEN];\n};\n\nvoid register_gpu_vendor(struct gpu_vendor *vendor);\n\nbool extract_drm_fdinfo_key_value(char *buf, char **key, char **val);\n\nvoid gpuinfo_refresh_utilisation_rate(struct gpu_info *gpu_info);\n\n// fdinfo DRM interface names common to multiple drivers\nextern const char drm_pdev[];\nextern const char drm_client_id[];\n\ninline unsigned busy_usage_from_time_usage_round(uint64_t current_use_ns, uint64_t previous_use_ns,\n                                                 uint64_t time_between_measurement) {\n  return ((current_use_ns - previous_use_ns) * UINT64_C(100) + time_between_measurement / UINT64_C(2)) /\n         time_between_measurement;\n}\n\nunsigned nvtop_pcie_gen_from_link_speed(unsigned linkSpeed);\n\n#endif // EXTRACT_GPUINFO_COMMON_H__\n"
  },
  {
    "path": "include/nvtop/extract_processinfo_fdinfo.h",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef NVTOP_EXTRACT_PROCESSINFO_FDINFO__\n#define NVTOP_EXTRACT_PROCESSINFO_FDINFO__\n\n#include \"nvtop/extract_gpuinfo_common.h\"\n\n#include <stdio.h>\n\n/**\n * @brief A callback function that populates the \\p process_info structure from\n * the information gathered while parsing the fdinfo file \\p fdinfo_file. Return true if the data in process_info is\n * valid, false otherwise.\n */\ntypedef bool (*processinfo_fdinfo_callback)(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info);\n\n/**\n * @brief Register a callback function to parse a fdinfo file opened to a DRM driver\n *\n * @param callback The callback function\n * @param info The struct gpu_info that will be updated when the callback succeeds.\n */\nvoid processinfo_register_fdinfo_callback(processinfo_fdinfo_callback callback, struct gpu_info *info);\n\n/**\n * @brief Remove a previously registered callback.\n *\n * @param info The callback to this gpu_info will be removed\n */\nvoid processinfo_drop_callback(const struct gpu_info *info);\n\n/**\n * @brief Enables or disables a fdinfo processing callback\n *\n * @param info Enabling/Disabling the callback to this gpu_info\n * @param enable True to enable the callback, false to disable\n */\nvoid processinfo_enable_disable_callback_for(const struct gpu_info *info, bool enable);\n\n/**\n * @brief Scan all the processes in /proc. Call the registered callbacks on\n * each file descriptor to the DRM driver that can successfully be opened. If a\n * callback succeeds, the gpu_info structure processes array will be updated\n * with the retrieved data.\n */\nvoid processinfo_sweep_fdinfos(void);\n\n#endif // NVTOP_EXTRACT_PROCESSINFO_FDINFO__\n"
  },
  {
    "path": "include/nvtop/get_process_info.h",
    "content": "/*\n *\n * Copyright (C) 2017-2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef GET_PROCESS_INFO_H_\n#define GET_PROCESS_INFO_H_\n\n#include <stdbool.h>\n#include <stdlib.h>\n#include <sys/types.h>\n\n#include \"nvtop/time.h\"\n\nstruct process_cpu_usage {\n  double total_user_time;   // Seconds\n  double total_kernel_time; // Seconds\n  size_t virtual_memory;    // Bytes\n  size_t resident_memory;   // Bytes\n  nvtop_time timestamp;\n};\n\nvoid get_username_from_pid(pid_t pid, char **buffer);\n\nvoid get_command_from_pid(pid_t pid, char **buffer);\n\nbool get_process_info(pid_t pid, struct process_cpu_usage *usage);\n\n#endif // GET_PROCESS_INFO_H_\n"
  },
  {
    "path": "include/nvtop/info_messages.h",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef NVTOP_INFO_MESSAGES_H__\n#define NVTOP_INFO_MESSAGES_H__\n\nvoid get_info_messages(struct list_head *devices, unsigned *num_messages, const char ***messages);\n\n#endif // NVTOP_INFO_MESSAGES_H__\n"
  },
  {
    "path": "include/nvtop/interface.h",
    "content": "/*\n *\n * Copyright (C) 2017-2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef INTERFACE_H_\n#define INTERFACE_H_\n\n#include \"nvtop/interface_options.h\"\n\n#include <stdbool.h>\n\nstruct nvtop_interface;\n\nstruct nvtop_interface *initialize_curses(unsigned total_devices, unsigned num_devices, unsigned largest_device_name,\n                                          nvtop_interface_option options);\n\nvoid clean_ncurses(struct nvtop_interface *interface);\n\nvoid interface_check_monitored_gpu_change(struct nvtop_interface **interface, unsigned allDevCount,\n                                          unsigned *num_monitored_gpus, struct list_head *monitoredGpus,\n                                          struct list_head *nonMonitoredGpus);\n\nunsigned interface_largest_gpu_name(struct list_head *devices);\n\nvoid draw_gpu_info_ncurses(unsigned monitored_dev_count, struct list_head *devices, struct nvtop_interface *interface);\n\nvoid save_current_data_to_ring(struct list_head *devices, struct nvtop_interface *interface);\n\nvoid update_window_size_to_terminal_size(struct nvtop_interface *inter);\n\nvoid interface_key(int keyId, struct nvtop_interface *inter);\n\nbool is_escape_for_quit(struct nvtop_interface *inter);\n\nbool interface_freeze_processes(struct nvtop_interface *interface);\n\nint interface_update_interval(const struct nvtop_interface *interface);\n\nbool show_information_messages(unsigned num_messages, const char **messages);\n\nvoid print_snapshot(struct list_head *devices, bool use_fahrenheit_option);\n\n#endif // INTERFACE_H_\n"
  },
  {
    "path": "include/nvtop/interface_common.h",
    "content": "/*\n *\n * Copyright (C) 2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef INTERFACE_COMMON_H__\n#define INTERFACE_COMMON_H__\n\nenum plot_information {\n  plot_gpu_rate = 0,\n  plot_gpu_mem_rate,\n  plot_encoder_rate,\n  plot_decoder_rate,\n  plot_gpu_temperature,\n  plot_gpu_power_draw_rate,\n  plot_fan_speed,\n  plot_gpu_clock_rate,\n  plot_gpu_mem_clock_rate,\n  plot_effective_load_rate,\n  plot_information_count\n};\n\ntypedef int plot_info_to_draw;\n\nenum process_field {\n  process_pid = 0,\n  process_user,\n  process_gpu_id,\n  process_type,\n  process_gpu_rate,\n  process_enc_rate,\n  process_dec_rate,\n  process_memory,\n  process_cpu_usage,\n  process_cpu_mem_usage,\n  process_command,\n  process_field_count,\n};\n\ntypedef int process_field_displayed;\n\n#endif // INTERFACE_COMMON_H__\n"
  },
  {
    "path": "include/nvtop/interface_internal_common.h",
    "content": "/*\n *\n * Copyright (C) 2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef INTERFACE_INTERNAL_COMMON_H__\n#define INTERFACE_INTERNAL_COMMON_H__\n\n#include \"nvtop/common.h\"\n#include \"nvtop/interface_options.h\"\n#include \"nvtop/interface_ring_buffer.h\"\n#include \"nvtop/time.h\"\n\n#include <ncurses.h>\n#include <stdbool.h>\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))\n\nenum nvtop_option_window_state {\n  nvtop_option_state_hidden,\n  nvtop_option_state_kill,\n  nvtop_option_state_sort_by,\n};\n\nenum interface_color {\n  cyan_color = 1,\n  yellow_color,\n  magenta_color,\n  green_color,\n  red_color,\n  blue_color,\n};\n\nstruct device_window {\n  WINDOW *name_win; // Name of the GPU\n  WINDOW *gpu_util_enc_dec;\n  WINDOW *gpu_util_no_enc_or_dec;\n  WINDOW *gpu_util_no_enc_and_dec;\n  WINDOW *mem_util_enc_dec;\n  WINDOW *mem_util_no_enc_or_dec;\n  WINDOW *mem_util_no_enc_and_dec;\n  WINDOW *encode_util;\n  WINDOW *decode_util;\n  WINDOW *encdec_util;\n  WINDOW *fan_speed;\n  WINDOW *temperature;\n  WINDOW *power_info;\n  WINDOW *gpu_clock_info;\n  WINDOW *mem_clock_info;\n  WINDOW *pcie_info;\n  WINDOW *shader_cores;\n  WINDOW *l2_cache_size;\n  WINDOW *exec_engines;\n  bool enc_was_visible;\n  bool dec_was_visible;\n  nvtop_time last_decode_seen;\n  nvtop_time last_encode_seen;\n};\n\nstatic const unsigned int option_window_size = 13;\nstruct option_window {\n  enum nvtop_option_window_state state;\n  enum nvtop_option_window_state previous_state;\n  unsigned int selected_row;\n  unsigned int offset;\n  WINDOW *option_win;\n};\n\nstruct process_window {\n  unsigned offset;\n  unsigned offset_column;\n  WINDOW *process_win;\n  WINDOW *process_with_option_win;\n  unsigned selected_row;\n  pid_t selected_pid;\n  struct option_window option_window;\n};\n\nstruct plot_window {\n  size_t num_data;\n  double *data;\n  WINDOW *win;\n  WINDOW *plot_window;\n  unsigned num_devices_to_plot;\n  unsigned devices_ids[MAX_LINES_PER_PLOT];\n};\n\nenum setup_window_section {\n  setup_general_selected,\n  setup_header_selected,\n  setup_chart_selected,\n  setup_process_list_selected,\n  setup_monitored_gpu_list_selected,\n  setup_window_selection_count\n};\n\nstruct setup_window {\n  unsigned indentation_level;\n  enum setup_window_section selected_section;\n  bool visible;\n  WINDOW *clean_space;\n  WINDOW *setup;\n  WINDOW *single;\n  WINDOW *split[2];\n  unsigned options_selected[2];\n};\n\n// Keep gpu information every 1 second for 10 minutes\nstruct nvtop_interface {\n  nvtop_interface_option options;\n  unsigned total_dev_count;\n  unsigned monitored_dev_count;\n  struct device_window *devices_win;\n  struct process_window process;\n  WINDOW *shortcut_window;\n  unsigned num_plots;\n  struct plot_window *plots;\n  interface_ring_buffer saved_data_ring;\n  struct setup_window setup_win;\n};\n\nenum device_field {\n  device_name = 0,\n  device_fan_speed,\n  device_temperature,\n  device_power,\n  device_pcie,\n  device_clock,\n  device_mem_clock,\n  device_shadercores,\n  device_l2features,\n  device_execengines,\n  device_field_count,\n};\n\ninline void set_attribute_between(WINDOW *win, int startY, int startX, int endX, attr_t attr, short pair) {\n  int rows, cols;\n  getmaxyx(win, rows, cols);\n  (void)rows;\n  if (startX >= cols || endX < 0)\n    return;\n  startX = startX < 0 ? 0 : startX;\n  endX = endX > cols ? cols : endX;\n  int size = endX - startX;\n  mvwchgat(win, startY, startX, size, attr, pair, NULL);\n}\n\n#endif // INTERFACE_INTERNAL_COMMON_H__\n"
  },
  {
    "path": "include/nvtop/interface_layout_selection.h",
    "content": "#ifndef INTERFACE_LAYOUT_SELECTION_H__\n#define INTERFACE_LAYOUT_SELECTION_H__\n\n#include \"nvtop/interface_common.h\"\n#include \"nvtop/interface_options.h\"\n\n#include <stdbool.h>\n\nstruct window_position {\n  unsigned posX, posY, sizeX, sizeY;\n};\n\n// Should be fine\n#define MAX_CHARTS 64\n\nvoid compute_sizes_from_layout(unsigned monitored_dev_count, unsigned device_header_rows, unsigned device_header_cols,\n                               unsigned rows, unsigned cols, const nvtop_interface_gpu_opts *gpu_opts,\n                               process_field_displayed process_field_displayed,\n                               struct window_position *device_positions, unsigned *num_plots,\n                               struct window_position plot_positions[MAX_CHARTS], unsigned *map_device_to_plot,\n                               struct window_position *process_position, struct window_position *setup_position,\n                               bool process_win_hide);\n\n#endif // INTERFACE_LAYOUT_SELECTION_H__\n"
  },
  {
    "path": "include/nvtop/interface_options.h",
    "content": "/*\n *\n * Copyright (C) 2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef INTERFACE_OPTIONS_H__\n#define INTERFACE_OPTIONS_H__\n\n#include \"nvtop/common.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/interface_common.h\"\n\n#include <stdbool.h>\n\ntypedef struct {\n  plot_info_to_draw to_draw;  // The set of metrics to draw for this gpu\n  bool doNotMonitor;          // True if this GPU should not be monitored\n  struct gpu_info *linkedGpu; // The gpu to which this option apply\n} nvtop_interface_gpu_opts;\n\ntypedef struct nvtop_interface_option_struct {\n  bool\n      plot_left_to_right; // true to reverse the plot refresh direction defines inactivity (0 use rate) before hiding it\n  bool temperature_in_fahrenheit;                   // Switch from celsius to fahrenheit temperature scale\n  bool use_color;                                   // Name self explanatory\n  double encode_decode_hiding_timer;                // Negative to always display, positive\n  nvtop_interface_gpu_opts *gpu_specific_opts;      // GPU specific options\n  char *config_file_location;                       // Location of the config file\n  enum process_field sort_processes_by;             // Specify the field used to order the processes\n  bool sort_descending_order;                       // Sort in descending order\n  int update_interval;                              // Interval between interface update in milliseconds\n  process_field_displayed process_fields_displayed; // Which columns of the\n                                                    // process list are displayed\n  bool show_startup_messages;                       // True to show the startup messages\n  bool filter_nvtop_pid;                            // Do not show nvtop pid in the processes list\n  bool has_monitored_set_changed;                   // True if the set of monitored gpu was modified through the interface\n  bool has_gpu_info_bar;                            // Show info bar with additional GPU parameters\n  bool hide_processes_list;                         // Hide processes list\n} nvtop_interface_option;\n\ninline bool plot_isset_draw_info(enum plot_information check_info, plot_info_to_draw to_draw) {\n  return (to_draw & (1 << check_info)) > 0;\n}\n\ninline unsigned plot_count_draw_info(plot_info_to_draw to_draw) {\n  unsigned count = 0;\n  for (int i = plot_gpu_rate; i < plot_information_count; ++i) {\n    count += plot_isset_draw_info((enum plot_information)i, to_draw);\n  }\n  return count;\n}\n\ninline plot_info_to_draw plot_add_draw_info(enum plot_information set_info, plot_info_to_draw to_draw) {\n  if (plot_count_draw_info(to_draw) < MAX_LINES_PER_PLOT)\n    return to_draw | (1 << set_info);\n  else\n    return to_draw;\n}\n\ninline plot_info_to_draw plot_remove_draw_info(enum plot_information reset_info, plot_info_to_draw to_draw) {\n  return to_draw & (~(1 << reset_info));\n}\n\ninline plot_info_to_draw plot_default_draw_info(void) { return (1 << plot_gpu_rate) | (1 << plot_gpu_mem_rate); }\n\nvoid alloc_interface_options_internals(char *config_file_location, unsigned num_devices, struct list_head *devices,\n                                       nvtop_interface_option *options);\n\nunsigned interface_check_and_fix_monitored_gpus(unsigned num_devices, struct list_head *monitoredGpus,\n                                                struct list_head *nonMonitoredGpus, nvtop_interface_option *options);\n\nbool load_interface_options_from_config_file(unsigned num_devices, nvtop_interface_option *options);\n\nbool save_interface_options_to_config_file(unsigned total_dev_count, const nvtop_interface_option *options);\n\ninline bool process_is_field_displayed(enum process_field field, process_field_displayed fields_displayed) {\n  return (fields_displayed & (1 << field)) > 0;\n}\n\ninline process_field_displayed process_remove_field_to_display(enum process_field field,\n                                                               process_field_displayed fields_displayed) {\n  return fields_displayed & (~(1 << field));\n}\n\ninline process_field_displayed process_add_field_to_display(enum process_field field,\n                                                            process_field_displayed fields_displayed) {\n  return fields_displayed | (1 << field);\n}\n\ninline process_field_displayed process_default_displayed_field(void) {\n  process_field_displayed to_display = 0;\n  for (int field = process_pid; field < process_field_count; ++field) {\n    to_display = process_add_field_to_display((enum process_field)field, to_display);\n  }\n  to_display = process_remove_field_to_display(process_enc_rate, to_display);\n  to_display = process_remove_field_to_display(process_dec_rate, to_display);\n  return to_display;\n}\n\ninline unsigned process_field_displayed_count(process_field_displayed fields_displayed) {\n  unsigned displayed_count = 0;\n  for (int field = process_pid; field < process_field_count; ++field) {\n    if (process_is_field_displayed((enum process_field)field, fields_displayed))\n      displayed_count++;\n  }\n  return displayed_count;\n}\n\nenum process_field process_default_sort_by_from(process_field_displayed fields_displayed);\n\n#endif // INTERFACE_OPTIONS_H__\n"
  },
  {
    "path": "include/nvtop/interface_ring_buffer.h",
    "content": "/*\n *\n * Copyright (C) 2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef INTERFACE_RING_BUFFER_H__\n#define INTERFACE_RING_BUFFER_H__\n\n#include <assert.h>\n\ntypedef struct interface_ring_buffer_st {\n  unsigned monitored_dev_count;\n  unsigned per_device_data_saved;\n  unsigned buffer_size;\n  void *ring_buffer[2];\n} interface_ring_buffer;\n\n#define INTERFACE_RING_BUFFER_DATA(ring_buffer_ptr, name)                                                              \\\n  unsigned(*name)[ring_buffer_ptr->per_device_data_saved][ring_buffer_ptr->buffer_size] =                              \\\n      (unsigned(*)[ring_buffer_ptr->per_device_data_saved][ring_buffer_ptr->buffer_size])                              \\\n          ring_buffer_ptr->ring_buffer[1];\n\n#define INTERFACE_RING_BUFFER_INDICES(ring_buffer_ptr, name)                                                           \\\n  unsigned(*name)[ring_buffer_ptr->per_device_data_saved][2] =                                                         \\\n      (unsigned(*)[ring_buffer_ptr->per_device_data_saved][2])ring_buffer_ptr->ring_buffer[0];\n\nvoid interface_alloc_ring_buffer(unsigned monitored_dev_count, unsigned per_device_data, unsigned buffer_size,\n                                 interface_ring_buffer *ring_buffer);\n\nvoid interface_free_ring_buffer(interface_ring_buffer *buffer);\n\ninline unsigned interface_ring_buffer_data_stored(const interface_ring_buffer *buff, unsigned device,\n                                                  unsigned which_data) {\n  INTERFACE_RING_BUFFER_INDICES(buff, indices);\n  unsigned start = indices[device][which_data][0];\n  unsigned end = indices[device][which_data][1];\n  unsigned length = end - start;\n  if (end < start) { // Has wrapped around the buffer\n    length += buff->buffer_size;\n  }\n  return length;\n}\n\ninline unsigned interface_index_in_ring(const interface_ring_buffer *buff, unsigned device, unsigned which_data,\n                                        unsigned index) {\n  assert(interface_ring_buffer_data_stored(buff, device, which_data) > index);\n  INTERFACE_RING_BUFFER_INDICES(buff, indices);\n  unsigned start = indices[device][which_data][0];\n  unsigned location = start + index;\n  if (location >= buff->buffer_size)\n    location -= buff->buffer_size;\n  return location;\n}\n\ninline unsigned interface_ring_buffer_get(const interface_ring_buffer *buff, unsigned device, unsigned which_data,\n                                          unsigned index) {\n  INTERFACE_RING_BUFFER_DATA(buff, data);\n  unsigned index_in_ring = interface_index_in_ring(buff, device, which_data, index);\n  return data[device][which_data][index_in_ring];\n}\n\ninline void interface_ring_buffer_push(interface_ring_buffer *buff, unsigned device, unsigned which_data,\n                                       unsigned value) {\n  INTERFACE_RING_BUFFER_INDICES(buff, indices);\n  INTERFACE_RING_BUFFER_DATA(buff, data);\n  unsigned start = indices[device][which_data][0];\n  unsigned end = indices[device][which_data][1];\n  // If ring full, move start index\n  data[device][which_data][end] = value;\n  end++;\n  if (end == buff->buffer_size)\n    end -= buff->buffer_size;\n  if (end == start) {\n    start++;\n    if (start == buff->buffer_size)\n      start -= buff->buffer_size;\n  }\n  indices[device][which_data][0] = start;\n  indices[device][which_data][1] = end;\n}\n\ninline void interface_ring_buffer_pop(interface_ring_buffer *buff, unsigned device, unsigned which_data) {\n  INTERFACE_RING_BUFFER_INDICES(buff, indices);\n  unsigned start = indices[device][which_data][0];\n  unsigned end = indices[device][which_data][1];\n  if (start != end) {\n    start++;\n    if (start == buff->buffer_size)\n      start -= buff->buffer_size;\n    indices[device][which_data][0] = start;\n  }\n}\n\ninline void interface_ring_buffer_empty_select(interface_ring_buffer *buff, unsigned device, unsigned which_data) {\n  INTERFACE_RING_BUFFER_INDICES(buff, indices);\n  indices[device][which_data][0] = 0;\n  indices[device][which_data][1] = 0;\n}\n\ninline void interface_ring_buffer_empty(interface_ring_buffer *buff, unsigned device) {\n  for (unsigned i = 0; i < buff->per_device_data_saved; ++i) {\n    interface_ring_buffer_empty_select(buff, device, i);\n  }\n}\n\n#endif // INTERFACE_RING_BUFFER_H__\n"
  },
  {
    "path": "include/nvtop/interface_setup_win.h",
    "content": "/*\n *\n * Copyright (C) 2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef INTERFACE_SETUP_WIN_H__\n#define INTERFACE_SETUP_WIN_H__\n\n#include \"nvtop/extract_gpuinfo.h\"\n#include \"nvtop/interface_internal_common.h\"\n#include \"nvtop/interface_layout_selection.h\"\n\nvoid alloc_setup_window(struct window_position *position, struct setup_window *setup_win);\n\nvoid free_setup_window(struct setup_window *setup_win);\n\nvoid show_setup_window(struct nvtop_interface *interface);\n\nvoid hide_setup_window(struct nvtop_interface *interface);\n\nvoid draw_setup_window(unsigned monitored_dev_count, struct list_head *devices, struct nvtop_interface *interface);\n\nvoid draw_setup_window_shortcuts(struct nvtop_interface *interface);\n\nvoid handle_setup_win_keypress(int keyId, struct nvtop_interface *interface);\n\n#endif // INTERFACE_SETUP_WIN_H__\n"
  },
  {
    "path": "include/nvtop/plot.h",
    "content": "/*\n *\n * Copyright (C) 2018 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef __PLOT_H_\n#define __PLOT_H_\n\n#include \"nvtop/common.h\"\n\n#include <ncurses.h>\n#include <stdbool.h>\n#include <stddef.h>\n\n#define PLOT_MAX_LEGEND_SIZE 35\n\nvoid nvtop_line_plot(WINDOW *win, size_t num_data, const double *data, unsigned num_plots, bool legend_left,\n                     char legend[MAX_LINES_PER_PLOT][PLOT_MAX_LEGEND_SIZE]);\n\nvoid draw_rectangle(WINDOW *win, unsigned startX, unsigned startY, unsigned sizeX, unsigned sizeY);\n\n#endif // __PLOT_H_\n"
  },
  {
    "path": "include/nvtop/time.h",
    "content": "/*\n *\n * Copyright (C) 2018-2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef NVTOP_TIME_H_\n#define NVTOP_TIME_H_\n\n#include <stdbool.h>\n#include <stdint.h>\n#include <time.h>\n\n#ifdef CLOCK_MONOTONIC_RAW\n#define NVTOP_CLOCK CLOCK_MONOTONIC_RAW\n#else\n#define NVTOP_CLOCK CLOCK_MONOTONIC\n#endif\n\ntypedef struct timespec nvtop_time;\n\ninline void nvtop_get_current_time(nvtop_time *time) { clock_gettime(NVTOP_CLOCK, time); }\n\ninline double nvtop_difftime(nvtop_time t0, nvtop_time t1) {\n  double secdiff = difftime(t1.tv_sec, t0.tv_sec);\n  if (t1.tv_nsec < t0.tv_nsec) {\n    long val = 1000000000l - t0.tv_nsec + t1.tv_nsec;\n    secdiff += (double)val / 1e9 - 1.;\n  } else {\n    long val = t1.tv_nsec - t0.tv_nsec;\n    secdiff += (double)val / 1e9;\n  }\n  return secdiff;\n}\n\ninline uint64_t nvtop_time_u64(nvtop_time t0) { return (uint64_t)(t0.tv_sec) * UINT64_C(1000000000) + t0.tv_nsec; }\n\ninline uint64_t nvtop_difftime_u64(nvtop_time t0, nvtop_time t1) {\n  return (uint64_t)(t1.tv_sec - t0.tv_sec) * UINT64_C(1000000000) + (uint64_t)t1.tv_nsec - (uint64_t)t0.tv_nsec;\n}\n\ninline nvtop_time nvtop_hmns_to_time(unsigned hour, unsigned minutes, unsigned long nanosec) {\n  nvtop_time t = {hour * 60 * 60 + 60 * minutes + nanosec / 1000000, nanosec % 1000000};\n  return t;\n}\n\ninline nvtop_time nvtop_substract_time(nvtop_time t0, nvtop_time t1) {\n  nvtop_time t = t0.tv_nsec - t1.tv_nsec < 0\n                     ? (nvtop_time){t0.tv_sec - t1.tv_sec - 1, t0.tv_nsec - t1.tv_nsec + 1000000}\n                     : (nvtop_time){t0.tv_sec - t1.tv_sec, t0.tv_nsec - t1.tv_nsec};\n  return t;\n}\n\ninline nvtop_time nvtop_add_time(nvtop_time t0, nvtop_time t1) {\n  nvtop_time t = t0.tv_nsec + t1.tv_nsec > 1000000\n                     ? (nvtop_time){t0.tv_sec + t1.tv_sec + 1, t0.tv_nsec + t1.tv_nsec - 1000000}\n                     : (nvtop_time){t0.tv_sec + t1.tv_sec, t0.tv_nsec + t1.tv_nsec};\n  return t;\n}\n\n#endif // NVTOP_TIME_H_\n"
  },
  {
    "path": "include/nvtop/version.h.in",
    "content": "/*\n *\n * Copyright (C) 2018 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef __NVTOP_VERSION_H_\n#define __NVTOP_VERSION_H_\n\n#define NVTOP_VERSION_MAJOR @nvtop_VERSION_MAJOR@\n#define NVTOP_VERSION_MINOR @nvtop_VERSION_MINOR@\n#define NVTOP_VERSION_PATCH @nvtop_VERSION_PATCH@\n\n#define NVTOP_VERSION_STRING \"@nvtop_VERSION_MAJOR@.@nvtop_VERSION_MINOR@.@nvtop_VERSION_PATCH@\"\n\n#endif // __NVTOP_VERSION_H_\n"
  },
  {
    "path": "include/uthash.h",
    "content": "/*\nCopyright (c) 2003-2021, Troy D. Hanson     http://troydhanson.github.io/uthash/\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\nOR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#ifndef UTHASH_H\n#define UTHASH_H\n\n#define UTHASH_VERSION 2.3.0\n\n#include <string.h>   /* memcmp, memset, strlen */\n#include <stddef.h>   /* ptrdiff_t */\n#include <stdlib.h>   /* exit */\n\n#if defined(HASH_DEFINE_OWN_STDINT) && HASH_DEFINE_OWN_STDINT\n/* This codepath is provided for backward compatibility, but I plan to remove it. */\n#warning \"HASH_DEFINE_OWN_STDINT is deprecated; please use HASH_NO_STDINT instead\"\ntypedef unsigned int uint32_t;\ntypedef unsigned char uint8_t;\n#elif defined(HASH_NO_STDINT) && HASH_NO_STDINT\n#else\n#include <stdint.h>   /* uint8_t, uint32_t */\n#endif\n\n/* These macros use decltype or the earlier __typeof GNU extension.\n   As decltype is only available in newer compilers (VS2010 or gcc 4.3+\n   when compiling c++ source) this code uses whatever method is needed\n   or, for VS2008 where neither is available, uses casting workarounds. */\n#if !defined(DECLTYPE) && !defined(NO_DECLTYPE)\n#if defined(_MSC_VER)   /* MS compiler */\n#if _MSC_VER >= 1600 && defined(__cplusplus)  /* VS2010 or newer in C++ mode */\n#define DECLTYPE(x) (decltype(x))\n#else                   /* VS2008 or older (or VS2010 in C mode) */\n#define NO_DECLTYPE\n#endif\n#elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__)\n#define NO_DECLTYPE\n#else                   /* GNU, Sun and other compilers */\n#define DECLTYPE(x) (__typeof(x))\n#endif\n#endif\n\n#ifdef NO_DECLTYPE\n#define DECLTYPE(x)\n#define DECLTYPE_ASSIGN(dst,src)                                                 \\\ndo {                                                                             \\\n  char **_da_dst = (char**)(&(dst));                                             \\\n  *_da_dst = (char*)(src);                                                       \\\n} while (0)\n#else\n#define DECLTYPE_ASSIGN(dst,src)                                                 \\\ndo {                                                                             \\\n  (dst) = DECLTYPE(dst)(src);                                                    \\\n} while (0)\n#endif\n\n#ifndef uthash_malloc\n#define uthash_malloc(sz) malloc(sz)      /* malloc fcn                      */\n#endif\n#ifndef uthash_free\n#define uthash_free(ptr,sz) free(ptr)     /* free fcn                        */\n#endif\n#ifndef uthash_bzero\n#define uthash_bzero(a,n) memset(a,'\\0',n)\n#endif\n#ifndef uthash_strlen\n#define uthash_strlen(s) strlen(s)\n#endif\n\n#ifndef HASH_FUNCTION\n#define HASH_FUNCTION(keyptr,keylen,hashv) HASH_JEN(keyptr, keylen, hashv)\n#endif\n\n#ifndef HASH_KEYCMP\n#define HASH_KEYCMP(a,b,n) memcmp(a,b,n)\n#endif\n\n#ifndef uthash_noexpand_fyi\n#define uthash_noexpand_fyi(tbl)          /* can be defined to log noexpand  */\n#endif\n#ifndef uthash_expand_fyi\n#define uthash_expand_fyi(tbl)            /* can be defined to log expands   */\n#endif\n\n#ifndef HASH_NONFATAL_OOM\n#define HASH_NONFATAL_OOM 0\n#endif\n\n#if HASH_NONFATAL_OOM\n/* malloc failures can be recovered from */\n\n#ifndef uthash_nonfatal_oom\n#define uthash_nonfatal_oom(obj) do {} while (0)    /* non-fatal OOM error */\n#endif\n\n#define HASH_RECORD_OOM(oomed) do { (oomed) = 1; } while (0)\n#define IF_HASH_NONFATAL_OOM(x) x\n\n#else\n/* malloc failures result in lost memory, hash tables are unusable */\n\n#ifndef uthash_fatal\n#define uthash_fatal(msg) exit(-1)        /* fatal OOM error */\n#endif\n\n#define HASH_RECORD_OOM(oomed) uthash_fatal(\"out of memory\")\n#define IF_HASH_NONFATAL_OOM(x)\n\n#endif\n\n/* initial number of buckets */\n#define HASH_INITIAL_NUM_BUCKETS 32U     /* initial number of buckets        */\n#define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */\n#define HASH_BKT_CAPACITY_THRESH 10U     /* expand when bucket count reaches */\n\n/* calculate the element whose hash handle address is hhp */\n#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho)))\n/* calculate the hash handle from element address elp */\n#define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle*)(void*)(((char*)(elp)) + ((tbl)->hho)))\n\n#define HASH_ROLLBACK_BKT(hh, head, itemptrhh)                                   \\\ndo {                                                                             \\\n  struct UT_hash_handle *_hd_hh_item = (itemptrhh);                              \\\n  unsigned _hd_bkt;                                                              \\\n  HASH_TO_BKT(_hd_hh_item->hashv, (head)->hh.tbl->num_buckets, _hd_bkt);         \\\n  (head)->hh.tbl->buckets[_hd_bkt].count++;                                      \\\n  _hd_hh_item->hh_next = NULL;                                                   \\\n  _hd_hh_item->hh_prev = NULL;                                                   \\\n} while (0)\n\n#define HASH_VALUE(keyptr,keylen,hashv)                                          \\\ndo {                                                                             \\\n  HASH_FUNCTION(keyptr, keylen, hashv);                                          \\\n} while (0)\n\n#define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out)                 \\\ndo {                                                                             \\\n  (out) = NULL;                                                                  \\\n  if (head) {                                                                    \\\n    unsigned _hf_bkt;                                                            \\\n    HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt);                  \\\n    if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) {                         \\\n      HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \\\n    }                                                                            \\\n  }                                                                              \\\n} while (0)\n\n#define HASH_FIND(hh,head,keyptr,keylen,out)                                     \\\ndo {                                                                             \\\n  (out) = NULL;                                                                  \\\n  if (head) {                                                                    \\\n    unsigned _hf_hashv;                                                          \\\n    HASH_VALUE(keyptr, keylen, _hf_hashv);                                       \\\n    HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out);             \\\n  }                                                                              \\\n} while (0)\n\n#ifdef HASH_BLOOM\n#define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM)\n#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL)\n#define HASH_BLOOM_MAKE(tbl,oomed)                                               \\\ndo {                                                                             \\\n  (tbl)->bloom_nbits = HASH_BLOOM;                                               \\\n  (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN);                 \\\n  if (!(tbl)->bloom_bv) {                                                        \\\n    HASH_RECORD_OOM(oomed);                                                      \\\n  } else {                                                                       \\\n    uthash_bzero((tbl)->bloom_bv, HASH_BLOOM_BYTELEN);                           \\\n    (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE;                                     \\\n  }                                                                              \\\n} while (0)\n\n#define HASH_BLOOM_FREE(tbl)                                                     \\\ndo {                                                                             \\\n  uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN);                              \\\n} while (0)\n\n#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U)))\n#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U)))\n\n#define HASH_BLOOM_ADD(tbl,hashv)                                                \\\n  HASH_BLOOM_BITSET((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U)))\n\n#define HASH_BLOOM_TEST(tbl,hashv)                                               \\\n  HASH_BLOOM_BITTEST((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U)))\n\n#else\n#define HASH_BLOOM_MAKE(tbl,oomed)\n#define HASH_BLOOM_FREE(tbl)\n#define HASH_BLOOM_ADD(tbl,hashv)\n#define HASH_BLOOM_TEST(tbl,hashv) (1)\n#define HASH_BLOOM_BYTELEN 0U\n#endif\n\n#define HASH_MAKE_TABLE(hh,head,oomed)                                           \\\ndo {                                                                             \\\n  (head)->hh.tbl = (UT_hash_table*)uthash_malloc(sizeof(UT_hash_table));         \\\n  if (!(head)->hh.tbl) {                                                         \\\n    HASH_RECORD_OOM(oomed);                                                      \\\n  } else {                                                                       \\\n    uthash_bzero((head)->hh.tbl, sizeof(UT_hash_table));                         \\\n    (head)->hh.tbl->tail = &((head)->hh);                                        \\\n    (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS;                      \\\n    (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2;            \\\n    (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head);                  \\\n    (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc(                    \\\n        HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket));               \\\n    (head)->hh.tbl->signature = HASH_SIGNATURE;                                  \\\n    if (!(head)->hh.tbl->buckets) {                                              \\\n      HASH_RECORD_OOM(oomed);                                                    \\\n      uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                        \\\n    } else {                                                                     \\\n      uthash_bzero((head)->hh.tbl->buckets,                                      \\\n          HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket));             \\\n      HASH_BLOOM_MAKE((head)->hh.tbl, oomed);                                    \\\n      IF_HASH_NONFATAL_OOM(                                                      \\\n        if (oomed) {                                                             \\\n          uthash_free((head)->hh.tbl->buckets,                                   \\\n              HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket));           \\\n          uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                    \\\n        }                                                                        \\\n      )                                                                          \\\n    }                                                                            \\\n  }                                                                              \\\n} while (0)\n\n#define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \\\ndo {                                                                             \\\n  (replaced) = NULL;                                                             \\\n  HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \\\n  if (replaced) {                                                                \\\n    HASH_DELETE(hh, head, replaced);                                             \\\n  }                                                                              \\\n  HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \\\n} while (0)\n\n#define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \\\ndo {                                                                             \\\n  (replaced) = NULL;                                                             \\\n  HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \\\n  if (replaced) {                                                                \\\n    HASH_DELETE(hh, head, replaced);                                             \\\n  }                                                                              \\\n  HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \\\n} while (0)\n\n#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced)                   \\\ndo {                                                                             \\\n  unsigned _hr_hashv;                                                            \\\n  HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv);                         \\\n  HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \\\n} while (0)\n\n#define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn)    \\\ndo {                                                                             \\\n  unsigned _hr_hashv;                                                            \\\n  HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv);                         \\\n  HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \\\n} while (0)\n\n#define HASH_APPEND_LIST(hh, head, add)                                          \\\ndo {                                                                             \\\n  (add)->hh.next = NULL;                                                         \\\n  (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail);           \\\n  (head)->hh.tbl->tail->next = (add);                                            \\\n  (head)->hh.tbl->tail = &((add)->hh);                                           \\\n} while (0)\n\n#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn)                                 \\\ndo {                                                                             \\\n  do {                                                                           \\\n    if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) {                             \\\n      break;                                                                     \\\n    }                                                                            \\\n  } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next));           \\\n} while (0)\n\n#ifdef NO_DECLTYPE\n#undef HASH_AKBI_INNER_LOOP\n#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn)                                 \\\ndo {                                                                             \\\n  char *_hs_saved_head = (char*)(head);                                          \\\n  do {                                                                           \\\n    DECLTYPE_ASSIGN(head, _hs_iter);                                             \\\n    if (cmpfcn(head, add) > 0) {                                                 \\\n      DECLTYPE_ASSIGN(head, _hs_saved_head);                                     \\\n      break;                                                                     \\\n    }                                                                            \\\n    DECLTYPE_ASSIGN(head, _hs_saved_head);                                       \\\n  } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next));           \\\n} while (0)\n#endif\n\n#if HASH_NONFATAL_OOM\n\n#define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed)            \\\ndo {                                                                             \\\n  if (!(oomed)) {                                                                \\\n    unsigned _ha_bkt;                                                            \\\n    (head)->hh.tbl->num_items++;                                                 \\\n    HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt);                  \\\n    HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed);    \\\n    if (oomed) {                                                                 \\\n      HASH_ROLLBACK_BKT(hh, head, &(add)->hh);                                   \\\n      HASH_DELETE_HH(hh, head, &(add)->hh);                                      \\\n      (add)->hh.tbl = NULL;                                                      \\\n      uthash_nonfatal_oom(add);                                                  \\\n    } else {                                                                     \\\n      HASH_BLOOM_ADD((head)->hh.tbl, hashval);                                   \\\n      HASH_EMIT_KEY(hh, head, keyptr, keylen_in);                                \\\n    }                                                                            \\\n  } else {                                                                       \\\n    (add)->hh.tbl = NULL;                                                        \\\n    uthash_nonfatal_oom(add);                                                    \\\n  }                                                                              \\\n} while (0)\n\n#else\n\n#define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed)            \\\ndo {                                                                             \\\n  unsigned _ha_bkt;                                                              \\\n  (head)->hh.tbl->num_items++;                                                   \\\n  HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt);                    \\\n  HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed);      \\\n  HASH_BLOOM_ADD((head)->hh.tbl, hashval);                                       \\\n  HASH_EMIT_KEY(hh, head, keyptr, keylen_in);                                    \\\n} while (0)\n\n#endif\n\n\n#define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \\\ndo {                                                                             \\\n  IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; )                                     \\\n  (add)->hh.hashv = (hashval);                                                   \\\n  (add)->hh.key = (char*) (keyptr);                                              \\\n  (add)->hh.keylen = (unsigned) (keylen_in);                                     \\\n  if (!(head)) {                                                                 \\\n    (add)->hh.next = NULL;                                                       \\\n    (add)->hh.prev = NULL;                                                       \\\n    HASH_MAKE_TABLE(hh, add, _ha_oomed);                                         \\\n    IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { )                                    \\\n      (head) = (add);                                                            \\\n    IF_HASH_NONFATAL_OOM( } )                                                    \\\n  } else {                                                                       \\\n    void *_hs_iter = (head);                                                     \\\n    (add)->hh.tbl = (head)->hh.tbl;                                              \\\n    HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn);                                 \\\n    if (_hs_iter) {                                                              \\\n      (add)->hh.next = _hs_iter;                                                 \\\n      if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) {     \\\n        HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add);              \\\n      } else {                                                                   \\\n        (head) = (add);                                                          \\\n      }                                                                          \\\n      HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add);                      \\\n    } else {                                                                     \\\n      HASH_APPEND_LIST(hh, head, add);                                           \\\n    }                                                                            \\\n  }                                                                              \\\n  HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed);       \\\n  HASH_FSCK(hh, head, \"HASH_ADD_KEYPTR_BYHASHVALUE_INORDER\");                    \\\n} while (0)\n\n#define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn)             \\\ndo {                                                                             \\\n  unsigned _hs_hashv;                                                            \\\n  HASH_VALUE(keyptr, keylen_in, _hs_hashv);                                      \\\n  HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \\\n} while (0)\n\n#define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \\\n  HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn)\n\n#define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn)                 \\\n  HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn)\n\n#define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add)        \\\ndo {                                                                             \\\n  IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; )                                     \\\n  (add)->hh.hashv = (hashval);                                                   \\\n  (add)->hh.key = (const void*) (keyptr);                                        \\\n  (add)->hh.keylen = (unsigned) (keylen_in);                                     \\\n  if (!(head)) {                                                                 \\\n    (add)->hh.next = NULL;                                                       \\\n    (add)->hh.prev = NULL;                                                       \\\n    HASH_MAKE_TABLE(hh, add, _ha_oomed);                                         \\\n    IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { )                                    \\\n      (head) = (add);                                                            \\\n    IF_HASH_NONFATAL_OOM( } )                                                    \\\n  } else {                                                                       \\\n    (add)->hh.tbl = (head)->hh.tbl;                                              \\\n    HASH_APPEND_LIST(hh, head, add);                                             \\\n  }                                                                              \\\n  HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed);       \\\n  HASH_FSCK(hh, head, \"HASH_ADD_KEYPTR_BYHASHVALUE\");                            \\\n} while (0)\n\n#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add)                            \\\ndo {                                                                             \\\n  unsigned _ha_hashv;                                                            \\\n  HASH_VALUE(keyptr, keylen_in, _ha_hashv);                                      \\\n  HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add);      \\\n} while (0)\n\n#define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add)            \\\n  HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add)\n\n#define HASH_ADD(hh,head,fieldname,keylen_in,add)                                \\\n  HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add)\n\n#define HASH_TO_BKT(hashv,num_bkts,bkt)                                          \\\ndo {                                                                             \\\n  bkt = ((hashv) & ((num_bkts) - 1U));                                           \\\n} while (0)\n\n/* delete \"delptr\" from the hash table.\n * \"the usual\" patch-up process for the app-order doubly-linked-list.\n * The use of _hd_hh_del below deserves special explanation.\n * These used to be expressed using (delptr) but that led to a bug\n * if someone used the same symbol for the head and deletee, like\n *  HASH_DELETE(hh,users,users);\n * We want that to work, but by changing the head (users) below\n * we were forfeiting our ability to further refer to the deletee (users)\n * in the patch-up process. Solution: use scratch space to\n * copy the deletee pointer, then the latter references are via that\n * scratch pointer rather than through the repointed (users) symbol.\n */\n#define HASH_DELETE(hh,head,delptr)                                              \\\n    HASH_DELETE_HH(hh, head, &(delptr)->hh)\n\n#define HASH_DELETE_HH(hh,head,delptrhh)                                         \\\ndo {                                                                             \\\n  struct UT_hash_handle *_hd_hh_del = (delptrhh);                                \\\n  if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) {                \\\n    HASH_BLOOM_FREE((head)->hh.tbl);                                             \\\n    uthash_free((head)->hh.tbl->buckets,                                         \\\n                (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket));    \\\n    uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                          \\\n    (head) = NULL;                                                               \\\n  } else {                                                                       \\\n    unsigned _hd_bkt;                                                            \\\n    if (_hd_hh_del == (head)->hh.tbl->tail) {                                    \\\n      (head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev);     \\\n    }                                                                            \\\n    if (_hd_hh_del->prev != NULL) {                                              \\\n      HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next;   \\\n    } else {                                                                     \\\n      DECLTYPE_ASSIGN(head, _hd_hh_del->next);                                   \\\n    }                                                                            \\\n    if (_hd_hh_del->next != NULL) {                                              \\\n      HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev;   \\\n    }                                                                            \\\n    HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt);        \\\n    HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del);               \\\n    (head)->hh.tbl->num_items--;                                                 \\\n  }                                                                              \\\n  HASH_FSCK(hh, head, \"HASH_DELETE_HH\");                                         \\\n} while (0)\n\n/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */\n#define HASH_FIND_STR(head,findstr,out)                                          \\\ndo {                                                                             \\\n    unsigned _uthash_hfstr_keylen = (unsigned)uthash_strlen(findstr);            \\\n    HASH_FIND(hh, head, findstr, _uthash_hfstr_keylen, out);                     \\\n} while (0)\n#define HASH_ADD_STR(head,strfield,add)                                          \\\ndo {                                                                             \\\n    unsigned _uthash_hastr_keylen = (unsigned)uthash_strlen((add)->strfield);    \\\n    HASH_ADD(hh, head, strfield[0], _uthash_hastr_keylen, add);                  \\\n} while (0)\n#define HASH_REPLACE_STR(head,strfield,add,replaced)                             \\\ndo {                                                                             \\\n    unsigned _uthash_hrstr_keylen = (unsigned)uthash_strlen((add)->strfield);    \\\n    HASH_REPLACE(hh, head, strfield[0], _uthash_hrstr_keylen, add, replaced);    \\\n} while (0)\n#define HASH_FIND_INT(head,findint,out)                                          \\\n    HASH_FIND(hh,head,findint,sizeof(int),out)\n#define HASH_ADD_INT(head,intfield,add)                                          \\\n    HASH_ADD(hh,head,intfield,sizeof(int),add)\n#define HASH_REPLACE_INT(head,intfield,add,replaced)                             \\\n    HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced)\n#define HASH_FIND_PTR(head,findptr,out)                                          \\\n    HASH_FIND(hh,head,findptr,sizeof(void *),out)\n#define HASH_ADD_PTR(head,ptrfield,add)                                          \\\n    HASH_ADD(hh,head,ptrfield,sizeof(void *),add)\n#define HASH_REPLACE_PTR(head,ptrfield,add,replaced)                             \\\n    HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced)\n#define HASH_DEL(head,delptr)                                                    \\\n    HASH_DELETE(hh,head,delptr)\n\n/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined.\n * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined.\n */\n#ifdef HASH_DEBUG\n#include <stdio.h>   /* fprintf, stderr */\n#define HASH_OOPS(...) do { fprintf(stderr, __VA_ARGS__); exit(-1); } while (0)\n#define HASH_FSCK(hh,head,where)                                                 \\\ndo {                                                                             \\\n  struct UT_hash_handle *_thh;                                                   \\\n  if (head) {                                                                    \\\n    unsigned _bkt_i;                                                             \\\n    unsigned _count = 0;                                                         \\\n    char *_prev;                                                                 \\\n    for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) {           \\\n      unsigned _bkt_count = 0;                                                   \\\n      _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head;                            \\\n      _prev = NULL;                                                              \\\n      while (_thh) {                                                             \\\n        if (_prev != (char*)(_thh->hh_prev)) {                                   \\\n          HASH_OOPS(\"%s: invalid hh_prev %p, actual %p\\n\",                       \\\n              (where), (void*)_thh->hh_prev, (void*)_prev);                      \\\n        }                                                                        \\\n        _bkt_count++;                                                            \\\n        _prev = (char*)(_thh);                                                   \\\n        _thh = _thh->hh_next;                                                    \\\n      }                                                                          \\\n      _count += _bkt_count;                                                      \\\n      if ((head)->hh.tbl->buckets[_bkt_i].count !=  _bkt_count) {                \\\n        HASH_OOPS(\"%s: invalid bucket count %u, actual %u\\n\",                    \\\n            (where), (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count);         \\\n      }                                                                          \\\n    }                                                                            \\\n    if (_count != (head)->hh.tbl->num_items) {                                   \\\n      HASH_OOPS(\"%s: invalid hh item count %u, actual %u\\n\",                     \\\n          (where), (head)->hh.tbl->num_items, _count);                           \\\n    }                                                                            \\\n    _count = 0;                                                                  \\\n    _prev = NULL;                                                                \\\n    _thh =  &(head)->hh;                                                         \\\n    while (_thh) {                                                               \\\n      _count++;                                                                  \\\n      if (_prev != (char*)_thh->prev) {                                          \\\n        HASH_OOPS(\"%s: invalid prev %p, actual %p\\n\",                            \\\n            (where), (void*)_thh->prev, (void*)_prev);                           \\\n      }                                                                          \\\n      _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh);                         \\\n      _thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL);     \\\n    }                                                                            \\\n    if (_count != (head)->hh.tbl->num_items) {                                   \\\n      HASH_OOPS(\"%s: invalid app item count %u, actual %u\\n\",                    \\\n          (where), (head)->hh.tbl->num_items, _count);                           \\\n    }                                                                            \\\n  }                                                                              \\\n} while (0)\n#else\n#define HASH_FSCK(hh,head,where)\n#endif\n\n/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to\n * the descriptor to which this macro is defined for tuning the hash function.\n * The app can #include <unistd.h> to get the prototype for write(2). */\n#ifdef HASH_EMIT_KEYS\n#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)                                   \\\ndo {                                                                             \\\n  unsigned _klen = fieldlen;                                                     \\\n  write(HASH_EMIT_KEYS, &_klen, sizeof(_klen));                                  \\\n  write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen);                        \\\n} while (0)\n#else\n#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)\n#endif\n\n/* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */\n#define HASH_BER(key,keylen,hashv)                                               \\\ndo {                                                                             \\\n  unsigned _hb_keylen = (unsigned)keylen;                                        \\\n  const unsigned char *_hb_key = (const unsigned char*)(key);                    \\\n  (hashv) = 0;                                                                   \\\n  while (_hb_keylen-- != 0U) {                                                   \\\n    (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++;                           \\\n  }                                                                              \\\n} while (0)\n\n\n/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at\n * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */\n#define HASH_SAX(key,keylen,hashv)                                               \\\ndo {                                                                             \\\n  unsigned _sx_i;                                                                \\\n  const unsigned char *_hs_key = (const unsigned char*)(key);                    \\\n  hashv = 0;                                                                     \\\n  for (_sx_i=0; _sx_i < keylen; _sx_i++) {                                       \\\n    hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i];                       \\\n  }                                                                              \\\n} while (0)\n/* FNV-1a variation */\n#define HASH_FNV(key,keylen,hashv)                                               \\\ndo {                                                                             \\\n  unsigned _fn_i;                                                                \\\n  const unsigned char *_hf_key = (const unsigned char*)(key);                    \\\n  (hashv) = 2166136261U;                                                         \\\n  for (_fn_i=0; _fn_i < keylen; _fn_i++) {                                       \\\n    hashv = hashv ^ _hf_key[_fn_i];                                              \\\n    hashv = hashv * 16777619U;                                                   \\\n  }                                                                              \\\n} while (0)\n\n#define HASH_OAT(key,keylen,hashv)                                               \\\ndo {                                                                             \\\n  unsigned _ho_i;                                                                \\\n  const unsigned char *_ho_key=(const unsigned char*)(key);                      \\\n  hashv = 0;                                                                     \\\n  for(_ho_i=0; _ho_i < keylen; _ho_i++) {                                        \\\n      hashv += _ho_key[_ho_i];                                                   \\\n      hashv += (hashv << 10);                                                    \\\n      hashv ^= (hashv >> 6);                                                     \\\n  }                                                                              \\\n  hashv += (hashv << 3);                                                         \\\n  hashv ^= (hashv >> 11);                                                        \\\n  hashv += (hashv << 15);                                                        \\\n} while (0)\n\n#define HASH_JEN_MIX(a,b,c)                                                      \\\ndo {                                                                             \\\n  a -= b; a -= c; a ^= ( c >> 13 );                                              \\\n  b -= c; b -= a; b ^= ( a << 8 );                                               \\\n  c -= a; c -= b; c ^= ( b >> 13 );                                              \\\n  a -= b; a -= c; a ^= ( c >> 12 );                                              \\\n  b -= c; b -= a; b ^= ( a << 16 );                                              \\\n  c -= a; c -= b; c ^= ( b >> 5 );                                               \\\n  a -= b; a -= c; a ^= ( c >> 3 );                                               \\\n  b -= c; b -= a; b ^= ( a << 10 );                                              \\\n  c -= a; c -= b; c ^= ( b >> 15 );                                              \\\n} while (0)\n\n#define HASH_JEN(key,keylen,hashv)                                               \\\ndo {                                                                             \\\n  unsigned _hj_i,_hj_j,_hj_k;                                                    \\\n  unsigned const char *_hj_key=(unsigned const char*)(key);                      \\\n  hashv = 0xfeedbeefu;                                                           \\\n  _hj_i = _hj_j = 0x9e3779b9u;                                                   \\\n  _hj_k = (unsigned)(keylen);                                                    \\\n  while (_hj_k >= 12U) {                                                         \\\n    _hj_i +=    (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 )                      \\\n        + ( (unsigned)_hj_key[2] << 16 )                                         \\\n        + ( (unsigned)_hj_key[3] << 24 ) );                                      \\\n    _hj_j +=    (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 )                      \\\n        + ( (unsigned)_hj_key[6] << 16 )                                         \\\n        + ( (unsigned)_hj_key[7] << 24 ) );                                      \\\n    hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 )                         \\\n        + ( (unsigned)_hj_key[10] << 16 )                                        \\\n        + ( (unsigned)_hj_key[11] << 24 ) );                                     \\\n                                                                                 \\\n     HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                          \\\n                                                                                 \\\n     _hj_key += 12;                                                              \\\n     _hj_k -= 12U;                                                               \\\n  }                                                                              \\\n  hashv += (unsigned)(keylen);                                                   \\\n  switch ( _hj_k ) {                                                             \\\n    case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */         \\\n    case 10: hashv += ( (unsigned)_hj_key[9] << 16 );  /* FALLTHROUGH */         \\\n    case 9:  hashv += ( (unsigned)_hj_key[8] << 8 );   /* FALLTHROUGH */         \\\n    case 8:  _hj_j += ( (unsigned)_hj_key[7] << 24 );  /* FALLTHROUGH */         \\\n    case 7:  _hj_j += ( (unsigned)_hj_key[6] << 16 );  /* FALLTHROUGH */         \\\n    case 6:  _hj_j += ( (unsigned)_hj_key[5] << 8 );   /* FALLTHROUGH */         \\\n    case 5:  _hj_j += _hj_key[4];                      /* FALLTHROUGH */         \\\n    case 4:  _hj_i += ( (unsigned)_hj_key[3] << 24 );  /* FALLTHROUGH */         \\\n    case 3:  _hj_i += ( (unsigned)_hj_key[2] << 16 );  /* FALLTHROUGH */         \\\n    case 2:  _hj_i += ( (unsigned)_hj_key[1] << 8 );   /* FALLTHROUGH */         \\\n    case 1:  _hj_i += _hj_key[0];                      /* FALLTHROUGH */         \\\n    default: ;                                                                   \\\n  }                                                                              \\\n  HASH_JEN_MIX(_hj_i, _hj_j, hashv);                                             \\\n} while (0)\n\n/* The Paul Hsieh hash function */\n#undef get16bits\n#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__)             \\\n  || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)\n#define get16bits(d) (*((const uint16_t *) (d)))\n#endif\n\n#if !defined (get16bits)\n#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)             \\\n                       +(uint32_t)(((const uint8_t *)(d))[0]) )\n#endif\n#define HASH_SFH(key,keylen,hashv)                                               \\\ndo {                                                                             \\\n  unsigned const char *_sfh_key=(unsigned const char*)(key);                     \\\n  uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen;                                \\\n                                                                                 \\\n  unsigned _sfh_rem = _sfh_len & 3U;                                             \\\n  _sfh_len >>= 2;                                                                \\\n  hashv = 0xcafebabeu;                                                           \\\n                                                                                 \\\n  /* Main loop */                                                                \\\n  for (;_sfh_len > 0U; _sfh_len--) {                                             \\\n    hashv    += get16bits (_sfh_key);                                            \\\n    _sfh_tmp  = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv;              \\\n    hashv     = (hashv << 16) ^ _sfh_tmp;                                        \\\n    _sfh_key += 2U*sizeof (uint16_t);                                            \\\n    hashv    += hashv >> 11;                                                     \\\n  }                                                                              \\\n                                                                                 \\\n  /* Handle end cases */                                                         \\\n  switch (_sfh_rem) {                                                            \\\n    case 3: hashv += get16bits (_sfh_key);                                       \\\n            hashv ^= hashv << 16;                                                \\\n            hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18;              \\\n            hashv += hashv >> 11;                                                \\\n            break;                                                               \\\n    case 2: hashv += get16bits (_sfh_key);                                       \\\n            hashv ^= hashv << 11;                                                \\\n            hashv += hashv >> 17;                                                \\\n            break;                                                               \\\n    case 1: hashv += *_sfh_key;                                                  \\\n            hashv ^= hashv << 10;                                                \\\n            hashv += hashv >> 1;                                                 \\\n            break;                                                               \\\n    default: ;                                                                   \\\n  }                                                                              \\\n                                                                                 \\\n  /* Force \"avalanching\" of final 127 bits */                                    \\\n  hashv ^= hashv << 3;                                                           \\\n  hashv += hashv >> 5;                                                           \\\n  hashv ^= hashv << 4;                                                           \\\n  hashv += hashv >> 17;                                                          \\\n  hashv ^= hashv << 25;                                                          \\\n  hashv += hashv >> 6;                                                           \\\n} while (0)\n\n/* iterate over items in a known bucket to find desired item */\n#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out)               \\\ndo {                                                                             \\\n  if ((head).hh_head != NULL) {                                                  \\\n    DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head));                     \\\n  } else {                                                                       \\\n    (out) = NULL;                                                                \\\n  }                                                                              \\\n  while ((out) != NULL) {                                                        \\\n    if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) {       \\\n      if (HASH_KEYCMP((out)->hh.key, keyptr, keylen_in) == 0) {                  \\\n        break;                                                                   \\\n      }                                                                          \\\n    }                                                                            \\\n    if ((out)->hh.hh_next != NULL) {                                             \\\n      DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next));                \\\n    } else {                                                                     \\\n      (out) = NULL;                                                              \\\n    }                                                                            \\\n  }                                                                              \\\n} while (0)\n\n/* add an item to a bucket  */\n#define HASH_ADD_TO_BKT(head,hh,addhh,oomed)                                     \\\ndo {                                                                             \\\n  UT_hash_bucket *_ha_head = &(head);                                            \\\n  _ha_head->count++;                                                             \\\n  (addhh)->hh_next = _ha_head->hh_head;                                          \\\n  (addhh)->hh_prev = NULL;                                                       \\\n  if (_ha_head->hh_head != NULL) {                                               \\\n    _ha_head->hh_head->hh_prev = (addhh);                                        \\\n  }                                                                              \\\n  _ha_head->hh_head = (addhh);                                                   \\\n  if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \\\n      && !(addhh)->tbl->noexpand) {                                              \\\n    HASH_EXPAND_BUCKETS(addhh,(addhh)->tbl, oomed);                              \\\n    IF_HASH_NONFATAL_OOM(                                                        \\\n      if (oomed) {                                                               \\\n        HASH_DEL_IN_BKT(head,addhh);                                             \\\n      }                                                                          \\\n    )                                                                            \\\n  }                                                                              \\\n} while (0)\n\n/* remove an item from a given bucket */\n#define HASH_DEL_IN_BKT(head,delhh)                                              \\\ndo {                                                                             \\\n  UT_hash_bucket *_hd_head = &(head);                                            \\\n  _hd_head->count--;                                                             \\\n  if (_hd_head->hh_head == (delhh)) {                                            \\\n    _hd_head->hh_head = (delhh)->hh_next;                                        \\\n  }                                                                              \\\n  if ((delhh)->hh_prev) {                                                        \\\n    (delhh)->hh_prev->hh_next = (delhh)->hh_next;                                \\\n  }                                                                              \\\n  if ((delhh)->hh_next) {                                                        \\\n    (delhh)->hh_next->hh_prev = (delhh)->hh_prev;                                \\\n  }                                                                              \\\n} while (0)\n\n/* Bucket expansion has the effect of doubling the number of buckets\n * and redistributing the items into the new buckets. Ideally the\n * items will distribute more or less evenly into the new buckets\n * (the extent to which this is true is a measure of the quality of\n * the hash function as it applies to the key domain).\n *\n * With the items distributed into more buckets, the chain length\n * (item count) in each bucket is reduced. Thus by expanding buckets\n * the hash keeps a bound on the chain length. This bounded chain\n * length is the essence of how a hash provides constant time lookup.\n *\n * The calculation of tbl->ideal_chain_maxlen below deserves some\n * explanation. First, keep in mind that we're calculating the ideal\n * maximum chain length based on the *new* (doubled) bucket count.\n * In fractions this is just n/b (n=number of items,b=new num buckets).\n * Since the ideal chain length is an integer, we want to calculate\n * ceil(n/b). We don't depend on floating point arithmetic in this\n * hash, so to calculate ceil(n/b) with integers we could write\n *\n *      ceil(n/b) = (n/b) + ((n%b)?1:0)\n *\n * and in fact a previous version of this hash did just that.\n * But now we have improved things a bit by recognizing that b is\n * always a power of two. We keep its base 2 log handy (call it lb),\n * so now we can write this with a bit shift and logical AND:\n *\n *      ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)\n *\n */\n#define HASH_EXPAND_BUCKETS(hh,tbl,oomed)                                        \\\ndo {                                                                             \\\n  unsigned _he_bkt;                                                              \\\n  unsigned _he_bkt_i;                                                            \\\n  struct UT_hash_handle *_he_thh, *_he_hh_nxt;                                   \\\n  UT_hash_bucket *_he_new_buckets, *_he_newbkt;                                  \\\n  _he_new_buckets = (UT_hash_bucket*)uthash_malloc(                              \\\n           sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U);             \\\n  if (!_he_new_buckets) {                                                        \\\n    HASH_RECORD_OOM(oomed);                                                      \\\n  } else {                                                                       \\\n    uthash_bzero(_he_new_buckets,                                                \\\n        sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U);                \\\n    (tbl)->ideal_chain_maxlen =                                                  \\\n       ((tbl)->num_items >> ((tbl)->log2_num_buckets+1U)) +                      \\\n       ((((tbl)->num_items & (((tbl)->num_buckets*2U)-1U)) != 0U) ? 1U : 0U);    \\\n    (tbl)->nonideal_items = 0;                                                   \\\n    for (_he_bkt_i = 0; _he_bkt_i < (tbl)->num_buckets; _he_bkt_i++) {           \\\n      _he_thh = (tbl)->buckets[ _he_bkt_i ].hh_head;                             \\\n      while (_he_thh != NULL) {                                                  \\\n        _he_hh_nxt = _he_thh->hh_next;                                           \\\n        HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt);           \\\n        _he_newbkt = &(_he_new_buckets[_he_bkt]);                                \\\n        if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) {                 \\\n          (tbl)->nonideal_items++;                                               \\\n          if (_he_newbkt->count > _he_newbkt->expand_mult * (tbl)->ideal_chain_maxlen) { \\\n            _he_newbkt->expand_mult++;                                           \\\n          }                                                                      \\\n        }                                                                        \\\n        _he_thh->hh_prev = NULL;                                                 \\\n        _he_thh->hh_next = _he_newbkt->hh_head;                                  \\\n        if (_he_newbkt->hh_head != NULL) {                                       \\\n          _he_newbkt->hh_head->hh_prev = _he_thh;                                \\\n        }                                                                        \\\n        _he_newbkt->hh_head = _he_thh;                                           \\\n        _he_thh = _he_hh_nxt;                                                    \\\n      }                                                                          \\\n    }                                                                            \\\n    uthash_free((tbl)->buckets, (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \\\n    (tbl)->num_buckets *= 2U;                                                    \\\n    (tbl)->log2_num_buckets++;                                                   \\\n    (tbl)->buckets = _he_new_buckets;                                            \\\n    (tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ?   \\\n        ((tbl)->ineff_expands+1U) : 0U;                                          \\\n    if ((tbl)->ineff_expands > 1U) {                                             \\\n      (tbl)->noexpand = 1;                                                       \\\n      uthash_noexpand_fyi(tbl);                                                  \\\n    }                                                                            \\\n    uthash_expand_fyi(tbl);                                                      \\\n  }                                                                              \\\n} while (0)\n\n\n/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */\n/* Note that HASH_SORT assumes the hash handle name to be hh.\n * HASH_SRT was added to allow the hash handle name to be passed in. */\n#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)\n#define HASH_SRT(hh,head,cmpfcn)                                                 \\\ndo {                                                                             \\\n  unsigned _hs_i;                                                                \\\n  unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize;               \\\n  struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail;            \\\n  if (head != NULL) {                                                            \\\n    _hs_insize = 1;                                                              \\\n    _hs_looping = 1;                                                             \\\n    _hs_list = &((head)->hh);                                                    \\\n    while (_hs_looping != 0U) {                                                  \\\n      _hs_p = _hs_list;                                                          \\\n      _hs_list = NULL;                                                           \\\n      _hs_tail = NULL;                                                           \\\n      _hs_nmerges = 0;                                                           \\\n      while (_hs_p != NULL) {                                                    \\\n        _hs_nmerges++;                                                           \\\n        _hs_q = _hs_p;                                                           \\\n        _hs_psize = 0;                                                           \\\n        for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) {                           \\\n          _hs_psize++;                                                           \\\n          _hs_q = ((_hs_q->next != NULL) ?                                       \\\n            HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL);                   \\\n          if (_hs_q == NULL) {                                                   \\\n            break;                                                               \\\n          }                                                                      \\\n        }                                                                        \\\n        _hs_qsize = _hs_insize;                                                  \\\n        while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) {    \\\n          if (_hs_psize == 0U) {                                                 \\\n            _hs_e = _hs_q;                                                       \\\n            _hs_q = ((_hs_q->next != NULL) ?                                     \\\n              HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL);                 \\\n            _hs_qsize--;                                                         \\\n          } else if ((_hs_qsize == 0U) || (_hs_q == NULL)) {                     \\\n            _hs_e = _hs_p;                                                       \\\n            if (_hs_p != NULL) {                                                 \\\n              _hs_p = ((_hs_p->next != NULL) ?                                   \\\n                HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL);               \\\n            }                                                                    \\\n            _hs_psize--;                                                         \\\n          } else if ((cmpfcn(                                                    \\\n                DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_p)),             \\\n                DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_q))              \\\n                )) <= 0) {                                                       \\\n            _hs_e = _hs_p;                                                       \\\n            if (_hs_p != NULL) {                                                 \\\n              _hs_p = ((_hs_p->next != NULL) ?                                   \\\n                HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL);               \\\n            }                                                                    \\\n            _hs_psize--;                                                         \\\n          } else {                                                               \\\n            _hs_e = _hs_q;                                                       \\\n            _hs_q = ((_hs_q->next != NULL) ?                                     \\\n              HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL);                 \\\n            _hs_qsize--;                                                         \\\n          }                                                                      \\\n          if ( _hs_tail != NULL ) {                                              \\\n            _hs_tail->next = ((_hs_e != NULL) ?                                  \\\n              ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL);                       \\\n          } else {                                                               \\\n            _hs_list = _hs_e;                                                    \\\n          }                                                                      \\\n          if (_hs_e != NULL) {                                                   \\\n            _hs_e->prev = ((_hs_tail != NULL) ?                                  \\\n              ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL);                    \\\n          }                                                                      \\\n          _hs_tail = _hs_e;                                                      \\\n        }                                                                        \\\n        _hs_p = _hs_q;                                                           \\\n      }                                                                          \\\n      if (_hs_tail != NULL) {                                                    \\\n        _hs_tail->next = NULL;                                                   \\\n      }                                                                          \\\n      if (_hs_nmerges <= 1U) {                                                   \\\n        _hs_looping = 0;                                                         \\\n        (head)->hh.tbl->tail = _hs_tail;                                         \\\n        DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list));           \\\n      }                                                                          \\\n      _hs_insize *= 2U;                                                          \\\n    }                                                                            \\\n    HASH_FSCK(hh, head, \"HASH_SRT\");                                             \\\n  }                                                                              \\\n} while (0)\n\n/* This function selects items from one hash into another hash.\n * The end result is that the selected items have dual presence\n * in both hashes. There is no copy of the items made; rather\n * they are added into the new hash through a secondary hash\n * hash handle that must be present in the structure. */\n#define HASH_SELECT(hh_dst, dst, hh_src, src, cond)                              \\\ndo {                                                                             \\\n  unsigned _src_bkt, _dst_bkt;                                                   \\\n  void *_last_elt = NULL, *_elt;                                                 \\\n  UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL;                         \\\n  ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst));                 \\\n  if ((src) != NULL) {                                                           \\\n    for (_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) {    \\\n      for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head;               \\\n        _src_hh != NULL;                                                         \\\n        _src_hh = _src_hh->hh_next) {                                            \\\n        _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh);                         \\\n        if (cond(_elt)) {                                                        \\\n          IF_HASH_NONFATAL_OOM( int _hs_oomed = 0; )                             \\\n          _dst_hh = (UT_hash_handle*)(void*)(((char*)_elt) + _dst_hho);          \\\n          _dst_hh->key = _src_hh->key;                                           \\\n          _dst_hh->keylen = _src_hh->keylen;                                     \\\n          _dst_hh->hashv = _src_hh->hashv;                                       \\\n          _dst_hh->prev = _last_elt;                                             \\\n          _dst_hh->next = NULL;                                                  \\\n          if (_last_elt_hh != NULL) {                                            \\\n            _last_elt_hh->next = _elt;                                           \\\n          }                                                                      \\\n          if ((dst) == NULL) {                                                   \\\n            DECLTYPE_ASSIGN(dst, _elt);                                          \\\n            HASH_MAKE_TABLE(hh_dst, dst, _hs_oomed);                             \\\n            IF_HASH_NONFATAL_OOM(                                                \\\n              if (_hs_oomed) {                                                   \\\n                uthash_nonfatal_oom(_elt);                                       \\\n                (dst) = NULL;                                                    \\\n                continue;                                                        \\\n              }                                                                  \\\n            )                                                                    \\\n          } else {                                                               \\\n            _dst_hh->tbl = (dst)->hh_dst.tbl;                                    \\\n          }                                                                      \\\n          HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt);      \\\n          HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], hh_dst, _dst_hh, _hs_oomed); \\\n          (dst)->hh_dst.tbl->num_items++;                                        \\\n          IF_HASH_NONFATAL_OOM(                                                  \\\n            if (_hs_oomed) {                                                     \\\n              HASH_ROLLBACK_BKT(hh_dst, dst, _dst_hh);                           \\\n              HASH_DELETE_HH(hh_dst, dst, _dst_hh);                              \\\n              _dst_hh->tbl = NULL;                                               \\\n              uthash_nonfatal_oom(_elt);                                         \\\n              continue;                                                          \\\n            }                                                                    \\\n          )                                                                      \\\n          HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv);                          \\\n          _last_elt = _elt;                                                      \\\n          _last_elt_hh = _dst_hh;                                                \\\n        }                                                                        \\\n      }                                                                          \\\n    }                                                                            \\\n  }                                                                              \\\n  HASH_FSCK(hh_dst, dst, \"HASH_SELECT\");                                         \\\n} while (0)\n\n#define HASH_CLEAR(hh,head)                                                      \\\ndo {                                                                             \\\n  if ((head) != NULL) {                                                          \\\n    HASH_BLOOM_FREE((head)->hh.tbl);                                             \\\n    uthash_free((head)->hh.tbl->buckets,                                         \\\n                (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket));      \\\n    uthash_free((head)->hh.tbl, sizeof(UT_hash_table));                          \\\n    (head) = NULL;                                                               \\\n  }                                                                              \\\n} while (0)\n\n#define HASH_OVERHEAD(hh,head)                                                   \\\n (((head) != NULL) ? (                                                           \\\n (size_t)(((head)->hh.tbl->num_items   * sizeof(UT_hash_handle))   +             \\\n          ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket))   +             \\\n           sizeof(UT_hash_table)                                   +             \\\n           (HASH_BLOOM_BYTELEN))) : 0U)\n\n#ifdef NO_DECLTYPE\n#define HASH_ITER(hh,head,el,tmp)                                                \\\nfor(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \\\n  (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL)))\n#else\n#define HASH_ITER(hh,head,el,tmp)                                                \\\nfor(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL));      \\\n  (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL)))\n#endif\n\n/* obtain a count of items in the hash */\n#define HASH_COUNT(head) HASH_CNT(hh,head)\n#define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U)\n\ntypedef struct UT_hash_bucket {\n   struct UT_hash_handle *hh_head;\n   unsigned count;\n\n   /* expand_mult is normally set to 0. In this situation, the max chain length\n    * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If\n    * the bucket's chain exceeds this length, bucket expansion is triggered).\n    * However, setting expand_mult to a non-zero value delays bucket expansion\n    * (that would be triggered by additions to this particular bucket)\n    * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.\n    * (The multiplier is simply expand_mult+1). The whole idea of this\n    * multiplier is to reduce bucket expansions, since they are expensive, in\n    * situations where we know that a particular bucket tends to be overused.\n    * It is better to let its chain length grow to a longer yet-still-bounded\n    * value, than to do an O(n) bucket expansion too often.\n    */\n   unsigned expand_mult;\n\n} UT_hash_bucket;\n\n/* random signature used only to find hash tables in external analysis */\n#define HASH_SIGNATURE 0xa0111fe1u\n#define HASH_BLOOM_SIGNATURE 0xb12220f2u\n\ntypedef struct UT_hash_table {\n   UT_hash_bucket *buckets;\n   unsigned num_buckets, log2_num_buckets;\n   unsigned num_items;\n   struct UT_hash_handle *tail; /* tail hh in app order, for fast append    */\n   ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */\n\n   /* in an ideal situation (all buckets used equally), no bucket would have\n    * more than ceil(#items/#buckets) items. that's the ideal chain length. */\n   unsigned ideal_chain_maxlen;\n\n   /* nonideal_items is the number of items in the hash whose chain position\n    * exceeds the ideal chain maxlen. these items pay the penalty for an uneven\n    * hash distribution; reaching them in a chain traversal takes >ideal steps */\n   unsigned nonideal_items;\n\n   /* ineffective expands occur when a bucket doubling was performed, but\n    * afterward, more than half the items in the hash had nonideal chain\n    * positions. If this happens on two consecutive expansions we inhibit any\n    * further expansion, as it's not helping; this happens when the hash\n    * function isn't a good fit for the key domain. When expansion is inhibited\n    * the hash will still work, albeit no longer in constant time. */\n   unsigned ineff_expands, noexpand;\n\n   uint32_t signature; /* used only to find hash tables in external analysis */\n#ifdef HASH_BLOOM\n   uint32_t bloom_sig; /* used only to test bloom exists in external analysis */\n   uint8_t *bloom_bv;\n   uint8_t bloom_nbits;\n#endif\n\n} UT_hash_table;\n\ntypedef struct UT_hash_handle {\n   struct UT_hash_table *tbl;\n   void *prev;                       /* prev element in app order      */\n   void *next;                       /* next element in app order      */\n   struct UT_hash_handle *hh_prev;   /* previous hh in bucket order    */\n   struct UT_hash_handle *hh_next;   /* next hh in bucket order        */\n   const void *key;                  /* ptr to enclosing struct's key  */\n   unsigned keylen;                  /* enclosing struct's key len     */\n   unsigned hashv;                   /* result of hash-fcn(key)        */\n} UT_hash_handle;\n\n#endif /* UTHASH_H */\n"
  },
  {
    "path": "manpage/nvtop.in",
    "content": ".\\\" Manpage for nvtop\n.\\\" Contact maxime.schmitt91@gmail.com\n\n.TH nvtop 1 \"@TODAY_MANPAGE@\" \"Version @nvtop_VERSION_MAJOR@.@nvtop_VERSION_MINOR@.@nvtop_VERSION_PATCH@\" \"nvtop command\"\n\n.SH NAME\nnvtop \\- interactive GPU process viewer\n\n.SH SYNOPSIS\n.B nvtop\n\\fR[\\fB\\-hvCfpPris\\fR]\n\\fR[\\fB\\-d\\fR \\fIdelay\\fR]\n\\fR[\\fB\\-c\\fR \\fIconfig-file\\fR]\n\\fR[\\fB\\-E\\fR \\fIseconds\\fR]\n\n.SH DESCRIPTION\nnvtop is a ncurses\\-based GPU status viewer for AMD, Intel and NVIDIA GPUs.\n\n.SH COMMAND\\-LINE OPTIONS\n.TP\n.BR \\-d \", \" \\-\\-delay =\\fIdelay\\fR\nDelay between updates, in tenths of seconds (\\fIdelay\\fR * 0.1s).\n.TP\n.BR \\-h \", \" \\-\\-help\nPrint the help and exit.\n.TP\n.BR \\-C \", \" \\-\\-no\\-color\nMonochrome mode.\n.TP\n.BR \\-f \", \" \\-\\-freedom\\-unit\nUse fahrenheit as temperature scale.\n.TP\n.BR \\-E \", \" \\-\\-encode\\-hide =\\fIseconds\\fR\nModify the setting for the encode/decode auto-hide timer. Always visible if negative. Default to 30 seconds.\n.TP\n.BR \\-r \", \" \\-\\-reverse\\-abs\nReverse abscissa: switch the plot data order from \"old --- recent\" (default) to \"recent --- old\".\n.TP\n.BR \\-p \", \" \\-\\-no\\-plot\nShow only one bar plot corresponding to the maximum of all GPUs.\n.TP\n.BR \\-v \", \" \\-\\-version\nPrint the version and exit.\n\n.SH INTERACTIVE SETUP WINDOW\n.TP\nYou can enter the setup utility by pressing \\fBF2\\fR to view and modify the following interface options:\n.TP\n.I General\nThis section deals with general interface options. \\fBColor support\\fR and \\fBinterface update interval\\fR can be modified.\n.TP\n.I Devices\nThis section deals with the devices display (top of the interface). You can \\fBswitch the temperature scale to fahrenheit\\fR and \\fBset the encoder/decoder hiding timer\\fR.\n.TP\n.I Chart\nThis section deals with the line plots (middle of the interface). You can \\fBreverse the plot direction\\fR and \\fBselect which metric is being shown in the plots\\fR.\n.TP\n.I Processes\nThis section deals with the process list (bottom of the interface). You can \\fBselect the sort order\\fR, \\fBselect the metric by which to sort the processes by\\fR and \\fBselect which metric is displayed\\fR.\n\n.SH INTERACTIVE COMMANDS\n.TP\nThe following commands are available while in nvtop:\n.TP\n.BR Up\nSelect (highlight) the previous process.\n.TP\n.BR Down\nSelect (highlight) the next process.\n.TP\n.BR Left\\ /\\ Right\nScroll in the process row.\n.TP\n.BR +\nSort increasingly.\n.TP\n.BR -\nSort decreasingly.\n.TP\n.BR F2\nEnter the setup utility to modify the interface options.\n.TP\n.BR F12\nSave the current interface options to persistent storage.\nSee the \\fBCONFIGURATION FILE\\fR section.\n.TP\n.BR F9\n\"Kill\" process: Select a signal to send to the highlighted process.\n.TP\n.BR F6\nSort: Select the field for sorting. The current sort field is highlighted inside the header bar.\n.TP\n.BR F10 \", \" q \", \" Esc\nQuit.\n\n.SH DYNAMIC METERS\n.TP\nWhen the video encoder (ENC) and decoder (DEC) of the GPU are in use, new percentage meters will appear next to the GPU utilization bar. They will disappear automatically after some time of inactivity (see option -E).\n\n.SH CONFIGURATION FILE\n.LP\nThe configuration file follows the \\fIXDG Base Directory Specification\\fR and is stored at \\fI$XDG_CONFIG_HOME/nvtop/interface.ini\\fR. The location defaults to \\fI$HOME/.config/nvtop/interface.ini\\fR if the XDG location is not defined.\n.LP\nDo not edit this file. The file is automatically created or updated upon toggling the interface saving key \\fBF12\\fR.\n.LP\nThe configuration is loaded during program initialization.\nIf no configuration file is present, default options are used.\n\n.SH MEMORY SIZES\n.TP\nMemory sizes in nvtop are displayed as multiples of 1024 bytes or 1 KiB.\n\n.SH BUGS\n.TP\n.BR \"Some fields are shown as N/A\"\nAsk AMD or NVIDIA for better support of your hardware!\n\nIf your card uses the AMDGPU driver, a more recent kernel might have improved support.\n.TP\n.BR \"Compatibility issues\"\nDoes not work with nouveau driver stack and older NVIDIA GPU for the time being.\n\nDoes not work for AMD graphics card using the old radeon driver.\n.SH AUTHOR\nWritten by Maxime Schmitt.\n"
  },
  {
    "path": "snap/snapcraft.yaml",
    "content": "name: nvtop\nbase: core22\nadopt-info: nvtop\nsummary: 'GPUs monitoring tool for AMD, Intel and NVIDIA'\ndescription: |\n  Nvtop stands for Neat Videocard TOP, a (h)top like task monitor for AMD, Intel and NVIDIA GPUs. It can handle multiple GPUs and print information about them in a htop familiar way.\nlicense: GPL-3.0-or-later\nissues: https://github.com/Syllo/nvtop/issues\nicon: desktop/nvtop.svg\ngrade: stable\nconfinement: strict\narchitectures:\n- build-on: amd64\n- build-on: arm64\n- build-on: armhf\n- build-on: ppc64el\n- build-on: s390x\ncompression: lzo\napps:\n  nvtop:\n    command: usr/bin/nvtop\n    desktop: usr/share/applications/nvtop.desktop\n    plugs:\n    - opengl\n    - home\n    - hardware-observe\n    - process-control\n    - system-observe\n    # - kubernetes-support # Temporarily required for nvtop to display AMD GPU processes. Once apparmor rule to allow access to @{PROC}/[0-9]*/fdinfo/ is added to system-observe, this can be removed.\n# layout:\n#   /usr/share/libdrm:\n#     symlink: $SNAP/usr/share/libdrm\nparts:\n  libdrm:\n    source: https://gitlab.freedesktop.org/mesa/drm.git\n    source-tag: libdrm-2.4.113\n    plugin: meson\n    meson-parameters:\n    - --prefix=/usr\n    - --sysconfdir=/etc\n    - --libdir=lib/$CRAFT_ARCH_TRIPLET\n    - -Dradeon=enabled\n    - -Damdgpu=enabled\n    - -Dudev=true\n    - -Dnouveau=enabled\n    - -Dintel=enabled\n    build-packages:\n    - meson\n    - pkg-config\n    - libudev-dev\n    - libpciaccess-dev\n    stage-packages:\n    - libpciaccess0\n    prime:\n    - -usr/include\n    - -usr/lib/$CRAFT_ARCH_TRIPLET/pkgconfig\n  nvtop:\n    after: [ libdrm ]\n    source: .\n    plugin: cmake\n    cmake-parameters:\n    - -DCMAKE_INSTALL_PREFIX=/usr\n    - -DNVIDIA_SUPPORT=ON\n    - -DAMDGPU_SUPPORT=ON\n    - -DINTEL_SUPPORT=ON\n    override-pull: |\n      set -eux\n      craftctl default\n      VERSION=\"$(git describe --tags $(git rev-list --tags --max-count=1))\"\n      craftctl set version=$VERSION\n      git checkout $VERSION\n    build-snaps:\n    - cmake\n    build-packages:\n    - gcc\n    - libncurses-dev\n    - libsystemd-dev\n    stage-packages:\n    - libncurses6\n    - libncursesw6\n    - libsystemd0\n    prime:\n    - -usr/share/doc\n"
  },
  {
    "path": "src/CMakeLists.txt",
    "content": "include(CheckCSourceCompiles)\n\nconfigure_file(\n  \"${PROJECT_SOURCE_DIR}/include/nvtop/version.h.in\"\n  \"${PROJECT_BINARY_DIR}/include/nvtop/version.h\"\n  IMMEDIATE @ONLY)\n\nadd_executable(nvtop\n  nvtop.c\n  interface.c\n  interface_layout_selection.c\n  interface_options.c\n  interface_setup_win.c\n  interface_ring_buffer.c\n  extract_gpuinfo.c\n  time.c\n  plot.c\n  ini.c\n)\n\ncheck_c_source_compiles(\n  \"\n  #include <stdlib.h>\n  int main() {\n    int *buf = NULL;\n    buf = reallocarray(buf, 15, sizeof(*buf));\n    return EXIT_SUCCESS;\n  }\n  \"\n  HAS_REALLOCARRAY\n)\n\nif(HAS_REALLOCARRAY)\n  target_compile_definitions(nvtop PRIVATE HAS_REALLOCARRAY)\nendif()\n\nfind_package(UDev)\nfind_package(Systemd)\noption(USE_LIBUDEV_OVER_LIBSYSTEMD \"Use libudev, even if libsystemd is present\" OFF)\n\nif(UNIX AND NOT APPLE)\n  target_sources(nvtop PRIVATE\n    get_process_info_linux.c\n    extract_processinfo_fdinfo.c\n    info_messages_linux.c)\nelseif(APPLE)\n  target_sources(nvtop PRIVATE\n    get_process_info_mac.c\n    extract_processinfo_mac.c\n    info_messages_mac.c)\nendif()\n\nif(NVIDIA_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_nvidia.c)\nendif()\n\nif(ASCEND_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_ascend.c)\n  set(DCMI_LIBRARY_PATH /usr/local/Ascend/driver/lib64/driver)\n  target_link_libraries(nvtop PRIVATE \"${DCMI_LIBRARY_PATH}/libdcmi.so\")\nendif()\n\nif(AMDGPU_SUPPORT OR INTEL_SUPPORT OR V3D_SUPPORT)\n  if((SYSTEMD_FOUND AND UDEV_FOUND AND USE_LIBUDEV_OVER_LIBSYSTEMD) OR(NOT SYSTEMD_FOUND AND UDEV_FOUND))\n    target_compile_definitions(nvtop PRIVATE USING_LIBUDEV)\n    target_link_libraries(nvtop PRIVATE udev)\n  elseif(SYSTEMD_FOUND)\n    target_compile_definitions(nvtop PRIVATE USING_LIBSYSTEMD)\n    target_link_libraries(nvtop PRIVATE systemd)\n  else()\n    message(FATAL_ERROR \"Neither libsystemd nor libudev were found; These are required for AMDGPU, INTEL and V3D support\")\n  endif()\n\n  target_sources(nvtop PRIVATE device_discovery_linux.c)\nendif()\n\nif(AMDGPU_SUPPORT OR INTEL_SUPPORT OR MSM_SUPPORT OR PANFROST_SUPPORT OR PANTHOR_SUPPORT)\n  # Search for libdrm for AMDGPU support\n  find_package(Libdrm)\n\n  if(Libdrm_FOUND)\n    message(STATUS \"Found libdrm; Enabling support\")\n    target_include_directories(nvtop PRIVATE ${Libdrm_INCLUDE_DIRS})\n  else()\n    message(FATAL_ERROR \"libdrm not found; This library is required for AMDGPU, INTEL, MSM, PANFROST and PANTHOR support\")\n    # CMake will exit if libdrm is not found\n  endif()\nendif()\n\nif (AMDGPU_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_amdgpu.c)\n  target_sources(nvtop PRIVATE extract_gpuinfo_amdgpu_utils.c)\nendif()\n\nif (MSM_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_msm.c)\n  target_sources(nvtop PRIVATE extract_gpuinfo_msm_utils.c)\nendif()\n\nif(INTEL_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_intel.c)\n  target_sources(nvtop PRIVATE extract_gpuinfo_intel_i915.c)\n  target_sources(nvtop PRIVATE extract_gpuinfo_intel_xe.c)\nendif()\n\nif(V3D_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_v3d.c)\n  target_sources(nvtop PRIVATE extract_gpuinfo_v3d_utils.c)\nendif()\n\nif(APPLE_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_apple.m)\n  target_link_libraries(nvtop PRIVATE\n    \"-framework Metal\"\n    \"-framework AppKit\"\n    \"-framework Foundation\"\n    \"-framework QuartzCore\"\n    \"-framework IOKit\")\nendif()\n\nif (PANFROST_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_panfrost.c)\n  target_sources(nvtop PRIVATE extract_gpuinfo_panfrost_utils.c)\nendif()\n\nif (PANTHOR_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_panthor.c)\n  target_sources(nvtop PRIVATE extract_gpuinfo_panthor_utils.c)\nendif()\n\nif ((PANFROST_SUPPORT) OR (PANTHOR_SUPPORT))\n  target_sources(nvtop PRIVATE extract_gpuinfo_mali_common.c)\nendif()\n\nif(TPU_SUPPORT)\n  find_library(LIBTPUINFO\n    NAMES libtpuinfo.so\n    PATHS /usr/lib /usr/lib64 /usr/local/lib /usr/local/lib64\n    HINTS ${CMAKE_INSTALL_PREFIX}/lib ${CMAKE_INSTALL_PREFIX}/lib64 lib lib64\n  )\n  if (NOT LIBTPUINFO)\n    message(WARNING \"TPU Support enabled, but libtpuinfo.so not found in ldconfig path, we will not be able to read TPU usage\")\n    set(TPU_SUPPORT_DEFAULT OFF)\n  endif()\n  target_sources(nvtop PRIVATE extract_gpuinfo_tpu.c)\nendif()\n\nif(ROCKCHIP_SUPPORT)\n  message(STATUS \"Building with Rockchip NPU support\")\n\n  target_sources(nvtop PRIVATE extract_npuinfo_rockchip.c)\nendif()\n\nif(METAX_SUPPORT)\n  target_sources(nvtop PRIVATE extract_gpuinfo_metax.c)\nendif()\n\nif(ENFLAME_SUPPORT)\n  message(STATUS \"Building with Enflame GCU support\")\n  target_sources(nvtop PRIVATE extract_gcuinfo_enflame.c)\nendif()\n\ntarget_include_directories(nvtop PRIVATE\n  ${PROJECT_SOURCE_DIR}/include\n  ${PROJECT_BINARY_DIR}/include)\n\nfind_package(Sanitizers)\n\nadd_sanitizers(nvtop)\n\nset_property(TARGET nvtop PROPERTY C_STANDARD 11)\n\ntarget_compile_definitions(nvtop PRIVATE _GNU_SOURCE)\n\ntarget_link_libraries(nvtop\n  PRIVATE ncurses m ${CMAKE_DL_LIBS})\n\ninstall(TARGETS nvtop\n  RUNTIME DESTINATION bin)\n\ninclude(compile-flags-helpers)\ninclude(${PROJECT_SOURCE_DIR}/cmake/optimization_flags.cmake)\n\nadd_compiler_option_to_target_type(nvtop Debug PRIVATE ${ADDITIONAL_DEBUG_COMPILE_OPTIONS})\nadd_linker_option_to_all_but_target_type(nvtop dummy PRIVATE ${ADDITIONAL_RELEASE_LINK_OPTIONS})\n"
  },
  {
    "path": "src/amdgpu_ids.h",
    "content": "\n/*\n * Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.\n *\n * This file is modified from libdrm. MIT License.\n *\n * URL: https://gitlab.freedesktop.org/mesa/drm/-/blob/main/data/amdgpu.ids\n * The amdgpu_ids has to be modified after new GPU release.\n *\n */\n\n#ifndef AMDGPU_IDS_H\n#define AMDGPU_IDS_H\n\nstruct amdgpu_id_struct {\n    uint32_t asic_id;\n    uint32_t pci_rev_id;\n    const char *name;\n};\n\nstatic struct amdgpu_id_struct amdgpu_ids[] = {\n    {0x1309, 0x00, \"AMD Radeon R7 Graphics\"},\n    {0x130A, 0x00, \"AMD Radeon R6 Graphics\"},\n    {0x130B, 0x00, \"AMD Radeon R4 Graphics\"},\n    {0x130C, 0x00, \"AMD Radeon R7 Graphics\"},\n    {0x130D, 0x00, \"AMD Radeon R6 Graphics\"},\n    {0x130E, 0x00, \"AMD Radeon R5 Graphics\"},\n    {0x130F, 0x00, \"AMD Radeon R7 Graphics\"},\n    {0x130F, 0xD4, \"AMD Radeon R7 Graphics\"},\n    {0x130F, 0xD5, \"AMD Radeon R7 Graphics\"},\n    {0x130F, 0xD6, \"AMD Radeon R7 Graphics\"},\n    {0x130F, 0xD7, \"AMD Radeon R7 Graphics\"},\n    {0x1313, 0x00, \"AMD Radeon R7 Graphics\"},\n    {0x1313, 0xD4, \"AMD Radeon R7 Graphics\"},\n    {0x1313, 0xD5, \"AMD Radeon R7 Graphics\"},\n    {0x1313, 0xD6, \"AMD Radeon R7 Graphics\"},\n    {0x1315, 0x00, \"AMD Radeon R5 Graphics\"},\n    {0x1315, 0xD4, \"AMD Radeon R5 Graphics\"},\n    {0x1315, 0xD5, \"AMD Radeon R5 Graphics\"},\n    {0x1315, 0xD6, \"AMD Radeon R5 Graphics\"},\n    {0x1315, 0xD7, \"AMD Radeon R5 Graphics\"},\n    {0x1316, 0x00, \"AMD Radeon R5 Graphics\"},\n    {0x1318, 0x00, \"AMD Radeon R5 Graphics\"},\n    {0x131B, 0x00, \"AMD Radeon R4 Graphics\"},\n    {0x131C, 0x00, \"AMD Radeon R7 Graphics\"},\n    {0x131D, 0x00, \"AMD Radeon R6 Graphics\"},\n    {0x15D8, 0x00, \"AMD Radeon RX Vega 8 Graphics WS\"},\n    {0x15D8, 0x91, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0x91, \"AMD Ryzen Embedded R1606G with Radeon Vega Gfx\"},\n    {0x15D8, 0x92, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0x92, \"AMD Ryzen Embedded R1505G with Radeon Vega Gfx\"},\n    {0x15D8, 0x93, \"AMD Radeon Vega 1 Graphics\"},\n    {0x15D8, 0xA1, \"AMD Radeon Vega 10 Graphics\"},\n    {0x15D8, 0xA2, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xA3, \"AMD Radeon Vega 6 Graphics\"},\n    {0x15D8, 0xA4, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xB1, \"AMD Radeon Vega 10 Graphics\"},\n    {0x15D8, 0xB2, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xB3, \"AMD Radeon Vega 6 Graphics\"},\n    {0x15D8, 0xB4, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xC1, \"AMD Radeon Vega 10 Graphics\"},\n    {0x15D8, 0xC2, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xC3, \"AMD Radeon Vega 6 Graphics\"},\n    {0x15D8, 0xC4, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xC5, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xC8, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15D8, 0xC9, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xCA, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15D8, 0xCB, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xCC, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xCE, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xCF, \"AMD Ryzen Embedded R1305G with Radeon Vega Gfx\"},\n    {0x15D8, 0xD1, \"AMD Radeon Vega 10 Graphics\"},\n    {0x15D8, 0xD2, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xD3, \"AMD Radeon Vega 6 Graphics\"},\n    {0x15D8, 0xD4, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xD8, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15D8, 0xD9, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xDA, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15D8, 0xDB, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xDB, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15D8, 0xDC, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xDD, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xDE, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xDF, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xE3, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15D8, 0xE4, \"AMD Ryzen Embedded R1102G with Radeon Vega Gfx\"},\n    {0x15DD, 0x81, \"AMD Ryzen Embedded V1807B with Radeon Vega Gfx\"},\n    {0x15DD, 0x82, \"AMD Ryzen Embedded V1756B with Radeon Vega Gfx\"},\n    {0x15DD, 0x83, \"AMD Ryzen Embedded V1605B with Radeon Vega Gfx\"},\n    {0x15DD, 0x84, \"AMD Radeon Vega 6 Graphics\"},\n    {0x15DD, 0x85, \"AMD Ryzen Embedded V1202B with Radeon Vega Gfx\"},\n    {0x15DD, 0x86, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15DD, 0x88, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xC1, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15DD, 0xC2, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xC3, \"AMD Radeon Vega 3 / 10 Graphics\"},\n    {0x15DD, 0xC4, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xC5, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15DD, 0xC6, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15DD, 0xC8, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xC9, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15DD, 0xCA, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xCB, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15DD, 0xCC, \"AMD Radeon Vega 6 Graphics\"},\n    {0x15DD, 0xCE, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15DD, 0xCF, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15DD, 0xD0, \"AMD Radeon Vega 10 Graphics\"},\n    {0x15DD, 0xD1, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xD3, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15DD, 0xD5, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xD6, \"AMD Radeon Vega 11 Graphics\"},\n    {0x15DD, 0xD7, \"AMD Radeon Vega 8 Graphics\"},\n    {0x15DD, 0xD8, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15DD, 0xD9, \"AMD Radeon Vega 6 Graphics\"},\n    {0x15DD, 0xE1, \"AMD Radeon Vega 3 Graphics\"},\n    {0x15DD, 0xE2, \"AMD Radeon Vega 3 Graphics\"},\n    {0x163F, 0xAE, \"AMD Custom GPU 0405\"},\n    {0x6600, 0x00, \"AMD Radeon HD 8600 / 8700M\"},\n    {0x6600, 0x81, \"AMD Radeon R7 M370\"},\n    {0x6601, 0x00, \"AMD Radeon HD 8500M / 8700M\"},\n    {0x6604, 0x00, \"AMD Radeon R7 M265 Series\"},\n    {0x6604, 0x81, \"AMD Radeon R7 M350\"},\n    {0x6605, 0x00, \"AMD Radeon R7 M260 Series\"},\n    {0x6605, 0x81, \"AMD Radeon R7 M340\"},\n    {0x6606, 0x00, \"AMD Radeon HD 8790M\"},\n    {0x6607, 0x00, \"AMD Radeon R5 M240\"},\n    {0x6608, 0x00, \"AMD FirePro W2100\"},\n    {0x6610, 0x00, \"AMD Radeon R7 200 Series\"},\n    {0x6610, 0x81, \"AMD Radeon R7 350\"},\n    {0x6610, 0x83, \"AMD Radeon R5 340\"},\n    {0x6610, 0x87, \"AMD Radeon R7 200 Series\"},\n    {0x6611, 0x00, \"AMD Radeon R7 200 Series\"},\n    {0x6611, 0x87, \"AMD Radeon R7 200 Series\"},\n    {0x6613, 0x00, \"AMD Radeon R7 200 Series\"},\n    {0x6617, 0x00, \"AMD Radeon R7 240 Series\"},\n    {0x6617, 0x87, \"AMD Radeon R7 200 Series\"},\n    {0x6617, 0xC7, \"AMD Radeon R7 240 Series\"},\n    {0x6640, 0x00, \"AMD Radeon HD 8950\"},\n    {0x6640, 0x80, \"AMD Radeon R9 M380\"},\n    {0x6646, 0x00, \"AMD Radeon R9 M280X\"},\n    {0x6646, 0x80, \"AMD Radeon R9 M385\"},\n    {0x6646, 0x80, \"AMD Radeon R9 M470X\"},\n    {0x6647, 0x00, \"AMD Radeon R9 M200X Series\"},\n    {0x6647, 0x80, \"AMD Radeon R9 M380\"},\n    {0x6649, 0x00, \"AMD FirePro W5100\"},\n    {0x6658, 0x00, \"AMD Radeon R7 200 Series\"},\n    {0x665C, 0x00, \"AMD Radeon HD 7700 Series\"},\n    {0x665D, 0x00, \"AMD Radeon R7 200 Series\"},\n    {0x665F, 0x81, \"AMD Radeon R7 360 Series\"},\n    {0x6660, 0x00, \"AMD Radeon HD 8600M Series\"},\n    {0x6660, 0x81, \"AMD Radeon R5 M335\"},\n    {0x6660, 0x83, \"AMD Radeon R5 M330\"},\n    {0x6663, 0x00, \"AMD Radeon HD 8500M Series\"},\n    {0x6663, 0x83, \"AMD Radeon R5 M320\"},\n    {0x6664, 0x00, \"AMD Radeon R5 M200 Series\"},\n    {0x6665, 0x00, \"AMD Radeon R5 M230 Series\"},\n    {0x6665, 0x83, \"AMD Radeon R5 M320\"},\n    {0x6665, 0xC3, \"AMD Radeon R5 M435\"},\n    {0x6666, 0x00, \"AMD Radeon R5 M200 Series\"},\n    {0x6667, 0x00, \"AMD Radeon R5 M200 Series\"},\n    {0x666F, 0x00, \"AMD Radeon HD 8500M\"},\n    {0x66A1, 0x02, \"AMD Instinct MI60 / MI50\"},\n    {0x66A1, 0x06, \"AMD Radeon Pro VII\"},\n    {0x66AF, 0xC1, \"AMD Radeon VII\"},\n    {0x6780, 0x00, \"AMD FirePro W9000\"},\n    {0x6784, 0x00, \"ATI FirePro V (FireGL V) Graphics Adapter\"},\n    {0x6788, 0x00, \"ATI FirePro V (FireGL V) Graphics Adapter\"},\n    {0x678A, 0x00, \"AMD FirePro W8000\"},\n    {0x6798, 0x00, \"AMD Radeon R9 200 / HD 7900 Series\"},\n    {0x6799, 0x00, \"AMD Radeon HD 7900 Series\"},\n    {0x679A, 0x00, \"AMD Radeon HD 7900 Series\"},\n    {0x679B, 0x00, \"AMD Radeon HD 7900 Series\"},\n    {0x679E, 0x00, \"AMD Radeon HD 7800 Series\"},\n    {0x67A0, 0x00, \"AMD Radeon FirePro W9100\"},\n    {0x67A1, 0x00, \"AMD Radeon FirePro W8100\"},\n    {0x67B0, 0x00, \"AMD Radeon R9 200 Series\"},\n    {0x67B0, 0x80, \"AMD Radeon R9 390 Series\"},\n    {0x67B1, 0x00, \"AMD Radeon R9 200 Series\"},\n    {0x67B1, 0x80, \"AMD Radeon R9 390 Series\"},\n    {0x67B9, 0x00, \"AMD Radeon R9 200 Series\"},\n    {0x67C0, 0x00, \"AMD Radeon Pro WX 7100 Graphics\"},\n    {0x67C0, 0x80, \"AMD Radeon E9550\"},\n    {0x67C2, 0x01, \"AMD Radeon Pro V7350x2\"},\n    {0x67C2, 0x02, \"AMD Radeon Pro V7300X\"},\n    {0x67C4, 0x00, \"AMD Radeon Pro WX 7100 Graphics\"},\n    {0x67C4, 0x80, \"AMD Radeon E9560 / E9565 Graphics\"},\n    {0x67C7, 0x00, \"AMD Radeon Pro WX 5100 Graphics\"},\n    {0x67C7, 0x80, \"AMD Radeon E9390 Graphics\"},\n    {0x67D0, 0x01, \"AMD Radeon Pro V7350x2\"},\n    {0x67D0, 0x02, \"AMD Radeon Pro V7300X\"},\n    {0x67DF, 0xC0, \"AMD Radeon Pro 580X\"},\n    {0x67DF, 0xC1, \"AMD Radeon RX 580 Series\"},\n    {0x67DF, 0xC2, \"AMD Radeon RX 570 Series\"},\n    {0x67DF, 0xC3, \"AMD Radeon RX 580 Series\"},\n    {0x67DF, 0xC4, \"AMD Radeon RX 480 Graphics\"},\n    {0x67DF, 0xC5, \"AMD Radeon RX 470 Graphics\"},\n    {0x67DF, 0xC6, \"AMD Radeon RX 570 Series\"},\n    {0x67DF, 0xC7, \"AMD Radeon RX 480 Graphics\"},\n    {0x67DF, 0xCF, \"AMD Radeon RX 470 Graphics\"},\n    {0x67DF, 0xD7, \"AMD Radeon RX 470 Graphics\"},\n    {0x67DF, 0xE0, \"AMD Radeon RX 470 Series\"},\n    {0x67DF, 0xE1, \"AMD Radeon RX 590 Series\"},\n    {0x67DF, 0xE3, \"AMD Radeon RX Series\"},\n    {0x67DF, 0xE7, \"AMD Radeon RX 580 Series\"},\n    {0x67DF, 0xEB, \"AMD Radeon Pro 580X\"},\n    {0x67DF, 0xEF, \"AMD Radeon RX 570 Series\"},\n    {0x67DF, 0xF7, \"AMD Radeon RX P30PH\"},\n    {0x67DF, 0xFF, \"AMD Radeon RX 470 Series\"},\n    {0x67E0, 0x00, \"AMD Radeon Pro WX Series\"},\n    {0x67E3, 0x00, \"AMD Radeon Pro WX 4100\"},\n    {0x67E8, 0x00, \"AMD Radeon Pro WX Series\"},\n    {0x67E8, 0x01, \"AMD Radeon Pro WX Series\"},\n    {0x67E8, 0x80, \"AMD Radeon E9260 Graphics\"},\n    {0x67EB, 0x00, \"AMD Radeon Pro V5300X\"},\n    {0x67EF, 0xC0, \"AMD Radeon RX Graphics\"},\n    {0x67EF, 0xC1, \"AMD Radeon RX 460 Graphics\"},\n    {0x67EF, 0xC2, \"AMD Radeon Pro Series\"},\n    {0x67EF, 0xC3, \"AMD Radeon RX Series\"},\n    {0x67EF, 0xC5, \"AMD Radeon RX 460 Graphics\"},\n    {0x67EF, 0xC7, \"AMD Radeon RX Graphics\"},\n    {0x67EF, 0xCF, \"AMD Radeon RX 460 Graphics\"},\n    {0x67EF, 0xE0, \"AMD Radeon RX 560 Series\"},\n    {0x67EF, 0xE1, \"AMD Radeon RX Series\"},\n    {0x67EF, 0xE2, \"AMD Radeon RX 560X\"},\n    {0x67EF, 0xE3, \"AMD Radeon RX Series\"},\n    {0x67EF, 0xE5, \"AMD Radeon RX 560 Series\"},\n    {0x67EF, 0xE7, \"AMD Radeon RX 560 Series\"},\n    {0x67EF, 0xEF, \"AMD Radeon 550 Series\"},\n    {0x67EF, 0xFF, \"AMD Radeon RX 460 Graphics\"},\n    {0x67FF, 0xC0, \"AMD Radeon Pro 465\"},\n    {0x67FF, 0xC1, \"AMD Radeon RX 560 Series\"},\n    {0x67FF, 0xCF, \"AMD Radeon RX 560 Series\"},\n    {0x67FF, 0xEF, \"AMD Radeon RX 560 Series\"},\n    {0x67FF, 0xFF, \"AMD Radeon RX 550 Series\"},\n    {0x6800, 0x00, \"AMD Radeon HD 7970M\"},\n    {0x6801, 0x00, \"AMD Radeon HD 8970M\"},\n    {0x6806, 0x00, \"AMD Radeon R9 M290X\"},\n    {0x6808, 0x00, \"AMD FirePro W7000\"},\n    {0x6808, 0x00, \"ATI FirePro V (FireGL V) Graphics Adapter\"},\n    {0x6809, 0x00, \"ATI FirePro W5000\"},\n    {0x6810, 0x00, \"AMD Radeon R9 200 Series\"},\n    {0x6810, 0x81, \"AMD Radeon R9 370 Series\"},\n    {0x6811, 0x00, \"AMD Radeon R9 200 Series\"},\n    {0x6811, 0x81, \"AMD Radeon R7 370 Series\"},\n    {0x6818, 0x00, \"AMD Radeon HD 7800 Series\"},\n    {0x6819, 0x00, \"AMD Radeon HD 7800 Series\"},\n    {0x6820, 0x00, \"AMD Radeon R9 M275X\"},\n    {0x6820, 0x81, \"AMD Radeon R9 M375\"},\n    {0x6820, 0x83, \"AMD Radeon R9 M375X\"},\n    {0x6821, 0x00, \"AMD Radeon R9 M200X Series\"},\n    {0x6821, 0x83, \"AMD Radeon R9 M370X\"},\n    {0x6821, 0x87, \"AMD Radeon R7 M380\"},\n    {0x6822, 0x00, \"AMD Radeon E8860\"},\n    {0x6823, 0x00, \"AMD Radeon R9 M200X Series\"},\n    {0x6825, 0x00, \"AMD Radeon HD 7800M Series\"},\n    {0x6826, 0x00, \"AMD Radeon HD 7700M Series\"},\n    {0x6827, 0x00, \"AMD Radeon HD 7800M Series\"},\n    {0x6828, 0x00, \"AMD FirePro W600\"},\n    {0x682B, 0x00, \"AMD Radeon HD 8800M Series\"},\n    {0x682B, 0x87, \"AMD Radeon R9 M360\"},\n    {0x682C, 0x00, \"AMD FirePro W4100\"},\n    {0x682D, 0x00, \"AMD Radeon HD 7700M Series\"},\n    {0x682F, 0x00, \"AMD Radeon HD 7700M Series\"},\n    {0x6830, 0x00, \"AMD Radeon 7800M Series\"},\n    {0x6831, 0x00, \"AMD Radeon 7700M Series\"},\n    {0x6835, 0x00, \"AMD Radeon R7 Series / HD 9000 Series\"},\n    {0x6837, 0x00, \"AMD Radeon HD 7700 Series\"},\n    {0x683D, 0x00, \"AMD Radeon HD 7700 Series\"},\n    {0x683F, 0x00, \"AMD Radeon HD 7700 Series\"},\n    {0x684C, 0x00, \"ATI FirePro V (FireGL V) Graphics Adapter\"},\n    {0x6860, 0x00, \"AMD Radeon Instinct MI25\"},\n    {0x6860, 0x01, \"AMD Radeon Instinct MI25\"},\n    {0x6860, 0x02, \"AMD Radeon Instinct MI25\"},\n    {0x6860, 0x03, \"AMD Radeon Pro V340\"},\n    {0x6860, 0x04, \"AMD Radeon Instinct MI25x2\"},\n    {0x6860, 0x07, \"AMD Radeon Pro V320\"},\n    {0x6861, 0x00, \"AMD Radeon Pro WX 9100\"},\n    {0x6862, 0x00, \"AMD Radeon Pro SSG\"},\n    {0x6863, 0x00, \"AMD Radeon Vega Frontier Edition\"},\n    {0x6864, 0x03, \"AMD Radeon Pro V340\"},\n    {0x6864, 0x04, \"AMD Radeon Instinct MI25x2\"},\n    {0x6864, 0x05, \"AMD Radeon Pro V340\"},\n    {0x6868, 0x00, \"AMD Radeon Pro WX 8200\"},\n    {0x686C, 0x00, \"AMD Radeon Instinct MI25 MxGPU\"},\n    {0x686C, 0x01, \"AMD Radeon Instinct MI25 MxGPU\"},\n    {0x686C, 0x02, \"AMD Radeon Instinct MI25 MxGPU\"},\n    {0x686C, 0x03, \"AMD Radeon Pro V340 MxGPU\"},\n    {0x686C, 0x04, \"AMD Radeon Instinct MI25x2 MxGPU\"},\n    {0x686C, 0x05, \"AMD Radeon Pro V340L MxGPU\"},\n    {0x686C, 0x06, \"AMD Radeon Instinct MI25 MxGPU\"},\n    {0x687F, 0x01, \"AMD Radeon RX Vega\"},\n    {0x687F, 0xC0, \"AMD Radeon RX Vega\"},\n    {0x687F, 0xC1, \"AMD Radeon RX Vega\"},\n    {0x687F, 0xC3, \"AMD Radeon RX Vega\"},\n    {0x687F, 0xC7, \"AMD Radeon RX Vega\"},\n    {0x6900, 0x00, \"AMD Radeon R7 M260\"},\n    {0x6900, 0x81, \"AMD Radeon R7 M360\"},\n    {0x6900, 0x83, \"AMD Radeon R7 M340\"},\n    {0x6900, 0xC1, \"AMD Radeon R5 M465 Series\"},\n    {0x6900, 0xC3, \"AMD Radeon R5 M445 Series\"},\n    {0x6900, 0xD1, \"AMD Radeon 530 Series\"},\n    {0x6900, 0xD3, \"AMD Radeon 530 Series\"},\n    {0x6901, 0x00, \"AMD Radeon R5 M255\"},\n    {0x6902, 0x00, \"AMD Radeon Series\"},\n    {0x6907, 0x00, \"AMD Radeon R5 M255\"},\n    {0x6907, 0x87, \"AMD Radeon R5 M315\"},\n    {0x6920, 0x00, \"AMD Radeon R9 M395X\"},\n    {0x6920, 0x01, \"AMD Radeon R9 M390X\"},\n    {0x6921, 0x00, \"AMD Radeon R9 M390X\"},\n    {0x6929, 0x00, \"AMD FirePro S7150\"},\n    {0x6929, 0x01, \"AMD FirePro S7100X\"},\n    {0x692B, 0x00, \"AMD FirePro W7100\"},\n    {0x6938, 0x00, \"AMD Radeon R9 200 Series\"},\n    {0x6938, 0xF0, \"AMD Radeon R9 200 Series\"},\n    {0x6938, 0xF1, \"AMD Radeon R9 380 Series\"},\n    {0x6939, 0x00, \"AMD Radeon R9 200 Series\"},\n    {0x6939, 0xF0, \"AMD Radeon R9 200 Series\"},\n    {0x6939, 0xF1, \"AMD Radeon R9 380 Series\"},\n    {0x694C, 0xC0, \"AMD Radeon RX Vega M GH Graphics\"},\n    {0x694E, 0xC0, \"AMD Radeon RX Vega M GL Graphics\"},\n    {0x6980, 0x00, \"AMD Radeon Pro WX 3100\"},\n    {0x6981, 0x00, \"AMD Radeon Pro WX 3200 Series\"},\n    {0x6981, 0x01, \"AMD Radeon Pro WX 3200 Series\"},\n    {0x6981, 0x10, \"AMD Radeon Pro WX 3200 Series\"},\n    {0x6985, 0x00, \"AMD Radeon Pro WX 3100\"},\n    {0x6986, 0x00, \"AMD Radeon Pro WX 2100\"},\n    {0x6987, 0x80, \"AMD Embedded Radeon E9171\"},\n    {0x6987, 0xC0, \"AMD Radeon 550X Series\"},\n    {0x6987, 0xC1, \"AMD Radeon RX 640\"},\n    {0x6987, 0xC3, \"AMD Radeon 540X Series\"},\n    {0x6987, 0xC7, \"AMD Radeon 540\"},\n    {0x6995, 0x00, \"AMD Radeon Pro WX 2100\"},\n    {0x6997, 0x00, \"AMD Radeon Pro WX 2100\"},\n    {0x699F, 0x81, \"AMD Embedded Radeon E9170 Series\"},\n    {0x699F, 0xC0, \"AMD Radeon 500 Series\"},\n    {0x699F, 0xC1, \"AMD Radeon 540 Series\"},\n    {0x699F, 0xC3, \"AMD Radeon 500 Series\"},\n    {0x699F, 0xC7, \"AMD Radeon RX 550 / 550 Series\"},\n    {0x699F, 0xC9, \"AMD Radeon 540\"},\n    {0x6FDF, 0xE7, \"AMD Radeon RX 590 GME\"},\n    {0x6FDF, 0xEF, \"AMD Radeon RX 580 2048SP\"},\n    {0x7300, 0xC1, \"AMD FirePro S9300 x2\"},\n    {0x7300, 0xC8, \"AMD Radeon R9 Fury Series\"},\n    {0x7300, 0xC9, \"AMD Radeon Pro Duo\"},\n    {0x7300, 0xCA, \"AMD Radeon R9 Fury Series\"},\n    {0x7300, 0xCB, \"AMD Radeon R9 Fury Series\"},\n    {0x7312, 0x00, \"AMD Radeon Pro W5700\"},\n    {0x731E, 0xC6, \"AMD Radeon RX 5700XTB\"},\n    {0x731E, 0xC7, \"AMD Radeon RX 5700B\"},\n    {0x731F, 0xC0, \"AMD Radeon RX 5700 XT 50th Anniversary\"},\n    {0x731F, 0xC1, \"AMD Radeon RX 5700 XT\"},\n    {0x731F, 0xC2, \"AMD Radeon RX 5600M\"},\n    {0x731F, 0xC3, \"AMD Radeon RX 5700M\"},\n    {0x731F, 0xC4, \"AMD Radeon RX 5700\"},\n    {0x731F, 0xC5, \"AMD Radeon RX 5700 XT\"},\n    {0x731F, 0xCA, \"AMD Radeon RX 5600 XT\"},\n    {0x731F, 0xCB, \"AMD Radeon RX 5600 OEM\"},\n    {0x7340, 0xC1, \"AMD Radeon RX 5500M\"},\n    {0x7340, 0xC3, \"AMD Radeon RX 5300M\"},\n    {0x7340, 0xC5, \"AMD Radeon RX 5500 XT\"},\n    {0x7340, 0xC7, \"AMD Radeon RX 5500\"},\n    {0x7340, 0xC9, \"AMD Radeon RX 5500XTB\"},\n    {0x7340, 0xCF, \"AMD Radeon RX 5300\"},\n    {0x7341, 0x00, \"AMD Radeon Pro W5500\"},\n    {0x7347, 0x00, \"AMD Radeon Pro W5500M\"},\n    {0x7360, 0x41, \"AMD Radeon Pro 5600M\"},\n    {0x7360, 0xC3, \"AMD Radeon Pro V520\"},\n    {0x738C, 0x01, \"AMD Instinct MI100\"},\n    {0x73A3, 0x00, \"AMD Radeon Pro W6800\"},\n    {0x73A5, 0xC0, \"AMD Radeon RX 6950 XT\"},\n    {0x73AF, 0xC0, \"AMD Radeon RX 6900 XT\"},\n    {0x73BF, 0xC0, \"AMD Radeon RX 6900 XT\"},\n    {0x73BF, 0xC1, \"AMD Radeon RX 6800 XT\"},\n    {0x73BF, 0xC3, \"AMD Radeon RX 6800\"},\n    {0x73DF, 0xC0, \"AMD Radeon RX 6750 XT\"},\n    {0x73DF, 0xC1, \"AMD Radeon RX 6700 XT\"},\n    {0x73DF, 0xC2, \"AMD Radeon RX 6800M\"},\n    {0x73DF, 0xC3, \"AMD Radeon RX 6800M\"},\n    {0x73DF, 0xC5, \"AMD Radeon RX 6700 XT\"},\n    {0x73DF, 0xCF, \"AMD Radeon RX 6700M\"},\n    {0x73DF, 0xD7, \"AMD TDC-235\"},\n    {0x73E1, 0x00, \"AMD Radeon Pro W6600M\"},\n    {0x73E3, 0x00, \"AMD Radeon Pro W6600\"},\n    {0x73EF, 0xC0, \"AMD Radeon RX 6800S\"},\n    {0x73EF, 0xC1, \"AMD Radeon RX 6650 XT\"},\n    {0x73EF, 0xC2, \"AMD Radeon RX 6700S\"},\n    {0x73EF, 0xC3, \"AMD Radeon RX 6650M\"},\n    {0x73EF, 0xC4, \"AMD Radeon RX 6650M XT\"},\n    {0x73FF, 0xC1, \"AMD Radeon RX 6600 XT\"},\n    {0x73FF, 0xC3, \"AMD Radeon RX 6600M\"},\n    {0x73FF, 0xC7, \"AMD Radeon RX 6600\"},\n    {0x73FF, 0xCB, \"AMD Radeon RX 6600S\"},\n    {0x7408, 0x00, \"AMD Instinct MI250X\"},\n    {0x740C, 0x01, \"AMD Instinct MI250X / MI250\"},\n    {0x740F, 0x02, \"AMD Instinct MI210\"},\n    {0x7421, 0x00, \"AMD Radeon Pro W6500M\"},\n    {0x7422, 0x00, \"AMD Radeon Pro W6400\"},\n    {0x7423, 0x00, \"AMD Radeon Pro W6300M\"},\n    {0x7423, 0x01, \"AMD Radeon Pro W6300\"},\n    {0x7424, 0x00, \"AMD Radeon RX 6300\"},\n    {0x743F, 0xC1, \"AMD Radeon RX 6500 XT\"},\n    {0x743F, 0xC3, \"AMD Radeon RX 6500\"},\n    {0x743F, 0xC3, \"AMD Radeon RX 6500M\"},\n    {0x743F, 0xC7, \"AMD Radeon RX 6400\"},\n    {0x743F, 0xCF, \"AMD Radeon RX 6300M\"},\n    {0x9830, 0x00, \"AMD Radeon HD 8400 / R3 Series\"},\n    {0x9831, 0x00, \"AMD Radeon HD 8400E\"},\n    {0x9832, 0x00, \"AMD Radeon HD 8330\"},\n    {0x9833, 0x00, \"AMD Radeon HD 8330E\"},\n    {0x9834, 0x00, \"AMD Radeon HD 8210\"},\n    {0x9835, 0x00, \"AMD Radeon HD 8210E\"},\n    {0x9836, 0x00, \"AMD Radeon HD 8200 / R3 Series\"},\n    {0x9837, 0x00, \"AMD Radeon HD 8280E\"},\n    {0x9838, 0x00, \"AMD Radeon HD 8200 / R3 series\"},\n    {0x9839, 0x00, \"AMD Radeon HD 8180\"},\n    {0x983D, 0x00, \"AMD Radeon HD 8250\"},\n    {0x9850, 0x00, \"AMD Radeon R3 Graphics\"},\n    {0x9850, 0x03, \"AMD Radeon R3 Graphics\"},\n    {0x9850, 0x40, \"AMD Radeon R2 Graphics\"},\n    {0x9850, 0x45, \"AMD Radeon R3 Graphics\"},\n    {0x9851, 0x00, \"AMD Radeon R4 Graphics\"},\n    {0x9851, 0x01, \"AMD Radeon R5E Graphics\"},\n    {0x9851, 0x05, \"AMD Radeon R5 Graphics\"},\n    {0x9851, 0x06, \"AMD Radeon R5E Graphics\"},\n    {0x9851, 0x40, \"AMD Radeon R4 Graphics\"},\n    {0x9851, 0x45, \"AMD Radeon R5 Graphics\"},\n    {0x9852, 0x00, \"AMD Radeon R2 Graphics\"},\n    {0x9852, 0x40, \"AMD Radeon E1 Graphics\"},\n    {0x9853, 0x00, \"AMD Radeon R2 Graphics\"},\n    {0x9853, 0x01, \"AMD Radeon R4E Graphics\"},\n    {0x9853, 0x03, \"AMD Radeon R2 Graphics\"},\n    {0x9853, 0x05, \"AMD Radeon R1E Graphics\"},\n    {0x9853, 0x06, \"AMD Radeon R1E Graphics\"},\n    {0x9853, 0x07, \"AMD Radeon R1E Graphics\"},\n    {0x9853, 0x08, \"AMD Radeon R1E Graphics\"},\n    {0x9853, 0x40, \"AMD Radeon R2 Graphics\"},\n    {0x9854, 0x00, \"AMD Radeon R3 Graphics\"},\n    {0x9854, 0x01, \"AMD Radeon R3E Graphics\"},\n    {0x9854, 0x02, \"AMD Radeon R3 Graphics\"},\n    {0x9854, 0x05, \"AMD Radeon R2 Graphics\"},\n    {0x9854, 0x06, \"AMD Radeon R4 Graphics\"},\n    {0x9854, 0x07, \"AMD Radeon R3 Graphics\"},\n    {0x9855, 0x02, \"AMD Radeon R6 Graphics\"},\n    {0x9855, 0x05, \"AMD Radeon R4 Graphics\"},\n    {0x9856, 0x00, \"AMD Radeon R2 Graphics\"},\n    {0x9856, 0x01, \"AMD Radeon R2E Graphics\"},\n    {0x9856, 0x02, \"AMD Radeon R2 Graphics\"},\n    {0x9856, 0x05, \"AMD Radeon R1E Graphics\"},\n    {0x9856, 0x06, \"AMD Radeon R2 Graphics\"},\n    {0x9856, 0x07, \"AMD Radeon R1E Graphics\"},\n    {0x9856, 0x08, \"AMD Radeon R1E Graphics\"},\n    {0x9856, 0x13, \"AMD Radeon R1E Graphics\"},\n    {0x9874, 0x81, \"AMD Radeon R6 Graphics\"},\n    {0x9874, 0x84, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0x85, \"AMD Radeon R6 Graphics\"},\n    {0x9874, 0x87, \"AMD Radeon R5 Graphics\"},\n    {0x9874, 0x88, \"AMD Radeon R7E Graphics\"},\n    {0x9874, 0x89, \"AMD Radeon R6E Graphics\"},\n    {0x9874, 0xC4, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xC5, \"AMD Radeon R6 Graphics\"},\n    {0x9874, 0xC6, \"AMD Radeon R6 Graphics\"},\n    {0x9874, 0xC7, \"AMD Radeon R5 Graphics\"},\n    {0x9874, 0xC8, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xC9, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xCA, \"AMD Radeon R5 Graphics\"},\n    {0x9874, 0xCB, \"AMD Radeon R5 Graphics\"},\n    {0x9874, 0xCC, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xCD, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xCE, \"AMD Radeon R5 Graphics\"},\n    {0x9874, 0xE1, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xE2, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xE3, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xE4, \"AMD Radeon R7 Graphics\"},\n    {0x9874, 0xE5, \"AMD Radeon R5 Graphics\"},\n    {0x9874, 0xE6, \"AMD Radeon R5 Graphics\"},\n    {0x98E4, 0x80, \"AMD Radeon R5E Graphics\"},\n    {0x98E4, 0x81, \"AMD Radeon R4E Graphics\"},\n    {0x98E4, 0x83, \"AMD Radeon R2E Graphics\"},\n    {0x98E4, 0x84, \"AMD Radeon R2E Graphics\"},\n    {0x98E4, 0x86, \"AMD Radeon R1E Graphics\"},\n    {0x98E4, 0xC0, \"AMD Radeon R4 Graphics\"},\n    {0x98E4, 0xC1, \"AMD Radeon R5 Graphics\"},\n    {0x98E4, 0xC2, \"AMD Radeon R4 Graphics\"},\n    {0x98E4, 0xC4, \"AMD Radeon R5 Graphics\"},\n    {0x98E4, 0xC6, \"AMD Radeon R5 Graphics\"},\n    {0x98E4, 0xC8, \"AMD Radeon R4 Graphics\"},\n    {0x98E4, 0xC9, \"AMD Radeon R4 Graphics\"},\n    {0x98E4, 0xCA, \"AMD Radeon R5 Graphics\"},\n    {0x98E4, 0xD0, \"AMD Radeon R2 Graphics\"},\n    {0x98E4, 0xD1, \"AMD Radeon R2 Graphics\"},\n    {0x98E4, 0xD2, \"AMD Radeon R2 Graphics\"},\n    {0x98E4, 0xD4, \"AMD Radeon R2 Graphics\"},\n    {0x98E4, 0xD9, \"AMD Radeon R5 Graphics\"},\n    {0x98E4, 0xDA, \"AMD Radeon R5 Graphics\"},\n    {0x98E4, 0xDB, \"AMD Radeon R3 Graphics\"},\n    {0x98E4, 0xE1, \"AMD Radeon R3 Graphics\"},\n    {0x98E4, 0xE2, \"AMD Radeon R3 Graphics\"},\n    {0x98E4, 0xE9, \"AMD Radeon R4 Graphics\"},\n    {0x98E4, 0xEA, \"AMD Radeon R4 Graphics\"},\n    {0x98E4, 0xEB, \"AMD Radeon R3 Graphics\"},\n    {0x98E4, 0xEC, \"AMD Radeon R4 Graphics\"},\n};\n\n#endif\n"
  },
  {
    "path": "src/device_discovery_linux.c",
    "content": "/*\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop and adapted from radeontop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/device_discovery.h\"\n\n#include <limits.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\n#if defined(USING_LIBUDEV) && defined(USING_LIBSYSTEMD)\n#error Cannot use libudev and libsystemd at the same time\n#endif\n\n#if defined(USING_LIBUDEV)\n\n#include <assert.h>\n#include <errno.h>\n#include <libudev.h>\n#include <stdlib.h>\n\ntypedef struct nvtop_device_enumerator {\n  unsigned refCount;\n  struct udev *udev;\n  struct udev_enumerate *enumerate;\n  unsigned num_devices;\n  unsigned current_device;\n  struct udev_device **devices;\n} nvtop_device_enumerator;\n\nnvtop_device *nvtop_device_ref(nvtop_device *device) {\n  udev_device_ref((struct udev_device *)device);\n  return device;\n}\n\nnvtop_device *nvtop_device_unref(nvtop_device *device) {\n  if (device)\n    udev_device_unref((struct udev_device *)device);\n  return NULL;\n}\n\nint nvtop_device_new_from_syspath(nvtop_device **dev, const char *syspath) {\n  struct udev *udev = udev_new();\n  if (!udev)\n    return -ENOMEM;\n  *dev = (nvtop_device *)udev_device_new_from_syspath(udev, syspath);\n  udev_unref(udev);\n  return *dev ? 1 : -ENOENT;\n}\n\nint nvtop_device_get_parent(nvtop_device *child, nvtop_device **parent) {\n  *parent = (nvtop_device *)udev_device_get_parent((struct udev_device *)child);\n  return *parent ? 0 : -ENOENT;\n}\n\nint nvtop_device_get_driver(nvtop_device *device, const char **driver) {\n  *driver = udev_device_get_driver((struct udev_device *)device);\n  return *driver ? 0 : -ENOENT;\n}\n\nint nvtop_device_get_devname(nvtop_device *device, const char **devname) {\n  *devname = udev_device_get_devnode((struct udev_device *)device);\n  return *devname ? 0 : -ENOENT;\n}\n\nint nvtop_device_get_property_value(nvtop_device *device, const char *key, const char **value) {\n  *value = udev_device_get_property_value((struct udev_device *)device, key);\n  return *value ? 0 : -ENOENT;\n}\n\nint nvtop_device_get_sysattr_value(nvtop_device *device, const char *sysattr, const char **value) {\n  *value = udev_device_get_sysattr_value((struct udev_device *)device, sysattr);\n  return *value ? 0 : -ENOENT;\n}\n\nint nvtop_device_get_syspath(nvtop_device *device, const char **sysPath) {\n  *sysPath = udev_device_get_syspath((struct udev_device *)device);\n  return *sysPath ? 0 : -ENOENT;\n}\n\nint nvtop_enumerator_new(nvtop_device_enumerator **enumerator) {\n  *enumerator = calloc(1, sizeof(**enumerator));\n  if (!enumerator)\n    return -1;\n  (*enumerator)->refCount = 1;\n  (*enumerator)->udev = udev_new();\n  if (!(*enumerator)->udev)\n    goto cleanAllocErr;\n  (*enumerator)->enumerate = udev_enumerate_new((*enumerator)->udev);\n  if (!(*enumerator)->enumerate)\n    goto cleanAllErr;\n\n  return 0;\n\ncleanAllErr:\n  udev_unref((*enumerator)->udev);\ncleanAllocErr:\n  free(*enumerator);\n  return -1;\n}\n\nstatic void nvtop_free_enumerator_devices(nvtop_device_enumerator *enumerator) {\n  if (enumerator->devices) {\n    for (unsigned i = 0; enumerator->devices && i < enumerator->num_devices; ++i) {\n      udev_device_unref(enumerator->devices[i]);\n    }\n    free(enumerator->devices);\n    enumerator->devices = NULL;\n  }\n}\n\nnvtop_device_enumerator *nvtop_enumerator_ref(nvtop_device_enumerator *enumerator) {\n  enumerator->refCount++;\n  udev_ref(enumerator->udev);\n  udev_enumerate_ref(enumerator->enumerate);\n  return enumerator;\n}\n\nnvtop_device_enumerator *nvtop_enumerator_unref(nvtop_device_enumerator *enumerator) {\n  enumerator->refCount--;\n  udev_enumerate_unref(enumerator->enumerate);\n  udev_unref(enumerator->udev);\n  if (!enumerator->refCount) {\n    nvtop_free_enumerator_devices(enumerator);\n    free(enumerator);\n    return NULL;\n  } else {\n    return enumerator;\n  }\n}\n\nint nvtop_device_enumerator_add_match_subsystem(nvtop_device_enumerator *enumerator, const char *subsystem, int match) {\n  assert(enumerator->refCount && \"Reference at zero\");\n  nvtop_free_enumerator_devices(enumerator);\n  int ret = 1;\n  if (match) {\n    ret = udev_enumerate_add_match_subsystem(enumerator->enumerate, subsystem);\n  } else {\n    ret = udev_enumerate_add_nomatch_subsystem(enumerator->enumerate, subsystem);\n  }\n  return ret;\n}\n\nint nvtop_device_enumerator_add_match_property(nvtop_device_enumerator *enumerator, const char *property,\n                                               const char *value) {\n  assert(enumerator->refCount && \"Reference at zero\");\n  nvtop_free_enumerator_devices(enumerator);\n  return udev_enumerate_add_match_property(enumerator->enumerate, property, value);\n}\n\nint nvtop_device_enumerator_add_match_parent(nvtop_device_enumerator *enumerator, nvtop_device *parent) {\n  assert(enumerator->refCount && \"Reference at zero\");\n  nvtop_free_enumerator_devices(enumerator);\n  return udev_enumerate_add_match_parent(enumerator->enumerate, (struct udev_device *)parent);\n}\n\nstatic nvtop_device *nvtop_enumerator_get_current(nvtop_device_enumerator *enumerator) {\n  if (!enumerator->devices || enumerator->current_device >= enumerator->num_devices)\n    return NULL;\n  return (nvtop_device *)enumerator->devices[enumerator->current_device];\n}\n\nnvtop_device *nvtop_enumerator_get_device_first(nvtop_device_enumerator *enumerator) {\n  if (!enumerator->devices) {\n    int err = udev_enumerate_scan_devices(enumerator->enumerate);\n    if (err < 0)\n      return NULL;\n    struct udev_list_entry *list = udev_enumerate_get_list_entry(enumerator->enumerate);\n    struct udev_list_entry *curr;\n    enumerator->num_devices = 0;\n    udev_list_entry_foreach(curr, list) { enumerator->num_devices++; }\n    enumerator->devices = calloc(enumerator->num_devices, sizeof(*enumerator->devices));\n    if (!enumerator->devices)\n      return NULL;\n    unsigned idx = 0;\n    udev_list_entry_foreach(curr, list) {\n      const char *path = udev_list_entry_get_name(curr);\n      enumerator->devices[idx++] = udev_device_new_from_syspath(enumerator->udev, path);\n    }\n  }\n  enumerator->current_device = 0;\n  return nvtop_enumerator_get_current(enumerator);\n}\n\nnvtop_device *nvtop_enumerator_get_device_next(nvtop_device_enumerator *enumerator) {\n  enumerator->current_device++;\n  return nvtop_enumerator_get_current(enumerator);\n}\n\n#elif defined(USING_LIBSYSTEMD)\n\n#include <assert.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <systemd/sd-device.h>\n\nnvtop_device *nvtop_device_ref(nvtop_device *device) { return (nvtop_device *)sd_device_ref((sd_device *)device); }\n\nnvtop_device *nvtop_device_unref(nvtop_device *device) {\n  if (!device)\n    return NULL;\n  return (nvtop_device *)sd_device_unref((sd_device *)device);\n}\n\nint nvtop_device_new_from_syspath(nvtop_device **dev, const char *syspath) {\n  return sd_device_new_from_syspath((sd_device **)dev, syspath);\n}\n\nint nvtop_device_get_parent(nvtop_device *child, nvtop_device **parent) {\n  return sd_device_get_parent((sd_device *)child, (sd_device **)parent);\n}\n\nint nvtop_device_get_driver(nvtop_device *device, const char **driver) {\n  return sd_device_get_driver((sd_device *)device, driver);\n}\n\nint nvtop_device_get_devname(nvtop_device *device, const char **devname) {\n  return sd_device_get_devname((sd_device *)device, devname);\n}\n\nint nvtop_device_get_property_value(nvtop_device *device, const char *key, const char **value) {\n  return sd_device_get_property_value((sd_device *)device, key, value);\n}\n\nint nvtop_device_get_sysattr_value(nvtop_device *device, const char *sysattr, const char **value) {\n  return sd_device_get_sysattr_value((sd_device *)device, sysattr, value);\n}\n\nint nvtop_device_get_syspath(nvtop_device *device, const char **sysPath) {\n  return sd_device_get_syspath((sd_device *)device, sysPath);\n}\n\nint nvtop_enumerator_new(nvtop_device_enumerator **enumerator) {\n  return sd_device_enumerator_new((sd_device_enumerator **)enumerator);\n}\n\nnvtop_device_enumerator *nvtop_enumerator_ref(nvtop_device_enumerator *enumerator) {\n  return (nvtop_device_enumerator *)sd_device_enumerator_ref((sd_device_enumerator *)enumerator);\n}\n\nnvtop_device_enumerator *nvtop_enumerator_unref(nvtop_device_enumerator *enumerator) {\n  return (nvtop_device_enumerator *)sd_device_enumerator_unref((sd_device_enumerator *)enumerator);\n}\n\nint nvtop_device_enumerator_add_match_subsystem(nvtop_device_enumerator *enumerator, const char *subsystem, int match) {\n  return sd_device_enumerator_add_match_subsystem((sd_device_enumerator *)enumerator, subsystem, match);\n}\n\nint nvtop_device_enumerator_add_match_property(nvtop_device_enumerator *enumerator, const char *property,\n                                               const char *value) {\n  return sd_device_enumerator_add_match_property((sd_device_enumerator *)enumerator, property, value);\n}\n\nint nvtop_device_enumerator_add_match_parent(nvtop_device_enumerator *enumerator, nvtop_device *parent) {\n  return sd_device_enumerator_add_match_parent((sd_device_enumerator *)enumerator, (sd_device *)parent);\n}\n\nnvtop_device *nvtop_enumerator_get_device_first(nvtop_device_enumerator *enumerator) {\n  return (nvtop_device *)sd_device_enumerator_get_device_first((sd_device_enumerator *)enumerator);\n}\n\nnvtop_device *nvtop_enumerator_get_device_next(nvtop_device_enumerator *enumerator) {\n  return (nvtop_device *)sd_device_enumerator_get_device_next((sd_device_enumerator *)enumerator);\n}\n\n#endif // elif USE_LIBSYSTEMD\n\nstatic int pcie_walker_helper(nvtop_device *dev, nvtop_pcie_link *pcie_info, const char *link_speed_attr,\n                              const char *link_width_attr) {\n  bool valid = false;\n  const char *driver;\n  int ret = nvtop_device_get_driver(dev, &driver);\n  if (ret < 0)\n    return ret;\n  if (!strcmp(driver, \"pcieport\")) {\n    const char *speed_str, *width_str;\n    unsigned speed, width;\n    ret = nvtop_device_get_sysattr_value(dev, link_speed_attr, &speed_str);\n    if (ret < 0)\n      return ret;\n    ret = nvtop_device_get_sysattr_value(dev, link_width_attr, &width_str);\n    if (ret < 0)\n      return ret;\n    ret = sscanf(speed_str, \"%u\", &speed);\n    if (ret != 1)\n      return -1;\n    ret = sscanf(width_str, \"%u\", &width);\n    if (ret != 1)\n      return -1;\n    pcie_info->speed = pcie_info->speed > speed ? speed : pcie_info->speed;\n    pcie_info->width = pcie_info->width > width ? width : pcie_info->width;\n    valid = true;\n  }\n  nvtop_device *parent;\n  ret = nvtop_device_get_parent(dev, &parent);\n  if (ret < 0)\n    return valid;\n  ret = pcie_walker_helper(parent, pcie_info, link_speed_attr, link_width_attr);\n  return valid || ret >= 0;\n}\n\nint nvtop_device_maximum_pcie_link(nvtop_device *dev, nvtop_pcie_link *pcie_info) {\n  pcie_info->speed = UINT_MAX;\n  pcie_info->width = UINT_MAX;\n  return pcie_walker_helper(dev, pcie_info, \"max_link_speed\", \"max_link_width\");\n}\n\nint nvtop_device_current_pcie_link(nvtop_device *dev, nvtop_pcie_link *pcie_info) {\n  // We open a new device to avoid cached values\n  const char *path;\n  nvtop_device_get_syspath(dev, &path);\n  nvtop_device *dev_samepath;\n  int ret = nvtop_device_new_from_syspath(&dev_samepath, path);\n  if (ret < 0)\n    return ret;\n  pcie_info->speed = UINT_MAX;\n  pcie_info->width = UINT_MAX;\n  ret = pcie_walker_helper(dev_samepath, pcie_info, \"current_link_speed\", \"current_link_width\");\n  nvtop_device_unref(dev_samepath);\n  return ret;\n}\n\nnvtop_device *nvtop_device_get_hwmon(nvtop_device *dev) {\n  nvtop_device_enumerator *enumerator;\n  int ret = nvtop_enumerator_new(&enumerator);\n  if (ret < 0)\n    return NULL;\n  ret = nvtop_device_enumerator_add_match_subsystem(enumerator, \"hwmon\", true);\n  if (ret < 0)\n    return NULL;\n  ret = nvtop_device_enumerator_add_match_parent(enumerator, dev);\n  if (ret < 0)\n    return NULL;\n  nvtop_device *hwmon = nvtop_enumerator_get_device_first(enumerator);\n  if (!hwmon)\n    return NULL;\n  nvtop_device_ref(hwmon);\n  nvtop_enumerator_unref(enumerator);\n  return hwmon;\n}\n"
  },
  {
    "path": "src/extract_gcuinfo_enflame.c",
    "content": "/*\n *\n * Copyright (c) 2025 Enflame Technology (Shanghai) Co., Ltd. All rights reserved.\n *\n * This file is part of Nvtop and adapted from efml from Enflame Technology (Shanghai) Co., Ltd.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/common.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n\n#include <dlfcn.h>\n#include <errno.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define EFML_SUCCESS 0\n#define EFML_ERROR_INSUFFICIENT_SIZE 7\n\ntypedef struct efmlDevice *efmlDevice_t;\ntypedef int efmlReturn_v1_t; // store the enum as int\n\n// Init and shutdown\n\nstatic efmlReturn_v1_t (*efmlInit)(void);\n\nstatic efmlReturn_v1_t (*efmlShutdown)(void);\n\n// Static information and helper functions\n\nstatic efmlReturn_v1_t (*efmlDeviceGetCount)(unsigned int *deviceCount);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetHandleByIndex)(unsigned int index, efmlDevice_t *device);\n\nstatic const char *(*efmlErrorString)(efmlReturn_v1_t);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetName)(efmlDevice_t device, char *name, unsigned int length);\n\ntypedef struct {\n  char busIdLegacy[16];\n  unsigned int domain;\n  unsigned int bus;\n  unsigned int device;\n  unsigned int pciDeviceId;\n  unsigned int pciSubSystemId;\n  char busId[32];\n} efmlPciInfo_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetPciInfo)(efmlDevice_t device, efmlPciInfo_t *pciInfo);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetMaxPcieLinkGeneration)(efmlDevice_t device, unsigned int *maxLinkGen);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetMaxPcieLinkWidth)(efmlDevice_t device, unsigned int *maxLinkWidth);\n\ntypedef enum {\n  EFML_TEMPERATURE_THRESHOLD_SHUTDOWN = 0,\n  EFML_TEMPERATURE_THRESHOLD_SLOWDOWN = 1,\n  EFML_TEMPERATURE_THRESHOLD_MEM_MAX = 2,\n  EFML_TEMPERATURE_THRESHOLD_GCU_MAX = 3,\n  EFML_TEMPERATURE_THRESHOLD_ACOUSTIC_MIN = 4,\n  EFML_TEMPERATURE_THRESHOLD_ACOUSTIC_CURR = 5,\n  EFML_TEMPERATURE_THRESHOLD_ACOUSTIC_MAX = 6,\n} efmlTemperatureThresholds_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetTemperatureThreshold)(efmlDevice_t device, efmlTemperatureThresholds_t thresholdType,\n                                                         unsigned int *temp);\n\n// Dynamic information extraction\n\ntypedef enum {\n  EFML_CLOCK_GRAPHICS = 0,\n  EFML_CLOCK_SM = 1,\n  EFML_CLOCK_MEM = 2,\n  EFML_CLOCK_VIDEO = 3,\n} efmlClockType_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetClockInfo)(efmlDevice_t device, efmlClockType_t type, unsigned int *clock);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetMaxClockInfo)(efmlDevice_t device, efmlClockType_t type, unsigned int *clock);\n\ntypedef struct {\n  unsigned int gcu;\n  unsigned int memory;\n} efmlUtilization_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetUtilizationRates)(efmlDevice_t device, efmlUtilization_t *utilization);\n\ntypedef struct {\n  unsigned long long total;\n  unsigned long long free;\n  unsigned long long used;\n} efmlMemory_v1_t;\n\ntypedef struct {\n  unsigned int version;\n  unsigned long long total;\n  unsigned long long reserved;\n  unsigned long long free;\n  unsigned long long used;\n} efmlMemory_v2_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetMemoryInfo)(efmlDevice_t device, efmlMemory_v1_t *memory);\nstatic efmlReturn_v1_t (*efmlDeviceGetMemoryInfo_v2)(efmlDevice_t device, efmlMemory_v2_t *memory);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetCurrPcieLinkGeneration)(efmlDevice_t device, unsigned int *currLinkGen);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetCurrPcieLinkWidth)(efmlDevice_t device, unsigned int *currLinkWidth);\n\ntypedef enum {\n  EFML_PCIE_UTIL_TX_BYTES = 0,\n  EFML_PCIE_UTIL_RX_BYTES = 1,\n} efmlPcieUtilCounter_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetPcieThroughput)(efmlDevice_t device, efmlPcieUtilCounter_t counter,\n                                                   unsigned int *value);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetFanSpeed)(efmlDevice_t device, unsigned int *speed);\n\ntypedef enum {\n  EFML_TEMPERATURE_GCU = 0,\n} efmlTemperatureSensors_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetTemperature)(efmlDevice_t device, efmlTemperatureSensors_t sensorType,\n                                                unsigned int *temp);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetPowerUsage)(efmlDevice_t device, unsigned int *power);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetEnforcedPowerLimit)(efmlDevice_t device, unsigned int *limit);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetEncoderUtilization)(efmlDevice_t device, unsigned int *utilization,\n                                                       unsigned int *samplingPeriodUs);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetDecoderUtilization)(efmlDevice_t device, unsigned int *utilization,\n                                                       unsigned int *samplingPeriodUs);\n\n// Processes running on GCU\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long usedGcuMemory;\n} efmlProcessInfo_v1_t;\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long usedGcuMemory;\n  unsigned int gcuInstanceId;\n  unsigned int computeInstanceId;\n} efmlProcessInfo_v2_t;\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long usedGcuMemory;\n  unsigned int gcuInstanceId;\n  unsigned int computeInstanceId;\n} efmlProcessInfo_v3_t;\n\nstatic efmlReturn_v1_t (*efmlDeviceGetGraphicsRunningProcesses_v1)(efmlDevice_t device, unsigned int *infoCount,\n                                                                efmlProcessInfo_v1_t *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetGraphicsRunningProcesses_v2)(efmlDevice_t device, unsigned int *infoCount,\n                                                                efmlProcessInfo_v2_t *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetGraphicsRunningProcesses_v3)(efmlDevice_t device, unsigned int *infoCount,\n                                                                efmlProcessInfo_v3_t *infos);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetComputeRunningProcesses_v1)(efmlDevice_t device, unsigned int *infoCount,\n                                                               efmlProcessInfo_v1_t *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetComputeRunningProcesses_v2)(efmlDevice_t device, unsigned int *infoCount,\n                                                               efmlProcessInfo_v2_t *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetComputeRunningProcesses_v3)(efmlDevice_t device, unsigned int *infoCount,\n                                                               efmlProcessInfo_v3_t *infos);\n\nstatic efmlReturn_v1_t (*efmlDeviceGetMPSComputeRunningProcesses_v1)(efmlDevice_t device, unsigned int *infoCount,\n                                                                  efmlProcessInfo_v1_t *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetMPSComputeRunningProcesses_v2)(efmlDevice_t device, unsigned int *infoCount,\n                                                                  efmlProcessInfo_v2_t *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetMPSComputeRunningProcesses_v3)(efmlDevice_t device, unsigned int *infoCount,\n                                                                  efmlProcessInfo_v3_t *infos);\n\n// Common interface passing void*\nstatic efmlReturn_v1_t (*efmlDeviceGetGraphicsRunningProcesses[4])(efmlDevice_t device, unsigned int *infoCount,\n                                                                void *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetComputeRunningProcesses[4])(efmlDevice_t device, unsigned int *infoCount,\n                                                               void *infos);\nstatic efmlReturn_v1_t (*efmlDeviceGetMPSComputeRunningProcesses[4])(efmlDevice_t device, unsigned int *infoCount,\n                                                                  void *infos);\n\n#define EFML_DEVICE_DRS_DISABLE 0x0\n#define EFML_DEVICE_DRS_ENABLE 0x1\nefmlReturn_v1_t (*efmlDeviceGetDrsMode)(efmlDevice_t device, unsigned int *currentMode, unsigned int *pendingMode);\n\nstatic void *libefml_handle;\n\nstatic efmlReturn_v1_t last_efml_return_status = EFML_SUCCESS;\nstatic char didnt_call_gcuinfo_init[] = \"The ENFLAME extraction has not been initialized, please call \"\n                                        \"gcuinfo_enflame_init\\n\";\nstatic const char *local_error_string = didnt_call_gcuinfo_init;\n\n// Processes GCU Utilization\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long timeStamp;\n  unsigned int sipUtil;\n  unsigned int memUtil;\n  unsigned int encUtil;\n  unsigned int decUtil;\n} efmlProcessUtilizationSample_t;\n\nefmlReturn_v1_t (*efmlDeviceGetProcessUtilization)(efmlDevice_t device, efmlProcessUtilizationSample_t *utilization,\n                                                unsigned int *processSamplesCount,\n                                                unsigned long long lastSeenTimeStamp);\n\nstruct gcu_info_enflame {\n  struct gpu_info base;\n  struct list_head allocate_list;\n\n  efmlDevice_t gcuhandle;\n  bool isInDrsMode;\n  unsigned long long last_utilization_timestamp;\n};\n\nstatic LIST_HEAD(allocations);\n\nstatic bool gcuinfo_enflame_init(void);\nstatic void gcuinfo_enflame_shutdown(void);\nstatic const char *gcuinfo_enflame_last_error_string(void);\nstatic bool gcuinfo_enflame_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gcuinfo_enflame_populate_static_info(struct gpu_info *_gcu_info);\nstatic void gcuinfo_enflame_refresh_dynamic_info(struct gpu_info *_gcu_info);\nstatic void gcuinfo_enflame_get_running_processes(struct gpu_info *_gcu_info);\n\nstruct gpu_vendor gcu_vendor_enflame = {\n    .init = gcuinfo_enflame_init,\n    .shutdown = gcuinfo_enflame_shutdown,\n    .last_error_string = gcuinfo_enflame_last_error_string,\n    .get_device_handles = gcuinfo_enflame_get_device_handles,\n    .populate_static_info = gcuinfo_enflame_populate_static_info,\n    .refresh_dynamic_info = gcuinfo_enflame_refresh_dynamic_info,\n    .refresh_running_processes = gcuinfo_enflame_get_running_processes,\n    .name = \"ENFLAME\",\n};\n\n__attribute__((constructor)) static void init_extract_gcuinfo_enflame(void) { register_gpu_vendor(&gcu_vendor_enflame); }\n\n/*\n *\n * This function loads the libefml.so shared object, initializes the\n * required function pointers and calls the enflame library initialization\n * function. Returns true if everything has been initialized successfully. If\n * false is returned, the cause of the error can be retrieved by calling the\n * function gcuinfo_enflame_last_error_string.\n *\n */\nstatic bool gcuinfo_enflame_init(void) {\n\n  libefml_handle = dlopen(\"libefml.so\", RTLD_LAZY);\n  if (!libefml_handle)\n    libefml_handle = dlopen(\"libefml.so.1\", RTLD_LAZY);\n  if (!libefml_handle) {\n    local_error_string = dlerror();\n    return false;\n  }\n\n  // Default to last version\n  efmlInit = dlsym(libefml_handle, \"efmlInit_v2\");\n  if (!efmlInit)\n    efmlInit = dlsym(libefml_handle, \"efmlInit\");\n  if (!efmlInit)\n    goto init_error_clean_exit;\n\n  efmlShutdown = dlsym(libefml_handle, \"efmlShutdown\");\n  if (!efmlShutdown)\n    goto init_error_clean_exit;\n\n  // Default to last version if available\n  efmlDeviceGetCount = dlsym(libefml_handle, \"efmlDeviceGetCount_v2\");\n  if (!efmlDeviceGetCount)\n    efmlDeviceGetCount = dlsym(libefml_handle, \"efmlDeviceGetCount\");\n  if (!efmlDeviceGetCount)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetHandleByIndex = dlsym(libefml_handle, \"efmlDeviceGetHandleByIndex_v2\");\n  if (!efmlDeviceGetHandleByIndex)\n    efmlDeviceGetHandleByIndex = dlsym(libefml_handle, \"efmlDeviceGetHandleByIndex\");\n  if (!efmlDeviceGetHandleByIndex)\n    goto init_error_clean_exit;\n\n  efmlErrorString = dlsym(libefml_handle, \"efmlErrorString\");\n  if (!efmlErrorString)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetName = dlsym(libefml_handle, \"efmlDeviceGetName\");\n  if (!efmlDeviceGetName)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetPciInfo = dlsym(libefml_handle, \"efmlDeviceGetPciInfo_v3\");\n  if (!efmlDeviceGetPciInfo)\n    efmlDeviceGetPciInfo = dlsym(libefml_handle, \"efmlDeviceGetPciInfo_v2\");\n  if (!efmlDeviceGetPciInfo)\n    efmlDeviceGetPciInfo = dlsym(libefml_handle, \"efmlDeviceGetPciInfo\");\n  if (!efmlDeviceGetPciInfo)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetMaxPcieLinkGeneration = dlsym(libefml_handle, \"efmlDeviceGetMaxPcieLinkGeneration\");\n  if (!efmlDeviceGetMaxPcieLinkGeneration)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetMaxPcieLinkWidth = dlsym(libefml_handle, \"efmlDeviceGetMaxPcieLinkWidth\");\n  if (!efmlDeviceGetMaxPcieLinkWidth)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetTemperatureThreshold = dlsym(libefml_handle, \"efmlDeviceGetTemperatureThreshold\");\n  if (!efmlDeviceGetTemperatureThreshold)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetClockInfo = dlsym(libefml_handle, \"efmlDeviceGetClockInfo\");\n  if (!efmlDeviceGetClockInfo)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetMaxClockInfo = dlsym(libefml_handle, \"efmlDeviceGetMaxClockInfo\");\n  if (!efmlDeviceGetMaxClockInfo)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetUtilizationRates = dlsym(libefml_handle, \"efmlDeviceGetUtilizationRates\");\n  if (!efmlDeviceGetUtilizationRates)\n    goto init_error_clean_exit;\n\n  // Get v2 and fallback to v1\n  efmlDeviceGetMemoryInfo_v2 = dlsym(libefml_handle, \"efmlDeviceGetMemoryInfo_v2\");\n  efmlDeviceGetMemoryInfo = dlsym(libefml_handle, \"efmlDeviceGetMemoryInfo\");\n  if (!efmlDeviceGetMemoryInfo_v2 && !efmlDeviceGetMemoryInfo)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetCurrPcieLinkGeneration = dlsym(libefml_handle, \"efmlDeviceGetCurrPcieLinkGeneration\");\n  if (!efmlDeviceGetCurrPcieLinkGeneration)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetCurrPcieLinkWidth = dlsym(libefml_handle, \"efmlDeviceGetCurrPcieLinkWidth\");\n  if (!efmlDeviceGetCurrPcieLinkWidth)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetPcieThroughput = dlsym(libefml_handle, \"efmlDeviceGetPcieThroughput\");\n  if (!efmlDeviceGetPcieThroughput)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetFanSpeed = dlsym(libefml_handle, \"efmlDeviceGetFanSpeed\");\n  if (!efmlDeviceGetFanSpeed)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetTemperature = dlsym(libefml_handle, \"efmlDeviceGetTemperature\");\n  if (!efmlDeviceGetTemperature)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetPowerUsage = dlsym(libefml_handle, \"efmlDeviceGetPowerUsage\");\n  if (!efmlDeviceGetPowerUsage)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetEnforcedPowerLimit = dlsym(libefml_handle, \"efmlDeviceGetEnforcedPowerLimit\");\n  if (!efmlDeviceGetEnforcedPowerLimit)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetEncoderUtilization = dlsym(libefml_handle, \"efmlDeviceGetEncoderUtilization\");\n  if (!efmlDeviceGetEncoderUtilization)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetDecoderUtilization = dlsym(libefml_handle, \"efmlDeviceGetDecoderUtilization\");\n  if (!efmlDeviceGetDecoderUtilization)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetGraphicsRunningProcesses_v3 = dlsym(libefml_handle, \"efmlDeviceGetGraphicsRunningProcesses_v3\");\n  efmlDeviceGetGraphicsRunningProcesses_v2 = dlsym(libefml_handle, \"efmlDeviceGetGraphicsRunningProcesses_v2\");\n  efmlDeviceGetGraphicsRunningProcesses_v1 = dlsym(libefml_handle, \"efmlDeviceGetGraphicsRunningProcesses\");\n  if (!efmlDeviceGetGraphicsRunningProcesses_v3 && !efmlDeviceGetGraphicsRunningProcesses_v2 &&\n      !efmlDeviceGetGraphicsRunningProcesses_v1)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetGraphicsRunningProcesses[1] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetGraphicsRunningProcesses_v1;\n  efmlDeviceGetGraphicsRunningProcesses[2] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetGraphicsRunningProcesses_v2;\n  efmlDeviceGetGraphicsRunningProcesses[3] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetGraphicsRunningProcesses_v3;\n\n  efmlDeviceGetComputeRunningProcesses_v3 = dlsym(libefml_handle, \"efmlDeviceGetComputeRunningProcesses_v3\");\n  efmlDeviceGetComputeRunningProcesses_v2 = dlsym(libefml_handle, \"efmlDeviceGetComputeRunningProcesses_v2\");\n  efmlDeviceGetComputeRunningProcesses_v1 = dlsym(libefml_handle, \"efmlDeviceGetComputeRunningProcesses\");\n  if (!efmlDeviceGetComputeRunningProcesses_v3 && !efmlDeviceGetComputeRunningProcesses_v2 &&\n      !efmlDeviceGetComputeRunningProcesses_v1)\n    goto init_error_clean_exit;\n\n  efmlDeviceGetComputeRunningProcesses[1] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetComputeRunningProcesses_v1;\n  efmlDeviceGetComputeRunningProcesses[2] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetComputeRunningProcesses_v2;\n  efmlDeviceGetComputeRunningProcesses[3] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetComputeRunningProcesses_v3;\n\n  efmlDeviceGetMPSComputeRunningProcesses_v3 = dlsym(libefml_handle, \"efmlDeviceGetMPSComputeRunningProcesses_v3\");\n  efmlDeviceGetMPSComputeRunningProcesses_v2 = dlsym(libefml_handle, \"efmlDeviceGetMPSComputeRunningProcesses_v2\");\n  efmlDeviceGetMPSComputeRunningProcesses_v1 = dlsym(libefml_handle, \"efmlDeviceGetMPSComputeRunningProcesses\");\n\n  efmlDeviceGetMPSComputeRunningProcesses[1] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetMPSComputeRunningProcesses_v1;\n  efmlDeviceGetMPSComputeRunningProcesses[2] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetMPSComputeRunningProcesses_v2;\n  efmlDeviceGetMPSComputeRunningProcesses[3] =\n      (efmlReturn_v1_t(*)(efmlDevice_t, unsigned int *, void *))efmlDeviceGetMPSComputeRunningProcesses_v3;\n\n  efmlDeviceGetProcessUtilization = dlsym(libefml_handle, \"efmlDeviceGetProcessUtilization\");\n  efmlDeviceGetDrsMode = dlsym(libefml_handle, \"efmlDeviceGetDrsMode\");\n\n  last_efml_return_status = efmlInit();\n  if (last_efml_return_status != EFML_SUCCESS) {\n    return false;\n  }\n  local_error_string = NULL;\n\n  return true;\n\ninit_error_clean_exit:\n  dlclose(libefml_handle);\n  libefml_handle = NULL;\n  return false;\n}\n\nstatic void gcuinfo_enflame_shutdown(void) {\n  if (libefml_handle) {\n    efmlShutdown();\n    dlclose(libefml_handle);\n    libefml_handle = NULL;\n    local_error_string = didnt_call_gcuinfo_init;\n  }\n\n  struct gcu_info_enflame *allocated, *tmp;\n\n  list_for_each_entry_safe(allocated, tmp, &allocations, allocate_list) {\n    list_del(&allocated->allocate_list);\n    free(allocated);\n  }\n}\n\nstatic const char *gcuinfo_enflame_last_error_string(void) {\n  if (local_error_string) {\n    return local_error_string;\n  } else if (libefml_handle && efmlErrorString) {\n    return efmlErrorString(last_efml_return_status);\n  } else {\n    return \"An unanticipated error occurred while accessing ENFLAME GCU \"\n           \"information\\n\";\n  }\n}\n\nstatic bool gcuinfo_enflame_get_device_handles(struct list_head *devices, unsigned *count) {\n\n  if (!libefml_handle)\n    return false;\n\n  unsigned num_devices;\n  last_efml_return_status = efmlDeviceGetCount(&num_devices);\n  if (last_efml_return_status != EFML_SUCCESS)\n    return false;\n\n  struct gcu_info_enflame *gcu_infos = calloc(num_devices, sizeof(*gcu_infos));\n  if (!gcu_infos) {\n    local_error_string = strerror(errno);\n    return false;\n  }\n\n  list_add(&gcu_infos[0].allocate_list, &allocations);\n\n  *count = 0;\n  for (unsigned int i = 0; i < num_devices; ++i) {\n    last_efml_return_status = efmlDeviceGetHandleByIndex(i, &gcu_infos[*count].gcuhandle);\n    if (last_efml_return_status == EFML_SUCCESS) {\n      gcu_infos[*count].base.vendor = &gcu_vendor_enflame;\n      efmlPciInfo_t pciInfo;\n      efmlReturn_v1_t pciInfoRet = efmlDeviceGetPciInfo(gcu_infos[*count].gcuhandle, &pciInfo);\n      if (pciInfoRet == EFML_SUCCESS) {\n        strncpy(gcu_infos[*count].base.pdev, pciInfo.busIdLegacy, PDEV_LEN);\n        list_add_tail(&gcu_infos[*count].base.list, devices);\n        *count += 1;\n      }\n    }\n  }\n\n  return true;\n}\n\nstatic void gcuinfo_enflame_populate_static_info(struct gpu_info *_gcu_info) {\n  struct gcu_info_enflame *gcu_info = container_of(_gcu_info, struct gcu_info_enflame, base);\n  struct gpuinfo_static_info *static_info = &gcu_info->base.static_info;\n  efmlDevice_t device = gcu_info->gcuhandle;\n\n  static_info->integrated_graphics = false;\n  static_info->encode_decode_shared = false;\n  RESET_ALL(static_info->valid);\n\n  last_efml_return_status = efmlDeviceGetName(device, static_info->device_name, MAX_DEVICE_NAME);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n\n  last_efml_return_status = efmlDeviceGetMaxPcieLinkGeneration(device, &static_info->max_pcie_gen);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_max_pcie_gen_valid, static_info->valid);\n\n  last_efml_return_status = efmlDeviceGetMaxPcieLinkWidth(device, &static_info->max_pcie_link_width);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_max_pcie_link_width_valid, static_info->valid);\n\n  last_efml_return_status = efmlDeviceGetTemperatureThreshold(device, EFML_TEMPERATURE_THRESHOLD_SHUTDOWN,\n                                                              &static_info->temperature_shutdown_threshold);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_temperature_shutdown_threshold_valid, static_info->valid);\n\n  last_efml_return_status = efmlDeviceGetTemperatureThreshold(device, EFML_TEMPERATURE_THRESHOLD_SLOWDOWN,\n                                                              &static_info->temperature_slowdown_threshold);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_temperature_slowdown_threshold_valid, static_info->valid);\n}\n\nstatic void gcuinfo_enflame_refresh_dynamic_info(struct gpu_info *_gcu_info) {\n  struct gcu_info_enflame *gcu_info = container_of(_gcu_info, struct gcu_info_enflame, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gcu_info->base.dynamic_info;\n  efmlDevice_t device = gcu_info->gcuhandle;\n\n  bool graphics_clock_valid = false;\n  unsigned graphics_clock;\n  bool sm_clock_valid = false;\n  unsigned sm_clock;\n  efmlClockType_t getMaxClockFrom = EFML_CLOCK_GRAPHICS;\n\n  RESET_ALL(dynamic_info->valid);\n\n  // GCU current speed\n  last_efml_return_status = efmlDeviceGetClockInfo(device, EFML_CLOCK_GRAPHICS, &graphics_clock);\n  graphics_clock_valid = last_efml_return_status == EFML_SUCCESS;\n\n  last_efml_return_status = efmlDeviceGetClockInfo(device, EFML_CLOCK_SM, &sm_clock);\n  sm_clock_valid = last_efml_return_status == EFML_SUCCESS;\n\n  if (graphics_clock_valid && sm_clock_valid && graphics_clock < sm_clock) {\n    getMaxClockFrom = EFML_CLOCK_SM;\n  } else if (!graphics_clock_valid && sm_clock_valid) {\n    getMaxClockFrom = EFML_CLOCK_SM;\n  }\n\n  if (getMaxClockFrom == EFML_CLOCK_GRAPHICS && graphics_clock_valid) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, graphics_clock);\n  }\n  if (getMaxClockFrom == EFML_CLOCK_SM && sm_clock_valid) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, sm_clock);\n  }\n\n  // GCU max speed\n  last_efml_return_status = efmlDeviceGetMaxClockInfo(device, getMaxClockFrom, &dynamic_info->gpu_clock_speed_max);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_gpu_clock_speed_max_valid, dynamic_info->valid);\n\n  // Memory current speed\n  last_efml_return_status = efmlDeviceGetClockInfo(device, EFML_CLOCK_MEM, &dynamic_info->mem_clock_speed);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_mem_clock_speed_valid, dynamic_info->valid);\n\n  // Memory max speed\n  last_efml_return_status = efmlDeviceGetMaxClockInfo(device, EFML_CLOCK_MEM, &dynamic_info->mem_clock_speed_max);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_mem_clock_speed_max_valid, dynamic_info->valid);\n\n  // CPU and Memory utilization rates\n  efmlUtilization_t utilization_percentages;\n  last_efml_return_status = efmlDeviceGetUtilizationRates(device, &utilization_percentages);\n  if (last_efml_return_status == EFML_SUCCESS) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, utilization_percentages.gcu);\n  }\n\n  // Encoder utilization rate\n  unsigned ignored_period;\n  last_efml_return_status = efmlDeviceGetEncoderUtilization(device, &dynamic_info->encoder_rate, &ignored_period);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_encoder_rate_valid, dynamic_info->valid);\n\n  // Decoder utilization rate\n  last_efml_return_status = efmlDeviceGetDecoderUtilization(device, &dynamic_info->decoder_rate, &ignored_period);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_decoder_rate_valid, dynamic_info->valid);\n\n  // Device memory info (total,used,free)\n  bool got_meminfo = false;\n  bool has_unified_memory = false;\n\n  if (efmlDeviceGetMemoryInfo_v2) {\n    efmlMemory_v2_t memory_info;\n    memory_info.version = 0x02000028;\n    last_efml_return_status = efmlDeviceGetMemoryInfo_v2(device, &memory_info);\n    if (last_efml_return_status == EFML_SUCCESS) {\n      // Check if this is a unified memory GCU (total == 0 indicates unified memory)\n      if (memory_info.total == 0) {\n        has_unified_memory = true;\n      } else {\n        got_meminfo = true;\n        SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, memory_info.total);\n        SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, memory_info.used);\n        SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, memory_info.free);\n        SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, memory_info.used * 100 / memory_info.total);\n      }\n    } else {\n      // Memory query failed - likely unified memory GCU (error code 13 = NOT_SUPPORTED)\n      has_unified_memory = true;\n    }\n  }\n  if (!got_meminfo && !has_unified_memory && efmlDeviceGetMemoryInfo) {\n    efmlMemory_v1_t memory_info;\n    last_efml_return_status = efmlDeviceGetMemoryInfo(device, &memory_info);\n    if (last_efml_return_status == EFML_SUCCESS) {\n      // Check if this is a unified memory GCU (total == 0 indicates unified memory)\n      if (memory_info.total == 0) {\n        has_unified_memory = true;\n      } else {\n        SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, memory_info.total);\n        SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, memory_info.used);\n        SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, memory_info.free);\n        SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, memory_info.used * 100 / memory_info.total);\n      }\n    } else {\n      // Memory query failed - likely unified memory GCU\n      has_unified_memory = true;\n    }\n  }\n\n  // Handle unified memory GCUs - query actual GCU allocations and system memory\n  if (has_unified_memory) {\n    // Get actual GCU memory usage from running processes\n    unsigned long long gcu_used_memory = 0;\n\n    // Sum up memory used by compute processes\n    if (efmlDeviceGetComputeRunningProcesses_v3 || efmlDeviceGetComputeRunningProcesses_v2 ||\n        efmlDeviceGetComputeRunningProcesses_v1) {\n      unsigned int process_count = 0;\n      efmlReturn_v1_t (*getProcesses)(efmlDevice_t, unsigned int *, void *) = NULL;\n      size_t process_info_size = 0;\n\n      // Choose the latest available version\n      if (efmlDeviceGetComputeRunningProcesses_v3) {\n        getProcesses = efmlDeviceGetComputeRunningProcesses[3];\n        process_info_size = sizeof(efmlProcessInfo_v3_t);\n      } else if (efmlDeviceGetComputeRunningProcesses_v2) {\n        getProcesses = efmlDeviceGetComputeRunningProcesses[2];\n        process_info_size = sizeof(efmlProcessInfo_v2_t);\n      } else {\n        getProcesses = efmlDeviceGetComputeRunningProcesses[1];\n        process_info_size = sizeof(efmlProcessInfo_v1_t);\n      }\n\n      // First call to get count\n      efmlReturn_v1_t ret = getProcesses(device, &process_count, NULL);\n      if (ret == EFML_SUCCESS || ret == EFML_ERROR_INSUFFICIENT_SIZE) {\n        if (process_count > 0) {\n          void *process_infos = malloc(process_count * process_info_size);\n          if (process_infos) {\n            ret = getProcesses(device, &process_count, process_infos);\n            if (ret == EFML_SUCCESS) {\n              // Sum up memory from all processes\n              for (unsigned int i = 0; i < process_count; i++) {\n                if (efmlDeviceGetComputeRunningProcesses_v3) {\n                  gcu_used_memory += ((efmlProcessInfo_v3_t *)process_infos)[i].usedGcuMemory;\n                } else if (efmlDeviceGetComputeRunningProcesses_v2) {\n                  gcu_used_memory += ((efmlProcessInfo_v2_t *)process_infos)[i].usedGcuMemory;\n                } else {\n                  gcu_used_memory += ((efmlProcessInfo_v1_t *)process_infos)[i].usedGcuMemory;\n                }\n              }\n            }\n            free(process_infos);\n          }\n        }\n      }\n    }\n\n    // Also check graphics processes\n    if (efmlDeviceGetGraphicsRunningProcesses_v3 || efmlDeviceGetGraphicsRunningProcesses_v2 ||\n        efmlDeviceGetGraphicsRunningProcesses_v1) {\n      unsigned int process_count = 0;\n      efmlReturn_v1_t (*getProcesses)(efmlDevice_t, unsigned int *, void *) = NULL;\n      size_t process_info_size = 0;\n\n      if (efmlDeviceGetGraphicsRunningProcesses_v3) {\n        getProcesses = efmlDeviceGetGraphicsRunningProcesses[3];\n        process_info_size = sizeof(efmlProcessInfo_v3_t);\n      } else if (efmlDeviceGetGraphicsRunningProcesses_v2) {\n        getProcesses = efmlDeviceGetGraphicsRunningProcesses[2];\n        process_info_size = sizeof(efmlProcessInfo_v2_t);\n      } else {\n        getProcesses = efmlDeviceGetGraphicsRunningProcesses[1];\n        process_info_size = sizeof(efmlProcessInfo_v1_t);\n      }\n\n      efmlReturn_v1_t ret = getProcesses(device, &process_count, NULL);\n      if (ret == EFML_SUCCESS || ret == EFML_ERROR_INSUFFICIENT_SIZE) {\n        if (process_count > 0) {\n          void *process_infos = malloc(process_count * process_info_size);\n          if (process_infos) {\n            ret = getProcesses(device, &process_count, process_infos);\n            if (ret == EFML_SUCCESS) {\n              for (unsigned int i = 0; i < process_count; i++) {\n                if (efmlDeviceGetGraphicsRunningProcesses_v3) {\n                  gcu_used_memory += ((efmlProcessInfo_v3_t *)process_infos)[i].usedGcuMemory;\n                } else if (efmlDeviceGetGraphicsRunningProcesses_v2) {\n                  gcu_used_memory += ((efmlProcessInfo_v2_t *)process_infos)[i].usedGcuMemory;\n                } else {\n                  gcu_used_memory += ((efmlProcessInfo_v1_t *)process_infos)[i].usedGcuMemory;\n                }\n              }\n            }\n            free(process_infos);\n          }\n        }\n      }\n    }\n\n    // Read MemAvailable from /proc/meminfo for available memory\n    FILE *meminfo = fopen(\"/proc/meminfo\", \"r\");\n    if (meminfo) {\n      unsigned long long available_ram = 0;\n      char line[256];\n\n      while (fgets(line, sizeof(line), meminfo)) {\n        if (sscanf(line, \"MemAvailable: %llu kB\", &available_ram) == 1) {\n          available_ram *= 1024; // Convert KB to bytes\n          break;\n        }\n      }\n      fclose(meminfo);\n\n      if (available_ram > 0) {\n        unsigned long long total_memory = gcu_used_memory + available_ram;\n\n        SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, total_memory);\n        SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, gcu_used_memory);\n        SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, available_ram);\n        if (total_memory > 0) {\n          SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, gcu_used_memory * 100 / total_memory);\n        }\n      }\n    }\n  }\n\n  // Pcie generation used by the device\n  last_efml_return_status = efmlDeviceGetCurrPcieLinkGeneration(device, &dynamic_info->pcie_link_gen);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_link_gen_valid, dynamic_info->valid);\n\n  // Pcie width used by the device\n  last_efml_return_status = efmlDeviceGetCurrPcieLinkWidth(device, &dynamic_info->pcie_link_width);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_link_width_valid, dynamic_info->valid);\n\n  // Pcie reception throughput\n  last_efml_return_status = efmlDeviceGetPcieThroughput(device, EFML_PCIE_UTIL_RX_BYTES, &dynamic_info->pcie_rx);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_rx_valid, dynamic_info->valid);\n\n  // Pcie transmission throughput\n  last_efml_return_status = efmlDeviceGetPcieThroughput(device, EFML_PCIE_UTIL_TX_BYTES, &dynamic_info->pcie_tx);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_tx_valid, dynamic_info->valid);\n\n  // Fan speed\n  last_efml_return_status = efmlDeviceGetFanSpeed(device, &dynamic_info->fan_speed);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_fan_speed_valid, dynamic_info->valid);\n\n  // GCU temperature\n  last_efml_return_status = efmlDeviceGetTemperature(device, EFML_TEMPERATURE_GCU, &dynamic_info->gpu_temp);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_gpu_temp_valid, dynamic_info->valid);\n\n  // Device power usage\n  last_efml_return_status = efmlDeviceGetPowerUsage(device, &dynamic_info->power_draw);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_power_draw_valid, dynamic_info->valid);\n\n  // Maximum enforced power usage\n  last_efml_return_status = efmlDeviceGetEnforcedPowerLimit(device, &dynamic_info->power_draw_max);\n  if (last_efml_return_status == EFML_SUCCESS)\n    SET_VALID(gpuinfo_power_draw_max_valid, dynamic_info->valid);\n\n  // DRS mode\n  if (efmlDeviceGetDrsMode) {\n    unsigned currentMode, pendingMode;\n    last_efml_return_status = efmlDeviceGetDrsMode(device, &currentMode, &pendingMode);\n    if (last_efml_return_status == EFML_SUCCESS) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, multi_instance_mode, currentMode == EFML_DEVICE_DRS_ENABLE);\n    }\n  }\n}\n\nstatic void gcuinfo_enflame_get_process_utilization(struct gcu_info_enflame *gcu_info, unsigned num_processes_recovered,\n                                                   struct gpu_process processes[num_processes_recovered]) {\n  efmlDevice_t device = gcu_info->gcuhandle;\n\n  if (num_processes_recovered && efmlDeviceGetProcessUtilization) {\n    unsigned samples_count = 0;\n    efmlReturn_v1_t retval =\n        efmlDeviceGetProcessUtilization(device, NULL, &samples_count, gcu_info->last_utilization_timestamp);\n    if (retval != EFML_ERROR_INSUFFICIENT_SIZE)\n      return;\n    efmlProcessUtilizationSample_t *samples = malloc(samples_count * sizeof(*samples));\n    retval = efmlDeviceGetProcessUtilization(device, samples, &samples_count, gcu_info->last_utilization_timestamp);\n    if (retval != EFML_SUCCESS) {\n      free(samples);\n      return;\n    }\n    unsigned long long newest_timestamp_candidate = gcu_info->last_utilization_timestamp;\n    for (unsigned i = 0; i < samples_count; ++i) {\n      bool process_matched = false;\n      for (unsigned j = 0; !process_matched && j < num_processes_recovered; ++j) {\n        if ((pid_t)samples[i].pid == processes[j].pid && samples[i].sipUtil <= 100 && samples[i].encUtil <= 100 &&\n            samples[i].decUtil <= 100 && samples[i].timeStamp > gcu_info->last_utilization_timestamp) {\n          // Collect the largest valid timestamp for this device to filter out\n          // the samples during the next call to the function\n          // efmlDeviceGetProcessUtilization\n          if (samples[i].timeStamp > newest_timestamp_candidate)\n            newest_timestamp_candidate = samples[i].timeStamp;\n\n          SET_GPUINFO_PROCESS(&processes[j], gpu_usage, samples[i].sipUtil);\n          SET_GPUINFO_PROCESS(&processes[j], encode_usage, samples[i].encUtil);\n          SET_GPUINFO_PROCESS(&processes[j], decode_usage, samples[i].decUtil);\n          process_matched = true;\n        }\n      }\n    }\n    gcu_info->last_utilization_timestamp = newest_timestamp_candidate;\n    free(samples);\n  }\n  // Mark the ones w/o update since last sample period to 0% usage\n  for (unsigned j = 0; j < num_processes_recovered; ++j) {\n    if (!IS_VALID(gpuinfo_process_gpu_usage_valid, processes[j].valid))\n      SET_GPUINFO_PROCESS(&processes[j], gpu_usage, 0);\n    if (!IS_VALID(gpuinfo_process_encode_usage_valid, processes[j].valid))\n      SET_GPUINFO_PROCESS(&processes[j], encode_usage, 0);\n    if (!IS_VALID(gpuinfo_process_decode_usage_valid, processes[j].valid))\n      SET_GPUINFO_PROCESS(&processes[j], decode_usage, 0);\n  }\n}\n\nstatic void gcuinfo_enflame_get_running_processes(struct gpu_info *_gcu_info) {\n  struct gcu_info_enflame *gcu_info = container_of(_gcu_info, struct gcu_info_enflame, base);\n  efmlDevice_t device = gcu_info->gcuhandle;\n  bool validProcessGathering = false;\n  for (unsigned version = 3; !validProcessGathering && version > 0; version--) {\n    // Get the size of the actual function being used\n    size_t sizeof_efmlProcessInfo;\n    switch (version) {\n    case 3:\n      sizeof_efmlProcessInfo = sizeof(efmlProcessInfo_v3_t);\n      break;\n    case 2:\n      sizeof_efmlProcessInfo = sizeof(efmlProcessInfo_v2_t);\n      break;\n    default:\n      sizeof_efmlProcessInfo = sizeof(efmlProcessInfo_v1_t);\n      break;\n    }\n\n    _gcu_info->processes_count = 0;\n    static size_t array_size = 0;\n    static char *retrieved_infos = NULL;\n    unsigned graphical_count = 0, compute_count = 0, recovered_count;\n    if (efmlDeviceGetGraphicsRunningProcesses[version]) {\n    retry_query_graphical:\n      recovered_count = array_size;\n      last_efml_return_status =\n          efmlDeviceGetGraphicsRunningProcesses[version](device, &recovered_count, retrieved_infos);\n      if (last_efml_return_status == EFML_ERROR_INSUFFICIENT_SIZE) {\n        array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n        retrieved_infos = reallocarray(retrieved_infos, array_size, sizeof_efmlProcessInfo);\n        if (!retrieved_infos) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n        goto retry_query_graphical;\n      }\n      if (last_efml_return_status == EFML_SUCCESS) {\n        validProcessGathering = true;\n        graphical_count = recovered_count;\n      }\n    }\n\n    if (efmlDeviceGetComputeRunningProcesses[version]) {\n    retry_query_compute:\n      recovered_count = array_size - graphical_count;\n      last_efml_return_status = efmlDeviceGetComputeRunningProcesses[version](\n          device, &recovered_count, retrieved_infos + graphical_count * sizeof_efmlProcessInfo);\n      if (last_efml_return_status == EFML_ERROR_INSUFFICIENT_SIZE) {\n        array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n        retrieved_infos = reallocarray(retrieved_infos, array_size, sizeof_efmlProcessInfo);\n        if (!retrieved_infos) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n        goto retry_query_compute;\n      }\n      if (last_efml_return_status == EFML_SUCCESS) {\n        validProcessGathering = true;\n        compute_count = recovered_count;\n      }\n    }\n\n    if (efmlDeviceGetMPSComputeRunningProcesses[version]) {\n    retry_query_compute_MPS:\n      recovered_count = array_size - graphical_count - compute_count;\n      last_efml_return_status = efmlDeviceGetMPSComputeRunningProcesses[version](\n          device, &recovered_count, retrieved_infos + (graphical_count + compute_count) * sizeof_efmlProcessInfo);\n      if (last_efml_return_status == EFML_ERROR_INSUFFICIENT_SIZE) {\n        array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n        retrieved_infos = reallocarray(retrieved_infos, array_size, sizeof_efmlProcessInfo);\n        if (!retrieved_infos) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n        goto retry_query_compute_MPS;\n      }\n      if (last_efml_return_status == EFML_SUCCESS) {\n        validProcessGathering = true;\n        compute_count += recovered_count;\n      }\n    }\n\n    if (!validProcessGathering)\n      continue;\n\n    _gcu_info->processes_count = graphical_count + compute_count;\n    if (_gcu_info->processes_count > 0) {\n      if (_gcu_info->processes_count > _gcu_info->processes_array_size) {\n        _gcu_info->processes_array_size = _gcu_info->processes_count + COMMON_PROCESS_LINEAR_REALLOC_INC;\n        _gcu_info->processes =\n            reallocarray(_gcu_info->processes, _gcu_info->processes_array_size, sizeof(*_gcu_info->processes));\n        if (!_gcu_info->processes) {\n          perror(\"Could not allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n      }\n      memset(_gcu_info->processes, 0, _gcu_info->processes_count * sizeof(*_gcu_info->processes));\n      for (unsigned i = 0; i < graphical_count + compute_count; ++i) {\n        if (i < graphical_count)\n          _gcu_info->processes[i].type = gpu_process_graphical;\n        else\n          _gcu_info->processes[i].type = gpu_process_compute;\n        switch (version) {\n        case 2: {\n          efmlProcessInfo_v2_t *pinfo = (efmlProcessInfo_v2_t *)retrieved_infos;\n          _gcu_info->processes[i].pid = pinfo[i].pid;\n          _gcu_info->processes[i].gpu_memory_usage = pinfo[i].usedGcuMemory;\n        } break;\n        case 3: {\n          efmlProcessInfo_v3_t *pinfo = (efmlProcessInfo_v3_t *)retrieved_infos;\n          _gcu_info->processes[i].pid = pinfo[i].pid;\n          _gcu_info->processes[i].gpu_memory_usage = pinfo[i].usedGcuMemory;\n        } break;\n        default: {\n          efmlProcessInfo_v1_t *pinfo = (efmlProcessInfo_v1_t *)retrieved_infos;\n          _gcu_info->processes[i].pid = pinfo[i].pid;\n          _gcu_info->processes[i].gpu_memory_usage = pinfo[i].usedGcuMemory;\n        } break;\n        }\n        SET_VALID(gpuinfo_process_gpu_memory_usage_valid, _gcu_info->processes[i].valid);\n      }\n    }\n  }\n  // If the GCU is in DRS mode; process utilization is not supported\n  if (!gcu_info->base.dynamic_info.multi_instance_mode)\n    gcuinfo_enflame_get_process_utilization(gcu_info, _gcu_info->processes_count, _gcu_info->processes);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo.c",
    "content": "/*\n *\n * Copyright (C) 2017-2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <ctype.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include \"nvtop/extract_gpuinfo.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/get_process_info.h\"\n#include \"nvtop/time.h\"\n#include \"uthash.h\"\n\n#define HASH_FIND_PID(head, key_ptr, out_ptr) HASH_FIND(hh, head, key_ptr, sizeof(*key_ptr), out_ptr)\n\n#define HASH_ADD_PID(head, in_ptr) HASH_ADD(hh, head, pid, sizeof(pid_t), in_ptr)\n\nconst char drm_pdev[] = \"drm-pdev\";\nconst char drm_client_id[] = \"drm-client-id\";\n\nstruct process_info_cache {\n  pid_t pid;\n  char *cmdline;\n  char *user_name;\n  double last_total_consumed_cpu_time;\n  nvtop_time last_measurement_timestamp;\n  UT_hash_handle hh;\n};\n\nstruct process_info_cache *cached_process_info = NULL;\nstruct process_info_cache *updated_process_info = NULL;\n\nstatic LIST_HEAD(gpu_vendors);\n\nvoid register_gpu_vendor(struct gpu_vendor *vendor) { list_add(&vendor->list, &gpu_vendors); }\n\nbool gpuinfo_init_info_extraction(unsigned *monitored_dev_count, struct list_head *devices) {\n  struct gpu_vendor *vendor;\n\n  *monitored_dev_count = 0;\n  list_for_each_entry(vendor, &gpu_vendors, list) {\n    unsigned vendor_devices_count = 0;\n\n    if (vendor->init()) {\n      bool retval = vendor->get_device_handles(devices, &vendor_devices_count);\n      if (!retval || (retval && vendor_devices_count == 0)) {\n        vendor->shutdown();\n        vendor_devices_count = 0;\n      }\n    }\n\n    *monitored_dev_count += vendor_devices_count;\n  }\n\n  return true;\n}\n\nbool gpuinfo_shutdown_info_extraction(struct list_head *devices) {\n  struct gpu_info *device, *tmp;\n  struct gpu_vendor *vendor;\n\n  list_for_each_entry_safe(device, tmp, devices, list) {\n    free(device->processes);\n    list_del(&device->list);\n  }\n\n  list_for_each_entry(vendor, &gpu_vendors, list) { vendor->shutdown(); }\n  gpuinfo_clear_cache();\n  return true;\n}\n\nbool gpuinfo_populate_static_infos(struct list_head *devices) {\n  struct gpu_info *device;\n\n  list_for_each_entry(device, devices, list) { device->vendor->populate_static_info(device); }\n  return true;\n}\n\nstatic void calculate_effective_load(struct gpuinfo_dynamic_info *dynamic_info) {\n  if (GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, gpu_util_rate) &&\n      GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, power_draw) &&\n      GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, power_draw_max) && dynamic_info->power_draw_max > 0) {\n    double power_factor = (double)dynamic_info->power_draw / (double)dynamic_info->power_draw_max;\n    unsigned int effective_load = (unsigned int)(dynamic_info->gpu_util_rate * power_factor);\n    effective_load = effective_load > 100 ? 100 : effective_load;\n    SET_GPUINFO_DYNAMIC(dynamic_info, effective_load_rate, effective_load);\n  } else {\n    RESET_GPUINFO_DYNAMIC(dynamic_info, effective_load_rate);\n  }\n}\n\nbool gpuinfo_refresh_dynamic_info(struct list_head *devices) {\n  struct gpu_info *device;\n\n  list_for_each_entry(device, devices, list) {\n    device->vendor->refresh_dynamic_info(device);\n    calculate_effective_load(&device->dynamic_info);\n  }\n  return true;\n}\n\n#undef MYMIN\n#define MYMIN(a, b) (((a) < (b)) ? (a) : (b))\nbool gpuinfo_fix_dynamic_info_from_process_info(struct list_head *devices) {\n  struct gpu_info *device;\n\n  list_for_each_entry(device, devices, list) {\n\n    struct gpuinfo_dynamic_info *dynamic_info = &device->dynamic_info;\n    // If the global GPU usage is not available, try computing it from the processes info\n    // Some integrated AMDGPU report 100% usage while process usage is actually low\n\n    bool needGpuRate = true;\n    bool validReportedGpuRate = GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, gpu_util_rate);\n    unsigned reportedGpuRate = dynamic_info->gpu_util_rate;\n    RESET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate);\n\n    // AMDGPU does not provide encode and decode utilization through the DRM sensor info.\n    // Update them here since per-process sysfs exposes this information.\n    bool needGpuEncode = !GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, encoder_rate);\n    bool needGpuDecode = !GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, decoder_rate);\n    bool needGPUMemory = !GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, used_memory) &&\n                         GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, total_memory);\n    if (needGpuRate || needGpuEncode || needGpuDecode || needGPUMemory) {\n      for (unsigned processIdx = 0; processIdx < device->processes_count; ++processIdx) {\n        struct gpu_process *process_info = &device->processes[processIdx];\n        if (needGpuRate && GPUINFO_PROCESS_FIELD_VALID(process_info, gpu_usage)) {\n          if (GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, gpu_util_rate)) {\n            dynamic_info->gpu_util_rate = MYMIN(100, dynamic_info->gpu_util_rate + process_info->gpu_usage);\n          } else {\n            SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, MYMIN(100, process_info->gpu_usage));\n          }\n        }\n        if (needGpuEncode && GPUINFO_PROCESS_FIELD_VALID(process_info, encode_usage)) {\n          if (GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, encoder_rate)) {\n            dynamic_info->encoder_rate = MYMIN(100, dynamic_info->encoder_rate + process_info->encode_usage);\n          } else {\n            SET_GPUINFO_DYNAMIC(dynamic_info, encoder_rate, MYMIN(100, process_info->encode_usage));\n          }\n        }\n        if (needGpuDecode && GPUINFO_PROCESS_FIELD_VALID(process_info, decode_usage)) {\n          if (GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, decoder_rate)) {\n            dynamic_info->decoder_rate = MYMIN(100, dynamic_info->decoder_rate + process_info->decode_usage);\n          } else {\n            SET_GPUINFO_DYNAMIC(dynamic_info, decoder_rate, MYMIN(100, process_info->decode_usage));\n          }\n        }\n        if (needGPUMemory && GPUINFO_PROCESS_FIELD_VALID(process_info, gpu_memory_usage)) {\n          if (GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, used_memory)) {\n            dynamic_info->used_memory += dynamic_info->used_memory + process_info->gpu_memory_usage;\n          } else {\n            SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, process_info->gpu_memory_usage);\n          }\n        }\n      }\n    }\n    // Sanitize what we got from processes: we can't have more than the total!\n    if (needGPUMemory && GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, used_memory) &&\n        GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, total_memory) &&\n        dynamic_info->used_memory > dynamic_info->total_memory) {\n      RESET_GPUINFO_DYNAMIC(dynamic_info, used_memory);\n    }\n    if (needGPUMemory && !GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, free_memory) &&\n        GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, used_memory) &&\n        GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, total_memory)) {\n      // We already checked that used_memory <= total_memory so no underflow can happen here\n      unsigned long long free = dynamic_info->total_memory - dynamic_info->used_memory;\n      SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, free);\n    }\n    if (!GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, gpu_util_rate) && validReportedGpuRate) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, reportedGpuRate);\n    } else if (GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, gpu_util_rate) && validReportedGpuRate) {\n      SET_GPUINFO_DYNAMIC(\n          dynamic_info, gpu_util_rate,\n          (dynamic_info->gpu_util_rate > reportedGpuRate ? dynamic_info->gpu_util_rate : reportedGpuRate));\n    }\n    calculate_effective_load(dynamic_info);\n  }\n  return true;\n}\n#undef MYMIN\n\nstatic void gpuinfo_populate_process_info(struct gpu_info *device) {\n  for (unsigned j = 0; j < device->processes_count; ++j) {\n    pid_t current_pid = device->processes[j].pid;\n    struct process_info_cache *cached_pid_info;\n\n    HASH_FIND_PID(cached_process_info, &current_pid, cached_pid_info);\n    if (!cached_pid_info) {\n      HASH_FIND_PID(updated_process_info, &current_pid, cached_pid_info);\n      if (!cached_pid_info) {\n        // Newly encountered pid\n        cached_pid_info = calloc(1, sizeof(*cached_pid_info));\n        cached_pid_info->pid = current_pid;\n        get_username_from_pid(current_pid, &cached_pid_info->user_name);\n        get_command_from_pid(current_pid, &cached_pid_info->cmdline);\n        cached_pid_info->last_total_consumed_cpu_time = -1.;\n        HASH_ADD_PID(updated_process_info, cached_pid_info);\n      }\n    } else {\n      // Already encountered so delete from cached list to avoid freeing\n      // memory at the end of this function\n      HASH_DEL(cached_process_info, cached_pid_info);\n      HASH_ADD_PID(updated_process_info, cached_pid_info);\n    }\n\n    if (cached_pid_info->cmdline) {\n      SET_GPUINFO_PROCESS(&device->processes[j], cmdline, cached_pid_info->cmdline);\n    }\n    if (cached_pid_info->user_name) {\n      SET_GPUINFO_PROCESS(&device->processes[j], user_name, cached_pid_info->user_name);\n    }\n\n    struct process_cpu_usage cpu_usage;\n    if (get_process_info(current_pid, &cpu_usage)) {\n      if (cached_pid_info->last_total_consumed_cpu_time > -1.) {\n        double usage_percent = round(\n            100. *\n            (cpu_usage.total_user_time + cpu_usage.total_kernel_time - cached_pid_info->last_total_consumed_cpu_time) /\n            nvtop_difftime(cached_pid_info->last_measurement_timestamp, cpu_usage.timestamp));\n        SET_GPUINFO_PROCESS(&device->processes[j], cpu_usage, (unsigned)usage_percent);\n      } else {\n        SET_GPUINFO_PROCESS(&device->processes[j], cpu_usage, 0);\n      }\n      SET_GPUINFO_PROCESS(&device->processes[j], cpu_memory_res, cpu_usage.resident_memory);\n      SET_GPUINFO_PROCESS(&device->processes[j], cpu_memory_virt, cpu_usage.virtual_memory);\n      cached_pid_info->last_measurement_timestamp = cpu_usage.timestamp;\n      cached_pid_info->last_total_consumed_cpu_time = cpu_usage.total_kernel_time + cpu_usage.total_user_time;\n    } else {\n      cached_pid_info->last_total_consumed_cpu_time = -1;\n    }\n    // Process memory usage percent of total device memory\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, total_memory) &&\n        GPUINFO_PROCESS_FIELD_VALID(&device->processes[j], gpu_memory_usage)) {\n      // Sanitize process inputs\n      if (device->dynamic_info.total_memory < device->processes[j].gpu_memory_usage) {\n        RESET_GPUINFO_PROCESS(&device->processes[j], gpu_memory_usage);\n      } else {\n        double percentage = fmin(\n            round(100. * ((double)device->processes[j].gpu_memory_usage / (double)device->dynamic_info.total_memory)),\n            100.);\n        SET_GPUINFO_PROCESS(&device->processes[j], gpu_memory_percentage, (unsigned)percentage);\n      }\n    }\n  }\n}\n\nstatic void gpuinfo_clean_old_cache(void) {\n  struct process_info_cache *pid_not_encountered, *tmp;\n  HASH_ITER(hh, cached_process_info, pid_not_encountered, tmp) {\n    HASH_DEL(cached_process_info, pid_not_encountered);\n    free(pid_not_encountered->cmdline);\n    free(pid_not_encountered->user_name);\n    free(pid_not_encountered);\n  }\n  cached_process_info = updated_process_info;\n  updated_process_info = NULL;\n}\n\nbool gpuinfo_refresh_processes(struct list_head *devices) {\n  struct gpu_info *device;\n\n  list_for_each_entry(device, devices, list) { device->processes_count = 0; }\n\n  // Go through the /proc hierarchy once and populate the processes for all registered GPUs\n  processinfo_sweep_fdinfos();\n\n  list_for_each_entry(device, devices, list) {\n    device->vendor->refresh_running_processes(device);\n    gpuinfo_populate_process_info(device);\n  }\n  gpuinfo_clean_old_cache();\n\n  return true;\n}\n\nbool gpuinfo_utilisation_rate(struct list_head *devices) {\n  struct gpu_info *device;\n\n  list_for_each_entry(device, devices, list) {\n    if (device->vendor->refresh_utilisation_rate)\n      device->vendor->refresh_utilisation_rate(device);\n  }\n\n  return true;\n}\n\nvoid gpuinfo_clear_cache(void) {\n  if (cached_process_info) {\n    struct process_info_cache *pid_cached, *tmp;\n    HASH_ITER(hh, cached_process_info, pid_cached, tmp) {\n      HASH_DEL(cached_process_info, pid_cached);\n      free(pid_cached->cmdline);\n      free(pid_cached->user_name);\n      free(pid_cached);\n    }\n  }\n}\n\nbool extract_drm_fdinfo_key_value(char *buf, char **key, char **val) {\n  char *p = buf;\n\n  p = index(buf, ':');\n  if (!p || p == buf)\n    return false;\n  *p = '\\0';\n\n  while (*++p && isspace(*p))\n    ;\n  if (!*p)\n    return false;\n\n  *key = buf;\n  *val = p;\n\n  return true;\n}\n\nextern inline unsigned busy_usage_from_time_usage_round(uint64_t current_use_ns, uint64_t previous_use_ns,\n                                                        uint64_t time_between_measurement);\n\nunsigned nvtop_pcie_gen_from_link_speed(unsigned linkSpeed) {\n  unsigned pcieGen = 0;\n  switch (linkSpeed) {\n  case 2:\n    pcieGen = 1;\n    break;\n  case 5:\n    pcieGen = 2;\n    break;\n  case 8:\n    pcieGen = 3;\n    break;\n  case 16:\n    pcieGen = 4;\n    break;\n  case 32:\n    pcieGen = 5;\n    break;\n  case 64:\n    pcieGen = 6;\n    break;\n  }\n  return pcieGen;\n}\n\nvoid gpuinfo_refresh_utilisation_rate(struct gpu_info *gpu_info) {\n  /*\n   * kernel Documentation/gpu/drm-usage-stats.rst:\n   *  - drm-maxfreq-<keystr>: <uint> [Hz|MHz|KHz]\n   *  Engine identifier string must be the same as the one specified in the\n   *  drm-engine-<keystr> tag and shall contain the maximum frequency for the given\n   *  engine. Taken together with drm-cycles-<keystr>, this can be used to calculate\n   *  percentage utilization of the engine, whereas drm-engine-<keystr> only reflects\n   *  time active without considering what frequency the engine is operating as a\n   *  percentage of it's maximum frequency.\n   *\n   */\n\n  uint64_t gfx_total_process_cycles = 0;\n  uint64_t total_delta = 0;\n  unsigned int utilisation_rate;\n  uint64_t max_freq_hz;\n  double avg_delta_secs;\n  unsigned int ec;\n\n  for (unsigned processIdx = 0; processIdx < gpu_info->processes_count; ++processIdx) {\n    struct gpu_process *process_info = &gpu_info->processes[processIdx];\n\n    gfx_total_process_cycles += process_info->gpu_cycles;\n    total_delta += process_info->sample_delta;\n  }\n\n  if (!gfx_total_process_cycles)\n    return;\n\n  if (IS_VALID(gpuinfo_engine_count_valid, gpu_info->static_info.valid))\n          ec = gpu_info->static_info.engine_count;\n  else\n          ec = 1;\n\n  avg_delta_secs = ((double)total_delta / gpu_info->processes_count) / 1000000000.0;\n  max_freq_hz = gpu_info->dynamic_info.gpu_clock_speed_max * 1000000;\n  utilisation_rate = (unsigned int)((((double)gfx_total_process_cycles) / (((double)max_freq_hz) * avg_delta_secs * ec)) * 100);\n  utilisation_rate = utilisation_rate > 100 ? 100 : utilisation_rate;\n\n  SET_GPUINFO_DYNAMIC(&gpu_info->dynamic_info, gpu_util_rate, utilisation_rate);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_amdgpu.c",
    "content": "/*\n * Copyright (C) 2012 Lauri Kasanen\n * Copyright (C) 2018 Genesis Cloud Ltd.\n * Copyright (C) 2022 YiFei Zhu <zhuyifei1999@gmail.com>\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n * Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.\n *\n * This file is part of Nvtop and adapted from radeontop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/common.h\"\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include <assert.h>\n#include <dirent.h>\n#include <dlfcn.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <inttypes.h>\n#include <libdrm/amdgpu.h>\n#include <libdrm/amdgpu_drm.h>\n#include <math.h>\n#include <stdarg.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/syscall.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <uthash.h>\n#include <xf86drm.h>\n\n// extern\nconst char *amdgpu_parse_marketing_name(struct amdgpu_gpu_info *info);\n\n// Local function pointers to DRM interface\nstatic typeof(drmGetDevices) *_drmGetDevices;\nstatic typeof(drmGetDevices2) *_drmGetDevices2;\nstatic typeof(drmFreeDevices) *_drmFreeDevices;\nstatic typeof(drmGetVersion) *_drmGetVersion;\nstatic typeof(drmFreeVersion) *_drmFreeVersion;\nstatic typeof(drmGetMagic) *_drmGetMagic;\nstatic typeof(drmAuthMagic) *_drmAuthMagic;\nstatic typeof(drmDropMaster) *_drmDropMaster;\n\n// Local function pointers to amdgpu DRM interface\nstatic typeof(amdgpu_device_initialize) *_amdgpu_device_initialize;\nstatic typeof(amdgpu_device_deinitialize) *_amdgpu_device_deinitialize;\nstatic typeof(amdgpu_get_marketing_name) *_amdgpu_get_marketing_name;\nstatic typeof(amdgpu_query_hw_ip_info) *_amdgpu_query_hw_ip_info;\nstatic typeof(amdgpu_query_gpu_info) *_amdgpu_query_gpu_info;\nstatic typeof(amdgpu_query_info) *_amdgpu_query_info;\nstatic typeof(amdgpu_query_sensor_info) *_amdgpu_query_sensor_info;\n\nstatic void *libdrm_handle;\nstatic void *libdrm_amdgpu_handle;\n\nstatic int last_libdrm_return_status = 0;\nstatic char didnt_call_gpuinfo_init[] = \"uninitialized\";\nstatic const char *local_error_string = didnt_call_gpuinfo_init;\n\n#define HASH_FIND_CLIENT(head, key_ptr, out_ptr) HASH_FIND(hh, head, key_ptr, sizeof(struct unique_cache_id), out_ptr)\n\n#define HASH_ADD_CLIENT(head, in_ptr) HASH_ADD(hh, head, client_id, sizeof(struct unique_cache_id), in_ptr)\n\n#define SET_AMDGPU_CACHE(cachePtr, field, value) SET_VALUE(cachePtr, field, value, amdgpu_cache_)\n#define RESET_AMDGPU_CACHE(cachePtr, field) INVALIDATE_VALUE(cachePtr, field, amdgpu_cache_)\n#define AMDGPU_CACHE_FIELD_VALID(cachePtr, field) VALUE_IS_VALID(cachePtr, field, amdgpu_cache_)\n\nenum amdgpu_process_info_cache_valid {\n  amdgpu_cache_gfx_engine_used_valid = 0,\n  amdgpu_cache_compute_engine_used_valid,\n  amdgpu_cache_enc_engine_used_valid,\n  amdgpu_cache_dec_engine_used_valid,\n  amdgpu_cache_process_info_cache_valid_count\n};\n\nstruct __attribute__((__packed__)) unique_cache_id {\n  unsigned client_id;\n  pid_t pid;\n  char *pdev;\n};\n\nstruct amdgpu_process_info_cache {\n  struct unique_cache_id client_id;\n  uint64_t gfx_engine_used;\n  uint64_t compute_engine_used;\n  uint64_t enc_engine_used;\n  uint64_t dec_engine_used;\n  nvtop_time last_measurement_tstamp;\n  unsigned char valid[(amdgpu_cache_process_info_cache_valid_count + CHAR_BIT - 1) / CHAR_BIT];\n  UT_hash_handle hh;\n};\n\nstruct gpu_info_amdgpu {\n  struct gpu_info base;\n\n  drmVersionPtr drmVersion;\n  int fd;\n  amdgpu_device_handle amdgpu_device;\n\n  // We poll the fan frequently enough and want to avoid the open/close overhead of the sysfs file\n  FILE *fanSpeedFILE; // FILE* for this device current fan speed\n  FILE *PCIeBW;       // FILE* for this device PCIe bandwidth over one second\n  FILE *powerCap;     // FILE* for this device power cap\n\n  nvtop_device *amdgpuDevice; // The AMDGPU driver device\n  nvtop_device *hwmonDevice;  // The AMDGPU driver hwmon device\n\n  struct amdgpu_process_info_cache *last_update_process_cache, *current_update_process_cache; // Cached processes info\n\n  // Used to compute the actual fan speed\n  unsigned maxFanValue;\n};\n\nunsigned amdgpu_count;\nstatic struct gpu_info_amdgpu *gpu_infos;\n\nstatic bool gpuinfo_amdgpu_init(void);\nstatic void gpuinfo_amdgpu_shutdown(void);\nstatic const char *gpuinfo_amdgpu_last_error_string(void);\nstatic bool gpuinfo_amdgpu_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_amdgpu_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_amdgpu_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_amdgpu_get_running_processes(struct gpu_info *_gpu_info);\n\nstruct gpu_vendor gpu_vendor_amdgpu = {\n    .init = gpuinfo_amdgpu_init,\n    .shutdown = gpuinfo_amdgpu_shutdown,\n    .last_error_string = gpuinfo_amdgpu_last_error_string,\n    .get_device_handles = gpuinfo_amdgpu_get_device_handles,\n    .populate_static_info = gpuinfo_amdgpu_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_amdgpu_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_amdgpu_get_running_processes,\n    .name = \"AMD\",\n};\n\nstatic int readAttributeFromDevice(nvtop_device *dev, const char *sysAttr, const char *format, ...);\n\n__attribute__((constructor)) static void init_extract_gpuinfo_amdgpu(void) { register_gpu_vendor(&gpu_vendor_amdgpu); }\n\nstatic int wrap_drmGetDevices(drmDevicePtr devices[], int max_devices) {\n  assert(_drmGetDevices2 || _drmGetDevices);\n\n  if (_drmGetDevices2)\n    return _drmGetDevices2(0, devices, max_devices);\n  return _drmGetDevices(devices, max_devices);\n}\n\nstatic bool parse_drm_fdinfo_amd(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info);\n\nstatic bool gpuinfo_amdgpu_init(void) {\n  libdrm_handle = dlopen(\"libdrm.so\", RTLD_LAZY);\n  if (!libdrm_handle)\n    libdrm_handle = dlopen(\"libdrm.so.2\", RTLD_LAZY);\n  if (!libdrm_handle)\n    libdrm_handle = dlopen(\"libdrm.so.1\", RTLD_LAZY);\n  if (!libdrm_handle) {\n    local_error_string = dlerror();\n    return false;\n  }\n\n  _drmGetDevices2 = dlsym(libdrm_handle, \"drmGetDevices2\");\n  if (!_drmGetDevices2)\n    _drmGetDevices = dlsym(libdrm_handle, \"drmGetDevices\");\n  if (!_drmGetDevices2 && !_drmGetDevices)\n    goto init_error_clean_exit;\n\n  _drmFreeDevices = dlsym(libdrm_handle, \"drmFreeDevices\");\n  if (!_drmFreeDevices)\n    goto init_error_clean_exit;\n\n  _drmGetVersion = dlsym(libdrm_handle, \"drmGetVersion\");\n  if (!_drmGetVersion)\n    goto init_error_clean_exit;\n\n  _drmFreeVersion = dlsym(libdrm_handle, \"drmFreeVersion\");\n  if (!_drmFreeVersion)\n    goto init_error_clean_exit;\n\n  _drmGetMagic = dlsym(libdrm_handle, \"drmGetMagic\");\n  if (!_drmGetMagic)\n    goto init_error_clean_exit;\n\n  _drmAuthMagic = dlsym(libdrm_handle, \"drmAuthMagic\");\n  if (!_drmAuthMagic)\n    goto init_error_clean_exit;\n\n  _drmDropMaster = dlsym(libdrm_handle, \"drmDropMaster\");\n  if (!_drmDropMaster)\n    goto init_error_clean_exit;\n\n  libdrm_amdgpu_handle = dlopen(\"libdrm_amdgpu.so\", RTLD_LAZY);\n  if (!libdrm_amdgpu_handle)\n    libdrm_amdgpu_handle = dlopen(\"libdrm_amdgpu.so.1\", RTLD_LAZY);\n\n  if (libdrm_amdgpu_handle) {\n    _amdgpu_device_initialize = dlsym(libdrm_amdgpu_handle, \"amdgpu_device_initialize\");\n    _amdgpu_device_deinitialize = dlsym(libdrm_amdgpu_handle, \"amdgpu_device_deinitialize\");\n    _amdgpu_get_marketing_name = dlsym(libdrm_amdgpu_handle, \"amdgpu_get_marketing_name\");\n    _amdgpu_query_hw_ip_info = dlsym(libdrm_amdgpu_handle, \"amdgpu_query_hw_ip_info\");\n    _amdgpu_query_info = dlsym(libdrm_amdgpu_handle, \"amdgpu_query_info\");\n    _amdgpu_query_gpu_info = dlsym(libdrm_amdgpu_handle, \"amdgpu_query_gpu_info\");\n    _amdgpu_query_sensor_info = dlsym(libdrm_amdgpu_handle, \"amdgpu_query_sensor_info\");\n  }\n\n  local_error_string = NULL;\n  return true;\n\ninit_error_clean_exit:\n  dlclose(libdrm_handle);\n  libdrm_handle = NULL;\n  return false;\n}\n\nstatic void gpuinfo_amdgpu_shutdown(void) {\n  for (unsigned i = 0; i < amdgpu_count; ++i) {\n    struct gpu_info_amdgpu *gpu_info = &gpu_infos[i];\n    if (gpu_info->fanSpeedFILE)\n      fclose(gpu_info->fanSpeedFILE);\n    if (gpu_info->PCIeBW)\n      fclose(gpu_info->PCIeBW);\n    if (gpu_info->powerCap)\n      fclose(gpu_info->powerCap);\n    nvtop_device_unref(gpu_info->amdgpuDevice);\n    nvtop_device_unref(gpu_info->hwmonDevice);\n    _drmFreeVersion(gpu_info->drmVersion);\n    _amdgpu_device_deinitialize(gpu_info->amdgpu_device);\n    // Clean the process cache\n    struct amdgpu_process_info_cache *cache_entry, *cache_tmp;\n    HASH_ITER(hh, gpu_info->last_update_process_cache, cache_entry, cache_tmp) {\n      HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n      free(cache_entry);\n    }\n  }\n  free(gpu_infos);\n  gpu_infos = NULL;\n  amdgpu_count = 0;\n\n  if (libdrm_handle) {\n    dlclose(libdrm_handle);\n    libdrm_handle = NULL;\n    local_error_string = didnt_call_gpuinfo_init;\n  }\n\n  if (libdrm_amdgpu_handle) {\n    dlclose(libdrm_amdgpu_handle);\n    libdrm_amdgpu_handle = NULL;\n  }\n}\n\nstatic const char *gpuinfo_amdgpu_last_error_string(void) {\n  if (local_error_string) {\n    return local_error_string;\n  } else if (last_libdrm_return_status < 0) {\n    switch (last_libdrm_return_status) {\n    case DRM_ERR_NO_DEVICE:\n      return \"no device\\n\";\n    case DRM_ERR_NO_ACCESS:\n      return \"no access\\n\";\n    case DRM_ERR_NOT_ROOT:\n      return \"not root\\n\";\n    case DRM_ERR_INVALID:\n      return \"invalid args\\n\";\n    case DRM_ERR_NO_FD:\n      return \"no fd\\n\";\n    default:\n      return \"unknown error\\n\";\n    }\n  } else {\n    return \"An unanticipated error occurred while accessing AMDGPU \"\n           \"information\\n\";\n  }\n}\n\nstatic void authenticate_drm(int fd) {\n  drm_magic_t magic;\n\n  if (_drmGetMagic(fd, &magic) < 0) {\n    return;\n  }\n\n  if (_drmAuthMagic(fd, magic) == 0) {\n    if (_drmDropMaster(fd)) {\n      perror(\"Failed to drop DRM master\");\n      fprintf(\n          stderr,\n          \"\\nWARNING: other DRM clients will crash on VT switch while nvtop is running!\\npress ENTER to continue\\n\");\n      fgetc(stdin);\n    }\n    return;\n  }\n\n  // XXX: Ideally I'd implement this too, but I'd need to pull in libxcb and yet\n  // more functions and structs that may break ABI compatibility.\n  // See radeontop auth_xcb.c for what is involved here\n  fprintf(stderr, \"Failed to authenticate to DRM; XCB authentication unimplemented\\n\");\n}\n\nstatic void initDeviceSysfsPaths(struct gpu_info_amdgpu *gpu_info) {\n  // Open the device sys folder to gather information not available through the DRM driver\n  char devicePath[22 + PDEV_LEN];\n  snprintf(devicePath, sizeof(devicePath), \"/sys/bus/pci/devices/%s\", gpu_info->base.pdev);\n  nvtop_device_new_from_syspath(&gpu_info->amdgpuDevice, devicePath);\n  assert(gpu_info->amdgpuDevice != NULL);\n\n  gpu_info->hwmonDevice = nvtop_device_get_hwmon(gpu_info->amdgpuDevice);\n  if (gpu_info->hwmonDevice) {\n    // Open the device hwmon folder (Fan speed are available there)\n    const char *hwmonPath;\n    nvtop_device_get_syspath(gpu_info->hwmonDevice, &hwmonPath);\n    int hwmonFD = open(hwmonPath, O_RDONLY);\n\n    // Look for which fan to use (PWM or RPM)\n    gpu_info->fanSpeedFILE = NULL;\n    unsigned pwmIsEnabled;\n    int NreadPatterns = readAttributeFromDevice(gpu_info->hwmonDevice, \"pwm1_enable\", \"%u\", &pwmIsEnabled);\n    bool usePWMSensor = NreadPatterns == 1 && pwmIsEnabled > 0;\n\n    bool useRPMSensor = false;\n    if (!usePWMSensor) {\n      unsigned rpmIsEnabled;\n      NreadPatterns = readAttributeFromDevice(gpu_info->hwmonDevice, \"fan1_enable\", \"%u\", &rpmIsEnabled);\n      useRPMSensor = NreadPatterns && rpmIsEnabled > 0;\n    }\n    // Either RPM or PWM or neither\n    assert((useRPMSensor ^ usePWMSensor) || (!useRPMSensor && !usePWMSensor));\n    if (usePWMSensor || useRPMSensor) {\n      char *maxFanSpeedFile = usePWMSensor ? \"pwm1_max\" : \"fan1_max\";\n      char *fanSensorFile = usePWMSensor ? \"pwm1\" : \"fan1_input\";\n      unsigned maxSpeedVal;\n      NreadPatterns = readAttributeFromDevice(gpu_info->hwmonDevice, maxFanSpeedFile, \"%u\", &maxSpeedVal);\n      if (NreadPatterns == 1) {\n        gpu_info->maxFanValue = maxSpeedVal;\n        // Open the fan file for dynamic info gathering\n        int fanSpeedFD = openat(hwmonFD, fanSensorFile, O_RDONLY);\n        if (fanSpeedFD >= 0) {\n          gpu_info->fanSpeedFILE = fdopen(fanSpeedFD, \"r\");\n          if (!gpu_info->fanSpeedFILE)\n            close(fanSpeedFD);\n        }\n      }\n    }\n    // Open the power cap file for dynamic info gathering\n    gpu_info->powerCap = NULL;\n    int powerCapFD = openat(hwmonFD, \"power1_cap\", O_RDONLY);\n    if (powerCapFD) {\n      gpu_info->powerCap = fdopen(powerCapFD, \"r\");\n    }\n    close(hwmonFD);\n  }\n\n  int sysfsFD = open(devicePath, O_RDONLY);\n  // Open the PCIe bandwidth file for dynamic info gathering\n  gpu_info->PCIeBW = NULL;\n  int pcieBWFD = openat(sysfsFD, \"pcie_bw\", O_RDONLY);\n  if (pcieBWFD) {\n    gpu_info->PCIeBW = fdopen(pcieBWFD, \"r\");\n  }\n\n  close(sysfsFD);\n}\n\n#define VENDOR_AMD 0x1002\n\nstatic bool gpuinfo_amdgpu_get_device_handles(struct list_head *devices, unsigned *count) {\n  if (!libdrm_handle)\n    return false;\n\n  last_libdrm_return_status = wrap_drmGetDevices(NULL, 0);\n  if (last_libdrm_return_status <= 0)\n    return false;\n\n  drmDevicePtr devs[last_libdrm_return_status];\n  last_libdrm_return_status = wrap_drmGetDevices(devs, last_libdrm_return_status);\n  if (last_libdrm_return_status <= 0)\n    return false;\n\n  unsigned int libdrm_count = last_libdrm_return_status;\n  gpu_infos = calloc(libdrm_count, sizeof(*gpu_infos));\n  if (!gpu_infos) {\n    local_error_string = strerror(errno);\n    return false;\n  }\n\n  for (unsigned int i = 0; i < libdrm_count; i++) {\n    if (devs[i]->bustype != DRM_BUS_PCI || devs[i]->deviceinfo.pci->vendor_id != VENDOR_AMD)\n      continue;\n\n    int fd = -1;\n\n    // Try render node first\n    if (1 << DRM_NODE_RENDER & devs[i]->available_nodes) {\n      fd = open(devs[i]->nodes[DRM_NODE_RENDER], O_RDWR);\n    }\n    if (fd < 0) {\n      // Fallback to primary node (control nodes are unused according to the DRM documentation)\n      if (1 << DRM_NODE_PRIMARY & devs[i]->available_nodes) {\n        fd = open(devs[i]->nodes[DRM_NODE_PRIMARY], O_RDWR);\n      }\n    }\n\n    if (fd < 0)\n      continue;\n\n    drmVersionPtr ver = _drmGetVersion(fd);\n\n    if (!ver) {\n      close(fd);\n      continue;\n    }\n\n    bool is_radeon = false; // TODO: !strcmp(ver->name, \"radeon\");\n    bool is_amdgpu = !strcmp(ver->name, \"amdgpu\");\n\n    if (!is_amdgpu && !is_radeon) {\n      _drmFreeVersion(ver);\n      close(fd);\n      continue;\n    }\n\n    authenticate_drm(fd);\n\n    if (is_amdgpu) {\n      if (!libdrm_amdgpu_handle || !_amdgpu_device_initialize) {\n        _drmFreeVersion(ver);\n        close(fd);\n        continue;\n      }\n\n      uint32_t drm_major, drm_minor;\n      last_libdrm_return_status =\n          _amdgpu_device_initialize(fd, &drm_major, &drm_minor, &gpu_infos[amdgpu_count].amdgpu_device);\n    } else {\n      // TODO: radeon support here\n      assert(false);\n    }\n\n    if (!last_libdrm_return_status) {\n      gpu_infos[amdgpu_count].drmVersion = ver;\n      gpu_infos[amdgpu_count].fd = fd;\n      gpu_infos[amdgpu_count].base.vendor = &gpu_vendor_amdgpu;\n\n      snprintf(gpu_infos[amdgpu_count].base.pdev, PDEV_LEN - 1, \"%04x:%02x:%02x.%d\", devs[i]->businfo.pci->domain,\n               devs[i]->businfo.pci->bus, devs[i]->businfo.pci->dev, devs[i]->businfo.pci->func);\n      initDeviceSysfsPaths(&gpu_infos[amdgpu_count]);\n      list_add_tail(&gpu_infos[amdgpu_count].base.list, devices);\n      // Register a fdinfo callback for this GPU\n      processinfo_register_fdinfo_callback(parse_drm_fdinfo_amd, &gpu_infos[amdgpu_count].base);\n      amdgpu_count++;\n    } else {\n      _drmFreeVersion(ver);\n      close(fd);\n      continue;\n    }\n  }\n\n  _drmFreeDevices(devs, libdrm_count);\n  *count = amdgpu_count;\n\n  return true;\n}\n\nstatic int rewindAndReadPattern(FILE *file, const char *format, ...) {\n  if (!file)\n    return 0;\n  va_list args;\n  va_start(args, format);\n  rewind(file);\n  fflush(file);\n  int matches = vfscanf(file, format, args);\n  va_end(args);\n  return matches;\n}\n\nstatic int readAttributeFromDevice(nvtop_device *dev, const char *sysAttr, const char *format, ...) {\n  va_list args;\n  va_start(args, format);\n  const char *val;\n  int ret = nvtop_device_get_sysattr_value(dev, sysAttr, &val);\n  if (ret < 0) {\n    va_end(args);\n    return ret;\n  }\n  // Read the pattern\n  int nread = vsscanf(val, format, args);\n  va_end(args);\n  return nread;\n}\n\nstatic void gpuinfo_amdgpu_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_amdgpu *gpu_info = container_of(_gpu_info, struct gpu_info_amdgpu, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  bool info_query_success = false;\n  struct amdgpu_gpu_info info;\n  const char *name = NULL;\n\n  static_info->integrated_graphics = false;\n  static_info->encode_decode_shared = false;\n  RESET_ALL(static_info->valid);\n\n  if (libdrm_amdgpu_handle && _amdgpu_get_marketing_name)\n    name = _amdgpu_get_marketing_name(gpu_info->amdgpu_device);\n\n  if (libdrm_amdgpu_handle && _amdgpu_query_gpu_info)\n    info_query_success = !_amdgpu_query_gpu_info(gpu_info->amdgpu_device, &info);\n\n  /* check name again.\n   * the previous name is from libdrm, which may not be the latest version.\n   * it may not contain latest AMD GPU types/names\n   *\n   * the libdrm is from vendor, Linux and a Linux distribution.\n   * It may take long time for a Linux distribution to get latest GPU info.\n   * here a GPU IDS is maintained, which allows to support GPU info faster. */\n  if (!name) {\n    name = amdgpu_parse_marketing_name(&info);\n  }\n\n  static_info->device_name[MAX_DEVICE_NAME - 1] = '\\0';\n  if (name && strlen(name)) {\n    strncpy(static_info->device_name, name, MAX_DEVICE_NAME - 1);\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n  } else if (gpu_info->drmVersion->desc && strlen(gpu_info->drmVersion->desc)) {\n    strncpy(static_info->device_name, gpu_info->drmVersion->desc, MAX_DEVICE_NAME - 1);\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n\n    if (info_query_success) {\n      size_t len = strlen(static_info->device_name);\n      assert(len < MAX_DEVICE_NAME);\n\n      char *dst = static_info->device_name + len;\n      size_t remaining_len = MAX_DEVICE_NAME - 1 - len;\n      switch (info.family_id) {\n#ifdef AMDGPU_FAMILY_SI\n      case AMDGPU_FAMILY_SI:\n        strncpy(dst, \" (Hainan / Oland / Verde / Pitcairn / Tahiti)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_CI\n      case AMDGPU_FAMILY_CI:\n        strncpy(dst, \" (Bonaire / Hawaii)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_KV\n      case AMDGPU_FAMILY_KV:\n        strncpy(dst, \" (Kaveri / Kabini / Mullins)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_VI\n      case AMDGPU_FAMILY_VI:\n        strncpy(dst, \" (Iceland / Tonga)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_CZ\n      case AMDGPU_FAMILY_CZ:\n        strncpy(dst, \" (Carrizo / Stoney)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_AI\n      case AMDGPU_FAMILY_AI:\n        strncpy(dst, \" (Vega10)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_RV\n      case AMDGPU_FAMILY_RV:\n        strncpy(dst, \" (Raven)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_NV\n      case AMDGPU_FAMILY_NV:\n        strncpy(dst, \" (Navi10)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_VGH\n      case AMDGPU_FAMILY_VGH:\n        strncpy(dst, \" (Van Gogh)\", remaining_len);\n        break;\n#endif\n#ifdef AMDGPU_FAMILY_YC\n      case AMDGPU_FAMILY_YC:\n        strncpy(dst, \" (Yellow Carp)\", remaining_len);\n        break;\n#endif\n      default:\n        break;\n      }\n    }\n  }\n\n  // Retrieve infos from sysfs.\n\n  // 1) Fan\n  // If multiple fans are present, use the first one. Some hardware do not wire\n  // the sensor for the second fan, or use the same value as the first fan.\n\n  // Critical temperature\n  // temp1_* files should always be the GPU die in millidegrees Celsius\n  if (gpu_info->hwmonDevice) {\n    unsigned criticalTemp;\n    int nReadPatterns = readAttributeFromDevice(gpu_info->hwmonDevice, \"temp1_crit\", \"%u\", &criticalTemp);\n    if (nReadPatterns == 1) {\n      SET_GPUINFO_STATIC(static_info, temperature_slowdown_threshold, criticalTemp);\n    }\n\n    // Emergency/shutdown temperature\n    unsigned emergencyTemp;\n    nReadPatterns = readAttributeFromDevice(gpu_info->hwmonDevice, \"temp1_emergency\", \"%u\", &emergencyTemp);\n    if (nReadPatterns == 1) {\n      SET_GPUINFO_STATIC(static_info, temperature_shutdown_threshold, emergencyTemp);\n    }\n  }\n\n  nvtop_pcie_link max_link_characteristics;\n  int ret = nvtop_device_maximum_pcie_link(gpu_info->amdgpuDevice, &max_link_characteristics);\n  if (ret >= 0) {\n    SET_GPUINFO_STATIC(static_info, max_pcie_link_width, max_link_characteristics.width);\n    unsigned pcieGen = nvtop_pcie_gen_from_link_speed(max_link_characteristics.speed);\n    SET_GPUINFO_STATIC(static_info, max_pcie_gen, pcieGen);\n  }\n\n  // Mark integrated graphics\n  if (info_query_success && (info.ids_flags & AMDGPU_IDS_FLAGS_FUSION)) {\n    static_info->integrated_graphics = true;\n  }\n\n  // Checking if Encode and Decode are unified:AMDGPU_INFO_HW_IP_INFO\n  if (_amdgpu_query_hw_ip_info) {\n    struct drm_amdgpu_info_hw_ip vcn_ip_info;\n    if (_amdgpu_query_hw_ip_info(gpu_info->amdgpu_device, AMDGPU_HW_IP_VCN_ENC, 0, &vcn_ip_info) == 0) {\n      static_info->encode_decode_shared = vcn_ip_info.hw_ip_version_major >= 4;\n    }\n  }\n}\n\nstatic void gpuinfo_amdgpu_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_amdgpu *gpu_info = container_of(_gpu_info, struct gpu_info_amdgpu, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  bool info_query_success = false;\n  struct amdgpu_gpu_info info;\n  uint32_t out32;\n\n  RESET_ALL(dynamic_info->valid);\n\n  if (libdrm_amdgpu_handle && _amdgpu_query_gpu_info)\n    info_query_success = !_amdgpu_query_gpu_info(gpu_info->amdgpu_device, &info);\n\n  // GPU current speed\n  if (libdrm_amdgpu_handle && _amdgpu_query_sensor_info)\n    last_libdrm_return_status =\n        _amdgpu_query_sensor_info(gpu_info->amdgpu_device, AMDGPU_INFO_SENSOR_GFX_SCLK, sizeof(out32), &out32);\n  else\n    last_libdrm_return_status = 1;\n  if (!last_libdrm_return_status) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, out32);\n  }\n\n  // GPU max speed\n  if (info_query_success) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed_max, info.max_engine_clk / 1000);\n  }\n\n  // Memory current speed\n  if (libdrm_amdgpu_handle && _amdgpu_query_sensor_info)\n    last_libdrm_return_status =\n        _amdgpu_query_sensor_info(gpu_info->amdgpu_device, AMDGPU_INFO_SENSOR_GFX_MCLK, sizeof(out32), &out32);\n  else\n    last_libdrm_return_status = 1;\n  if (!last_libdrm_return_status) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_clock_speed, out32);\n  }\n\n  // Memory max speed\n  if (info_query_success) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_clock_speed_max, info.max_memory_clk / 1000);\n  }\n\n  // Load\n  if (libdrm_amdgpu_handle && _amdgpu_query_sensor_info)\n    last_libdrm_return_status =\n        _amdgpu_query_sensor_info(gpu_info->amdgpu_device, AMDGPU_INFO_SENSOR_GPU_LOAD, sizeof(out32), &out32);\n  else\n    last_libdrm_return_status = 1;\n  if (!last_libdrm_return_status) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, out32);\n  }\n\n  // Memory usage\n  struct drm_amdgpu_memory_info memory_info;\n  if (libdrm_amdgpu_handle && _amdgpu_query_info)\n    last_libdrm_return_status =\n        _amdgpu_query_info(gpu_info->amdgpu_device, AMDGPU_INFO_MEMORY, sizeof(memory_info), &memory_info);\n  else\n    last_libdrm_return_status = 1;\n  if (!last_libdrm_return_status) {\n    if (gpu_info->base.static_info.integrated_graphics) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, memory_info.vram.total_heap_size + memory_info.gtt.total_heap_size);\n      SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, memory_info.vram.heap_usage + memory_info.gtt.heap_usage);\n      SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, memory_info.vram.total_heap_size + memory_info.gtt.total_heap_size - dynamic_info->used_memory);\n    } else {\n      SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, memory_info.vram.total_heap_size);\n      SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, memory_info.vram.heap_usage);\n      SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, memory_info.vram.total_heap_size - memory_info.vram.heap_usage);\n    }\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate,\n                        (dynamic_info->total_memory - dynamic_info->free_memory) * 100 / dynamic_info->total_memory);\n  }\n\n  // GPU temperature\n  if (libdrm_amdgpu_handle && _amdgpu_query_sensor_info)\n    last_libdrm_return_status =\n        _amdgpu_query_sensor_info(gpu_info->amdgpu_device, AMDGPU_INFO_SENSOR_GPU_TEMP, sizeof(out32), &out32);\n  else\n    last_libdrm_return_status = 1;\n  if (!last_libdrm_return_status) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_temp, out32 / 1000);\n  }\n\n  // Fan speed\n  unsigned currentFanSpeed;\n  int patternsMatched = rewindAndReadPattern(gpu_info->fanSpeedFILE, \"%u\", &currentFanSpeed);\n  if (patternsMatched == 1) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, fan_speed, currentFanSpeed * 100 / gpu_info->maxFanValue);\n  }\n\n  // Device power usage\n  if (libdrm_amdgpu_handle && _amdgpu_query_sensor_info)\n    last_libdrm_return_status =\n        _amdgpu_query_sensor_info(gpu_info->amdgpu_device, AMDGPU_INFO_SENSOR_GPU_AVG_POWER, sizeof(out32), &out32);\n  else\n    last_libdrm_return_status = 1;\n  if (!last_libdrm_return_status) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, power_draw, out32 * 1000);\n  }\n\n  nvtop_pcie_link curr_link_characteristics;\n  int ret = nvtop_device_current_pcie_link(gpu_info->amdgpuDevice, &curr_link_characteristics);\n  if (ret >= 0) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, pcie_link_width, curr_link_characteristics.width);\n    unsigned pcieGen = nvtop_pcie_gen_from_link_speed(curr_link_characteristics.speed);\n    SET_GPUINFO_DYNAMIC(dynamic_info, pcie_link_gen, pcieGen);\n  }\n\n  // PCIe bandwidth\n  if (gpu_info->PCIeBW) {\n    // According to https://github.com/torvalds/linux/blob/master/drivers/gpu/drm/amd/pm/amdgpu_pm.c, under the pcie_bw\n    // section, we should be able to read the number of packets received and sent by the GPU and get the maximum payload\n    // size during the last second. This is untested but should work when the file is populated by the driver.\n    uint64_t received, transmitted;\n    int maxPayloadSize;\n    int NreadPatterns =\n        rewindAndReadPattern(gpu_info->PCIeBW, \"%\" SCNu64 \" %\" SCNu64 \" %i\", &received, &transmitted, &maxPayloadSize);\n    if (NreadPatterns == 3) {\n      received *= maxPayloadSize;\n      transmitted *= maxPayloadSize;\n      // Set in KiB\n      received /= 1024;\n      transmitted /= 1024;\n      SET_GPUINFO_DYNAMIC(dynamic_info, pcie_rx, received);\n      SET_GPUINFO_DYNAMIC(dynamic_info, pcie_tx, transmitted);\n    }\n  }\n\n  if (gpu_info->powerCap) {\n    // The power cap in microwatts\n    unsigned powerCap;\n    int NreadPatterns = rewindAndReadPattern(gpu_info->powerCap, \"%u\", &powerCap);\n    if (NreadPatterns == 1) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, power_draw_max, powerCap / 1000);\n    }\n  }\n}\n\nstatic const char drm_amdgpu_pdev_old[] = \"pdev\";\nstatic const char drm_amdgpu_vram_old[] = \"vram mem\";\nstatic const char drm_amdgpu_vram[] = \"drm-memory-vram\";\nstatic const char drm_amdgpu_gfx_old[] = \"gfx\";\nstatic const char drm_amdgpu_gfx[] = \"drm-engine-gfx\";\nstatic const char drm_amdgpu_compute_old[] = \"compute\";\nstatic const char drm_amdgpu_compute[] = \"drm-engine-compute\";\nstatic const char drm_amdgpu_dec_old[] = \"dec\";\nstatic const char drm_amdgpu_dec[] = \"drm-engine-dec\";\nstatic const char drm_amdgpu_enc_old[] = \"enc\";\nstatic const char drm_amdgpu_enc[] = \"drm-engine-enc\";\n\nstatic bool parse_drm_fdinfo_amd(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n  struct gpu_info_amdgpu *gpu_info = container_of(info, struct gpu_info_amdgpu, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  ssize_t count = 0;\n\n  bool client_id_set = false;\n  unsigned cid;\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n\n  while ((count = getline(&line, &line_buf_size, fdinfo_file)) != -1) {\n    char *key, *val;\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    // see drivers/gpu/drm/amd/amdgpu/amdgpu_fdinfo.c amdgpu_show_fdinfo()\n    if (!strcmp(key, drm_amdgpu_pdev_old) || !strcmp(key, drm_pdev)) {\n      if (strcmp(val, gpu_info->base.pdev)) {\n        return false;\n      }\n    } else if (!strcmp(key, drm_client_id)) {\n      // Client id is a unique identifier. From the DRM documentation \"Unique value relating to the open DRM\n      // file descriptor used to distinguish duplicated and shared file descriptors. Conceptually the value should map\n      // 1:1 to the in kernel representation of struct drm_file instances.\"\n      char *endptr;\n      cid = strtoul(val, &endptr, 10);\n      if (*endptr)\n        continue;\n      client_id_set = true;\n    } else if (!strcmp(key, drm_amdgpu_vram_old) || !strcmp(key, drm_amdgpu_vram)) {\n      // TODO: do we count \"gtt mem\" too?\n      unsigned long mem_int;\n      char *endptr;\n\n      mem_int = strtoul(val, &endptr, 10);\n      if (endptr == val || (strcmp(endptr, \" kB\") && strcmp(endptr, \" KiB\")))\n        continue;\n\n      SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, mem_int * 1024);\n    } else {\n      bool is_gfx_old = !strncmp(key, drm_amdgpu_gfx_old, sizeof(drm_amdgpu_gfx_old) - 1);\n      bool is_compute_old = !strncmp(key, drm_amdgpu_compute_old, sizeof(drm_amdgpu_compute_old) - 1);\n      bool is_dec_old = !strncmp(key, drm_amdgpu_dec_old, sizeof(drm_amdgpu_dec_old) - 1);\n      bool is_enc_old = !strncmp(key, drm_amdgpu_enc_old, sizeof(drm_amdgpu_enc_old) - 1);\n\n      bool is_gfx_new = !strncmp(key, drm_amdgpu_gfx, sizeof(drm_amdgpu_gfx) - 1);\n      bool is_dec_new = !strncmp(key, drm_amdgpu_dec, sizeof(drm_amdgpu_dec) - 1);\n      bool is_enc_new = !strncmp(key, drm_amdgpu_enc, sizeof(drm_amdgpu_enc) - 1);\n      bool is_compute_new = !strncmp(key, drm_amdgpu_compute, sizeof(drm_amdgpu_compute) - 1);\n\n      if (is_gfx_old || is_compute_old || is_dec_old || is_enc_old) {\n        // The old interface exposes a usage percentage with an unknown update interval\n        unsigned int usage_percent_int;\n        char *key_off, *endptr;\n        double usage_percent;\n\n        if (is_gfx_old)\n          key_off = key + sizeof(drm_amdgpu_gfx_old) - 1;\n        else if (is_compute_old)\n          key_off = key + sizeof(drm_amdgpu_compute_old) - 1;\n        else if (is_dec_old)\n          key_off = key + sizeof(drm_amdgpu_dec_old) - 1;\n        else if (is_enc_old)\n          key_off = key + sizeof(drm_amdgpu_enc_old) - 1;\n        else\n          continue;\n\n        // The prefix should be followed by a number and only a number\n        if (!*key_off)\n          continue;\n        strtoul(key_off, &endptr, 10);\n        if (*endptr)\n          continue;\n\n        usage_percent_int = (unsigned int)(usage_percent = round(strtod(val, &endptr)));\n        if (endptr == val || strcmp(endptr, \"%\"))\n          continue;\n\n        if (is_gfx_old) {\n          process_info->type |= gpu_process_graphical;\n          SET_GPUINFO_PROCESS(process_info, gpu_usage, process_info->gpu_usage + usage_percent_int);\n        } else if (is_compute_old) {\n          process_info->type |= gpu_process_compute;\n          SET_GPUINFO_PROCESS(process_info, gpu_usage, process_info->gpu_usage + usage_percent_int);\n        } else if (is_dec_old) {\n          SET_GPUINFO_PROCESS(process_info, decode_usage, process_info->decode_usage + usage_percent_int);\n        } else if (is_enc_old) {\n          SET_GPUINFO_PROCESS(process_info, encode_usage, process_info->encode_usage + usage_percent_int);\n        }\n      } else if (is_gfx_new || is_compute_new || is_dec_new || is_enc_new) {\n        char *endptr;\n        uint64_t time_spent = strtoull(val, &endptr, 10);\n        if (endptr == val || strcmp(endptr, \" ns\"))\n          continue;\n\n        if (is_gfx_new) {\n          process_info->type |= gpu_process_graphical;\n          SET_GPUINFO_PROCESS(process_info, gfx_engine_used, time_spent);\n        } else if (is_compute_new) {\n          process_info->type |= gpu_process_compute;\n          SET_GPUINFO_PROCESS(process_info, compute_engine_used, time_spent);\n        } else if (is_enc_new) {\n          SET_GPUINFO_PROCESS(process_info, enc_engine_used, time_spent);\n        } else if (is_dec_new) {\n          SET_GPUINFO_PROCESS(process_info, dec_engine_used, time_spent);\n        }\n      }\n    }\n  }\n\n  // The AMDGPU fdinfo interface in kernels >=5.19 is way nicer; it provides the\n  // cumulative GPU engines (e.g., gfx, enc, dec) usage in nanoseconds.\n  // Previously, we displayed the usage provided in fdinfo by the kernel/driver\n  // which uses an internal update interval. Now, we can compute an accurate\n  // busy percentage since the last measurement.\n  if (client_id_set) {\n    struct amdgpu_process_info_cache *cache_entry;\n    struct unique_cache_id ucid = {.client_id = cid, .pid = process_info->pid, .pdev = gpu_info->base.pdev};\n    HASH_FIND_CLIENT(gpu_info->last_update_process_cache, &ucid, cache_entry);\n    if (cache_entry) {\n      uint64_t time_elapsed = nvtop_difftime_u64(cache_entry->last_measurement_tstamp, current_time);\n      HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n      if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used) &&\n          AMDGPU_CACHE_FIELD_VALID(cache_entry, gfx_engine_used) &&\n          // In some rare occasions, the gfx engine usage reported by the driver is lowering (might be a driver bug)\n          process_info->gfx_engine_used >= cache_entry->gfx_engine_used &&\n          process_info->gfx_engine_used - cache_entry->gfx_engine_used <= time_elapsed) {\n        SET_GPUINFO_PROCESS(process_info, gpu_usage,\n                            busy_usage_from_time_usage_round(process_info->gfx_engine_used,\n                                                             cache_entry->gfx_engine_used, time_elapsed));\n      }\n      if (GPUINFO_PROCESS_FIELD_VALID(process_info, compute_engine_used) &&\n          AMDGPU_CACHE_FIELD_VALID(cache_entry, compute_engine_used) &&\n          process_info->compute_engine_used >= cache_entry->compute_engine_used &&\n          process_info->compute_engine_used - cache_entry->compute_engine_used <= time_elapsed) {\n        unsigned gfx_usage = GPUINFO_PROCESS_FIELD_VALID(process_info, gpu_usage) ? process_info->gpu_usage : 0;\n        SET_GPUINFO_PROCESS(process_info, gpu_usage,\n                            gfx_usage + busy_usage_from_time_usage_round(process_info->compute_engine_used,\n                                                                         cache_entry->compute_engine_used,\n                                                                         time_elapsed));\n      }\n      if (GPUINFO_PROCESS_FIELD_VALID(process_info, dec_engine_used) &&\n          AMDGPU_CACHE_FIELD_VALID(cache_entry, dec_engine_used) &&\n          process_info->dec_engine_used >= cache_entry->dec_engine_used &&\n          process_info->dec_engine_used - cache_entry->dec_engine_used <= time_elapsed) {\n        SET_GPUINFO_PROCESS(process_info, decode_usage,\n                            busy_usage_from_time_usage_round(process_info->dec_engine_used,\n                                                             cache_entry->dec_engine_used, time_elapsed));\n      }\n      if (GPUINFO_PROCESS_FIELD_VALID(process_info, enc_engine_used) &&\n          AMDGPU_CACHE_FIELD_VALID(cache_entry, enc_engine_used) &&\n          process_info->enc_engine_used >= cache_entry->enc_engine_used &&\n          process_info->enc_engine_used - cache_entry->enc_engine_used <= time_elapsed) {\n        SET_GPUINFO_PROCESS(process_info, encode_usage,\n                            busy_usage_from_time_usage_round(process_info->enc_engine_used,\n                                                             cache_entry->enc_engine_used, time_elapsed));\n      }\n    } else {\n      cache_entry = calloc(1, sizeof(*cache_entry));\n      if (!cache_entry)\n        goto parse_fdinfo_exit;\n      cache_entry->client_id.client_id = cid;\n      cache_entry->client_id.pid = process_info->pid;\n      cache_entry->client_id.pdev = gpu_info->base.pdev;\n    }\n\n    // The UI only shows the decode usage when `encode_decode_shared` is true\n    // but amdgpu should only use the encode usage field when it is shared.\n    // Lets add both together for good measure.\n    if (static_info->encode_decode_shared)\n      SET_GPUINFO_PROCESS(process_info, decode_usage, process_info->decode_usage + process_info->encode_usage);\n\n    // Check if we already processed this client_id in the current update cycle.\n    // This can happen when a process has multiple file descriptors referencing\n    // the same DRM client (e.g., via DRM master operations).\n    struct amdgpu_process_info_cache *cache_entry_check;\n    HASH_FIND_CLIENT(gpu_info->current_update_process_cache, &cache_entry->client_id, cache_entry_check);\n    if (cache_entry_check) {\n      // Already processed this client_id, free the entry if we allocated it\n      if (cache_entry != cache_entry_check)\n        free(cache_entry);\n      goto parse_fdinfo_exit;\n    }\n\n    // Store this measurement data\n    RESET_ALL(cache_entry->valid);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used))\n      SET_AMDGPU_CACHE(cache_entry, gfx_engine_used, process_info->gfx_engine_used);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, compute_engine_used))\n      SET_AMDGPU_CACHE(cache_entry, compute_engine_used, process_info->compute_engine_used);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, dec_engine_used))\n      SET_AMDGPU_CACHE(cache_entry, dec_engine_used, process_info->dec_engine_used);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, enc_engine_used))\n      SET_AMDGPU_CACHE(cache_entry, enc_engine_used, process_info->enc_engine_used);\n\n    cache_entry->last_measurement_tstamp = current_time;\n    HASH_ADD_CLIENT(gpu_info->current_update_process_cache, cache_entry);\n  }\n\nparse_fdinfo_exit:\n  return true;\n}\n\nstatic void swap_process_cache_for_next_update(struct gpu_info_amdgpu *gpu_info) {\n  // Free old cache data and set the cache for the next update\n  if (gpu_info->last_update_process_cache) {\n    struct amdgpu_process_info_cache *cache_entry, *tmp;\n    HASH_ITER(hh, gpu_info->last_update_process_cache, cache_entry, tmp) {\n      HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n      free(cache_entry);\n    }\n  }\n  gpu_info->last_update_process_cache = gpu_info->current_update_process_cache;\n  gpu_info->current_update_process_cache = NULL;\n}\n\nstatic void gpuinfo_amdgpu_get_running_processes(struct gpu_info *_gpu_info) {\n  // For AMDGPU, we register a fdinfo callback that will fill the gpu_process datastructure of the gpu_info structure\n  // for us. This avoids going through /proc multiple times per update for multiple GPUs.\n  struct gpu_info_amdgpu *gpu_info = container_of(_gpu_info, struct gpu_info_amdgpu, base);\n  swap_process_cache_for_next_update(gpu_info);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_amdgpu_utils.c",
    "content": "/*\n * Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.\n *\n * MIT License.\n */\n\n\n#include <assert.h>\n#include <ctype.h>\n#include <dirent.h>\n#include <dlfcn.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <inttypes.h>\n\n#include <libdrm/amdgpu.h>\n#include <libdrm/amdgpu_drm.h>\n\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/types.h>\n\n#include \"amdgpu_ids.h\"\n\nconst char *amdgpu_parse_marketing_name(struct amdgpu_gpu_info *info);\n\nconst char * amdgpu_parse_marketing_name(struct amdgpu_gpu_info *info)\n{\n    int i;\n    int ntypes = sizeof(amdgpu_ids) / sizeof(amdgpu_ids[0]);\n\n    if (!info)\n        return NULL;\n\n    for (i = 0; i < ntypes; i++) {\n        if (info->asic_id == amdgpu_ids[i].asic_id && info->pci_rev_id == amdgpu_ids[i].pci_rev_id) {\n            return amdgpu_ids[i].name;\n        }\n    }\n\n    return NULL;\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_apple.m",
    "content": "/*\n * Copyright (C) 2023 Robin Voetter <robin@voetter.nl>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/common.h\"\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/time.h\"\n\n#include <assert.h>\n#include <Metal/Metal.h>\n#include <IOKit/IOKitLib.h>\n#include <QuartzCore/QuartzCore.h>\n\nstruct gpu_info_apple {\n  struct gpu_info base;\n  id<MTLDevice> device;\n  io_service_t gpu_service;\n};\n\nstatic bool gpuinfo_apple_init(void);\nstatic void gpuinfo_apple_shutdown(void);\nstatic const char *gpuinfo_apple_last_error_string(void);\nstatic bool gpuinfo_apple_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_apple_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_apple_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_apple_get_running_processes(struct gpu_info *_gpu_info);\n\nstatic struct gpu_vendor gpu_vendor_apple = {\n  .init = gpuinfo_apple_init,\n  .shutdown = gpuinfo_apple_shutdown,\n  .last_error_string = gpuinfo_apple_last_error_string,\n  .get_device_handles = gpuinfo_apple_get_device_handles,\n  .populate_static_info = gpuinfo_apple_populate_static_info,\n  .refresh_dynamic_info = gpuinfo_apple_refresh_dynamic_info,\n  .refresh_running_processes = gpuinfo_apple_get_running_processes,\n  .name = \"apple\",\n};\n\nstatic unsigned apple_gpu_count;\nstatic struct gpu_info_apple *gpu_infos;\n\n__attribute__((constructor)) static void init_extract_gpuinfo_apple(void) { register_gpu_vendor(&gpu_vendor_apple); }\n\nstatic bool gpuinfo_apple_init(void) {\n  apple_gpu_count = 0;\n  gpu_infos = NULL;\n  return true;\n}\n\nstatic void gpuinfo_apple_shutdown(void) {\n  for (unsigned i = 0; i < apple_gpu_count; ++i) {\n    struct gpu_info_apple *gpu_info = &gpu_infos[i];\n    [gpu_info->device release];\n    IOObjectRelease(gpu_info->gpu_service);\n  }\n\n  free(gpu_infos);\n  gpu_infos = NULL;\n  apple_gpu_count = 0;\n}\n\nstatic const char *gpuinfo_apple_last_error_string(void) {\n  return \"An unanticipated error occurred while accessing Apple \"\n         \"information\\n\";\n}\n\nstatic bool gpuinfo_apple_get_device_handles(struct list_head *devices, unsigned *count) {\n  NSArray<id<MTLDevice>> *mtl_devices = MTLCopyAllDevices();\n\n  const unsigned mtl_count = [mtl_devices count];\n  gpu_infos = calloc(mtl_count, sizeof(*gpu_infos));\n  for (unsigned int i = 0; i < mtl_count; ++i) {\n    id<MTLDevice> dev = mtl_devices[i];\n    const uint64_t registry_id = [dev registryID];\n    const io_service_t gpu_service = IOServiceGetMatchingService(kIOMainPortDefault, IORegistryEntryIDMatching(registry_id));\n    assert(MACH_PORT_VALID(gpu_service));\n\n    gpu_infos[apple_gpu_count].base.vendor = &gpu_vendor_apple;\n    gpu_infos[apple_gpu_count].device = dev;\n    gpu_infos[i].gpu_service = gpu_service;\n    list_add_tail(&gpu_infos[apple_gpu_count].base.list, devices);\n    ++apple_gpu_count;\n  }\n\n  *count = apple_gpu_count;\n\n  [mtl_devices release];\n  return true;\n}\n\nstatic void gpuinfo_apple_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_apple *gpu_info = container_of(_gpu_info, struct gpu_info_apple, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  RESET_ALL(static_info->valid);\n\n  const char *name = [[gpu_info->device name] UTF8String];\n  strncpy(static_info->device_name, name, sizeof(static_info->device_name));\n  SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n\n  static_info->integrated_graphics = [gpu_info->device location] == MTLDeviceLocationBuiltIn;\n  static_info->encode_decode_shared = true;\n}\n\nstatic void gpuinfo_apple_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_apple *gpu_info = container_of(_gpu_info, struct gpu_info_apple, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  RESET_ALL(dynamic_info->valid);\n\n  CFMutableDictionaryRef cf_props;\n  if (IORegistryEntryCreateCFProperties(gpu_info->gpu_service, &cf_props, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) {\n    return;\n  }\n  NSDictionary *props = (__bridge NSDictionary*) cf_props;\n  NSDictionary *performance_statistics = [props objectForKey:@\"PerformanceStatistics\"];\n  if (!performance_statistics) {\n    return;\n  }\n\n  id device_utilization_info = [performance_statistics objectForKey:@\"Device Utilization %\"];\n  if (device_utilization_info != nil) {\n    const uint64_t gpu_util_rate = [device_utilization_info integerValue];\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, gpu_util_rate);\n  }\n\n  if ([gpu_info->device hasUnifiedMemory]) {\n    // [gpu_info->device currentAllocatedSize] returns the amount of memory allocated by this process, not\n    // as allocated on the GPU globally. The performance statistics dictionary has the real value that we\n    // are interested in, the amount of system memory allocated by the GPU.\n    id system_memory_info = [performance_statistics objectForKey:@\"Alloc system memory\"];\n    if (system_memory_info != nil) {\n      const uint64_t mem_used = [system_memory_info integerValue];\n      SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, mem_used);\n    }\n\n    // Memory is unified, so query the amount of system memory instead.\n    mach_msg_type_number_t host_size = HOST_BASIC_INFO_COUNT;\n    host_basic_info_data_t info;\n    if (host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t) &info, &host_size) == KERN_SUCCESS) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, info.max_mem);\n    }\n  } else {\n    // TODO: Figure out how to get used memory for this case.\n\n    // It does not really seem to be possible to get the amount of memory of a particular GPU.\n    // In this case, just get the recommended working set size. This is what MoltenVK also does.\n    const uint64_t mem_total = [gpu_info->device recommendedMaxWorkingSetSize];\n    SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, mem_total);\n  }\n\n  CFRelease(props);\n\n  if (GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, used_memory) && GPUINFO_DYNAMIC_FIELD_VALID(dynamic_info, total_memory)) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, dynamic_info->total_memory - dynamic_info->used_memory);\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate,\n                        (dynamic_info->total_memory - dynamic_info->free_memory) * 100 / dynamic_info->total_memory);\n\n  }\n}\n\nstatic bool gpuinfo_apple_get_process_info(struct gpu_process* process, io_object_t user_client) {\n  RESET_ALL(process->valid);\n  process->type = gpu_process_graphical_compute;\n\n  CFMutableDictionaryRef cf_props;\n  if (IORegistryEntryCreateCFProperties(user_client, &cf_props, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) {\n    return false;\n  }\n  NSDictionary* user_client_info = (__bridge NSDictionary*) cf_props;\n\n  id client_creator_info = [user_client_info objectForKey:@\"IOUserClientCreator\"];\n  if (client_creator_info == nil) {\n    return false;\n  }\n\n  const char* client_creator = [client_creator_info UTF8String];\n  // Client creator is in form: pid <pid>, <name>\n  if (sscanf(client_creator, \"pid %u,\", &process->pid) < 1) {\n    return false;\n  }\n\n  CFRelease(cf_props);\n\n  return true;\n}\n\nstatic void gpuinfo_apple_get_running_processes(struct gpu_info *_gpu_info) {\n  struct gpu_info_apple *gpu_info = container_of(_gpu_info, struct gpu_info_apple, base);\n  _gpu_info->processes_count = 0;\n\n  // We can find out which processes are running on a particular GPU using the IO Registry. The\n  // IOService associated to the MTLDevice has \"AGXDeviceUserClient\" child nodes, which hold some\n  // basic information about processes that are running on the GPU.\n\n  io_iterator_t iterator;\n  if (IORegistryEntryGetChildIterator(gpu_info->gpu_service, kIOServicePlane, &iterator) != kIOReturnSuccess) {\n    return;\n  }\n\n  unsigned int count = 0;\n  for (io_object_t child = IOIteratorNext(iterator); child; child = IOIteratorNext(iterator)) {\n    io_name_t class_name;\n    if (IOObjectGetClass(child, class_name) != kIOReturnSuccess) {\n      continue;\n    } else if (strncmp(class_name, \"AGXDeviceUserClient\", sizeof(class_name)) != 0) {\n      continue;\n    }\n\n    if (_gpu_info->processes_array_size < count + 1) {\n      _gpu_info->processes_array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n      _gpu_info->processes = reallocarray(_gpu_info->processes, _gpu_info->processes_array_size, sizeof(*_gpu_info->processes));\n      if (!_gpu_info->processes) {\n        perror(\"Could not allocate memory: \");\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    if (gpuinfo_apple_get_process_info(&_gpu_info->processes[count], child)) {\n      ++count;\n    }\n\n    IOObjectRelease(child);\n  }\n\n  _gpu_info->processes_count = count;\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_ascend.c",
    "content": "/*\n * Copyright (C) 2023 klayer <klayer@163.com>\n *\n * This file is part of Nvtop and adapted from Ascend DCMI from Huawei Technologies Co., Ltd.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <errno.h>\n\n#include \"ascend/dcmi_interface_api.h\"\n#include \"list.h\"\n#include \"nvtop/common.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n\n#define KB_TO_GB (1024 * 1024)\n#define DCMI_SUCCESS 0\n#define MAX_DEVICE_NUM 64\n#define MAX_PROC_NUM 32\n#define PROC_ALLOC_INC 16\n\nstatic int last_dcmi_return_status = DCMI_SUCCESS;\nstatic const char *unknown_error = \"unknown Ascend DCMI error\";\nstatic const char *local_error_string = \"\";\n\nstruct gpu_info_ascend {\n  struct gpu_info base;\n  struct list_head allocate_list;\n};\n\nstatic LIST_HEAD(allocations);\n\nstatic bool gpuinfo_ascend_init(void);\nstatic void gpuinfo_ascend_shutdown(void);\nstatic const char *gpuinfo_ascend_last_error_string(void);\nstatic bool gpuinfo_ascend_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_ascend_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_ascend_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_ascend_get_running_processes(struct gpu_info *_gpu_info);\n\nstatic void _encode_card_device_id_to_pdev(char *pdev, int card_id, int device_id);\nstatic void _decode_card_device_id_from_pdev(const char *pdev, int *card_id, int *device_id);\n\nstruct gpu_vendor gpu_vendor_ascend = {\n    .init = gpuinfo_ascend_init,\n    .shutdown = gpuinfo_ascend_shutdown,\n    .last_error_string = gpuinfo_ascend_last_error_string,\n    .get_device_handles = gpuinfo_ascend_get_device_handles,\n    .populate_static_info = gpuinfo_ascend_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_ascend_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_ascend_get_running_processes,\n    .name = \"Ascend\",\n};\n\n__attribute__((constructor)) static void init_extract_gpuinfo_ascend(void) { register_gpu_vendor(&gpu_vendor_ascend); }\n\nstatic bool gpuinfo_ascend_init(void) {\n  last_dcmi_return_status = dcmi_init();\n  return last_dcmi_return_status == DCMI_SUCCESS;\n}\n\nstatic void gpuinfo_ascend_shutdown(void) {\n  local_error_string = \"\";\n\n  struct gpu_info_ascend *allocated, *tmp;\n  list_for_each_entry_safe(allocated, tmp, &allocations, allocate_list) {\n    list_del(&allocated->allocate_list);\n    free(allocated);\n  }\n}\n\nstatic const char *gpuinfo_ascend_last_error_string(void) {\n  return local_error_string;\n}\n\nstatic bool gpuinfo_ascend_get_device_handles(struct list_head *devices, unsigned *count) {\n  int num_cards;\n  int card_list[MAX_CARD_NUM] = {0};\n  last_dcmi_return_status = dcmi_get_card_list(&num_cards, card_list, MAX_DEVICE_NUM);\n  if (last_dcmi_return_status != DCMI_SUCCESS) {\n    local_error_string = \"Failed to get card num\";\n    return false;\n  } else if (num_cards == 0) {\n    local_error_string = \"Not found NPU(s)\";\n    return false;\n  }\n\n  int num_devices = 0;\n  int card_device_list[num_cards];\n  for (int i = 0; i < num_cards; ++i) {\n    int num_card_devices;\n    last_dcmi_return_status = dcmi_get_device_num_in_card(card_list[i], &num_card_devices);\n    if (last_dcmi_return_status != DCMI_SUCCESS) {\n      local_error_string = \"Failed to get device num of card\";\n      return false;\n    }\n    num_devices += num_card_devices;\n    card_device_list[i] = num_card_devices;\n  }\n\n  struct gpu_info_ascend *gpu_infos = calloc(num_devices, sizeof(*gpu_infos));\n  if (!gpu_infos) {\n    local_error_string = strerror(errno);\n    return false;\n  }\n\n  // todo: for free gpu_infos when shutting down, rewrite to direct free?\n  list_add(&gpu_infos[0].allocate_list, &allocations);\n\n  *count = 0;\n  for (int i = 0; i < num_cards; ++i) {\n    for (int j = 0; j < card_device_list[i]; ++j) {\n      gpu_infos[*count].base.vendor = &gpu_vendor_ascend;\n      _encode_card_device_id_to_pdev(gpu_infos[*count].base.pdev, i, j);\n      list_add_tail(&gpu_infos[*count].base.list, devices);\n      *count += 1;\n    }\n  }\n\n  return true;\n}\n\nstatic void _encode_card_device_id_to_pdev(char *pdev, int card_id, int device_id) {\n  sprintf(pdev, \"%d-%d\", (short)card_id, (short)device_id);\n}\n\nstatic void _decode_card_device_id_from_pdev(const char *pdev, int *card_id, int *device_id) {\n  sscanf(pdev, \"%d-%d\", card_id, device_id);\n}\n\nstatic void gpuinfo_ascend_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_ascend *gpu_info = container_of(_gpu_info, struct gpu_info_ascend, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  static_info->integrated_graphics = false;\n  static_info->encode_decode_shared = true;\n  RESET_ALL(static_info->valid);\n\n  int card_id, device_id;\n  _decode_card_device_id_from_pdev(_gpu_info->pdev, &card_id, &device_id);\n\n  struct dcmi_chip_info *chip_info = malloc(sizeof(struct dcmi_chip_info));\n  last_dcmi_return_status = dcmi_get_device_chip_info(card_id, device_id, chip_info);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    // assume Ascend only use ASCII code for chip name\n    static_info->device_name[MAX_DEVICE_NAME - 1] = '\\0';\n    strncpy(static_info->device_name, (char*) chip_info->chip_name, MAX_DEVICE_NAME - 1);\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n  }\n  free(chip_info);\n  // todo: it seems that other static infos are not supported by Ascend DCMI for now, will add if possible in future\n}\n\nstatic void gpuinfo_ascend_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_ascend *gpu_info = container_of(_gpu_info, struct gpu_info_ascend, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  RESET_ALL(dynamic_info->valid);\n\n  int card_id, device_id;\n  _decode_card_device_id_from_pdev(_gpu_info->pdev, &card_id, &device_id);\n\n  unsigned aicore_freq;\n  last_dcmi_return_status = dcmi_get_device_frequency(card_id, device_id, DCMI_FREQ_AICORE_CURRENT_, &aicore_freq);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    dynamic_info->gpu_clock_speed = aicore_freq;\n    SET_VALID(gpuinfo_gpu_clock_speed_valid, dynamic_info->valid);\n  }\n\n  unsigned aicore_max_freq;\n  last_dcmi_return_status = dcmi_get_device_frequency(card_id, device_id, DCMI_FREQ_AICORE_MAX, &aicore_max_freq);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    dynamic_info->gpu_clock_speed_max = aicore_max_freq;\n    SET_VALID(gpuinfo_gpu_clock_speed_max_valid, dynamic_info->valid);\n  }\n\n  unsigned hbm_freq;\n  last_dcmi_return_status = dcmi_get_device_frequency(card_id, device_id, DCMI_FREQ_HBM, &hbm_freq);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    dynamic_info->mem_clock_speed = hbm_freq;\n    SET_VALID(gpuinfo_mem_clock_speed_valid, dynamic_info->valid);\n  }\n\n  unsigned aicore_util_rate;\n  last_dcmi_return_status = dcmi_get_device_utilization_rate(card_id, device_id, DCMI_UTILIZATION_RATE_AICORE, &aicore_util_rate);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    dynamic_info->gpu_util_rate = aicore_util_rate;\n    SET_VALID(gpuinfo_gpu_util_rate_valid, dynamic_info->valid);\n  }\n\n  struct dsmi_hbm_info_stru hbm_info;\n  last_dcmi_return_status = dcmi_get_hbm_info(card_id, device_id, &hbm_info);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, hbm_info.memory_size * KB_TO_GB);\n    SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, hbm_info.memory_usage * KB_TO_GB);\n    SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, (hbm_info.memory_size - hbm_info.memory_usage) * KB_TO_GB);\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, hbm_info.memory_usage * 100 / hbm_info.memory_size);\n  }\n\n  int device_temperature;\n  last_dcmi_return_status = dcmi_get_device_temperature(card_id, device_id, &device_temperature);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    dynamic_info->gpu_temp = device_temperature;\n    SET_VALID(gpuinfo_gpu_temp_valid, dynamic_info->valid);\n  }\n\n  int power_usage;\n  last_dcmi_return_status = dcmi_get_device_power_info(card_id, device_id, &power_usage);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    dynamic_info->power_draw = power_usage * 100;\n    SET_VALID(gpuinfo_power_draw_valid, dynamic_info->valid);\n  }\n}\n\nstatic void gpuinfo_ascend_get_running_processes(struct gpu_info *_gpu_info) {\n  int card_id, device_id;\n  _decode_card_device_id_from_pdev(_gpu_info->pdev, &card_id, &device_id);\n\n  struct dcmi_proc_mem_info *proc_info = malloc(MAX_PROC_NUM * sizeof(struct dcmi_proc_mem_info));\n  int proc_num = 0;\n  last_dcmi_return_status = dcmi_get_device_resource_info(card_id, device_id, proc_info, &proc_num);\n  if (last_dcmi_return_status == DCMI_SUCCESS) {\n    _gpu_info->processes_count = proc_num;\n    _gpu_info->processes_array_size = proc_num + PROC_ALLOC_INC;\n    _gpu_info->processes = reallocarray(_gpu_info->processes, _gpu_info->processes_array_size, sizeof(*_gpu_info->processes));\n    if (!_gpu_info->processes) {\n      perror(\"Could not allocate memory: \");\n      exit(EXIT_FAILURE);\n    }\n    for (int i = 0; i < proc_num; i++) {\n      _gpu_info->processes[i].type = gpu_process_compute;\n      _gpu_info->processes[i].pid = proc_info[i].proc_id;\n      _gpu_info->processes[i].gpu_memory_usage = proc_info[i].proc_mem_usage;\n      SET_VALID(gpuinfo_process_gpu_memory_usage_valid, _gpu_info->processes[i].valid);\n    }\n  }\n  free(proc_info);\n}"
  },
  {
    "path": "src/extract_gpuinfo_intel.c",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop and adapted from igt-gpu-tools from Intel Corporation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include \"extract_gpuinfo_intel.h\"\n\n#include <assert.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n#include <uthash.h>\n\nstatic bool gpuinfo_intel_init(void);\nstatic void gpuinfo_intel_shutdown(void);\nstatic const char *gpuinfo_intel_last_error_string(void);\nstatic bool gpuinfo_intel_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_intel_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_intel_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_intel_get_running_processes(struct gpu_info *_gpu_info);\n\nstruct gpu_vendor gpu_vendor_intel = {\n    .init = gpuinfo_intel_init,\n    .shutdown = gpuinfo_intel_shutdown,\n    .last_error_string = gpuinfo_intel_last_error_string,\n    .get_device_handles = gpuinfo_intel_get_device_handles,\n    .populate_static_info = gpuinfo_intel_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_intel_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_intel_get_running_processes,\n    .name = \"Intel\",\n};\n\nunsigned intel_gpu_count;\nstatic struct gpu_info_intel *gpu_infos;\n\n#define STRINGIFY(x) STRINGIFY_HELPER_(x)\n#define STRINGIFY_HELPER_(x) #x\n\n#define VENDOR_INTEL 0x8086\n#define VENDOR_INTEL_STR STRINGIFY(VENDOR_INTEL)\n// The integrated Intel GPU is always this device\n// Discrete GPU are others\n#define INTEGRATED_I915_GPU_PCI_ID \"0000:00:02.0\"\n\n__attribute__((constructor)) static void init_extract_gpuinfo_intel(void) { register_gpu_vendor(&gpu_vendor_intel); }\n\nbool gpuinfo_intel_init(void) { return true; }\nvoid gpuinfo_intel_shutdown(void) {\n  for (unsigned i = 0; i < intel_gpu_count; ++i) {\n    struct gpu_info_intel *current = &gpu_infos[i];\n    if (current->card_fd)\n      close(current->card_fd);\n    nvtop_device_unref(current->card_device);\n    nvtop_device_unref(current->driver_device);\n  }\n}\n\nconst char *gpuinfo_intel_last_error_string(void) { return \"Err\"; }\n\nstatic bool parse_drm_fdinfo_intel(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n  struct gpu_info_intel *gpu_info = container_of(info, struct gpu_info_intel, base);\n  switch (gpu_info->driver) {\n  case DRIVER_I915:\n    return parse_drm_fdinfo_intel_i915(info, fdinfo_file, process_info);\n  case DRIVER_XE:\n    return parse_drm_fdinfo_intel_xe(info, fdinfo_file, process_info);\n  }\n  return false;\n}\n\nstatic void add_intel_cards(struct nvtop_device *dev, struct list_head *devices, unsigned *count) {\n  struct nvtop_device *parent;\n  if (nvtop_device_get_parent(dev, &parent) < 0)\n    return;\n  // Consider enabled Intel cards using the i915 or xe driver\n  const char *vendor, *driver, *enabled;\n  if (nvtop_device_get_sysattr_value(parent, \"vendor\", &vendor) < 0 || strcmp(vendor, VENDOR_INTEL_STR))\n    return;\n  if (nvtop_device_get_driver(parent, &driver) < 0 || (strcmp(driver, \"i915\") && strcmp(driver, \"xe\")))\n    return;\n  if (nvtop_device_get_sysattr_value(parent, \"enable\", &enabled) < 0 || strcmp(enabled, \"1\"))\n    return;\n\n  struct gpu_info_intel *thisGPU = &gpu_infos[intel_gpu_count++];\n  thisGPU->base.vendor = &gpu_vendor_intel;\n  thisGPU->driver = !strcmp(driver, \"xe\") ? DRIVER_XE : DRIVER_I915;\n  thisGPU->card_device = nvtop_device_ref(dev);\n  thisGPU->driver_device = nvtop_device_ref(parent);\n  thisGPU->hwmon_device = nvtop_device_get_hwmon(thisGPU->driver_device);\n\n  const char *devname;\n  if (nvtop_device_get_devname(thisGPU->card_device, &devname) >= 0)\n    thisGPU->card_fd = open(devname, O_WRONLY);\n\n  const char *pdev_val;\n  int retval = nvtop_device_get_property_value(thisGPU->driver_device, \"PCI_SLOT_NAME\", &pdev_val);\n  assert(retval >= 0 && pdev_val != NULL && \"Could not retrieve device PCI slot name\");\n  strncpy(thisGPU->base.pdev, pdev_val, PDEV_LEN);\n  list_add_tail(&thisGPU->base.list, devices);\n  // Register a fdinfo callback for this GPU\n  processinfo_register_fdinfo_callback(parse_drm_fdinfo_intel, &thisGPU->base);\n  (*count)++;\n}\n\nbool gpuinfo_intel_get_device_handles(struct list_head *devices_list, unsigned *count) {\n  *count = 0;\n  nvtop_device_enumerator *enumerator;\n  if (nvtop_enumerator_new(&enumerator) < 0)\n    return false;\n\n  if (nvtop_device_enumerator_add_match_subsystem(enumerator, \"drm\", true) < 0)\n    return false;\n\n  if (nvtop_device_enumerator_add_match_property(enumerator, \"DEVNAME\", \"/dev/dri/*\") < 0)\n    return false;\n\n  unsigned num_devices = 0;\n  for (nvtop_device *device = nvtop_enumerator_get_device_first(enumerator); device;\n       device = nvtop_enumerator_get_device_next(enumerator)) {\n    num_devices++;\n  }\n\n  gpu_infos = calloc(num_devices, sizeof(*gpu_infos));\n  if (!gpu_infos)\n    return false;\n\n  for (nvtop_device *device = nvtop_enumerator_get_device_first(enumerator); device;\n       device = nvtop_enumerator_get_device_next(enumerator)) {\n    num_devices++;\n    const char *devname;\n    if (nvtop_device_get_devname(device, &devname) < 0)\n      continue;\n    if (strstr(devname, \"/dev/dri/card\")) {\n      add_intel_cards(device, devices_list, count);\n    }\n  }\n\n  nvtop_enumerator_unref(enumerator);\n  return true;\n}\n\nvoid gpuinfo_intel_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_intel *gpu_info = container_of(_gpu_info, struct gpu_info_intel, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  const char *dev_name;\n\n  static_info->integrated_graphics = false;\n  static_info->encode_decode_shared = true;\n  RESET_ALL(static_info->valid);\n\n  if (nvtop_device_get_property_value(gpu_info->driver_device, \"ID_MODEL_FROM_DATABASE\", &dev_name) >= 0) {\n    snprintf(static_info->device_name, sizeof(static_info->device_name), \"%s\", dev_name);\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n    for (size_t idx = 0; idx < sizeof(static_info->device_name) && static_info->device_name[idx] != '\\0'; ++idx) {\n      if (static_info->device_name[idx] == '[')\n        static_info->device_name[idx] = '(';\n      if (static_info->device_name[idx] == ']')\n        static_info->device_name[idx] = ')';\n    }\n  }\n\n  // Mark integrated GPUs\n  if (strcmp(gpu_info->base.pdev, INTEGRATED_I915_GPU_PCI_ID) == 0) {\n    static_info->integrated_graphics = true;\n  }\n\n  nvtop_pcie_link max_link_characteristics;\n  int ret = nvtop_device_maximum_pcie_link(gpu_info->driver_device, &max_link_characteristics);\n  if (ret >= 0) {\n    // Some cards report PCIe GEN 1@ 1x, attempt to detect this and get the card's bridge link speeds\n    gpu_info->bridge_device = gpu_info->driver_device;\n    struct nvtop_device *parent;\n    const char *vendor, *class;\n    unsigned attempts = 0;\n    while (ret >= 0 && static_info->integrated_graphics == false &&\n           // check likely incorrect speed\n           max_link_characteristics.width == 1 && max_link_characteristics.speed == 2 &&\n           // check vendor\n           nvtop_device_get_sysattr_value(gpu_info->bridge_device, \"vendor\", &vendor) == 0 &&\n           strcmp(vendor, VENDOR_INTEL_STR) == 0 &&\n           // check class is either VGA or (non-host) PCI Bridge\n           nvtop_device_get_sysattr_value(gpu_info->bridge_device, \"class\", &class) == 0 &&\n           (strcmp(class, \"0x030000\") == 0 || strcmp(class, \"0x060400\") == 0) &&\n           // don't go more than 2 levels up\n           attempts++ < 2) {\n      ret = nvtop_device_get_parent(gpu_info->bridge_device, &parent);\n      if (ret >= 0 && nvtop_device_maximum_pcie_link(parent, &max_link_characteristics) >= 0) {\n        gpu_info->bridge_device = parent;\n      }\n    }\n    SET_GPUINFO_STATIC(static_info, max_pcie_link_width, max_link_characteristics.width);\n    unsigned pcieGen = nvtop_pcie_gen_from_link_speed(max_link_characteristics.speed);\n    SET_GPUINFO_STATIC(static_info, max_pcie_gen, pcieGen);\n  }\n}\n\nvoid gpuinfo_intel_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_intel *gpu_info = container_of(_gpu_info, struct gpu_info_intel, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  bool is_xe = gpu_info->driver == DRIVER_XE;\n\n  RESET_ALL(dynamic_info->valid);\n\n  // We are creating new devices because the device_get_sysattr_value caches its queries\n  const char *syspath;\n  nvtop_device *card_dev_noncached = NULL;\n  if (nvtop_device_get_syspath(gpu_info->card_device, &syspath) >= 0)\n    nvtop_device_new_from_syspath(&card_dev_noncached, syspath);\n  nvtop_device *driver_dev_noncached = NULL;\n  if (nvtop_device_get_syspath(gpu_info->driver_device, &syspath) >= 0)\n    nvtop_device_new_from_syspath(&driver_dev_noncached, syspath);\n  nvtop_device *hwmon_dev_noncached = NULL;\n  if (gpu_info->hwmon_device) {\n    if (nvtop_device_get_syspath(gpu_info->hwmon_device, &syspath) >= 0)\n      nvtop_device_new_from_syspath(&hwmon_dev_noncached, syspath);\n  }\n  nvtop_device *bridge_dev_noncached = NULL;\n  if (gpu_info->bridge_device) {\n    if (nvtop_device_get_syspath(gpu_info->bridge_device, &syspath) >= 0)\n      nvtop_device_new_from_syspath(&bridge_dev_noncached, syspath);\n  } else {\n    bridge_dev_noncached = driver_dev_noncached;\n  }\n\n  nvtop_device *clock_device = is_xe ? driver_dev_noncached : card_dev_noncached;\n  // GPU clock\n  const char *gt_cur_freq;\n  const char *gt_cur_freq_sysattr = is_xe ? \"tile0/gt0/freq0/cur_freq\" : \"gt_cur_freq_mhz\";\n  if (nvtop_device_get_sysattr_value(clock_device, gt_cur_freq_sysattr, &gt_cur_freq) >= 0) {\n    unsigned val = strtoul(gt_cur_freq, NULL, 10);\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, val);\n  }\n  const char *gt_max_freq;\n  const char *gt_max_freq_sysattr = is_xe ? \"tile0/gt0/freq0/max_freq\" : \"gt_max_freq_mhz\";\n  if (nvtop_device_get_sysattr_value(clock_device, gt_max_freq_sysattr, &gt_max_freq) >= 0) {\n    unsigned val = strtoul(gt_max_freq, NULL, 10);\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed_max, val);\n  }\n\n  if (!static_info->integrated_graphics) {\n    nvtop_pcie_link curr_link_characteristics;\n    int ret = nvtop_device_current_pcie_link(bridge_dev_noncached, &curr_link_characteristics);\n    if (ret >= 0) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, pcie_link_width, curr_link_characteristics.width);\n      unsigned pcieGen = nvtop_pcie_gen_from_link_speed(curr_link_characteristics.speed);\n      SET_GPUINFO_DYNAMIC(dynamic_info, pcie_link_gen, pcieGen);\n    }\n  }\n\n  if (hwmon_dev_noncached) {\n    const char *hwmon_fan;\n    if (nvtop_device_get_sysattr_value(hwmon_dev_noncached, \"fan1_input\", &hwmon_fan) >= 0) {\n      unsigned val = strtoul(hwmon_fan, NULL, 10);\n      SET_GPUINFO_DYNAMIC(dynamic_info, fan_rpm, val);\n    }\n\n    const char *hwmon_temp;\n    // temp1 is for i915, temp2 is for `pkg` on xe\n    if (nvtop_device_get_sysattr_value(hwmon_dev_noncached, is_xe ? \"temp2_input\" : \"temp1_input\", &hwmon_temp) >= 0) {\n      unsigned val = strtoul(hwmon_temp, NULL, 10);\n      SET_GPUINFO_DYNAMIC(dynamic_info, gpu_temp, val / 1000);\n    }\n\n    const char *hwmon_power_max = NULL;\n    const char *hwmon_energy = NULL;\n    for (unsigned i = 0; i < (is_xe ? 2 : 1); i++) {\n      // Max Power\n      if (hwmon_power_max == NULL || hwmon_power_max[0] == '0') {\n        // power1 is for i915 and `card` on supported cards on xe, power2 is `pkg` on xe\n        nvtop_device_get_sysattr_value(hwmon_dev_noncached, i == 0 ? \"power1_max\" : \"power2_max\", &hwmon_power_max);\n      }\n      if (hwmon_power_max == NULL || hwmon_power_max[0] == '0') {\n        // Battlemage (xe) uses power*_crit\n        nvtop_device_get_sysattr_value(hwmon_dev_noncached, i == 0 ? \"power1_crit\" : \"power2_crit\", &hwmon_power_max);\n      }\n      if (hwmon_power_max == NULL || hwmon_power_max[0] == '0') {\n        // Both drivers have this, but it seems to be 0\n        nvtop_device_get_sysattr_value(hwmon_dev_noncached, i == 0 ? \"power1_rated_max\" : \"power2_rated_max\", &hwmon_power_max);\n      }\n\n      // Energy Usage\n      if (hwmon_energy == NULL || hwmon_energy[0] == '0') {\n        // energy1 is for i915 and `card` on supported cards on xe, energy2 is `pkg` on xe\n        nvtop_device_get_sysattr_value(hwmon_dev_noncached, i == 0 ? \"energy1_input\" : \"energy2_input\", &hwmon_energy);\n      }\n    }\n\n    // Check if we found the max power draw\n    if (hwmon_power_max != NULL) {\n      unsigned val = strtoul(hwmon_power_max, NULL, 10);\n      SET_GPUINFO_DYNAMIC(dynamic_info, power_draw_max, val / 1000);\n    }\n\n    // Check if we found the energy usage and convert it into a wattage\n    if (hwmon_energy != NULL) {\n      nvtop_time ts;\n      nvtop_get_current_time(&ts);\n      unsigned val = strtoul(hwmon_energy, NULL, 10);\n      // Skip the first update so we have a time delta\n      if (gpu_info->energy.time.tv_sec != 0) {\n        unsigned old = gpu_info->energy.energy_uj;\n        uint64_t time = nvtop_difftime_u64(gpu_info->energy.time, ts);\n        unsigned power = ((val - old) * 1000000000LL) / time;\n        SET_GPUINFO_DYNAMIC(dynamic_info, power_draw, power / 1000);\n      }\n      gpu_info->energy.energy_uj = val;\n      gpu_info->energy.time = ts;\n    }\n  }\n\n  switch (gpu_info->driver) {\n  case DRIVER_I915:\n    gpuinfo_intel_i915_refresh_dynamic_info(_gpu_info);\n    break;\n  case DRIVER_XE:\n    gpuinfo_intel_xe_refresh_dynamic_info(_gpu_info);\n    break;\n  }\n\n  // Let the temporary devices be garbage collected\n  nvtop_device_unref(card_dev_noncached);\n  nvtop_device_unref(driver_dev_noncached);\n  if (hwmon_dev_noncached)\n    nvtop_device_unref(hwmon_dev_noncached);\n}\n\nstatic void swap_process_cache_for_next_update(struct gpu_info_intel *gpu_info) {\n  // Free old cache data and set the cache for the next update\n  if (gpu_info->last_update_process_cache) {\n    struct intel_process_info_cache *cache_entry, *tmp;\n    HASH_ITER(hh, gpu_info->last_update_process_cache, cache_entry, tmp) {\n      HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n      free(cache_entry);\n    }\n  }\n  gpu_info->last_update_process_cache = gpu_info->current_update_process_cache;\n  gpu_info->current_update_process_cache = NULL;\n}\n\nvoid gpuinfo_intel_get_running_processes(struct gpu_info *_gpu_info) {\n  // For Intel, we register a fdinfo callback that will fill the gpu_process datastructure of the gpu_info structure\n  // for us. This avoids going through /proc multiple times per update for multiple GPUs.\n  struct gpu_info_intel *gpu_info = container_of(_gpu_info, struct gpu_info_intel, base);\n  swap_process_cache_for_next_update(gpu_info);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_intel.h",
    "content": "#include <stdint.h>\n#include <uthash.h>\n\n#define HASH_FIND_CLIENT(head, key_ptr, out_ptr) HASH_FIND(hh, head, key_ptr, sizeof(struct unique_cache_id), out_ptr)\n#define HASH_ADD_CLIENT(head, in_ptr) HASH_ADD(hh, head, client_id, sizeof(struct unique_cache_id), in_ptr)\n\n#define SET_INTEL_CACHE(cachePtr, field, value) SET_VALUE(cachePtr, field, value, intel_cache_)\n#define RESET_INTEL_CACHE(cachePtr, field) INVALIDATE_VALUE(cachePtr, field, intel_cache_)\n#define INTEL_CACHE_FIELD_VALID(cachePtr, field) VALUE_IS_VALID(cachePtr, field, intel_cache_)\n\nenum intel_process_info_cache_valid {\n  intel_cache_engine_render_valid = 0,\n  intel_cache_engine_copy_valid,\n  intel_cache_engine_video_valid,\n  intel_cache_engine_video_enhance_valid,\n  intel_cache_engine_compute_valid,\n  intel_cache_gpu_cycles_valid,\n  intel_cache_total_cycles_valid,\n  intel_cache_process_info_cache_valid_count\n};\n\nstruct __attribute__((__packed__)) unique_cache_id {\n  unsigned client_id;\n  pid_t pid;\n  char *pdev;\n};\n\nunion intel_cycles {\n  struct {\n    uint64_t rcs;\n    uint64_t vcs;\n    uint64_t vecs;\n    uint64_t bcs;\n    uint64_t ccs;\n  };\n  uint64_t array[5];\n};\n\nstruct intel_process_info_cache {\n  struct unique_cache_id client_id;\n  uint64_t engine_render;\n  uint64_t engine_copy;\n  uint64_t engine_video;\n  uint64_t engine_video_enhance;\n  uint64_t engine_compute;\n  union intel_cycles gpu_cycles;\n  union intel_cycles total_cycles;\n  nvtop_time last_measurement_tstamp;\n  unsigned char valid[(intel_cache_process_info_cache_valid_count + CHAR_BIT - 1) / CHAR_BIT];\n  UT_hash_handle hh;\n};\n\nstruct gpu_info_intel {\n  struct gpu_info base;\n  enum { DRIVER_I915, DRIVER_XE } driver;\n\n  struct nvtop_device *card_device;\n  int card_fd;\n  \n  struct nvtop_device *driver_device;\n  struct nvtop_device *hwmon_device;\n  struct intel_process_info_cache *last_update_process_cache, *current_update_process_cache; // Cached processes info\n\n  struct nvtop_device *bridge_device;\n\n  struct {\n    unsigned energy_uj;\n    struct timespec time;\n  } energy;\n};\n\nextern void gpuinfo_intel_i915_refresh_dynamic_info(struct gpu_info *_gpu_info);\nextern void gpuinfo_intel_xe_refresh_dynamic_info(struct gpu_info *_gpu_info);\n\nextern bool parse_drm_fdinfo_intel_i915(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info);\nextern bool parse_drm_fdinfo_intel_xe(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info);\n"
  },
  {
    "path": "src/extract_gpuinfo_intel_i915.c",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop and adapted from igt-gpu-tools from Intel Corporation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include \"extract_gpuinfo_intel.h\"\n\n#include <assert.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <libdrm/drm.h>\n#include <libdrm/i915_drm.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#ifndef DRM_I915_QUERY_MEMORY_REGIONS\n// The versions of libdrm < 2.4.114 don't provide\n// DRM_I915_QUERY_MEMORY_REGIONS.\n// Copied from more recent libdrm/i915_drm.h\n\n#define DRM_I915_QUERY_MEMORY_REGIONS 4\n#define I915_MEMORY_CLASS_DEVICE 1\nstruct drm_i915_memory_region_info {\n  struct {\n    __u16 memory_class;\n    __u16 memory_instance;\n  } region;\n  __u32 rsvd0;\n  __u64 probed_size;\n  __u64 unallocated_size;\n  union {\n    __u64 rsvd1[8];\n    struct {\n      __u64 probed_cpu_visible_size;\n      __u64 unallocated_cpu_visible_size;\n    };\n  };\n};\nstruct drm_i915_query_memory_regions {\n  __u32 num_regions;\n  __u32 rsvd[3];\n  struct drm_i915_memory_region_info regions[];\n};\n#endif // not defined(DRM_I915_QUERY_MEMORY_REGIONS)\n\n// Copied from https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/intel/common/intel_gem.h\nstatic inline int intel_ioctl(int fd, unsigned long request, void *arg) {\n  int ret;\n\n  do {\n    ret = ioctl(fd, request, arg);\n  } while (ret == -1 && (errno == EINTR || errno == EAGAIN));\n  return ret;\n}\n// End Copy\n\n// Copied from https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/intel/common/i915/intel_gem.h\nstatic inline int intel_i915_query(int fd, uint64_t query_id, void *buffer, int32_t *buffer_len) {\n  struct drm_i915_query_item item = {\n      .query_id = query_id,\n      .length = *buffer_len,\n      .flags = 0,\n      .data_ptr = (uintptr_t)buffer,\n  };\n\n  struct drm_i915_query args = {\n      .num_items = 1,\n      .flags = 0,\n      .items_ptr = (uintptr_t)&item,\n  };\n\n  int ret = intel_ioctl(fd, DRM_IOCTL_I915_QUERY, &args);\n  if (ret != 0)\n    return -errno;\n  else if (item.length < 0)\n    return item.length;\n\n  *buffer_len = item.length;\n  return 0;\n}\n\nstatic inline void *intel_i915_query_alloc_fetch(int fd, uint64_t query_id, int32_t *query_length) {\n  if (query_length)\n    *query_length = 0;\n\n  int32_t length = 0;\n  int ret = intel_i915_query(fd, query_id, NULL, &length);\n  if (ret < 0)\n    return NULL;\n\n  void *data = calloc(1, length);\n  assert(data != NULL); /* This shouldn't happen in practice */\n  if (data == NULL)\n    return NULL;\n\n  ret = intel_i915_query(fd, query_id, data, &length);\n  assert(ret == 0); /* We should have caught the error above */\n  if (ret < 0) {\n    free(data);\n    return NULL;\n  }\n\n  if (query_length)\n    *query_length = length;\n\n  return data;\n}\n// End Copy\n\nvoid gpuinfo_intel_i915_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_intel *gpu_info = container_of(_gpu_info, struct gpu_info_intel, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  if (gpu_info->card_fd) {\n    int32_t length = 0;\n    struct drm_i915_query_memory_regions *regions =\n        intel_i915_query_alloc_fetch(gpu_info->card_fd, DRM_I915_QUERY_MEMORY_REGIONS, &length);\n    if (regions) {\n      for (unsigned i = 0; i < regions->num_regions; i++) {\n        struct drm_i915_memory_region_info mr = regions->regions[i];\n        // ARC will have device memory and system memory, integrated graphics will have only one system region\n        if (mr.region.memory_class == I915_MEMORY_CLASS_DEVICE || regions->num_regions == 1) {\n          SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, mr.probed_size);\n          // i915 will report the total memory as the unallocated size if we don't have CAP_PERFMON\n          if (mr.unallocated_size != mr.probed_size) {\n            SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, mr.unallocated_size);\n            SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, dynamic_info->total_memory - dynamic_info->free_memory);\n            SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate,\n                                dynamic_info->used_memory * 100 / dynamic_info->total_memory);\n          }\n          break;\n        }\n      }\n      free(regions);\n    }\n  }\n}\n\nstatic const char i915_drm_intel_render[] = \"drm-engine-render\";\nstatic const char i915_drm_intel_copy[] = \"drm-engine-copy\";\nstatic const char i915_drm_intel_video[] = \"drm-engine-video\";\nstatic const char i915_drm_intel_video_enhance[] = \"drm-engine-video-enhance\";\nstatic const char i915_drm_intel_compute[] = \"drm-engine-compute\";\nstatic const char i915_drm_intel_vram[] = \"drm-total-local0\";\nstatic const char i915_drm_intel_gtt[] = \"drm-total-system0\";\n\nbool parse_drm_fdinfo_intel_i915(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n  struct gpu_info_intel *gpu_info = container_of(info, struct gpu_info_intel, base);\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  ssize_t count = 0;\n\n  bool client_id_set = false;\n  unsigned cid;\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n\n  while ((count = getline(&line, &line_buf_size, fdinfo_file)) != -1) {\n    char *key, *val;\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    if (!strcmp(key, drm_pdev)) {\n      if (strcmp(val, gpu_info->base.pdev)) {\n        return false;\n      }\n    } else if (!strcmp(key, drm_client_id)) {\n      char *endptr;\n      cid = strtoul(val, &endptr, 10);\n      if (*endptr)\n        continue;\n      client_id_set = true;\n    } else {\n      bool is_render = !strcmp(key, i915_drm_intel_render);\n      bool is_copy = !strcmp(key, i915_drm_intel_copy);\n      bool is_video = !strcmp(key, i915_drm_intel_video);\n      bool is_video_enhance = !strcmp(key, i915_drm_intel_video_enhance);\n      bool is_compute = !strcmp(key, i915_drm_intel_compute);\n\n      if (!strcmp(key, i915_drm_intel_vram) || !strcmp(key, i915_drm_intel_gtt)) {\n        unsigned long mem_int;\n        char *endptr;\n\n        mem_int = strtoul(val, &endptr, 10);\n        if (endptr == val || (strcmp(endptr, \" kB\") && strcmp(endptr, \" KiB\")))\n          continue;\n\n        if GPUINFO_PROCESS_FIELD_VALID (process_info, gpu_memory_usage)\n          SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, process_info->gpu_memory_usage + (mem_int * 1024));\n        else\n          SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, mem_int * 1024);\n\n      } else if (is_render || is_copy || is_video || is_video_enhance || is_compute) {\n        char *endptr;\n        uint64_t time_spent = strtoull(val, &endptr, 10);\n        if (endptr == val || strcmp(endptr, \" ns\"))\n          continue;\n        if (is_render) {\n          SET_GPUINFO_PROCESS(process_info, gfx_engine_used, time_spent);\n        }\n        if (is_copy) {\n          // TODO: what is copy?\n        }\n        if (is_video) {\n          // Video represents encode and decode\n          SET_GPUINFO_PROCESS(process_info, dec_engine_used, time_spent);\n          SET_GPUINFO_PROCESS(process_info, enc_engine_used, time_spent);\n        }\n        if (is_video_enhance) {\n          // TODO: what is this\n        }\n        if (is_compute) {\n          SET_GPUINFO_PROCESS(process_info, compute_engine_used, time_spent);\n        }\n      }\n    }\n  }\n  if (!client_id_set)\n    return false;\n\n  process_info->type = gpu_process_unknown;\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used) && process_info->gfx_engine_used > 0)\n    process_info->type |= gpu_process_graphical;\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, compute_engine_used) && process_info->compute_engine_used > 0)\n    process_info->type |= gpu_process_compute;\n\n  struct intel_process_info_cache *cache_entry;\n  struct unique_cache_id ucid = {.client_id = cid, .pid = process_info->pid, .pdev = gpu_info->base.pdev};\n  HASH_FIND_CLIENT(gpu_info->last_update_process_cache, &ucid, cache_entry);\n  // TODO: find how to extract global utilization\n  // gpu util will be computed as the sum of all the processes utilization for now\n  if (cache_entry) {\n    uint64_t time_elapsed = nvtop_difftime_u64(cache_entry->last_measurement_tstamp, current_time);\n    HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used) &&\n        INTEL_CACHE_FIELD_VALID(cache_entry, engine_render) &&\n        // In some rare occasions, the gfx engine usage reported by the driver is lowering (might be a driver bug)\n        process_info->gfx_engine_used >= cache_entry->engine_render &&\n        process_info->gfx_engine_used - cache_entry->engine_render <= time_elapsed) {\n      SET_GPUINFO_PROCESS(\n          process_info, gpu_usage,\n          busy_usage_from_time_usage_round(process_info->gfx_engine_used, cache_entry->engine_render, time_elapsed));\n    }\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, dec_engine_used) &&\n        INTEL_CACHE_FIELD_VALID(cache_entry, engine_video) &&\n        process_info->dec_engine_used >= cache_entry->engine_video &&\n        process_info->dec_engine_used - cache_entry->engine_video <= time_elapsed) {\n      SET_GPUINFO_PROCESS(\n          process_info, decode_usage,\n          busy_usage_from_time_usage_round(process_info->dec_engine_used, cache_entry->engine_video, time_elapsed));\n    }\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, enc_engine_used) &&\n        INTEL_CACHE_FIELD_VALID(cache_entry, engine_video_enhance) &&\n        process_info->enc_engine_used >= cache_entry->engine_video_enhance &&\n        process_info->enc_engine_used - cache_entry->engine_video_enhance <= time_elapsed) {\n      SET_GPUINFO_PROCESS(process_info, encode_usage,\n                          busy_usage_from_time_usage_round(process_info->enc_engine_used,\n                                                           cache_entry->engine_video_enhance, time_elapsed));\n    }\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, compute_engine_used) &&\n        GPUINFO_PROCESS_FIELD_VALID(process_info, gpu_usage) && INTEL_CACHE_FIELD_VALID(cache_entry, engine_compute) &&\n        process_info->compute_engine_used >= cache_entry->engine_compute &&\n        process_info->compute_engine_used - cache_entry->engine_compute <= time_elapsed) {\n      SET_GPUINFO_PROCESS(process_info, gpu_usage,\n                          process_info->gpu_usage + busy_usage_from_time_usage_round(process_info->compute_engine_used,\n                                                                                     cache_entry->engine_compute,\n                                                                                     time_elapsed));\n    }\n  } else {\n    cache_entry = calloc(1, sizeof(*cache_entry));\n    if (!cache_entry)\n      goto parse_fdinfo_exit;\n    cache_entry->client_id.client_id = cid;\n    cache_entry->client_id.pid = process_info->pid;\n    cache_entry->client_id.pdev = gpu_info->base.pdev;\n  }\n\n  // Check if we already processed this client_id in the current update cycle.\n  // This can happen when a process has multiple file descriptors referencing\n  // the same DRM client (e.g., via DRM master operations).\n  struct intel_process_info_cache *cache_entry_check;\n  HASH_FIND_CLIENT(gpu_info->current_update_process_cache, &cache_entry->client_id, cache_entry_check);\n  if (cache_entry_check) {\n    // Already processed this client_id, free the entry if we allocated it\n    if (cache_entry != cache_entry_check)\n      free(cache_entry);\n    goto parse_fdinfo_exit;\n  }\n\n  RESET_ALL(cache_entry->valid);\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used))\n    SET_INTEL_CACHE(cache_entry, engine_render, process_info->gfx_engine_used);\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, dec_engine_used))\n    SET_INTEL_CACHE(cache_entry, engine_video, process_info->dec_engine_used);\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, enc_engine_used))\n    SET_INTEL_CACHE(cache_entry, engine_video_enhance, process_info->enc_engine_used);\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, compute_engine_used))\n    SET_INTEL_CACHE(cache_entry, engine_compute, process_info->compute_engine_used);\n\n  cache_entry->last_measurement_tstamp = current_time;\n  HASH_ADD_CLIENT(gpu_info->current_update_process_cache, cache_entry);\n\nparse_fdinfo_exit:\n  return true;\n}"
  },
  {
    "path": "src/extract_gpuinfo_intel_xe.c",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop and adapted from igt-gpu-tools from Intel Corporation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include \"extract_gpuinfo_intel.h\"\n\n#include <assert.h>\n#include <libdrm/drm.h>\n#include <libdrm/xe_drm.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n#include <uthash.h>\n\n#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))\n\n// Copied from https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/intel/common/intel_gem.h\nstatic inline int intel_ioctl(int fd, unsigned long request, void *arg) {\n  int ret;\n\n  do {\n    ret = ioctl(fd, request, arg);\n  } while (ret == -1 && (errno == EINTR || errno == EAGAIN));\n  return ret;\n}\n// End Copy\n\n// Copied from https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/intel/common/xe/intel_device_query.c\nstatic void *xe_device_query_alloc_fetch(int fd, uint32_t query_id, uint32_t *len) {\n  struct drm_xe_device_query query = {\n      .query = query_id,\n  };\n  if (intel_ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query))\n    return NULL;\n\n  void *data = calloc(1, query.size);\n  if (!data)\n    return NULL;\n\n  query.data = (uintptr_t)data;\n  if (intel_ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query)) {\n    free(data);\n    return NULL;\n  }\n\n  if (len)\n    *len = query.size;\n  return data;\n}\n// End Copy\n\nvoid gpuinfo_intel_xe_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_intel *gpu_info = container_of(_gpu_info, struct gpu_info_intel, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  if (gpu_info->card_fd) {\n    uint32_t length = 0;\n    struct drm_xe_query_mem_regions *regions =\n        xe_device_query_alloc_fetch(gpu_info->card_fd, DRM_XE_DEVICE_QUERY_MEM_REGIONS, &length);\n    if (regions) {\n      for (unsigned i = 0; i < regions->num_mem_regions; i++) {\n        struct drm_xe_mem_region mr = regions->mem_regions[i];\n        // ARC will have VRAM and SYSMEM, integrated graphics will have only one SYSMEM region\n        if (mr.mem_class == DRM_XE_MEM_REGION_CLASS_VRAM || regions->num_mem_regions == 1) {\n          SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, mr.total_size);\n          // xe will report 0 kb used if we don't have CAP_PERFMON\n          if (mr.used != 0) {\n            SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, mr.used);\n            SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, dynamic_info->total_memory - dynamic_info->used_memory);\n            SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, dynamic_info->used_memory * 100 / dynamic_info->total_memory);\n          }\n          break;\n        }\n      }\n      free(regions);\n    }\n  }\n}\n\nstatic const char xe_drm_intel_vram[] = \"drm-total-vram0\";\n// static const char xe_drm_intel_gtt[] = \"drm-total-gtt\";\n// Render\nstatic const char xe_drm_intel_cycles_rcs[] = \"drm-cycles-rcs\";\nstatic const char xe_drm_intel_total_cycles_rcs[] = \"drm-total-cycles-rcs\";\n// Video Decode\nstatic const char xe_drm_intel_cycles_vcs[] = \"drm-cycles-vcs\";\nstatic const char xe_drm_intel_total_cycles_vcs[] = \"drm-total-cycles-vcs\";\n// Video Enhance\nstatic const char xe_drm_intel_cycles_vecs[] = \"drm-cycles-vecs\";\nstatic const char xe_drm_intel_total_cycles_vecs[] = \"drm-total-cycles-vecs\";\n// Copy\nstatic const char xe_drm_intel_cycles_bcs[] = \"drm-cycles-bcs\";\nstatic const char xe_drm_intel_total_cycles_bcs[] = \"drm-total-cycles-bcs\";\n// Compute\nstatic const char xe_drm_intel_cycles_ccs[] = \"drm-cycles-ccs\";\nstatic const char xe_drm_intel_total_cycles_ccs[] = \"drm-total-cycles-ccs\";\n\nstatic const char *cycles_keys[] = {xe_drm_intel_cycles_rcs, xe_drm_intel_cycles_vcs, xe_drm_intel_cycles_vecs,\n                                    xe_drm_intel_cycles_bcs, xe_drm_intel_cycles_ccs};\n\nstatic const char *total_cycles_keys[] = {xe_drm_intel_total_cycles_rcs, xe_drm_intel_total_cycles_vcs,\n                                          xe_drm_intel_total_cycles_vecs, xe_drm_intel_total_cycles_bcs,\n                                          xe_drm_intel_total_cycles_ccs};\n\nbool parse_drm_fdinfo_intel_xe(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n  struct gpu_info_intel *gpu_info = container_of(info, struct gpu_info_intel, base);\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  ssize_t count = 0;\n\n  bool client_id_set = false;\n  unsigned cid;\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n\n  union intel_cycles gpu_cycles = {.array = {0}};\n\n  union intel_cycles total_cycles = {.array = {0}};\n\n  while ((count = getline(&line, &line_buf_size, fdinfo_file)) != -1) {\n    char *key, *val;\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    if (!strcmp(key, drm_pdev)) {\n      if (strcmp(val, gpu_info->base.pdev)) {\n        return false;\n      }\n    } else if (!strcmp(key, drm_client_id)) {\n      char *endptr;\n      cid = strtoul(val, &endptr, 10);\n      if (*endptr)\n        continue;\n      client_id_set = true;\n    } else {\n      if (!strcmp(key, xe_drm_intel_vram)) {\n        unsigned long mem_int;\n        char *endptr;\n\n        mem_int = strtoul(val, &endptr, 10);\n        if (endptr == val || (strcmp(endptr, \" kB\") && strcmp(endptr, \" KiB\")))\n          continue;\n\n        if GPUINFO_PROCESS_FIELD_VALID (process_info, gpu_memory_usage)\n          SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, process_info->gpu_memory_usage + (mem_int * 1024));\n        else\n          SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, mem_int * 1024);\n      } else {\n        unsigned long cycles;\n        char *endptr;\n\n        // Check for cycles\n        for (unsigned i = 0; i < ARRAY_SIZE(gpu_cycles.array); i++) {\n          if (!strcmp(key, cycles_keys[i])) {\n            cycles = strtoull(val, &endptr, 10);\n            gpu_cycles.array[i] = cycles;\n          }\n        }\n\n        // Check for total cycles\n        for (unsigned i = 0; i < ARRAY_SIZE(total_cycles_keys); i++) {\n          if (!strcmp(key, total_cycles_keys[i])) {\n            cycles = strtoull(val, &endptr, 10);\n            total_cycles.array[i] = cycles;\n          }\n        }\n      }\n    }\n  }\n\n  // Sum cycles for overall usage\n  {\n    uint64_t cycles_sum = 0;\n    for (unsigned i = 0; i < ARRAY_SIZE(gpu_cycles.array); i++) {\n      cycles_sum += gpu_cycles.array[i];\n    }\n    SET_GPUINFO_PROCESS(process_info, gpu_cycles, cycles_sum);\n  }\n\n  if (!client_id_set)\n    return false;\n\n  process_info->type = gpu_process_unknown;\n  if (gpu_cycles.rcs != 0)\n    process_info->type |= gpu_process_graphical;\n  if (gpu_cycles.ccs != 0)\n    process_info->type |= gpu_process_compute;\n\n  struct intel_process_info_cache *cache_entry;\n  struct unique_cache_id ucid = {.client_id = cid, .pid = process_info->pid, .pdev = gpu_info->base.pdev};\n  HASH_FIND_CLIENT(gpu_info->last_update_process_cache, &ucid, cache_entry);\n  if (cache_entry) {\n    HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n\n    // TODO: find how to extract global utilization\n    // gpu util will be computed as the sum of all the processes utilization for now\n    {\n      uint64_t cycles_delta = gpu_cycles.rcs - cache_entry->gpu_cycles.rcs;\n      uint64_t total_cycles_delta = total_cycles.rcs - cache_entry->total_cycles.rcs;\n      if (total_cycles_delta > 0)\n        SET_GPUINFO_PROCESS(process_info, gpu_usage, cycles_delta * 100 / total_cycles_delta);\n      else\n        SET_GPUINFO_PROCESS(process_info, gpu_usage, 0);\n    }\n    {\n      uint64_t cycles_delta = gpu_cycles.ccs - cache_entry->gpu_cycles.ccs;\n      uint64_t total_cycles_delta = total_cycles.ccs - cache_entry->total_cycles.ccs;\n      if (total_cycles_delta > 0)\n        SET_GPUINFO_PROCESS(process_info, gpu_usage, process_info->gpu_usage + cycles_delta * 100 / total_cycles_delta);\n    }\n    {\n      uint64_t cycles_delta = gpu_cycles.vcs - cache_entry->gpu_cycles.vcs;\n      uint64_t total_cycles_delta = total_cycles.vcs - cache_entry->total_cycles.vcs;\n      if (total_cycles_delta > 0)\n        SET_GPUINFO_PROCESS(process_info, decode_usage, cycles_delta * 100 / total_cycles_delta);\n    }\n\n  } else {\n    cache_entry = calloc(1, sizeof(*cache_entry));\n    if (!cache_entry)\n      goto parse_fdinfo_exit;\n    cache_entry->client_id.client_id = cid;\n    cache_entry->client_id.pid = process_info->pid;\n    cache_entry->client_id.pdev = gpu_info->base.pdev;\n  }\n\n  // Check if we already processed this client_id in the current update cycle.\n  // This can happen when a process has multiple file descriptors referencing\n  // the same DRM client (e.g., via DRM master operations).\n  struct intel_process_info_cache *cache_entry_check;\n  HASH_FIND_CLIENT(gpu_info->current_update_process_cache, &cache_entry->client_id, cache_entry_check);\n  if (cache_entry_check) {\n    // Already processed this client_id, free the entry if we allocated it\n    if (cache_entry != cache_entry_check)\n      free(cache_entry);\n    goto parse_fdinfo_exit;\n  }\n\n  RESET_ALL(cache_entry->valid);\n  SET_INTEL_CACHE(cache_entry, gpu_cycles, gpu_cycles);\n  SET_INTEL_CACHE(cache_entry, total_cycles, total_cycles);\n\n  HASH_ADD_CLIENT(gpu_info->current_update_process_cache, cache_entry);\n\nparse_fdinfo_exit:\n  return true;\n}"
  },
  {
    "path": "src/extract_gpuinfo_mali_common.c",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * This file is part of Nvtop and adapted from the msm implementation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <assert.h>\n#include <errno.h>\n#include <dlfcn.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <xf86drm.h>\n\n#include \"mali_common.h\"\n\nenum mali_process_info_cache_valid {\n  mali_cache_engine_render_valid = 0,\n  mali_cache_process_info_cache_valid_count\n};\n\nstruct __attribute__((__packed__)) unique_cache_id {\n  unsigned client_id;\n  pid_t pid;\n};\n\nstruct mali_process_info_cache {\n  struct unique_cache_id client_id;\n  uint64_t engine_render;\n  uint64_t last_cycles;\n  nvtop_time last_measurement_tstamp;\n  unsigned char valid[(mali_cache_process_info_cache_valid_count + CHAR_BIT - 1) / CHAR_BIT];\n  UT_hash_handle hh;\n};\n\nbool mali_init_drm_funcs(struct drmFuncTable *drmFuncs,\n\t\t\t struct mali_gpu_state *state)\n{\n    state->libdrm_handle = dlopen(\"libdrm.so\", RTLD_LAZY);\n  if (!state->libdrm_handle)\n    state->libdrm_handle = dlopen(\"libdrm.so.2\", RTLD_LAZY);\n  if (!state->libdrm_handle)\n    state->libdrm_handle = dlopen(\"libdrm.so.1\", RTLD_LAZY);\n  if (!state->libdrm_handle) {\n    state->local_error_string = dlerror();\n    return false;\n  }\n\n  drmFuncs->drmGetDevices2 = dlsym(state->libdrm_handle, \"drmGetDevices2\");\n  if (!drmFuncs->drmGetDevices2)\n    drmFuncs->drmGetDevices = dlsym(state->libdrm_handle, \"drmGetDevices\");\n  if (!drmFuncs->drmGetDevices2 && !drmFuncs->drmGetDevices)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmFreeDevices = dlsym(state->libdrm_handle, \"drmFreeDevices\");\n  if (!drmFuncs->drmFreeDevices)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmGetVersion = dlsym(state->libdrm_handle, \"drmGetVersion\");\n  if (!drmFuncs->drmGetVersion)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmFreeVersion = dlsym(state->libdrm_handle, \"drmFreeVersion\");\n  if (!drmFuncs->drmFreeVersion)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmGetMagic = dlsym(state->libdrm_handle, \"drmGetMagic\");\n  if (!drmFuncs->drmGetMagic)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmAuthMagic = dlsym(state->libdrm_handle, \"drmAuthMagic\");\n  if (!drmFuncs->drmAuthMagic)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmDropMaster = dlsym(state->libdrm_handle, \"drmDropMaster\");\n  if (!drmFuncs->drmDropMaster)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmCommandWriteRead = dlsym(state->libdrm_handle, \"drmCommandWriteRead\");\n  if (!drmFuncs->drmCommandWriteRead)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmGetDeviceFromDevId = dlsym(state->libdrm_handle, \"drmGetDeviceFromDevId\");\n  if (!drmFuncs->drmGetDeviceFromDevId)\n    goto init_error_clean_exit;\n\n  drmFuncs->drmIoctl = dlsym(state->libdrm_handle, \"drmIoctl\");\n  if (!drmFuncs->drmCommandWriteRead)\n    goto init_error_clean_exit;\n\n  state->local_error_string = NULL;\n\n  state->meminfo_file = fopen(\"/proc/meminfo\", \"r\");\n  if (!state->meminfo_file)\n    goto init_error_clean_exit;\n\n  state->didnt_call_gpuinfo_init = \"uninitialized\";\n\n  return true;\n\ninit_error_clean_exit:\n  dlclose(state->libdrm_handle);\n  state->libdrm_handle = NULL;\n  return false;\n}\n\nvoid mali_deinit_drm(struct mali_gpu_state *state)\n{\n  dlclose(state->libdrm_handle);\n  state->libdrm_handle = NULL;\n}\n\nvoid mali_shutdown_common(struct mali_gpu_state *state,\n\t\t\t  struct drmFuncTable *funcs)\n{\n  for (unsigned i = 0; i < state->mali_gpu_count; ++i) {\n    struct gpu_info_mali *current = &state->gpu_infos[i];\n    funcs->drmFreeVersion(current->drmVersion);\n  }\n\n  free(state->gpu_infos);\n  state->gpu_infos = NULL;\n  state->mali_gpu_count = 0;\n\n  if (state->libdrm_handle) {\n    dlclose(state->libdrm_handle);\n    state->libdrm_handle = NULL;\n    state->local_error_string = state->didnt_call_gpuinfo_init;\n  }\n\n  if (state->meminfo_file) {\n    fclose(state->meminfo_file);\n    state->meminfo_file = NULL;\n  }\n}\n\nconst char *mali_common_last_error_string(struct mali_gpu_state *state,\n\t\t\t\t\t  const char *drivername,\n\t\t\t\t\t  char error_str[])\n{\n  if (state->local_error_string) {\n    return state->local_error_string;\n  } else if (state->last_libdrm_return_status < 0) {\n    switch (state->last_libdrm_return_status) {\n    case DRM_ERR_NO_DEVICE:\n      return \"no device\\n\";\n    case DRM_ERR_NO_ACCESS:\n      return \"no access\\n\";\n    case DRM_ERR_NOT_ROOT:\n      return \"not root\\n\";\n    case DRM_ERR_INVALID:\n      return \"invalid args\\n\";\n    case DRM_ERR_NO_FD:\n      return \"no fd\\n\";\n    default:\n      return \"unknown error\\n\";\n    }\n  } else {\n\n    int ret = snprintf(error_str, MAX_ERR_STRING_LEN,\n\t\t       \"An unanticipated error occurred while accessing %s information\\n\",\n\t\t       drivername);\n    if (ret >= MAX_ERR_STRING_LEN)\n      error_str[MAX_ERR_STRING_LEN - 1]  = '\\0';\n    return error_str;\n  }\n}\n\nstatic int wrap_drmGetDevices(drmDevicePtr devices[], int max_devices, struct drmFuncTable *funcs) {\n  assert(funcs->drmGetDevices2 || funcs->drmGetDevices);\n\n  if (funcs->drmGetDevices2)\n    return funcs->drmGetDevices2(0, devices, max_devices);\n  return funcs->drmGetDevices(devices, max_devices);\n}\n\nstatic void authenticate_drm(int fd, struct drmFuncTable *funcs) {\n  drm_magic_t magic;\n\n  if (funcs->drmGetMagic(fd, &magic) < 0) {\n    return;\n  }\n\n  if (funcs->drmAuthMagic(fd, magic) == 0) {\n    if (funcs->drmDropMaster(fd)) {\n      perror(\"Failed to drop DRM master\");\n      fprintf(\n          stderr,\n          \"\\nWARNING: other DRM clients will crash on VT switch while nvtop is running!\\npress ENTER to continue\\n\");\n      fgetc(stdin);\n    }\n    return;\n  }\n\n  // XXX: Ideally I'd implement this too, but I'd need to pull in libxcb and yet\n  // more functions and structs that may break ABI compatibility.\n  // See radeontop auth_xcb.c for what is involved here\n  fprintf(stderr, \"Failed to authenticate to DRM; XCB authentication unimplemented\\n\");\n}\n\nbool mali_common_get_device_handles(struct mali_gpu_state *state,\n\t\t\t\t    struct drmFuncTable *funcs,\n\t\t\t\t    struct gpu_vendor *vendor,\n\t\t\t\t    processinfo_fdinfo_callback callback,\n\t\t\t\t    struct list_head *devices, unsigned *count,\n\t\t\t\t    bool (*handle_model) (struct gpu_info_mali *),\n\t\t\t\t    enum mali_version version)\n{\n  if (!state->libdrm_handle || version >= MALI_VERSIONS)\n    return false;\n\n  state->last_libdrm_return_status = wrap_drmGetDevices(NULL, 0, funcs);\n  if (state->last_libdrm_return_status <= 0)\n    return false;\n\n  drmDevicePtr devs[state->last_libdrm_return_status];\n  state->last_libdrm_return_status = wrap_drmGetDevices(devs, state->last_libdrm_return_status, funcs);\n  if (state->last_libdrm_return_status <= 0)\n    return false;\n\n  unsigned int libdrm_count = state->last_libdrm_return_status;\n  state->gpu_infos = calloc(libdrm_count, sizeof(*state->gpu_infos));\n  if (!state->gpu_infos) {\n    state->local_error_string = strerror(errno);\n    return false;\n  }\n\n  state->gpu_infos->version = version;\n  state->mali_gpu_count = 0;\n\n  for (unsigned int i = 0; i < libdrm_count; i++) {\n    int fd = -1;\n\n    // Try render node first\n    if (1 << DRM_NODE_RENDER & devs[i]->available_nodes) {\n      fd = open(devs[i]->nodes[DRM_NODE_RENDER], O_RDWR);\n    }\n    if (fd < 0) {\n      // Fallback to primary node (control nodes are unused according to the DRM documentation)\n      if (1 << DRM_NODE_PRIMARY & devs[i]->available_nodes) {\n        fd = open(devs[i]->nodes[DRM_NODE_PRIMARY], O_RDWR);\n      }\n    }\n\n    if (fd < 0)\n      continue;\n\n    drmVersionPtr ver = funcs->drmGetVersion(fd);\n\n    if (!ver) {\n      close(fd);\n      continue;\n    }\n\n    if (strcmp(ver->name, vendor->name)) {\n      funcs->drmFreeVersion(ver);\n      close(fd);\n      continue;\n    }\n\n    authenticate_drm(fd, funcs);\n\n    state->gpu_infos[state->mali_gpu_count].drmVersion = ver;\n    state->gpu_infos[state->mali_gpu_count].fd = fd;\n    state->gpu_infos[state->mali_gpu_count].base.vendor = vendor;\n\n    list_add_tail(&state->gpu_infos[state->mali_gpu_count].base.list, devices);\n    // Register a fdinfo callback for this GPU\n    processinfo_register_fdinfo_callback(callback, &state->gpu_infos[state->mali_gpu_count].base);\n\n    if (handle_model) {\n      if (!handle_model(&state->gpu_infos[state->mali_gpu_count])) {\n              funcs->drmFreeVersion(ver);\n              close(fd);\n              continue;\n      }\n    }\n\n    state->mali_gpu_count++;\n  }\n\n  funcs->drmFreeDevices(devs, libdrm_count);\n  *count = state->mali_gpu_count;\n\n  return true;\n}\n\nuint64_t parse_memory_multiplier(const char *str) {\n  if (strcmp(str, \" B\") == 0) {\n    return 1;\n  }\n  else if (strcmp(str, \" KiB\") == 0 || strcmp(str, \" kB\") == 0) {\n    return 1024;\n  }\n  else if (strcmp(str, \" MiB\") == 0) {\n    return 1024 * 1024;\n  }\n  else if (strcmp(str, \" GiB\") == 0) {\n    return 1024 * 1024 * 1024;\n  }\n\n  return 1;\n}\n\nvoid mali_common_refresh_dynamic_info(struct gpuinfo_dynamic_info *dynamic_info,\n\t\t\t\t      struct mali_gpu_state *state,\n\t\t\t\t      const char *meminfo_total,\n\t\t\t\t      const char *meminfo_available)\n{\n  RESET_ALL(dynamic_info->valid);\n\n  rewind(state->meminfo_file);\n  fflush(state->meminfo_file);\n\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  ssize_t count = 0;\n  uint64_t mem_total = 0;\n  uint64_t mem_available = 0;\n  size_t keys_acquired = 0;\n\n  while (keys_acquired != 2 && (count = getline(&line, &line_buf_size, state->meminfo_file)) != -1) {\n    char *key, *val;\n\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    bool is_total = !strcmp(key, meminfo_total);\n    bool is_available = !strcmp(key, meminfo_available);\n\n    if (is_total || is_available) {\n      uint64_t mem_int;\n      char *endptr;\n\n      mem_int = strtoull(val, &endptr, 10);\n      if (endptr == val)\n        continue;\n\n      mem_int *= parse_memory_multiplier(endptr);\n      if (is_total) {\n        mem_total = mem_int;\n      }\n      else if (is_available) {\n        mem_available = mem_int;\n      }\n      ++keys_acquired;\n    }\n  }\n\n  SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, mem_total);\n  SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, mem_total - mem_available);\n  SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, mem_available);\n  SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate,\n                      (dynamic_info->total_memory - dynamic_info->free_memory) * 100 / dynamic_info->total_memory);\n}\n\nstatic void swap_process_cache_for_next_update(struct gpu_info_mali *gpu_info) {\n  // Free old cache data and set the cache for the next update\n  if (gpu_info->last_update_process_cache) {\n    struct mali_process_info_cache *cache_entry, *tmp;\n    HASH_ITER(hh, gpu_info->last_update_process_cache, cache_entry, tmp) {\n      HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n      free(cache_entry);\n    }\n  }\n  gpu_info->last_update_process_cache = gpu_info->current_update_process_cache;\n  gpu_info->current_update_process_cache = NULL;\n}\n\nvoid mali_common_get_running_processes(struct gpu_info *_gpu_info, enum mali_version version) {\n  // For Mali, we register a fdinfo callback that will fill the gpu_process datastructure of the gpu_info structure\n  // for us. This avoids going through /proc multiple times per update for multiple GPUs.\n  struct gpu_info_mali *gpu_info = container_of(_gpu_info, struct gpu_info_mali, base);\n  if (gpu_info->version != version) {\n    fprintf(stderr, \"Wrong device version: %u\\n\", gpu_info->version);\n    abort();\n  }\n\n  swap_process_cache_for_next_update(gpu_info);\n}\n\nvoid mali_common_parse_fdinfo_handle_cache(struct gpu_info_mali *gpu_info,\n\t\t\t\t\t   struct gpu_process *process_info,\n\t\t\t\t\t   nvtop_time current_time,\n\t\t\t\t\t   uint64_t total_cycles,\n\t\t\t\t\t   unsigned cid,\n\t\t\t\t\t   bool engine_count)\n{\n  struct mali_process_info_cache *cache_entry;\n  struct unique_cache_id ucid = {.client_id = cid, .pid = process_info->pid};\n\n  HASH_FIND_CLIENT(gpu_info->last_update_process_cache, &ucid, cache_entry);\n\n  if (cache_entry) {\n    uint64_t time_elapsed = nvtop_difftime_u64(cache_entry->last_measurement_tstamp, current_time);\n    SET_GPUINFO_PROCESS(process_info, sample_delta, time_elapsed);\n    if (engine_count)\n      SET_GPUINFO_PROCESS(process_info, gpu_cycles, total_cycles - cache_entry->last_cycles);\n    cache_entry->last_cycles = total_cycles;\n    HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used) &&\n        MALI_CACHE_FIELD_VALID(cache_entry, engine_render) &&\n        // In some rare occasions, the gfx engine usage reported by the driver is lowering (might be a driver bug)\n        process_info->gfx_engine_used >= cache_entry->engine_render &&\n        process_info->gfx_engine_used - cache_entry->engine_render <= time_elapsed) {\n      SET_GPUINFO_PROCESS(\n          process_info, gpu_usage,\n          busy_usage_from_time_usage_round(process_info->gfx_engine_used, cache_entry->engine_render, time_elapsed));\n    }\n  } else {\n    cache_entry = calloc(1, sizeof(*cache_entry));\n    if (!cache_entry)\n      return;\n    cache_entry->client_id.client_id = cid;\n    cache_entry->client_id.pid = process_info->pid;\n    cache_entry->last_cycles = total_cycles;\n  }\n\n  // Check if we already processed this client_id in the current update cycle.\n  // This can happen when a process has multiple file descriptors referencing\n  // the same DRM client (e.g., via DRM master operations).\n  struct mali_process_info_cache *cache_entry_check;\n  HASH_FIND_CLIENT(gpu_info->current_update_process_cache, &cache_entry->client_id, cache_entry_check);\n  if (cache_entry_check) {\n    // Already processed this client_id, free the entry if we allocated it\n    if (cache_entry != cache_entry_check)\n      free(cache_entry);\n    return;\n  }\n\n  RESET_ALL(cache_entry->valid);\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used))\n    SET_MALI_CACHE(cache_entry, engine_render, process_info->gfx_engine_used);\n\n  cache_entry->last_measurement_tstamp = current_time;\n  HASH_ADD_CLIENT(gpu_info->current_update_process_cache, cache_entry);\n}\n\nbool mali_common_parse_drm_fdinfo(struct gpu_info *info, FILE *fdinfo_file,\n\t\t\t\t  struct gpu_process *process_info,\n\t\t\t\t  struct gpuinfo_dynamic_info *dynamic_info,\n\t\t\t\t  check_fdinfo_keys match_keys,\n\t\t\t\t  struct fdinfo_data *fid)\n{\n  struct gpuinfo_static_info *static_info = &info->static_info;\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  uint64_t total_time = 0;\n  bool client_id_set = false;\n  ssize_t count = 0;\n\n  fid->engine_count = 0;\n  fid->total_cycles = 0;\n\n  while ((count = getline(&line, &line_buf_size, fdinfo_file)) != -1) {\n    char *key, *val;\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    if (!strcmp(key, \"drm-driver\")) {\n      if (strcmp(val, info->vendor->name)) {\n        return false;\n      }\n    } else if(!strcmp(key, drm_client_id)) {\n      char *endptr;\n      fid->cid = strtoul(val, &endptr, 10);\n      if (*endptr)\n        continue;\n      client_id_set = true;\n    } else {\n      bool is_engine, is_cycles, is_maxfreq, is_curfreq, is_resident;\n      match_keys(&is_engine, &is_cycles, &is_maxfreq, &is_curfreq, &is_resident, key);\n\n      if (is_engine) {\n        char *endptr;\n        uint64_t time_spent = strtoull(val, &endptr, 10);\n        if (endptr == val || strcmp(endptr, \" ns\"))\n          continue;\n\n        total_time += time_spent;\n        fid->engine_count++;\n      } else if (is_maxfreq || is_curfreq) {\n        char *endptr;\n        uint64_t freq = strtoull(val, &endptr, 10);\n        if (endptr == val || strcmp(endptr, \" Hz\"))\n          continue;\n\n        if (is_maxfreq)\n          SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed_max, freq / 1000000);\n        else\n          SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, freq / 1000000);\n      } else if (is_cycles) {\n        char *endptr;\n        uint64_t cycles = strtoull(val, &endptr, 10);\n\n        if (endptr == val)\n          continue;\n\n        fid->total_cycles += cycles;\n      } else if (is_resident) {\n        uint64_t mem_int;\n        char *endptr;\n\n        mem_int = strtoull(val, &endptr, 10);\n        if (endptr == val)\n          continue;\n\n        uint64_t multiplier = parse_memory_multiplier(endptr);\n        SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, mem_int * multiplier);\n      }\n    }\n  }\n\n  if (fid->engine_count) {\n          SET_GPUINFO_PROCESS(process_info, gfx_engine_used, total_time);\n          SET_GPUINFO_STATIC(static_info, engine_count, fid->engine_count);\n  }\n\n  if (!client_id_set)\n    return false;\n\n  //  driver does not expose compute engine metrics as of yet\n  process_info->type |= gpu_process_graphical;\n\n  return true;\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_metax.c",
    "content": "/*\n *\n * Copyright (c) 2025 MetaX Integrated Circuits (Shanghai) Co., Ltd. All rights reserved.\n *\n * This file is part of Nvtop and adapted from mxsml from MetaX Integrated Circuits (Shanghai) Co., Ltd.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/common.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n\n#include <dlfcn.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MXSML_SUCCESS 0\n#define DEVICE_BDF_ID_SIZE 32           //!< Guaranteed maximum possible size for BDF ID\n#define DEVICE_UUID_SIZE 96             //!< Guaranteed maximum possible size for UUID\n#define DEVICE_NAME_SIZE 32             //!< Guaranteed maximum possible size for Device name\n#define PROCESS_NAME_SIZE 64            //!< Maximum length showed process name\n#define MAX_GPU_NUM_USED_BY_PROCESS 64  //!< Maximum stored GPU information used by a process\n\ntypedef unsigned int mxSmlReturn_t; // store the enum as unsigned int\n\n// Init\n\nstatic mxSmlReturn_t (*mxSmlInit)(void);\n\n// Static information and helper functions\n\nstatic unsigned int (*mxSmlGetDeviceCount)(void);\n\nstatic const char *(*mxSmlGetErrorString)(mxSmlReturn_t);\n\ntypedef enum {\n  MXSML_Device_Unknown = 0\n} mxSmlDeviceType_t;\n\ntypedef enum {\n  MXSML_Brand_Unknown = 0,\n  MXSML_Brand_N,\n  MXSML_Brand_C,\n  MXSML_Brand_G\n} mxSmlDeviceBrand_t;\n\ntypedef enum {\n  MXSML_Virtualization_Mode_None = 0,   //!< Represents bare metal\n  MXSML_Virtualization_Mode_Pf,         //!< Physical function after virtualization\n  MXSML_Virtualization_Mode_Vf          //!< Virtualized device\n} mxSmlDeviceVirtualizationMode_t;\n\ntypedef struct {\n  unsigned int deviceId;\n  mxSmlDeviceType_t type;           //!< Deprecated. Do not use.\n  char bdfId[DEVICE_BDF_ID_SIZE];\n  unsigned int gpuId;\n  unsigned int nodeId;\n  char uuid[DEVICE_UUID_SIZE];\n  mxSmlDeviceBrand_t brand;\n  mxSmlDeviceVirtualizationMode_t mode;\n  char deviceName[DEVICE_NAME_SIZE];\n} mxSmlDeviceInfo_t;\n\nstatic mxSmlReturn_t (*mxSmlGetDeviceInfo)(unsigned int deviceId, mxSmlDeviceInfo_t *deviceInfo);\n\nstatic mxSmlReturn_t (*mxSmlGetLimitedDeviceInfo)(unsigned int deviceId, mxSmlDeviceInfo_t *deviceInfo);\n\ntypedef struct {\n  float speed;\n  unsigned int width;\n} mxSmlPcieInfo_t;\n\nstatic mxSmlReturn_t (*mxSmlGetPcieInfo)(unsigned int deviceId, mxSmlPcieInfo_t *pcieInfo);\n\nstatic mxSmlReturn_t (*mxSmlGetPcieMaxLinkInfo)(unsigned int deviceId, mxSmlPcieInfo_t *_pcieInfo);\n\ntypedef enum {\n  MXSML_Temperature_Hotspot = 0,\n  MXSML_Temperature_HotLimit,\n} mxSmlTemperatureSensors_t;\n\nstatic mxSmlReturn_t (*mxSmlGetTemperatureInfo)(unsigned int deviceId, mxSmlTemperatureSensors_t sensorType,\n                                               int *temp);\n\n// Dynamic information extraction\ntypedef enum {\n  MXSML_Clock_Dla = 1,            //!< Valid for N-class device\n  MXSML_Clock_Mc = 2,             //!< Valid for N-class device\n  MXSML_Clock_Mc0 = 3,            //!< Valid for C-class device\n  MXSML_Clock_Xcore = 11          //!< Valid for C-class device\n} mxSmlClockIp_t;\n\nstatic mxSmlReturn_t (*mxSmlGetClocks)(unsigned int deviceId, mxSmlClockIp_t type,\n                                      unsigned int *clocksSize, unsigned int *clock);\n\ntypedef enum {\n  MXSML_Dpm_Dla = 0,              //!< Valid for N-class device\n  MXSML_Dpm_Xcore,                //!< Valid for C-class device\n  MXSML_Dpm_Mc,\n} mxSmlDpmIp_t;\n\nstatic mxSmlReturn_t (*mxSmlGetDpmIpClockInfo)(unsigned int deviceId, mxSmlDpmIp_t dpmIp,\n                                              unsigned int *clockInfo, unsigned int *size);\n\ntypedef enum {\n  MXSML_Usage_Dla,                //!< Valid for N-class device\n  MXSML_Usage_Vpue,\n  MXSML_Usage_Vpud,\n  MXSML_Usage_Xcore = 4,          //!< Valid for C-class device\n} mxSmlUsageIp_t;\n\nstatic mxSmlReturn_t (*mxSmlGetDeviceIpUsage)(unsigned int deviceId, mxSmlUsageIp_t ip, int *usage);\n\ntypedef struct {\n  long visVramTotal;\n  long visVramUse;\n  long vramTotal;\n  long vramUse;\n  long xttTotal;\n  long xttUse;\n} mxSmlMemoryInfo_t;\n\nstatic mxSmlReturn_t (*mxSmlGetMemoryInfo)(unsigned int deviceId, mxSmlMemoryInfo_t *memory);\n\ntypedef struct {\n  int rx;\n  int tx;\n} mxSmlPcieThroughput_t;\n\nstatic mxSmlReturn_t (*mxSmlGetPcieThroughput)(unsigned int deviceId, mxSmlPcieThroughput_t *pcieInfo);\n\nstatic mxSmlReturn_t (*mxSmlGetFanSpeedInfo)(unsigned int deviceId, unsigned int *rpm, unsigned int *pwm);\n\ntypedef struct {\n  unsigned int voltage;\n  unsigned int current;\n  unsigned int power;\n} mxSmlBoardWayElectricInfo_t;\n\nstatic mxSmlReturn_t (*mxSmlGetBoardPowerInfo)(unsigned int deviceId, unsigned int *infoSize,\n                                              mxSmlBoardWayElectricInfo_t* boardInfo);\n\nstatic mxSmlReturn_t (*mxSmlGetBoardPowerLimit)(unsigned int deviceId, unsigned int *limit);\n\n// Processes running on GPU\n\nstatic mxSmlReturn_t (*mxSmlGetNumberOfProcess)(unsigned int *processNumber);\n\ntypedef struct {\n  char bdfId[DEVICE_BDF_ID_SIZE];\n  unsigned int gpuId;\n  unsigned long gpuMemoryUsage;\n} mxSmlProcessGpuInfo_t;\n\ntypedef struct {\n  unsigned int processId;\n  char processName[PROCESS_NAME_SIZE];\n  unsigned int gpuNumber;\n  mxSmlProcessGpuInfo_t processGpuInfo[MAX_GPU_NUM_USED_BY_PROCESS];\n} mxSmlProcessInfo_t;\n\nstatic mxSmlReturn_t (*mxSmlGetSingleGpuProcess)(unsigned int deviceId, unsigned int *processNumber,\n                                                mxSmlProcessInfo_t* processInfo);\n\nstatic void *libmxsml_handle;\n\nstatic mxSmlReturn_t last_mxsml_return_status = MXSML_SUCCESS;\nstatic char didnt_call_gpuinfo_init[] = \"The METAX extraction has not been initialized, please call \"\n                                        \"gpuinfo_metax_init\\n\";\nstatic const char *local_error_string = didnt_call_gpuinfo_init;\n\nstruct gpu_info_metax {\n  struct gpu_info base;\n  struct list_head allocate_list;\n\n  mxSmlDeviceInfo_t device;\n};\n\nstatic LIST_HEAD(allocations);\n\nstatic bool gpuinfo_metax_init(void);\nstatic void gpuinfo_metax_shutdown(void);\nstatic const char *gpuinfo_metax_last_error_string(void);\nstatic bool gpuinfo_metax_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_metax_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_metax_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_metax_get_running_processes(struct gpu_info *_gpu_info);\n\nstruct gpu_vendor gpu_vendor_metax = {\n  .init = gpuinfo_metax_init,\n  .shutdown = gpuinfo_metax_shutdown,\n  .last_error_string = gpuinfo_metax_last_error_string,\n  .get_device_handles = gpuinfo_metax_get_device_handles,\n  .populate_static_info = gpuinfo_metax_populate_static_info,\n  .refresh_dynamic_info = gpuinfo_metax_refresh_dynamic_info,\n  .refresh_running_processes = gpuinfo_metax_get_running_processes,\n  .name = \"METAX\",\n};\n\n__attribute__((constructor)) static void init_extract_gpuinfo_metax(void) { register_gpu_vendor(&gpu_vendor_metax); }\n\n/*\n *\n * This function loads the libmxsml.so shared object, initializes the\n * required function pointers and calls the mxsml library initialization\n * function. If false is returned, the cause of the error can be retrieved\n * by calling the function gpuinfo_metax_last_error_string.\n *\n */\nstatic bool gpuinfo_metax_init(void) {\n  libmxsml_handle = dlopen(\"/opt/mxdriver/lib/libmxsml.so\", RTLD_LAZY);\n  if (!libmxsml_handle)\n    libmxsml_handle = dlopen(\"/opt/maca/lib/libmxsml.so\", RTLD_LAZY);\n  if (!libmxsml_handle)\n    libmxsml_handle = dlopen(\"/opt/mxn100/lib/libmxsml.so\", RTLD_LAZY);\n  if (!libmxsml_handle) {\n    local_error_string = dlerror();\n    return false;\n  }\n\n  mxSmlInit = dlsym(libmxsml_handle, \"mxSmlInit\");\n  if (!mxSmlInit)\n    goto init_error_clean_exit;\n\n  mxSmlGetDeviceCount = dlsym(libmxsml_handle, \"mxSmlGetDeviceCount\");\n  if (!mxSmlGetDeviceCount)\n    goto init_error_clean_exit;\n\n  mxSmlGetErrorString = dlsym(libmxsml_handle, \"mxSmlGetErrorString\");\n  if (!mxSmlGetErrorString)\n    goto init_error_clean_exit;\n\n  mxSmlGetDeviceInfo = dlsym(libmxsml_handle, \"mxSmlGetDeviceInfo\");\n  if (!mxSmlGetDeviceInfo)\n    goto init_error_clean_exit;\n\n  mxSmlGetLimitedDeviceInfo = dlsym(libmxsml_handle, \"mxSmlGetLimitedDeviceInfo\");\n  if (!mxSmlGetLimitedDeviceInfo)\n    goto init_error_clean_exit;\n\n  mxSmlGetPcieInfo = dlsym(libmxsml_handle, \"mxSmlGetPcieInfo\");\n  if (!mxSmlGetPcieInfo)\n    goto init_error_clean_exit;\n\n  mxSmlGetPcieMaxLinkInfo = dlsym(libmxsml_handle, \"mxSmlGetPcieMaxLinkInfo\");\n  if (!mxSmlGetPcieMaxLinkInfo)\n    goto init_error_clean_exit;\n\n  mxSmlGetTemperatureInfo = dlsym(libmxsml_handle, \"mxSmlGetTemperatureInfo\");\n  if (!mxSmlGetTemperatureInfo)\n    goto init_error_clean_exit;\n\n  mxSmlGetClocks = dlsym(libmxsml_handle, \"mxSmlGetClocks\");\n  if (!mxSmlGetClocks)\n    goto init_error_clean_exit;\n\n  mxSmlGetDpmIpClockInfo = dlsym(libmxsml_handle, \"mxSmlGetDpmIpClockInfo\");\n  if (!mxSmlGetDpmIpClockInfo)\n    goto init_error_clean_exit;\n\n  mxSmlGetDeviceIpUsage = dlsym(libmxsml_handle, \"mxSmlGetDeviceIpUsage\");\n  if (!mxSmlGetDeviceIpUsage)\n    goto init_error_clean_exit;\n\n  mxSmlGetMemoryInfo = dlsym(libmxsml_handle, \"mxSmlGetMemoryInfo\");\n  if (!mxSmlGetMemoryInfo)\n    goto init_error_clean_exit;\n\n  mxSmlGetPcieThroughput = dlsym(libmxsml_handle, \"mxSmlGetPcieThroughput\");\n  if (!mxSmlGetPcieThroughput)\n    goto init_error_clean_exit;\n\n  // for compatibility\n  mxSmlGetFanSpeedInfo = dlsym(libmxsml_handle, \"mxSmlGetFanSpeedInfo\");\n\n  mxSmlGetBoardPowerInfo = dlsym(libmxsml_handle, \"mxSmlGetBoardPowerInfo\");\n  if (!mxSmlGetBoardPowerInfo)\n    goto init_error_clean_exit;\n\n  // for compatibility\n  mxSmlGetBoardPowerLimit = dlsym(libmxsml_handle, \"mxSmlGetBoardPowerLimit\");\n\n  mxSmlGetNumberOfProcess = dlsym(libmxsml_handle, \"mxSmlGetNumberOfProcess\");\n  if (!mxSmlGetNumberOfProcess)\n    goto init_error_clean_exit;\n\n  mxSmlGetSingleGpuProcess = dlsym(libmxsml_handle, \"mxSmlGetSingleGpuProcess\");\n  if (!mxSmlGetSingleGpuProcess)\n    goto init_error_clean_exit;\n\n  last_mxsml_return_status = mxSmlInit();\n  if (last_mxsml_return_status != MXSML_SUCCESS)\n    return false;\n\n  local_error_string = NULL;\n  return true;\n\ninit_error_clean_exit:\n  dlclose(libmxsml_handle);\n  libmxsml_handle = NULL;\n  return false;\n}\n\nstatic void gpuinfo_metax_shutdown(void) {\n  if (libmxsml_handle) {\n    dlclose(libmxsml_handle);\n    libmxsml_handle = NULL;\n    local_error_string = didnt_call_gpuinfo_init;\n  }\n\n  struct gpu_info_metax *allocated, *tmp;\n\n  list_for_each_entry_safe(allocated, tmp, &allocations, allocate_list) {\n    list_del(&allocated->allocate_list);\n    free(allocated);\n  }\n}\n\nstatic const char *gpuinfo_metax_last_error_string(void) {\n  if (local_error_string) {\n    return local_error_string;\n  } else if (libmxsml_handle && mxSmlGetErrorString) {\n    return mxSmlGetErrorString(last_mxsml_return_status);\n  } else {\n    return \"An unanticipated error occurred while accessing METAX GPU \"\n           \"information\\n\";\n  }\n}\n\nstatic bool gpuinfo_metax_get_device_handles(struct list_head *devices, unsigned int *count) {\n  if (!libmxsml_handle)\n    return false;\n\n  unsigned int num_devices = mxSmlGetDeviceCount();\n  struct gpu_info_metax *gpu_infos = calloc(num_devices, sizeof(*gpu_infos));\n  if (!gpu_infos) {\n    local_error_string = strerror(errno);\n    return false;\n  }\n\n  list_add(&gpu_infos[0].allocate_list, &allocations);\n\n  *count = 0;\n  for (unsigned int i = 0; i < num_devices; ++i) {\n    mxSmlDeviceInfo_t deviceInfo;\n    mxSmlReturn_t deviceInfoRet = mxSmlGetDeviceInfo(i, &deviceInfo);\n    if (deviceInfoRet != MXSML_SUCCESS) {\n      deviceInfoRet = mxSmlGetLimitedDeviceInfo(i, &deviceInfo);\n      // Limited device\n      if (deviceInfoRet == MXSML_SUCCESS) {\n        gpu_infos[*count].device = deviceInfo;\n        gpu_infos[*count].base.vendor = &gpu_vendor_metax;\n        strncpy(gpu_infos[*count].base.pdev, deviceInfo.bdfId, PDEV_LEN);\n        list_add_tail(&gpu_infos[*count].base.list, devices);\n        *count += 1;\n      }\n    } else {\n      gpu_infos[*count].device = deviceInfo;\n      gpu_infos[*count].base.vendor = &gpu_vendor_metax;\n      strncpy(gpu_infos[*count].base.pdev, deviceInfo.bdfId, PDEV_LEN);\n      list_add_tail(&gpu_infos[*count].base.list, devices);\n      *count += 1;\n    }\n  }\n\n  return true;\n}\n\nstatic void gpuinfo_metax_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_metax *gpu_info = container_of(_gpu_info, struct gpu_info_metax, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  unsigned int deviceId = gpu_info->device.deviceId;\n\n  static_info->integrated_graphics = false;\n  static_info->encode_decode_shared = false;\n  RESET_ALL(static_info->valid);\n\n  strncpy(static_info->device_name, gpu_info->device.deviceName, MAX_DEVICE_NAME);\n  SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n\n  mxSmlPcieInfo_t maxPcieInfo;\n  last_mxsml_return_status = mxSmlGetPcieMaxLinkInfo(deviceId, &maxPcieInfo);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    static_info->max_pcie_gen = (unsigned)maxPcieInfo.speed;\n    static_info->max_pcie_link_width = maxPcieInfo.width;\n    SET_VALID(gpuinfo_max_pcie_gen_valid, static_info->valid);\n    SET_VALID(gpuinfo_max_pcie_link_width_valid, static_info->valid);\n  }\n\n  int shutdown_threshold;\n  last_mxsml_return_status = mxSmlGetTemperatureInfo(deviceId, MXSML_Temperature_HotLimit, &shutdown_threshold);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    static_info->temperature_slowdown_threshold = 9500;\n    static_info->temperature_shutdown_threshold = shutdown_threshold < 0 ? 0u : (unsigned)shutdown_threshold;\n    SET_VALID(gpuinfo_temperature_shutdown_threshold_valid, static_info->valid);\n    SET_VALID(gpuinfo_temperature_slowdown_threshold_valid, static_info->valid);\n  }\n}\n\nstatic void gpuinfo_metax_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_metax *gpu_info = container_of(_gpu_info, struct gpu_info_metax, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  unsigned int deviceId = gpu_info->device.deviceId;\n\n  RESET_ALL(dynamic_info->valid);\n\n  // GPU current speed\n  unsigned int clockSize = 2;\n  unsigned int gpuClockFreqs[clockSize];\n  mxSmlClockIp_t clockFrom = MXSML_Clock_Xcore;\n  if (gpu_info->device.brand == MXSML_Brand_N)\n    clockFrom = MXSML_Clock_Dla;\n\n  last_mxsml_return_status = mxSmlGetClocks(deviceId, clockFrom, &clockSize, gpuClockFreqs);\n  if (last_mxsml_return_status == MXSML_SUCCESS)\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, gpuClockFreqs[0]);\n\n  // GPU max speed\n  clockSize = 12;\n  unsigned int dpmGpuClockInfo[clockSize];\n  mxSmlDpmIp_t dpmFrom = MXSML_Dpm_Xcore;\n  if (gpu_info->device.brand == MXSML_Brand_N)\n    dpmFrom = MXSML_Dpm_Dla;\n\n  last_mxsml_return_status = mxSmlGetDpmIpClockInfo(deviceId, dpmFrom, dpmGpuClockInfo, &clockSize);\n  if (last_mxsml_return_status == MXSML_SUCCESS)\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed_max, dpmGpuClockInfo[clockSize-1]);\n\n  // Memory current speed\n  clockSize = 3;\n  unsigned int memClockFreqs[clockSize];\n  clockFrom = MXSML_Clock_Mc0;\n  if (gpu_info->device.brand == MXSML_Brand_N)\n    clockFrom = MXSML_Clock_Mc;\n\n  last_mxsml_return_status = mxSmlGetClocks(deviceId, clockFrom, &clockSize, memClockFreqs);\n  if(last_mxsml_return_status == MXSML_SUCCESS)\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_clock_speed, memClockFreqs[0]);\n\n  // Memory max speed\n  clockSize = 12;\n  unsigned int dpmMemClockInfo[clockSize];\n  last_mxsml_return_status = mxSmlGetDpmIpClockInfo(deviceId, MXSML_Dpm_Mc, dpmMemClockInfo, &clockSize);\n  if (last_mxsml_return_status == MXSML_SUCCESS)\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_clock_speed_max, dpmMemClockInfo[clockSize-1]);\n\n  // GPU utilization rates\n  mxSmlUsageIp_t usageIp = MXSML_Usage_Xcore;\n  if (gpu_info->device.brand == MXSML_Brand_N)\n    usageIp = MXSML_Usage_Dla;\n\n  int gpu_util_rate;\n  last_mxsml_return_status = mxSmlGetDeviceIpUsage(deviceId, usageIp, &gpu_util_rate);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    dynamic_info->gpu_util_rate = gpu_util_rate < 0 ? 0u : (unsigned)gpu_util_rate;\n    SET_VALID(gpuinfo_gpu_util_rate_valid, dynamic_info->valid);\n  }\n\n  // Encoder utilization rate\n  usageIp = MXSML_Usage_Vpue;\n  int encoder_rate;\n  last_mxsml_return_status = mxSmlGetDeviceIpUsage(deviceId, usageIp, &encoder_rate);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    dynamic_info->encoder_rate = encoder_rate < 0 ? 0u : (unsigned)encoder_rate;\n    SET_VALID(gpuinfo_encoder_rate_valid, dynamic_info->valid);\n  }\n\n  // Decoder utilization rate\n  usageIp = MXSML_Usage_Vpud;\n  int decoder_rate;\n  last_mxsml_return_status = mxSmlGetDeviceIpUsage(deviceId, usageIp, &decoder_rate);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    dynamic_info->decoder_rate = decoder_rate < 0 ? 0u : (unsigned)decoder_rate;\n    SET_VALID(gpuinfo_decoder_rate_valid, dynamic_info->valid);\n  }\n\n  // Device memory vis_vram info (total,used,free)\n  mxSmlMemoryInfo_t memory_info;\n  last_mxsml_return_status = mxSmlGetMemoryInfo(deviceId, &memory_info);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, memory_info.visVramTotal * 1024);\n    SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, memory_info.visVramUse * 1024);\n    SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, (memory_info.visVramTotal - memory_info.visVramUse) * 1024);\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, memory_info.visVramUse * 100 / memory_info.visVramTotal);\n  }\n\n  // PCIe generation and width used by the device\n  mxSmlPcieInfo_t pcieInfo;\n  last_mxsml_return_status = mxSmlGetPcieInfo(deviceId, &pcieInfo);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    dynamic_info->pcie_link_width = pcieInfo.width;\n    SET_VALID(gpuinfo_pcie_link_width_valid, dynamic_info->valid);\n\n    float pcieRates[] = {2.5, 5, 8, 16, 32};\n    // It's the expected interface so float equality should be fine\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wfloat-equal\"\n#endif\n    for (unsigned int i = 0; i < 5; i++) {\n      if (pcieRates[i] == pcieInfo.speed) {\n        dynamic_info->pcie_link_gen = i + 1;\n        SET_VALID(gpuinfo_pcie_link_gen_valid, dynamic_info->valid);\n      }\n    }\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\n  }\n\n  // PCIe reception and transmission throughput\n  mxSmlPcieThroughput_t pcieThroughput;\n  last_mxsml_return_status = mxSmlGetPcieThroughput(deviceId, &pcieThroughput);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    dynamic_info->pcie_rx = pcieThroughput.rx * 1000;\n    dynamic_info->pcie_tx = pcieThroughput.tx * 1000;\n    SET_VALID(gpuinfo_pcie_rx_valid, dynamic_info->valid);\n    SET_VALID(gpuinfo_pcie_tx_valid, dynamic_info->valid);\n  }\n\n  // Fan speed\n  if (mxSmlGetFanSpeedInfo) {\n    unsigned int fanRpm;\n    last_mxsml_return_status = mxSmlGetFanSpeedInfo(deviceId, &fanRpm, &dynamic_info->fan_speed);\n    if (last_mxsml_return_status == MXSML_SUCCESS)\n      SET_VALID(gpuinfo_fan_speed_valid, dynamic_info->valid);\n  }\n\n  // GPU temperature\n  int gpuTemp;\n  last_mxsml_return_status = mxSmlGetTemperatureInfo(deviceId, MXSML_Temperature_Hotspot, &gpuTemp);\n  if (last_mxsml_return_status == MXSML_SUCCESS)\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_temp, gpuTemp / 100);\n\n  // Device power usage\n  unsigned int infoSize = 3;\n  mxSmlBoardWayElectricInfo_t boardPower[infoSize];\n  last_mxsml_return_status = mxSmlGetBoardPowerInfo(deviceId, &infoSize, boardPower);\n  if (last_mxsml_return_status == MXSML_SUCCESS) {\n    dynamic_info->power_draw = 0;\n    for (unsigned int i = 0; i < infoSize; ++i)\n      dynamic_info->power_draw += boardPower[i].power;\n    SET_VALID(gpuinfo_power_draw_valid, dynamic_info->valid);\n  }\n\n  // Maximum enforced power usage\n  if (mxSmlGetBoardPowerLimit) {\n    last_mxsml_return_status = mxSmlGetBoardPowerLimit(deviceId, &dynamic_info->power_draw_max);\n    if (last_mxsml_return_status == MXSML_SUCCESS)\n      SET_VALID(gpuinfo_power_draw_max_valid, dynamic_info->valid);\n  } else {\n    if (gpu_info->device.brand == MXSML_Brand_N)\n      SET_GPUINFO_DYNAMIC(dynamic_info, power_draw_max, (unsigned int)70000);\n    else if (gpu_info->device.brand == MXSML_Brand_C)\n      SET_GPUINFO_DYNAMIC(dynamic_info, power_draw_max, (unsigned int)350000);\n  }\n}\n\nstatic void gpuinfo_metax_get_running_processes(struct gpu_info *_gpu_info) {\n  struct gpu_info_metax *gpu_info = container_of(_gpu_info, struct gpu_info_metax, base);\n  unsigned int deviceId = gpu_info->device.deviceId;\n\n  _gpu_info->processes_count = 0;\n  unsigned int processNum = 0;\n  last_mxsml_return_status = mxSmlGetNumberOfProcess(&processNum);\n  if (last_mxsml_return_status != MXSML_SUCCESS) {\n    perror(\"Could not get processes number: \");\n    exit(EXIT_FAILURE);\n  }\n\n  mxSmlProcessInfo_t processInfo[processNum];\n  last_mxsml_return_status = mxSmlGetSingleGpuProcess(deviceId, &processNum, processInfo);\n  if (last_mxsml_return_status != MXSML_SUCCESS) {\n    perror(\"Could not get process info: \");\n    exit(EXIT_FAILURE);\n  }\n\n  _gpu_info->processes_count = processNum;\n  if (_gpu_info->processes_count > 0) {\n    if (_gpu_info->processes_count > _gpu_info->processes_array_size) {\n      _gpu_info->processes_array_size = _gpu_info->processes_count + COMMON_PROCESS_LINEAR_REALLOC_INC;\n      _gpu_info->processes =\n        reallocarray(_gpu_info->processes, _gpu_info->processes_array_size, sizeof(*_gpu_info->processes));\n      if (!_gpu_info->processes) {\n        perror(\"Could not get processes info: \");\n        exit(EXIT_FAILURE);\n      }\n    }\n    memset(_gpu_info->processes, 0, _gpu_info->processes_count * sizeof(*_gpu_info->processes));\n    for (unsigned int i = 0; i < processNum; ++i) {\n      _gpu_info->processes[i].type = gpu_process_compute;\n      _gpu_info->processes[i].pid = processInfo[i].processId;\n      _gpu_info->processes[i].gpu_memory_usage = 0;\n      for (unsigned int j = 0; j < processInfo[i].gpuNumber; ++j)\n        _gpu_info->processes[i].gpu_memory_usage += processInfo[i].processGpuInfo[j].gpuMemoryUsage;\n      SET_VALID(gpuinfo_process_gpu_memory_usage_valid, _gpu_info->processes[i].valid);\n    }\n  }\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_msm.c",
    "content": "/*\n *\n * Copyright (C) 2023 Ryan Houdek <Sonicadvance1@gmail.com>\n *\n * This file is part of Nvtop and adapted from the amdgpu implementation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include <assert.h>\n#include <dlfcn.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <libdrm/msm_drm.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/sysinfo.h>\n#include <unistd.h>\n#include <uthash.h>\n#include <xf86drm.h>\n\n// extern\nconst char * msm_parse_marketing_name(uint64_t gpu_id);\n\n#define HASH_FIND_CLIENT(head, key_ptr, out_ptr) HASH_FIND(hh, head, key_ptr, sizeof(unsigned), out_ptr)\n#define HASH_ADD_CLIENT(head, in_ptr) HASH_ADD(hh, head, client_id, sizeof(unsigned), in_ptr)\n\n#define SET_MSM_CACHE(cachePtr, field, value) SET_VALUE(cachePtr, field, value, msm_cache_)\n#define RESET_MSM_CACHE(cachePtr, field) INVALIDATE_VALUE(cachePtr, field, msm_cache_)\n#define MSM_CACHE_FIELD_VALID(cachePtr, field) VALUE_IS_VALID(cachePtr, field, msm_cache_)\n\nenum intel_process_info_cache_valid {\n  msm_cache_engine_render_valid = 0,\n  msm_cache_process_info_cache_valid_count\n};\n\nstruct __attribute__((__packed__)) unique_cache_id {\n  unsigned client_id;\n  pid_t pid;\n};\n\nstruct msm_process_info_cache {\n  struct unique_cache_id client_id;\n  uint64_t engine_render;\n  nvtop_time last_measurement_tstamp;\n  unsigned char valid[(msm_cache_process_info_cache_valid_count + CHAR_BIT - 1) / CHAR_BIT];\n  UT_hash_handle hh;\n};\n\nstruct gpu_info_msm {\n  drmVersionPtr drmVersion;\n  struct gpu_info base;\n  int fd;\n\n  struct msm_process_info_cache *last_update_process_cache, *current_update_process_cache; // Cached processes info\n};\n\nstatic bool gpuinfo_msm_init(void);\nstatic void gpuinfo_msm_shutdown(void);\nstatic const char *gpuinfo_msm_last_error_string(void);\nstatic bool gpuinfo_msm_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_msm_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_msm_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_msm_get_running_processes(struct gpu_info *_gpu_info);\n\nstruct gpu_vendor gpu_vendor_msm = {\n    .init = gpuinfo_msm_init,\n    .shutdown = gpuinfo_msm_shutdown,\n    .last_error_string = gpuinfo_msm_last_error_string,\n    .get_device_handles = gpuinfo_msm_get_device_handles,\n    .populate_static_info = gpuinfo_msm_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_msm_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_msm_get_running_processes,\n    .name = \"msm\",\n};\n\nunsigned msm_gpu_count;\nstatic struct gpu_info_msm *gpu_infos;\n\nstatic void *libdrm_handle;\nstatic FILE* meminfo_file = NULL;\n\nstatic int last_libdrm_return_status = 0;\nstatic char didnt_call_gpuinfo_init[] = \"uninitialized\";\nstatic const char *local_error_string = didnt_call_gpuinfo_init;\n\n// Local function pointers to DRM interface\nstatic typeof(drmGetDevices) *_drmGetDevices;\nstatic typeof(drmGetDevices2) *_drmGetDevices2;\nstatic typeof(drmFreeDevices) *_drmFreeDevices;\nstatic typeof(drmGetVersion) *_drmGetVersion;\nstatic typeof(drmFreeVersion) *_drmFreeVersion;\nstatic typeof(drmGetMagic) *_drmGetMagic;\nstatic typeof(drmAuthMagic) *_drmAuthMagic;\nstatic typeof(drmDropMaster) *_drmDropMaster;\nstatic typeof(drmCommandWriteRead) *_drmCommandWriteRead;\n\nstatic int wrap_drmGetDevices(drmDevicePtr devices[], int max_devices) {\n  assert(_drmGetDevices2 || _drmGetDevices);\n\n  if (_drmGetDevices2)\n    return _drmGetDevices2(0, devices, max_devices);\n  return _drmGetDevices(devices, max_devices);\n}\n\nstatic void authenticate_drm(int fd) {\n  drm_magic_t magic;\n\n  if (_drmGetMagic(fd, &magic) < 0) {\n    return;\n  }\n\n  if (_drmAuthMagic(fd, magic) == 0) {\n    if (_drmDropMaster(fd)) {\n      perror(\"Failed to drop DRM master\");\n      fprintf(\n          stderr,\n          \"\\nWARNING: other DRM clients will crash on VT switch while nvtop is running!\\npress ENTER to continue\\n\");\n      fgetc(stdin);\n    }\n    return;\n  }\n\n  // XXX: Ideally I'd implement this too, but I'd need to pull in libxcb and yet\n  // more functions and structs that may break ABI compatibility.\n  // See radeontop auth_xcb.c for what is involved here\n  fprintf(stderr, \"Failed to authenticate to DRM; XCB authentication unimplemented\\n\");\n}\n\n#define STRINGIFY(x) STRINGIFY_HELPER_(x)\n#define STRINGIFY_HELPER_(x) #x\n\n__attribute__((constructor)) static void init_extract_gpuinfo_msm(void) { register_gpu_vendor(&gpu_vendor_msm); }\n\nbool gpuinfo_msm_init(void) {\n  libdrm_handle = dlopen(\"libdrm.so\", RTLD_LAZY);\n  if (!libdrm_handle)\n    libdrm_handle = dlopen(\"libdrm.so.2\", RTLD_LAZY);\n  if (!libdrm_handle)\n    libdrm_handle = dlopen(\"libdrm.so.1\", RTLD_LAZY);\n  if (!libdrm_handle) {\n    local_error_string = dlerror();\n    return false;\n  }\n\n  _drmGetDevices2 = dlsym(libdrm_handle, \"drmGetDevices2\");\n  if (!_drmGetDevices2)\n    _drmGetDevices = dlsym(libdrm_handle, \"drmGetDevices\");\n  if (!_drmGetDevices2 && !_drmGetDevices)\n    goto init_error_clean_exit;\n\n  _drmFreeDevices = dlsym(libdrm_handle, \"drmFreeDevices\");\n  if (!_drmFreeDevices)\n    goto init_error_clean_exit;\n\n  _drmGetVersion = dlsym(libdrm_handle, \"drmGetVersion\");\n  if (!_drmGetVersion)\n    goto init_error_clean_exit;\n\n  _drmFreeVersion = dlsym(libdrm_handle, \"drmFreeVersion\");\n  if (!_drmFreeVersion)\n    goto init_error_clean_exit;\n\n  _drmGetMagic = dlsym(libdrm_handle, \"drmGetMagic\");\n  if (!_drmGetMagic)\n    goto init_error_clean_exit;\n\n  _drmAuthMagic = dlsym(libdrm_handle, \"drmAuthMagic\");\n  if (!_drmAuthMagic)\n    goto init_error_clean_exit;\n\n  _drmDropMaster = dlsym(libdrm_handle, \"drmDropMaster\");\n  if (!_drmDropMaster)\n    goto init_error_clean_exit;\n\n  _drmCommandWriteRead = dlsym(libdrm_handle, \"drmCommandWriteRead\");\n  if (!_drmCommandWriteRead)\n    goto init_error_clean_exit;\n\n  local_error_string = NULL;\n\n  meminfo_file = fopen(\"/proc/meminfo\", \"r\");\n  return true;\n\ninit_error_clean_exit:\n  dlclose(libdrm_handle);\n  libdrm_handle = NULL;\n  return false;\n}\n\nvoid gpuinfo_msm_shutdown(void) {\n  for (unsigned i = 0; i < msm_gpu_count; ++i) {\n    struct gpu_info_msm *current = &gpu_infos[i];\n    _drmFreeVersion(current->drmVersion);\n  }\n\n  free(gpu_infos);\n  gpu_infos = NULL;\n  msm_gpu_count = 0;\n\n  if (libdrm_handle) {\n    dlclose(libdrm_handle);\n    libdrm_handle = NULL;\n    local_error_string = didnt_call_gpuinfo_init;\n  }\n\n  if (meminfo_file) {\n    fclose(meminfo_file);\n    meminfo_file = NULL;\n  }\n}\n\nstatic const char *gpuinfo_msm_last_error_string(void) {\n  if (local_error_string) {\n    return local_error_string;\n  } else if (last_libdrm_return_status < 0) {\n    switch (last_libdrm_return_status) {\n    case DRM_ERR_NO_DEVICE:\n      return \"no device\\n\";\n    case DRM_ERR_NO_ACCESS:\n      return \"no access\\n\";\n    case DRM_ERR_NOT_ROOT:\n      return \"not root\\n\";\n    case DRM_ERR_INVALID:\n      return \"invalid args\\n\";\n    case DRM_ERR_NO_FD:\n      return \"no fd\\n\";\n    default:\n      return \"unknown error\\n\";\n    }\n  } else {\n    return \"An unanticipated error occurred while accessing AMDGPU \"\n           \"information\\n\";\n  }\n}\n\nstatic uint64_t parse_memory_multiplier(const char *str) {\n  if (strcmp(str, \" B\") == 0) {\n    return 1;\n  }\n  else if (strcmp(str, \" KiB\") == 0 || strcmp(str, \" kB\") == 0) {\n    return 1024;\n  }\n  else if (strcmp(str, \" MiB\") == 0) {\n    return 1024 * 1024;\n  }\n  else if (strcmp(str, \" GiB\") == 0) {\n    return 1024 * 1024 * 1024;\n  }\n\n  return 1;\n}\n\nstatic const char drm_msm_engine_gpu[] = \"drm-engine-gpu\";\nstatic const char drm_msm_cycles_gpu[] = \"drm-cycles-gpu\";\nstatic const char drm_msm_maxfreq_gpu[] = \"drm-maxfreq-gpu\";\nstatic const char drm_msm_resident_mem[] = \"drm-resident-memory\";\n\nstatic bool parse_drm_fdinfo_msm(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n  struct gpu_info_msm *gpu_info = container_of(info, struct gpu_info_msm, base);\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  ssize_t count = 0;\n\n  bool client_id_set = false;\n  unsigned cid;\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n\n  while ((count = getline(&line, &line_buf_size, fdinfo_file)) != -1) {\n    char *key, *val;\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    if (!strcmp(key, drm_client_id)) {\n      char *endptr;\n      cid = strtoul(val, &endptr, 10);\n      if (*endptr)\n        continue;\n      client_id_set = true;\n    } else {\n      bool is_engine = !strcmp(key, drm_msm_engine_gpu);\n      bool is_cycles = !strcmp(key, drm_msm_cycles_gpu);\n      bool is_maxfreq = !strcmp(key, drm_msm_maxfreq_gpu);\n      bool is_resident = !strcmp(key, drm_msm_resident_mem);\n\n      if (is_engine || is_cycles || is_maxfreq) {\n        char *endptr;\n        uint64_t time_spent = strtoull(val, &endptr, 10);\n        if (endptr == val || strcmp(endptr, \" ns\"))\n          continue;\n        if (is_engine) {\n          SET_GPUINFO_PROCESS(process_info, gfx_engine_used, time_spent);\n        }\n      }\n      else if (is_resident) {\n        uint64_t mem_int;\n        char *endptr;\n\n        mem_int = strtoull(val, &endptr, 10);\n        if (endptr == val)\n          continue;\n\n        uint64_t multiplier = parse_memory_multiplier(endptr);\n        SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, mem_int * multiplier);\n      }\n    }\n  }\n  if (!client_id_set)\n    return false;\n\n  // The msm driver does not expose compute engine metrics as of yet\n  process_info->type |= gpu_process_graphical;\n\n  struct msm_process_info_cache *cache_entry;\n  struct unique_cache_id ucid = {.client_id = cid, .pid = process_info->pid};\n  HASH_FIND_CLIENT(gpu_info->last_update_process_cache, &ucid, cache_entry);\n  if (cache_entry) {\n    uint64_t time_elapsed = nvtop_difftime_u64(cache_entry->last_measurement_tstamp, current_time);\n    HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used) &&\n        MSM_CACHE_FIELD_VALID(cache_entry, engine_render) &&\n        // In some rare occasions, the gfx engine usage reported by the driver is lowering (might be a driver bug)\n        process_info->gfx_engine_used >= cache_entry->engine_render &&\n        process_info->gfx_engine_used - cache_entry->engine_render <= time_elapsed) {\n      SET_GPUINFO_PROCESS(\n          process_info, gpu_usage,\n          busy_usage_from_time_usage_round(process_info->gfx_engine_used, cache_entry->engine_render, time_elapsed));\n    }\n  } else {\n    cache_entry = calloc(1, sizeof(*cache_entry));\n    if (!cache_entry)\n      goto parse_fdinfo_exit;\n    cache_entry->client_id.client_id = cid;\n    cache_entry->client_id.pid = process_info->pid;\n  }\n\n  // Check if we already processed this client_id in the current update cycle.\n  // This can happen when a process has multiple file descriptors referencing\n  // the same DRM client (e.g., via DRM master operations).\n  struct msm_process_info_cache *cache_entry_check;\n  HASH_FIND_CLIENT(gpu_info->current_update_process_cache, &cache_entry->client_id, cache_entry_check);\n  if (cache_entry_check) {\n    // Already processed this client_id, free the entry if we allocated it\n    if (cache_entry != cache_entry_check)\n      free(cache_entry);\n    goto parse_fdinfo_exit;\n  }\n\n  RESET_ALL(cache_entry->valid);\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used))\n    SET_MSM_CACHE(cache_entry, engine_render, process_info->gfx_engine_used);\n\n  cache_entry->last_measurement_tstamp = current_time;\n  HASH_ADD_CLIENT(gpu_info->current_update_process_cache, cache_entry);\n\nparse_fdinfo_exit:\n  return true;\n}\n\nstatic bool gpuinfo_msm_get_device_handles(struct list_head *devices, unsigned *count) {\n  if (!libdrm_handle)\n    return false;\n\n  last_libdrm_return_status = wrap_drmGetDevices(NULL, 0);\n  if (last_libdrm_return_status <= 0)\n    return false;\n\n  drmDevicePtr devs[last_libdrm_return_status];\n  last_libdrm_return_status = wrap_drmGetDevices(devs, last_libdrm_return_status);\n  if (last_libdrm_return_status <= 0)\n    return false;\n\n  unsigned int libdrm_count = last_libdrm_return_status;\n  gpu_infos = calloc(libdrm_count, sizeof(*gpu_infos));\n  if (!gpu_infos) {\n    local_error_string = strerror(errno);\n    return false;\n  }\n\n  for (unsigned int i = 0; i < libdrm_count; i++) {\n    int fd = -1;\n\n    // Try render node first\n    if (1 << DRM_NODE_RENDER & devs[i]->available_nodes) {\n      fd = open(devs[i]->nodes[DRM_NODE_RENDER], O_RDWR);\n    }\n    if (fd < 0) {\n      // Fallback to primary node (control nodes are unused according to the DRM documentation)\n      if (1 << DRM_NODE_PRIMARY & devs[i]->available_nodes) {\n        fd = open(devs[i]->nodes[DRM_NODE_PRIMARY], O_RDWR);\n      }\n    }\n\n    if (fd < 0)\n      continue;\n\n    drmVersionPtr ver = _drmGetVersion(fd);\n\n    if (!ver) {\n      close(fd);\n      continue;\n    }\n\n    bool is_msm = !strcmp(ver->name, \"msm\");\n\n    if (!is_msm) {\n      _drmFreeVersion(ver);\n      close(fd);\n      continue;\n    }\n\n    authenticate_drm(fd);\n\n    gpu_infos[msm_gpu_count].drmVersion = ver;\n    gpu_infos[msm_gpu_count].fd = fd;\n    gpu_infos[msm_gpu_count].base.vendor = &gpu_vendor_msm;\n\n    list_add_tail(&gpu_infos[msm_gpu_count].base.list, devices);\n    // Register a fdinfo callback for this GPU\n    processinfo_register_fdinfo_callback(parse_drm_fdinfo_msm, &gpu_infos[msm_gpu_count].base);\n    msm_gpu_count++;\n  }\n\n  _drmFreeDevices(devs, libdrm_count);\n  *count = msm_gpu_count;\n\n  return true;\n}\n\nstatic int gpuinfo_msm_query_param(int gpu, uint32_t param, uint64_t *value) {\n  struct drm_msm_param req = {\n    .pipe = MSM_PIPE_3D0, // Only the 3D pipe.\n    .param = param,\n  };\n\n  int ret = _drmCommandWriteRead(gpu, DRM_MSM_GET_PARAM, &req, sizeof(req));\n\n  if (ret)\n    return ret;\n\n  *value = req.value;\n\n  return 0;\n}\n\nvoid gpuinfo_msm_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_msm *gpu_info = container_of(_gpu_info, struct gpu_info_msm, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n\n  static_info->integrated_graphics = true;\n  static_info->encode_decode_shared = true;\n  RESET_ALL(static_info->valid);\n\n  uint64_t gpuid;\n  if (gpuinfo_msm_query_param(gpu_info->fd, MSM_PARAM_CHIP_ID, &gpuid) == 0) {\n    const char* name = msm_parse_marketing_name(gpuid);\n    if (!name) {\n      // Try again ignoring speed-bin in the upper bits.\n      name = msm_parse_marketing_name(gpuid & 0x0000ffffffff);\n    }\n\n    if (name) {\n      strncpy(static_info->device_name, name, sizeof(static_info->device_name));\n    }\n    else {\n      snprintf(static_info->device_name, sizeof(static_info->device_name), \"Unknown Adreno %lx\", gpuid);\n    }\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n  }\n}\n\n\nstatic const char meminfo_total[] = \"MemTotal\";\nstatic const char meminfo_available[] = \"MemAvailable\";\n\nvoid gpuinfo_msm_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_msm *gpu_info = container_of(_gpu_info, struct gpu_info_msm, base);\n  // struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  RESET_ALL(dynamic_info->valid);\n\n  // GPU clock\n  uint64_t clock_val;\n  if (gpuinfo_msm_query_param(gpu_info->fd, MSM_PARAM_MAX_FREQ, &clock_val) == 0) {\n    // TODO: No way to query current clock speed.\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, clock_val / 1000000);\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed_max, clock_val / 1000000);\n  }\n\n  // Mem clock\n  // TODO: No way to query.\n\n  // TODO: find how to extract global utilization\n  // gpu util will be computed as the sum of all the processes utilization for now\n\n  rewind(meminfo_file);\n  fflush(meminfo_file);\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  ssize_t count = 0;\n  uint64_t mem_total = 0;\n  uint64_t mem_available = 0;\n  size_t keys_acquired = 0;\n  while (keys_acquired != 2 && (count = getline(&line, &line_buf_size, meminfo_file)) != -1) {\n    char *key, *val;\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    bool is_total = !strcmp(key, meminfo_total);\n    bool is_available = !strcmp(key, meminfo_available);\n\n    if (is_total || is_available) {\n      uint64_t mem_int;\n      char *endptr;\n\n      mem_int = strtoull(val, &endptr, 10);\n      if (endptr == val)\n        continue;\n\n      mem_int *= parse_memory_multiplier(endptr);\n      if (is_total) {\n        mem_total = mem_int;\n      }\n      else if (is_available) {\n        mem_available = mem_int;\n      }\n      ++keys_acquired;\n    }\n  }\n\n  SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, mem_total);\n  SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, mem_total - mem_available);\n  SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, mem_available);\n  SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate,\n                      (dynamic_info->total_memory - dynamic_info->free_memory) * 100 / dynamic_info->total_memory);\n}\n\nstatic void swap_process_cache_for_next_update(struct gpu_info_msm *gpu_info) {\n  // Free old cache data and set the cache for the next update\n  if (gpu_info->last_update_process_cache) {\n    struct msm_process_info_cache *cache_entry, *tmp;\n    HASH_ITER(hh, gpu_info->last_update_process_cache, cache_entry, tmp) {\n      HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n      free(cache_entry);\n    }\n  }\n  gpu_info->last_update_process_cache = gpu_info->current_update_process_cache;\n  gpu_info->current_update_process_cache = NULL;\n}\n\nvoid gpuinfo_msm_get_running_processes(struct gpu_info *_gpu_info) {\n  // For Adreno, we register a fdinfo callback that will fill the gpu_process datastructure of the gpu_info structure\n  // for us. This avoids going through /proc multiple times per update for multiple GPUs.\n  struct gpu_info_msm *gpu_info = container_of(_gpu_info, struct gpu_info_msm, base);\n  swap_process_cache_for_next_update(gpu_info);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_msm_utils.c",
    "content": "/*\n *\n * Copyright (C) 2023 Ryan Houdek <Sonicadvance1@gmail.com>\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/interface_internal_common.h\"\n#include <stdint.h>\n\nstruct msm_id_struct {\n  uint64_t id;\n  const char *name;\n};\n\n#define GetHundredDigit(coreid) (coreid / 100)\n#define GetHundred(coreid) (GetHundredDigit(coreid) * 100)\n#define GetTenDigit(coreid) ((coreid - GetHundred(coreid)) / 10)\n#define GetTen(coreid) (GetTenDigit(coreid) * 10)\n#define GetOneDigit(coreid) (coreid - (GetHundred(coreid) + GetTen(coreid)))\n\n#define CHIPID(coreid) \\\n  (GetHundredDigit(coreid) << 24) | \\\n  (GetTenDigit(coreid) << 16) | \\\n  (GetOneDigit(coreid) << 8)\n\nstatic const struct msm_id_struct msm_ids[] = {\n  // Adreno 2xx\n  {CHIPID(200),   \"Adreno 200\"},\n  {CHIPID(201),   \"Adreno 201\"},\n  {CHIPID(205),   \"Adreno 205\"},\n  {CHIPID(220),   \"Adreno 220\"},\n\n  // Adreno 3xx\n  {CHIPID(305),   \"Adreno 305\"},\n  {CHIPID(307),   \"Adreno 307\"},\n  {CHIPID(320),   \"Adreno 320\"},\n  {CHIPID(330),   \"Adreno 330\"},\n\n  // Adreno 4xx\n  {CHIPID(405),   \"Adreno 405\"},\n  {CHIPID(420),   \"Adreno 420\"},\n  {CHIPID(430),   \"Adreno 430\"},\n\n  // Adreno 5xx\n  {CHIPID(508),   \"Adreno 508\"},\n  {CHIPID(509),   \"Adreno 509\"},\n  {CHIPID(510),   \"Adreno 510\"},\n  {CHIPID(512),   \"Adreno 512\"},\n  {CHIPID(530),   \"Adreno 530\"},\n  {CHIPID(540),   \"Adreno 540\"},\n\n  // Adreno 6xx\n  {CHIPID(615),    \"Adreno 615\"},\n  {CHIPID(616),    \"Adreno 616\"},\n  {CHIPID(618),    \"Adreno 618\"},\n  {CHIPID(619),    \"Adreno 619\"},\n  {CHIPID(620),    \"Adreno 620\"},\n  {CHIPID(630),    \"Adreno 630\"},\n  {CHIPID(640),    \"Adreno 640\"},\n  // QCM6490\n  {0x00ac06030500, \"Adreno 643\"},\n  {CHIPID(650),    \"Adreno 650\"},\n  {CHIPID(660),    \"Adreno 660\"},\n  {CHIPID(680),    \"Adreno 680\"},\n  {CHIPID(690),    \"Adreno 690\"},\n  // no-speedbin Adreno 690\n  {0xffff06090000, \"Adreno 690\"},\n\n  // Adreno 7xx\n  {CHIPID(730),   \"Adreno 730\"},\n  {CHIPID(740),   \"Adreno 740\"},\n  {CHIPID(750),   \"Adreno 750\"},\n  {CHIPID(790),   \"Adreno 750\"},\n\n  // Misc\n  {0x00be06030500, \"Adreno 8c Gen 3\"},\n  {0x007506030500, \"Adreno 7c+ Gen 3\"},\n  {0x006006030500, \"Adreno 7c+ Gen 3 Lite\"},\n  {0x000043051401, \"Adreno 750\"},\n};\n\nconst char * msm_parse_marketing_name(uint64_t gpu_id);\n\nconst char * msm_parse_marketing_name(uint64_t gpu_id) {\n  for (unsigned i = 0; i < ARRAY_SIZE(msm_ids); i++) {\n    if (gpu_id == msm_ids[i].id) {\n      return msm_ids[i].name;\n    }\n  }\n\n  return NULL;\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_nvidia.c",
    "content": "/*\n *\n * Copyright (C) 2021-2024 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/common.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n\n#include <dlfcn.h>\n#include <errno.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define NVML_SUCCESS 0\n#define NVML_ERROR_NOT_SUPPORTED 3\n#define NVML_ERROR_INSUFFICIENT_SIZE 7\n\ntypedef struct nvmlDevice *nvmlDevice_t;\ntypedef int nvmlReturn_t; // store the enum as int\n\n// Init and shutdown\n\nstatic nvmlReturn_t (*nvmlInit)(void);\n\nstatic nvmlReturn_t (*nvmlShutdown)(void);\n\n// Static information and helper functions\n\nstatic nvmlReturn_t (*nvmlDeviceGetCount)(unsigned int *deviceCount);\n\nstatic nvmlReturn_t (*nvmlDeviceGetHandleByIndex)(unsigned int index, nvmlDevice_t *device);\n\nstatic const char *(*nvmlErrorString)(nvmlReturn_t);\n\nstatic nvmlReturn_t (*nvmlDeviceGetName)(nvmlDevice_t device, char *name, unsigned int length);\n\ntypedef struct {\n  char busIdLegacy[16];\n  unsigned int domain;\n  unsigned int bus;\n  unsigned int device;\n  unsigned int pciDeviceId;\n  // Added in NVML 2.285 API\n  unsigned int pciSubSystemId;\n  char busId[32];\n} nvmlPciInfo_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetPciInfo)(nvmlDevice_t device, nvmlPciInfo_t *pciInfo);\n\nstatic nvmlReturn_t (*nvmlDeviceGetMaxPcieLinkGeneration)(nvmlDevice_t device, unsigned int *maxLinkGen);\n\nstatic nvmlReturn_t (*nvmlDeviceGetMaxPcieLinkWidth)(nvmlDevice_t device, unsigned int *maxLinkWidth);\n\ntypedef enum {\n  NVML_TEMPERATURE_THRESHOLD_SHUTDOWN = 0,\n  NVML_TEMPERATURE_THRESHOLD_SLOWDOWN = 1,\n  NVML_TEMPERATURE_THRESHOLD_MEM_MAX = 2,\n  NVML_TEMPERATURE_THRESHOLD_GPU_MAX = 3,\n  NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MIN = 4,\n  NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_CURR = 5,\n  NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MAX = 6,\n} nvmlTemperatureThresholds_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetTemperatureThreshold)(nvmlDevice_t device, nvmlTemperatureThresholds_t thresholdType,\n                                                         unsigned int *temp);\n\n// Dynamic information extraction\n\ntypedef enum {\n  NVML_CLOCK_GRAPHICS = 0,\n  NVML_CLOCK_SM = 1,\n  NVML_CLOCK_MEM = 2,\n  NVML_CLOCK_VIDEO = 3,\n} nvmlClockType_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetClockInfo)(nvmlDevice_t device, nvmlClockType_t type, unsigned int *clock);\n\nstatic nvmlReturn_t (*nvmlDeviceGetMaxClockInfo)(nvmlDevice_t device, nvmlClockType_t type, unsigned int *clock);\n\ntypedef struct {\n  unsigned int gpu;\n  unsigned int memory;\n} nvmlUtilization_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetUtilizationRates)(nvmlDevice_t device, nvmlUtilization_t *utilization);\n\ntypedef struct {\n  unsigned long long total;\n  unsigned long long free;\n  unsigned long long used;\n} nvmlMemory_v1_t;\n\ntypedef struct {\n  unsigned int version;\n  unsigned long long total;\n  unsigned long long reserved;\n  unsigned long long free;\n  unsigned long long used;\n} nvmlMemory_v2_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetMemoryInfo)(nvmlDevice_t device, nvmlMemory_v1_t *memory);\nstatic nvmlReturn_t (*nvmlDeviceGetMemoryInfo_v2)(nvmlDevice_t device, nvmlMemory_v2_t *memory);\n\nstatic nvmlReturn_t (*nvmlDeviceGetCurrPcieLinkGeneration)(nvmlDevice_t device, unsigned int *currLinkGen);\n\nstatic nvmlReturn_t (*nvmlDeviceGetCurrPcieLinkWidth)(nvmlDevice_t device, unsigned int *currLinkWidth);\n\ntypedef enum {\n  NVML_PCIE_UTIL_TX_BYTES = 0,\n  NVML_PCIE_UTIL_RX_BYTES = 1,\n} nvmlPcieUtilCounter_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetPcieThroughput)(nvmlDevice_t device, nvmlPcieUtilCounter_t counter,\n                                                   unsigned int *value);\n\nstatic nvmlReturn_t (*nvmlDeviceGetFanSpeed)(nvmlDevice_t device, unsigned int *speed);\n\ntypedef enum {\n  NVML_TEMPERATURE_GPU = 0,\n} nvmlTemperatureSensors_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetTemperature)(nvmlDevice_t device, nvmlTemperatureSensors_t sensorType,\n                                                unsigned int *temp);\n\nstatic nvmlReturn_t (*nvmlDeviceGetPowerUsage)(nvmlDevice_t device, unsigned int *power);\n\nstatic nvmlReturn_t (*nvmlDeviceGetEnforcedPowerLimit)(nvmlDevice_t device, unsigned int *limit);\n\nstatic nvmlReturn_t (*nvmlDeviceGetEncoderUtilization)(nvmlDevice_t device, unsigned int *utilization,\n                                                       unsigned int *samplingPeriodUs);\n\nstatic nvmlReturn_t (*nvmlDeviceGetDecoderUtilization)(nvmlDevice_t device, unsigned int *utilization,\n                                                       unsigned int *samplingPeriodUs);\n\n// Processes running on GPU\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long usedGpuMemory;\n} nvmlProcessInfo_v1_t;\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long usedGpuMemory;\n  unsigned int gpuInstanceId;\n  unsigned int computeInstanceId;\n} nvmlProcessInfo_v2_t;\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long usedGpuMemory;\n  unsigned int gpuInstanceId;\n  unsigned int computeInstanceId;\n  // This is present in https://github.com/NVIDIA/DCGM/blob/master/sdk/nvidia/nvml/nvml.h#L294 but not the latest driver nvml.h\n  // unsigned long long usedGpuCcProtectedMemory;\n} nvmlProcessInfo_v3_t;\n\nstatic nvmlReturn_t (*nvmlDeviceGetGraphicsRunningProcesses_v1)(nvmlDevice_t device, unsigned int *infoCount,\n                                                                nvmlProcessInfo_v1_t *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetGraphicsRunningProcesses_v2)(nvmlDevice_t device, unsigned int *infoCount,\n                                                                nvmlProcessInfo_v2_t *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetGraphicsRunningProcesses_v3)(nvmlDevice_t device, unsigned int *infoCount,\n                                                                nvmlProcessInfo_v3_t *infos);\n\nstatic nvmlReturn_t (*nvmlDeviceGetComputeRunningProcesses_v1)(nvmlDevice_t device, unsigned int *infoCount,\n                                                               nvmlProcessInfo_v1_t *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetComputeRunningProcesses_v2)(nvmlDevice_t device, unsigned int *infoCount,\n                                                               nvmlProcessInfo_v2_t *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetComputeRunningProcesses_v3)(nvmlDevice_t device, unsigned int *infoCount,\n                                                               nvmlProcessInfo_v3_t *infos);\n\nstatic nvmlReturn_t (*nvmlDeviceGetMPSComputeRunningProcesses_v1)(nvmlDevice_t device, unsigned int *infoCount,\n                                                                  nvmlProcessInfo_v1_t *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetMPSComputeRunningProcesses_v2)(nvmlDevice_t device, unsigned int *infoCount,\n                                                                  nvmlProcessInfo_v2_t *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetMPSComputeRunningProcesses_v3)(nvmlDevice_t device, unsigned int *infoCount,\n                                                                  nvmlProcessInfo_v3_t *infos);\n\n// Common interface passing void*\nstatic nvmlReturn_t (*nvmlDeviceGetGraphicsRunningProcesses[4])(nvmlDevice_t device, unsigned int *infoCount,\n                                                                void *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetComputeRunningProcesses[4])(nvmlDevice_t device, unsigned int *infoCount,\n                                                               void *infos);\nstatic nvmlReturn_t (*nvmlDeviceGetMPSComputeRunningProcesses[4])(nvmlDevice_t device, unsigned int *infoCount,\n                                                                  void *infos);\n\n#define NVML_DEVICE_MIG_DISABLE 0x0\n#define NVML_DEVICE_MIG_ENABLE 0x1\nnvmlReturn_t (*nvmlDeviceGetMigMode)(nvmlDevice_t device, unsigned int *currentMode, unsigned int *pendingMode);\n\nstatic void *libnvidia_ml_handle;\n\nstatic nvmlReturn_t last_nvml_return_status = NVML_SUCCESS;\nstatic char didnt_call_gpuinfo_init[] = \"The NVIDIA extraction has not been initialized, please call \"\n                                        \"gpuinfo_nvidia_init\\n\";\nstatic const char *local_error_string = didnt_call_gpuinfo_init;\n\n// Processes GPU Utilization\n\ntypedef struct {\n  unsigned int pid;\n  unsigned long long timeStamp;\n  unsigned int smUtil;\n  unsigned int memUtil;\n  unsigned int encUtil;\n  unsigned int decUtil;\n} nvmlProcessUtilizationSample_t;\n\nnvmlReturn_t (*nvmlDeviceGetProcessUtilization)(nvmlDevice_t device, nvmlProcessUtilizationSample_t *utilization,\n                                                unsigned int *processSamplesCount,\n                                                unsigned long long lastSeenTimeStamp);\n\nstruct gpu_info_nvidia {\n  struct gpu_info base;\n  struct list_head allocate_list;\n\n  nvmlDevice_t gpuhandle;\n  bool isInMigMode;\n  unsigned long long last_utilization_timestamp;\n};\n\nstatic LIST_HEAD(allocations);\n\nstatic bool gpuinfo_nvidia_init(void);\nstatic void gpuinfo_nvidia_shutdown(void);\nstatic const char *gpuinfo_nvidia_last_error_string(void);\nstatic bool gpuinfo_nvidia_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_nvidia_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_nvidia_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_nvidia_get_running_processes(struct gpu_info *_gpu_info);\n\nstruct gpu_vendor gpu_vendor_nvidia = {\n    .init = gpuinfo_nvidia_init,\n    .shutdown = gpuinfo_nvidia_shutdown,\n    .last_error_string = gpuinfo_nvidia_last_error_string,\n    .get_device_handles = gpuinfo_nvidia_get_device_handles,\n    .populate_static_info = gpuinfo_nvidia_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_nvidia_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_nvidia_get_running_processes,\n    .name = \"NVIDIA\",\n};\n\n__attribute__((constructor)) static void init_extract_gpuinfo_nvidia(void) { register_gpu_vendor(&gpu_vendor_nvidia); }\n\n/*\n *\n * This function loads the libnvidia-ml.so shared object, initializes the\n * required function pointers and calls the nvidia library initialization\n * function. Returns true if everything has been initialized successfully. If\n * false is returned, the cause of the error can be retrieved by calling the\n * function gpuinfo_nvidia_last_error_string.\n *\n */\nstatic bool gpuinfo_nvidia_init(void) {\n\n  libnvidia_ml_handle = dlopen(\"libnvidia-ml.so\", RTLD_LAZY);\n  if (!libnvidia_ml_handle)\n    libnvidia_ml_handle = dlopen(\"libnvidia-ml.so.1\", RTLD_LAZY);\n  if (!libnvidia_ml_handle) {\n    local_error_string = dlerror();\n    return false;\n  }\n\n  // Default to last version\n  nvmlInit = dlsym(libnvidia_ml_handle, \"nvmlInit_v2\");\n  if (!nvmlInit)\n    nvmlInit = dlsym(libnvidia_ml_handle, \"nvmlInit\");\n  if (!nvmlInit)\n    goto init_error_clean_exit;\n\n  nvmlShutdown = dlsym(libnvidia_ml_handle, \"nvmlShutdown\");\n  if (!nvmlShutdown)\n    goto init_error_clean_exit;\n\n  // Default to last version if available\n  nvmlDeviceGetCount = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetCount_v2\");\n  if (!nvmlDeviceGetCount)\n    nvmlDeviceGetCount = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetCount\");\n  if (!nvmlDeviceGetCount)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetHandleByIndex = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetHandleByIndex_v2\");\n  if (!nvmlDeviceGetHandleByIndex)\n    nvmlDeviceGetHandleByIndex = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetHandleByIndex\");\n  if (!nvmlDeviceGetHandleByIndex)\n    goto init_error_clean_exit;\n\n  nvmlErrorString = dlsym(libnvidia_ml_handle, \"nvmlErrorString\");\n  if (!nvmlErrorString)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetName = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetName\");\n  if (!nvmlDeviceGetName)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetPciInfo = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetPciInfo_v3\");\n  if (!nvmlDeviceGetPciInfo)\n    nvmlDeviceGetPciInfo = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetPciInfo_v2\");\n  if (!nvmlDeviceGetPciInfo)\n    nvmlDeviceGetPciInfo = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetPciInfo\");\n  if (!nvmlDeviceGetPciInfo)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetMaxPcieLinkGeneration = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMaxPcieLinkGeneration\");\n  if (!nvmlDeviceGetMaxPcieLinkGeneration)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetMaxPcieLinkWidth = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMaxPcieLinkWidth\");\n  if (!nvmlDeviceGetMaxPcieLinkWidth)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetTemperatureThreshold = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetTemperatureThreshold\");\n  if (!nvmlDeviceGetTemperatureThreshold)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetClockInfo = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetClockInfo\");\n  if (!nvmlDeviceGetClockInfo)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetMaxClockInfo = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMaxClockInfo\");\n  if (!nvmlDeviceGetMaxClockInfo)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetUtilizationRates = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetUtilizationRates\");\n  if (!nvmlDeviceGetUtilizationRates)\n    goto init_error_clean_exit;\n\n  // Get v2 and fallback to v1\n  nvmlDeviceGetMemoryInfo_v2 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMemoryInfo_v2\");\n  nvmlDeviceGetMemoryInfo = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMemoryInfo\");\n  if (!nvmlDeviceGetMemoryInfo_v2 && !nvmlDeviceGetMemoryInfo)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetCurrPcieLinkGeneration = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetCurrPcieLinkGeneration\");\n  if (!nvmlDeviceGetCurrPcieLinkGeneration)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetCurrPcieLinkWidth = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetCurrPcieLinkWidth\");\n  if (!nvmlDeviceGetCurrPcieLinkWidth)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetPcieThroughput = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetPcieThroughput\");\n  if (!nvmlDeviceGetPcieThroughput)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetFanSpeed = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetFanSpeed\");\n  if (!nvmlDeviceGetFanSpeed)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetTemperature = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetTemperature\");\n  if (!nvmlDeviceGetTemperature)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetPowerUsage = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetPowerUsage\");\n  if (!nvmlDeviceGetPowerUsage)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetEnforcedPowerLimit = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetEnforcedPowerLimit\");\n  if (!nvmlDeviceGetEnforcedPowerLimit)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetEncoderUtilization = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetEncoderUtilization\");\n  if (!nvmlDeviceGetEncoderUtilization)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetDecoderUtilization = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetDecoderUtilization\");\n  if (!nvmlDeviceGetDecoderUtilization)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetGraphicsRunningProcesses_v3 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetGraphicsRunningProcesses_v3\");\n  nvmlDeviceGetGraphicsRunningProcesses_v2 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetGraphicsRunningProcesses_v2\");\n  nvmlDeviceGetGraphicsRunningProcesses_v1 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetGraphicsRunningProcesses\");\n  if (!nvmlDeviceGetGraphicsRunningProcesses_v3 && !nvmlDeviceGetGraphicsRunningProcesses_v2 &&\n      !nvmlDeviceGetGraphicsRunningProcesses_v1)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetGraphicsRunningProcesses[1] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetGraphicsRunningProcesses_v1;\n  nvmlDeviceGetGraphicsRunningProcesses[2] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetGraphicsRunningProcesses_v2;\n  nvmlDeviceGetGraphicsRunningProcesses[3] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetGraphicsRunningProcesses_v3;\n\n  nvmlDeviceGetComputeRunningProcesses_v3 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetComputeRunningProcesses_v3\");\n  nvmlDeviceGetComputeRunningProcesses_v2 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetComputeRunningProcesses_v2\");\n  nvmlDeviceGetComputeRunningProcesses_v1 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetComputeRunningProcesses\");\n  if (!nvmlDeviceGetComputeRunningProcesses_v3 && !nvmlDeviceGetComputeRunningProcesses_v2 &&\n      !nvmlDeviceGetComputeRunningProcesses_v1)\n    goto init_error_clean_exit;\n\n  nvmlDeviceGetComputeRunningProcesses[1] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetComputeRunningProcesses_v1;\n  nvmlDeviceGetComputeRunningProcesses[2] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetComputeRunningProcesses_v2;\n  nvmlDeviceGetComputeRunningProcesses[3] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetComputeRunningProcesses_v3;\n\n  // These functions were not available in older NVML libs; don't error if not present\n  nvmlDeviceGetMPSComputeRunningProcesses_v3 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMPSComputeRunningProcesses_v3\");\n  nvmlDeviceGetMPSComputeRunningProcesses_v2 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMPSComputeRunningProcesses_v2\");\n  nvmlDeviceGetMPSComputeRunningProcesses_v1 = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMPSComputeRunningProcesses\");\n\n  nvmlDeviceGetMPSComputeRunningProcesses[1] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetMPSComputeRunningProcesses_v1;\n  nvmlDeviceGetMPSComputeRunningProcesses[2] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetMPSComputeRunningProcesses_v2;\n  nvmlDeviceGetMPSComputeRunningProcesses[3] =\n      (nvmlReturn_t(*)(nvmlDevice_t, unsigned int *, void *))nvmlDeviceGetMPSComputeRunningProcesses_v3;\n\n  // These ones might not be available\n  nvmlDeviceGetProcessUtilization = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetProcessUtilization\");\n  nvmlDeviceGetMigMode = dlsym(libnvidia_ml_handle, \"nvmlDeviceGetMigMode\");\n\n  last_nvml_return_status = nvmlInit();\n  if (last_nvml_return_status != NVML_SUCCESS) {\n    return false;\n  }\n  local_error_string = NULL;\n\n  return true;\n\ninit_error_clean_exit:\n  dlclose(libnvidia_ml_handle);\n  libnvidia_ml_handle = NULL;\n  return false;\n}\n\nstatic void gpuinfo_nvidia_shutdown(void) {\n  if (libnvidia_ml_handle) {\n    nvmlShutdown();\n    dlclose(libnvidia_ml_handle);\n    libnvidia_ml_handle = NULL;\n    local_error_string = didnt_call_gpuinfo_init;\n  }\n\n  struct gpu_info_nvidia *allocated, *tmp;\n\n  list_for_each_entry_safe(allocated, tmp, &allocations, allocate_list) {\n    list_del(&allocated->allocate_list);\n    free(allocated);\n  }\n}\n\nstatic const char *gpuinfo_nvidia_last_error_string(void) {\n  if (local_error_string) {\n    return local_error_string;\n  } else if (libnvidia_ml_handle && nvmlErrorString) {\n    return nvmlErrorString(last_nvml_return_status);\n  } else {\n    return \"An unanticipated error occurred while accessing NVIDIA GPU \"\n           \"information\\n\";\n  }\n}\n\nstatic bool gpuinfo_nvidia_get_device_handles(struct list_head *devices, unsigned *count) {\n\n  if (!libnvidia_ml_handle)\n    return false;\n\n  unsigned num_devices;\n  last_nvml_return_status = nvmlDeviceGetCount(&num_devices);\n  if (last_nvml_return_status != NVML_SUCCESS)\n    return false;\n\n  struct gpu_info_nvidia *gpu_infos = calloc(num_devices, sizeof(*gpu_infos));\n  if (!gpu_infos) {\n    local_error_string = strerror(errno);\n    return false;\n  }\n\n  list_add(&gpu_infos[0].allocate_list, &allocations);\n\n  *count = 0;\n  for (unsigned int i = 0; i < num_devices; ++i) {\n    last_nvml_return_status = nvmlDeviceGetHandleByIndex(i, &gpu_infos[*count].gpuhandle);\n    if (last_nvml_return_status == NVML_SUCCESS) {\n      gpu_infos[*count].base.vendor = &gpu_vendor_nvidia;\n      nvmlPciInfo_t pciInfo;\n      nvmlReturn_t pciInfoRet = nvmlDeviceGetPciInfo(gpu_infos[*count].gpuhandle, &pciInfo);\n      if (pciInfoRet == NVML_SUCCESS) {\n        strncpy(gpu_infos[*count].base.pdev, pciInfo.busIdLegacy, PDEV_LEN);\n        list_add_tail(&gpu_infos[*count].base.list, devices);\n        *count += 1;\n      }\n    }\n  }\n\n  return true;\n}\n\nstatic void gpuinfo_nvidia_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_nvidia *gpu_info = container_of(_gpu_info, struct gpu_info_nvidia, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  nvmlDevice_t device = gpu_info->gpuhandle;\n\n  static_info->integrated_graphics = false;\n  static_info->encode_decode_shared = false;\n  RESET_ALL(static_info->valid);\n\n  last_nvml_return_status = nvmlDeviceGetName(device, static_info->device_name, MAX_DEVICE_NAME);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n\n  last_nvml_return_status = nvmlDeviceGetMaxPcieLinkGeneration(device, &static_info->max_pcie_gen);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_max_pcie_gen_valid, static_info->valid);\n\n  last_nvml_return_status = nvmlDeviceGetMaxPcieLinkWidth(device, &static_info->max_pcie_link_width);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_max_pcie_link_width_valid, static_info->valid);\n\n  last_nvml_return_status = nvmlDeviceGetTemperatureThreshold(device, NVML_TEMPERATURE_THRESHOLD_SHUTDOWN,\n                                                              &static_info->temperature_shutdown_threshold);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_temperature_shutdown_threshold_valid, static_info->valid);\n\n  last_nvml_return_status = nvmlDeviceGetTemperatureThreshold(device, NVML_TEMPERATURE_THRESHOLD_SLOWDOWN,\n                                                              &static_info->temperature_slowdown_threshold);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_temperature_slowdown_threshold_valid, static_info->valid);\n}\n\nstatic void gpuinfo_nvidia_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_nvidia *gpu_info = container_of(_gpu_info, struct gpu_info_nvidia, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  nvmlDevice_t device = gpu_info->gpuhandle;\n\n  bool graphics_clock_valid = false;\n  unsigned graphics_clock;\n  bool sm_clock_valid = false;\n  unsigned sm_clock;\n  nvmlClockType_t getMaxClockFrom = NVML_CLOCK_GRAPHICS;\n\n  RESET_ALL(dynamic_info->valid);\n\n  // GPU current speed\n  // Maximum between SM and Graphical\n  last_nvml_return_status = nvmlDeviceGetClockInfo(device, NVML_CLOCK_GRAPHICS, &graphics_clock);\n  graphics_clock_valid = last_nvml_return_status == NVML_SUCCESS;\n\n  last_nvml_return_status = nvmlDeviceGetClockInfo(device, NVML_CLOCK_SM, &sm_clock);\n  sm_clock_valid = last_nvml_return_status == NVML_SUCCESS;\n\n  if (graphics_clock_valid && sm_clock_valid && graphics_clock < sm_clock) {\n    getMaxClockFrom = NVML_CLOCK_SM;\n  } else if (!graphics_clock_valid && sm_clock_valid) {\n    getMaxClockFrom = NVML_CLOCK_SM;\n  }\n\n  if (getMaxClockFrom == NVML_CLOCK_GRAPHICS && graphics_clock_valid) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, graphics_clock);\n  }\n  if (getMaxClockFrom == NVML_CLOCK_SM && sm_clock_valid) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, sm_clock);\n  }\n\n  // GPU max speed\n  last_nvml_return_status = nvmlDeviceGetMaxClockInfo(device, getMaxClockFrom, &dynamic_info->gpu_clock_speed_max);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_gpu_clock_speed_max_valid, dynamic_info->valid);\n\n  // Memory current speed\n  last_nvml_return_status = nvmlDeviceGetClockInfo(device, NVML_CLOCK_MEM, &dynamic_info->mem_clock_speed);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_mem_clock_speed_valid, dynamic_info->valid);\n\n  // Memory max speed\n  last_nvml_return_status = nvmlDeviceGetMaxClockInfo(device, NVML_CLOCK_MEM, &dynamic_info->mem_clock_speed_max);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_mem_clock_speed_max_valid, dynamic_info->valid);\n\n  // CPU and Memory utilization rates\n  nvmlUtilization_t utilization_percentages;\n  last_nvml_return_status = nvmlDeviceGetUtilizationRates(device, &utilization_percentages);\n  if (last_nvml_return_status == NVML_SUCCESS) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, utilization_percentages.gpu);\n  }\n\n  // Encoder utilization rate\n  unsigned ignored_period;\n  last_nvml_return_status = nvmlDeviceGetEncoderUtilization(device, &dynamic_info->encoder_rate, &ignored_period);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_encoder_rate_valid, dynamic_info->valid);\n\n  // Decoder utilization rate\n  last_nvml_return_status = nvmlDeviceGetDecoderUtilization(device, &dynamic_info->decoder_rate, &ignored_period);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_decoder_rate_valid, dynamic_info->valid);\n\n  // Device memory info (total,used,free)\n  bool got_meminfo = false;\n  bool has_unified_memory = false;\n\n  if (nvmlDeviceGetMemoryInfo_v2) {\n    nvmlMemory_v2_t memory_info;\n    memory_info.version = 2;\n    last_nvml_return_status = nvmlDeviceGetMemoryInfo_v2(device, &memory_info);\n    if (last_nvml_return_status == NVML_SUCCESS) {\n      // Check if this is a unified memory GPU (total == 0 indicates unified memory)\n      got_meminfo = true;\n      if (memory_info.total == 0) {\n        has_unified_memory = true;\n      } else {\n        SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, memory_info.total);\n        SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, memory_info.used);\n        SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, memory_info.free);\n        SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, memory_info.used * 100 / memory_info.total);\n      }\n    } else if (last_nvml_return_status == NVML_ERROR_NOT_SUPPORTED) {\n      // From the NVM: documentation:\n      // On certain SOC platforms, the integrated GPU (iGPU) does not use a dedicated framebuffer but instead shares\n      // memory with the system. As a result, NVML_ERROR_NOT_SUPPORTED will be returned in this case.\n      got_meminfo = true;\n      has_unified_memory = true;\n    }\n  }\n  if (!got_meminfo && nvmlDeviceGetMemoryInfo) {\n    nvmlMemory_v1_t memory_info;\n    last_nvml_return_status = nvmlDeviceGetMemoryInfo(device, &memory_info);\n    if (last_nvml_return_status == NVML_SUCCESS) {\n      // Check if this is a unified memory GPU (total == 0 indicates unified memory)\n      if (memory_info.total == 0) {\n        has_unified_memory = true;\n      } else {\n        SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, memory_info.total);\n        SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, memory_info.used);\n        SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, memory_info.free);\n        SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, memory_info.used * 100 / memory_info.total);\n      }\n    } else if (last_nvml_return_status == NVML_ERROR_NOT_SUPPORTED) {\n      // From the NVM: documentation:\n      // On certain SOC platforms, the integrated GPU (iGPU) does not use a dedicated framebuffer but instead shares\n      // memory with the system. As a result, NVML_ERROR_NOT_SUPPORTED will be returned in this case.\n      has_unified_memory = true;\n    }\n  }\n\n  // Handle unified memory GPUs - query system memory\n  if (has_unified_memory) {\n    // Read MemAvailable from /proc/meminfo for available memory\n    FILE *meminfo = fopen(\"/proc/meminfo\", \"r\");\n    if (meminfo) {\n      unsigned long long total_memory = 0;\n      char line[256];\n\n      while (fgets(line, sizeof(line), meminfo)) {\n        if (sscanf(line, \"MemTotal: %llu kB\", &total_memory) == 1) {\n          total_memory *= 1024; // Convert KB to bytes\n          break;\n        }\n      }\n      fclose(meminfo);\n\n      // The used memory will be computed from process infos as part of the\n      // fixup function gpuinfo_fix_dynamic_info_from_process_info from\n      // extract_gpuinfo.c\n      if (total_memory > 0)\n        SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, total_memory);\n    }\n  }\n\n  // Pcie generation used by the device\n  last_nvml_return_status = nvmlDeviceGetCurrPcieLinkGeneration(device, &dynamic_info->pcie_link_gen);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_link_gen_valid, dynamic_info->valid);\n\n  // Pcie width used by the device\n  last_nvml_return_status = nvmlDeviceGetCurrPcieLinkWidth(device, &dynamic_info->pcie_link_width);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_link_width_valid, dynamic_info->valid);\n\n  // Pcie reception throughput\n  last_nvml_return_status = nvmlDeviceGetPcieThroughput(device, NVML_PCIE_UTIL_RX_BYTES, &dynamic_info->pcie_rx);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_rx_valid, dynamic_info->valid);\n\n  // Pcie transmission throughput\n  last_nvml_return_status = nvmlDeviceGetPcieThroughput(device, NVML_PCIE_UTIL_TX_BYTES, &dynamic_info->pcie_tx);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_pcie_tx_valid, dynamic_info->valid);\n\n  // Fan speed\n  last_nvml_return_status = nvmlDeviceGetFanSpeed(device, &dynamic_info->fan_speed);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_fan_speed_valid, dynamic_info->valid);\n\n  // GPU temperature\n  last_nvml_return_status = nvmlDeviceGetTemperature(device, NVML_TEMPERATURE_GPU, &dynamic_info->gpu_temp);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_gpu_temp_valid, dynamic_info->valid);\n\n  // Device power usage\n  last_nvml_return_status = nvmlDeviceGetPowerUsage(device, &dynamic_info->power_draw);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_power_draw_valid, dynamic_info->valid);\n\n  // Maximum enforced power usage\n  last_nvml_return_status = nvmlDeviceGetEnforcedPowerLimit(device, &dynamic_info->power_draw_max);\n  if (last_nvml_return_status == NVML_SUCCESS)\n    SET_VALID(gpuinfo_power_draw_max_valid, dynamic_info->valid);\n\n  // MIG mode\n  if (nvmlDeviceGetMigMode) {\n    unsigned currentMode, pendingMode;\n    last_nvml_return_status = nvmlDeviceGetMigMode(device, &currentMode, &pendingMode);\n    if (last_nvml_return_status == NVML_SUCCESS) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, multi_instance_mode, currentMode == NVML_DEVICE_MIG_ENABLE);\n    }\n  }\n}\n\nstatic void gpuinfo_nvidia_get_process_utilization(struct gpu_info_nvidia *gpu_info, unsigned num_processes_recovered,\n                                                   struct gpu_process processes[num_processes_recovered]) {\n  nvmlDevice_t device = gpu_info->gpuhandle;\n\n  if (num_processes_recovered && nvmlDeviceGetProcessUtilization) {\n    unsigned samples_count = 0;\n    nvmlReturn_t retval =\n        nvmlDeviceGetProcessUtilization(device, NULL, &samples_count, gpu_info->last_utilization_timestamp);\n    if (retval != NVML_ERROR_INSUFFICIENT_SIZE)\n      return;\n    nvmlProcessUtilizationSample_t *samples = malloc(samples_count * sizeof(*samples));\n    retval = nvmlDeviceGetProcessUtilization(device, samples, &samples_count, gpu_info->last_utilization_timestamp);\n    if (retval != NVML_SUCCESS) {\n      free(samples);\n      return;\n    }\n    unsigned long long newest_timestamp_candidate = gpu_info->last_utilization_timestamp;\n    for (unsigned i = 0; i < samples_count; ++i) {\n      bool process_matched = false;\n      for (unsigned j = 0; !process_matched && j < num_processes_recovered; ++j) {\n        // Filter out samples due to inconsistency in the results returned by\n        // the function nvmlDeviceGetProcessUtilization (see bug #110 on\n        // Github). Check for a valid running process returned by\n        // nvmlDeviceGetComputeRunningProcesses or\n        // nvmlDeviceGetGraphicsRunningProcesses, filter out inconsistent\n        // utilization value greater than 100% and filter out timestamp results\n        // that are less recent than what we were asking for\n        if ((pid_t)samples[i].pid == processes[j].pid && samples[i].smUtil <= 100 && samples[i].encUtil <= 100 &&\n            samples[i].decUtil <= 100 && samples[i].timeStamp > gpu_info->last_utilization_timestamp) {\n          // Collect the largest valid timestamp for this device to filter out\n          // the samples during the next call to the function\n          // nvmlDeviceGetProcessUtilization\n          if (samples[i].timeStamp > newest_timestamp_candidate)\n            newest_timestamp_candidate = samples[i].timeStamp;\n\n          SET_GPUINFO_PROCESS(&processes[j], gpu_usage, samples[i].smUtil);\n          SET_GPUINFO_PROCESS(&processes[j], encode_usage, samples[i].encUtil);\n          SET_GPUINFO_PROCESS(&processes[j], decode_usage, samples[i].decUtil);\n          process_matched = true;\n        }\n      }\n    }\n    gpu_info->last_utilization_timestamp = newest_timestamp_candidate;\n    free(samples);\n  }\n  // Mark the ones w/o update since last sample period to 0% usage\n  for (unsigned j = 0; j < num_processes_recovered; ++j) {\n    if (!IS_VALID(gpuinfo_process_gpu_usage_valid, processes[j].valid))\n      SET_GPUINFO_PROCESS(&processes[j], gpu_usage, 0);\n    if (!IS_VALID(gpuinfo_process_encode_usage_valid, processes[j].valid))\n      SET_GPUINFO_PROCESS(&processes[j], encode_usage, 0);\n    if (!IS_VALID(gpuinfo_process_decode_usage_valid, processes[j].valid))\n      SET_GPUINFO_PROCESS(&processes[j], decode_usage, 0);\n  }\n}\n\nstatic void gpuinfo_nvidia_get_running_processes(struct gpu_info *_gpu_info) {\n  struct gpu_info_nvidia *gpu_info = container_of(_gpu_info, struct gpu_info_nvidia, base);\n  nvmlDevice_t device = gpu_info->gpuhandle;\n  bool validProcessGathering = false;\n  for (unsigned version = 3; !validProcessGathering && version > 0; version--) {\n    // Get the size of the actual function being used\n    size_t sizeof_nvmlProcessInfo;\n    switch (version) {\n    case 3:\n      sizeof_nvmlProcessInfo = sizeof(nvmlProcessInfo_v3_t);\n      break;\n    case 2:\n      sizeof_nvmlProcessInfo = sizeof(nvmlProcessInfo_v2_t);\n      break;\n    default:\n      sizeof_nvmlProcessInfo = sizeof(nvmlProcessInfo_v1_t);\n      break;\n    }\n\n    _gpu_info->processes_count = 0;\n    static size_t array_size = 0;\n    static char *retrieved_infos = NULL;\n    unsigned graphical_count = 0, compute_count = 0, recovered_count;\n    if (nvmlDeviceGetGraphicsRunningProcesses[version]) {\n    retry_query_graphical:\n      recovered_count = array_size;\n      last_nvml_return_status =\n          nvmlDeviceGetGraphicsRunningProcesses[version](device, &recovered_count, retrieved_infos);\n      if (last_nvml_return_status == NVML_ERROR_INSUFFICIENT_SIZE) {\n        array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n        retrieved_infos = reallocarray(retrieved_infos, array_size, sizeof_nvmlProcessInfo);\n        if (!retrieved_infos) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n        goto retry_query_graphical;\n      }\n      if (last_nvml_return_status == NVML_SUCCESS) {\n        validProcessGathering = true;\n        graphical_count = recovered_count;\n      }\n    }\n\n    if (nvmlDeviceGetComputeRunningProcesses[version]) {\n    retry_query_compute:\n      recovered_count = array_size - graphical_count;\n      last_nvml_return_status = nvmlDeviceGetComputeRunningProcesses[version](\n          device, &recovered_count, retrieved_infos + graphical_count * sizeof_nvmlProcessInfo);\n      if (last_nvml_return_status == NVML_ERROR_INSUFFICIENT_SIZE) {\n        array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n        retrieved_infos = reallocarray(retrieved_infos, array_size, sizeof_nvmlProcessInfo);\n        if (!retrieved_infos) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n        goto retry_query_compute;\n      }\n      if (last_nvml_return_status == NVML_SUCCESS) {\n        validProcessGathering = true;\n        compute_count = recovered_count;\n      }\n    }\n\n    if (nvmlDeviceGetMPSComputeRunningProcesses[version]) {\n    retry_query_compute_MPS:\n      recovered_count = array_size - graphical_count - compute_count;\n      last_nvml_return_status = nvmlDeviceGetMPSComputeRunningProcesses[version](\n          device, &recovered_count, retrieved_infos + (graphical_count + compute_count) * sizeof_nvmlProcessInfo);\n      if (last_nvml_return_status == NVML_ERROR_INSUFFICIENT_SIZE) {\n        array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n        retrieved_infos = reallocarray(retrieved_infos, array_size, sizeof_nvmlProcessInfo);\n        if (!retrieved_infos) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n        goto retry_query_compute_MPS;\n      }\n      if (last_nvml_return_status == NVML_SUCCESS) {\n        validProcessGathering = true;\n        compute_count += recovered_count;\n      }\n    }\n\n    if (!validProcessGathering)\n      continue;\n\n    _gpu_info->processes_count = graphical_count + compute_count;\n    if (_gpu_info->processes_count > 0) {\n      if (_gpu_info->processes_count > _gpu_info->processes_array_size) {\n        _gpu_info->processes_array_size = _gpu_info->processes_count + COMMON_PROCESS_LINEAR_REALLOC_INC;\n        _gpu_info->processes =\n            reallocarray(_gpu_info->processes, _gpu_info->processes_array_size, sizeof(*_gpu_info->processes));\n        if (!_gpu_info->processes) {\n          perror(\"Could not allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n      }\n      memset(_gpu_info->processes, 0, _gpu_info->processes_count * sizeof(*_gpu_info->processes));\n      for (unsigned i = 0; i < graphical_count + compute_count; ++i) {\n        if (i < graphical_count)\n          _gpu_info->processes[i].type = gpu_process_graphical;\n        else\n          _gpu_info->processes[i].type = gpu_process_compute;\n        switch (version) {\n        case 2: {\n          nvmlProcessInfo_v2_t *pinfo = (nvmlProcessInfo_v2_t *)retrieved_infos;\n          _gpu_info->processes[i].pid = pinfo[i].pid;\n          _gpu_info->processes[i].gpu_memory_usage = pinfo[i].usedGpuMemory;\n        } break;\n        case 3: {\n          nvmlProcessInfo_v3_t *pinfo = (nvmlProcessInfo_v3_t *)retrieved_infos;\n          _gpu_info->processes[i].pid = pinfo[i].pid;\n          _gpu_info->processes[i].gpu_memory_usage = pinfo[i].usedGpuMemory;\n        } break;\n        default: {\n          nvmlProcessInfo_v1_t *pinfo = (nvmlProcessInfo_v1_t *)retrieved_infos;\n          _gpu_info->processes[i].pid = pinfo[i].pid;\n          _gpu_info->processes[i].gpu_memory_usage = pinfo[i].usedGpuMemory;\n        } break;\n        }\n        SET_VALID(gpuinfo_process_gpu_memory_usage_valid, _gpu_info->processes[i].valid);\n      }\n    }\n  }\n  // If the GPU is in MIG mode; process utilization is not supported\n  if (!(IS_VALID(gpuinfo_multi_instance_mode_valid, gpu_info->base.dynamic_info.valid) &&\n        !gpu_info->base.dynamic_info.multi_instance_mode))\n    gpuinfo_nvidia_get_process_utilization(gpu_info, _gpu_info->processes_count, _gpu_info->processes);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_panfrost.c",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * This file is part of Nvtop and adapted from the msm implementation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <sys/stat.h>\n#ifdef __linux__\n// for minor() on linux (available through sys/types.h on BSD)\n#include <sys/sysmacros.h>\n#endif\n#include <sys/types.h>\n#include <xf86drm.h>\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include \"panfrost_drm.h\"\n#include \"panfrost_utils.h\"\n#include \"mali_common.h\"\n\nstatic bool gpuinfo_panfrost_init(void);\nstatic void gpuinfo_panfrost_shutdown(void);\nstatic const char *gpuinfo_panfrost_last_error_string(void);\nstatic bool gpuinfo_panfrost_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_panfrost_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_panfrost_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_panfrost_get_running_processes(struct gpu_info *_gpu_info);\n\nstatic struct gpu_vendor gpu_vendor_panfrost = {\n    .init = gpuinfo_panfrost_init,\n    .shutdown = gpuinfo_panfrost_shutdown,\n    .last_error_string = gpuinfo_panfrost_last_error_string,\n    .get_device_handles = gpuinfo_panfrost_get_device_handles,\n    .populate_static_info = gpuinfo_panfrost_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_panfrost_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_panfrost_get_running_processes,\n    .refresh_utilisation_rate = gpuinfo_refresh_utilisation_rate,\n    .name = \"panfrost\",\n};\n\nstatic struct drmFuncTable drmFuncs;\nstatic struct mali_gpu_state mali_state;\n\n__attribute__((constructor)) static void init_extract_gpuinfo_panfrost(void) { register_gpu_vendor(&gpu_vendor_panfrost); }\n\nbool gpuinfo_panfrost_init(void) {\n  return mali_init_drm_funcs(&drmFuncs, &mali_state);\n}\n\nvoid gpuinfo_panfrost_shutdown(void) {\n  for (unsigned i = 0; i < mali_state.mali_gpu_count; ++i) {\n    struct panfrost_driver_data *prof_info = &mali_state.gpu_infos[i].model.panfrost;\n    FILE *fprofiling;\n\n    fprofiling = fopen(prof_info->sysfs_filename, \"w\");\n    if (fprofiling == NULL) {\n            fprintf(stderr, \"Panfrost's profile parameter sysfs hook seems gone\\n\");\n            free(prof_info->sysfs_filename);\n            continue;\n    }\n\n    char buf = prof_info->original_profiling_state ? '1' : '0';\n    size_t size = fwrite(&buf, sizeof(char), 1, fprofiling);\n    if (!size)\n            fprintf(stderr, \"restoring profiling state didn't work\\n\");\n    fclose(fprofiling);\n    free(prof_info->sysfs_filename);\n  }\n\n  mali_shutdown_common(&mali_state, &drmFuncs);\n}\n\nstatic const char *gpuinfo_panfrost_last_error_string(void) {\n  static char driver_msg[MAX_ERR_STRING_LEN] = {0};\n\n  return mali_common_last_error_string(&mali_state,\n                                       gpu_vendor_panfrost.name,\n                                       driver_msg);\n}\n\nstatic void panfrost_check_fdinfo_keys (bool *is_engine, bool *is_cycles,\n                                        bool *is_maxfreq, bool *is_curfreq,\n                                        bool *is_resident, char *key)\n{\n  static const char drm_panfrost_engine_vtx[] = \"drm-engine-vertex-tiler\";\n  static const char drm_panfrost_engine_frg[] = \"drm-engine-fragment\";\n  static const char drm_panfrost_cycles_vtx[] = \"drm-cycles-vertex-tiler\";\n  static const char drm_panfrost_cycles_frg[] = \"drm-cycles-fragment\";\n  static const char drm_panfrost_maxfreq_vtx[] = \"drm-maxfreq-vertex-tiler\";\n  static const char drm_panfrost_maxfreq_frg[] = \"drm-maxfreq-fragment\";\n  static const char drm_panfrost_curfreq_vtx[] = \"drm-curfreq-vertex-tiler\";\n  static const char drm_panfrost_curfreq_frg[] = \"drm-curfreq-fragment\";\n  static const char drm_panfrost_resident_mem[] = \"drm-resident-memory\";\n\n  *is_engine = !strcmp(key, drm_panfrost_engine_vtx) || !strcmp(key, drm_panfrost_engine_frg);\n  *is_cycles = !strcmp(key, drm_panfrost_cycles_vtx) || !strcmp(key, drm_panfrost_cycles_frg);\n  *is_maxfreq = !strcmp(key, drm_panfrost_maxfreq_vtx) || !strcmp(key, drm_panfrost_maxfreq_frg);\n  *is_curfreq = !strcmp(key, drm_panfrost_curfreq_vtx) || !strcmp(key, drm_panfrost_curfreq_frg);\n  *is_resident = !strcmp(key, drm_panfrost_resident_mem);\n}\n\nstatic bool parse_drm_fdinfo_panfrost(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n\n  struct gpu_info_mali *gpu_info = container_of(info, struct gpu_info_mali, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  struct fdinfo_data res = {0};\n\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n\n  if (!mali_common_parse_drm_fdinfo(info, fdinfo_file, process_info, dynamic_info,\n                                    panfrost_check_fdinfo_keys, &res))\n    return false;\n\n  mali_common_parse_fdinfo_handle_cache(gpu_info, process_info, current_time, res.total_cycles,\n\t\t\t\t\tres.cid, res.engine_count >= 1 ? true : false);\n\n  return true;\n}\n\nstatic char *get_sysfs_filename(struct gpu_info_mali *gpu_info) {\n  char sysfs_file[PATH_MAX + 1] = {0};\n  char *fullname, *of_name, *node;\n  const char *bus_name = NULL;\n  drmDevicePtr device;\n  struct stat filebuf;\n  unsigned int i;\n  int ret;\n\n  static struct {\n    const char *name;\n    int bus_type;\n  } bus_types[] = {\n    { \"/pci\", DRM_BUS_PCI },\n    { \"/usb\", DRM_BUS_USB },\n    { \"/platform\", DRM_BUS_PLATFORM },\n    { \"/host1x\", DRM_BUS_HOST1X },\n  };\n\n  fstat(gpu_info->fd, &filebuf);\n\n  ret = drmFuncs.drmGetDeviceFromDevId(filebuf.st_rdev, 0, &device);\n  if (ret) {\n    fprintf(stderr, \"drmGetDeviceFromDevId failed with %d\\n\", ret);\n    goto sysfs_end;\n  }\n\n  fullname = device->businfo.platform->fullname;\n\n  node = strrchr(fullname, '@');\n  of_name = strrchr(fullname, '/');\n  if (node == NULL || of_name == NULL)\n    goto sysfs_end;\n  *node = '\\0'; node++;;\n  *of_name = '\\0'; of_name++;\n\n  for (i = 0; i < (sizeof(bus_types) / sizeof(typeof(bus_types[0]))); i++) {\n    if (bus_types[i].bus_type == device->bustype) {\n      bus_name = bus_types[i].name;\n      break;\n    }\n  }\n\n  if (bus_name == NULL) {\n    fprintf(stderr, \"Unknown bus type = %d\\n\", device->bustype);\n    goto sysfs_end;\n  }\n\n  snprintf(sysfs_file, PATH_MAX + 1, \"/sys/devices%s%s/%s.%s/profiling\", bus_name, fullname, node, of_name);\n\nsysfs_end:\n  free(device);\n  return (!sysfs_file[0]) ? NULL : strdup(sysfs_file);\n}\n\nstatic bool panfrost_open_sysfs_profile(struct gpu_info_mali *gpu_info) {\n  struct panfrost_driver_data *prof_info = &gpu_info->model.panfrost;\n  FILE *fprofiling;\n  bool ret = true;\n\n  if (!gpu_info->fd || gpu_info->version != MALI_PANFROST)\n    return false;\n\n  prof_info->sysfs_filename = get_sysfs_filename(gpu_info);\n  if (prof_info->sysfs_filename == NULL)\n    return false;\n\n  fprofiling = fopen(prof_info->sysfs_filename, \"r\");\n  if (fprofiling == NULL) {\n    fprintf(stderr, \"Profiling state not available in Panfrost\\n\");\n    goto file_error;\n  }\n\n  char buf = 0;\n  size_t size = fread(&buf, sizeof(char), 1, fprofiling);\n  if (!size) {\n    fprintf(stderr, \"Error reading profiling state\\n\");\n    goto format_error;\n  }\n\n  prof_info->original_profiling_state = (buf == '1') ? true : false;\n\n  fclose(fprofiling);\n  fprofiling = fopen(prof_info->sysfs_filename, \"w\");\n  if (fprofiling == NULL) {\n    fprintf(stderr, \"Profiling state not available in Panfrost\\n\");\n    goto file_error;\n  }\n\n  buf = '1';\n  size = fwrite(&buf, sizeof(char), 1, fprofiling);\n  if (!size) {\n    fprintf(stderr, \"Error writing profiling state\\n\");\n  }\n\nformat_error:\n  fclose(fprofiling);\n  if (!size)\n    ret = false;\nfile_error:\n  if (fprofiling == NULL)\n    ret = false;\n  if (ret)\n    free(prof_info->sysfs_filename);\n  return ret;\n}\n\nstatic bool gpuinfo_panfrost_get_device_handles(struct list_head *devices, unsigned *count) {\n        return mali_common_get_device_handles(&mali_state, &drmFuncs, &gpu_vendor_panfrost,\n                                              parse_drm_fdinfo_panfrost, devices, count,\n                                              panfrost_open_sysfs_profile, MALI_PANFROST);\n}\n\nstatic int gpuinfo_panfrost_query_param(int gpu, uint32_t param, uint64_t *value) {\n\n  struct drm_panfrost_get_param req = {\n    .param = param,\n  };\n\n  int ret = drmFuncs.drmCommandWriteRead(gpu, DRM_PANFROST_GET_PARAM, &req, sizeof(req));\n\n  if (ret)\n    return ret;\n\n  *value = req.value;\n\n  return 0;\n}\n\nvoid gpuinfo_panfrost_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_mali *gpu_info = container_of(_gpu_info, struct gpu_info_mali, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n\n  static_info->integrated_graphics = true;\n  static_info->encode_decode_shared = true;\n  RESET_ALL(static_info->valid);\n\n  uint64_t gpuid;\n  if (gpuinfo_panfrost_query_param(gpu_info->fd, DRM_PANFROST_PARAM_GPU_PROD_ID, &gpuid) == 0) {\n    const char* name = panfrost_parse_marketing_name(gpuid);\n    if (name) {\n      strncpy(static_info->device_name, name, sizeof(static_info->device_name));\n    }\n    else {\n      snprintf(static_info->device_name, sizeof(static_info->device_name), \"Unknown Mali %lx\", gpuid);\n    }\n    SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n  }\n\n  uint64_t shader;\n  if (gpuinfo_panfrost_query_param(gpu_info->fd, DRM_PANFROST_PARAM_SHADER_PRESENT, &shader) == 0)\n    SET_GPUINFO_STATIC(static_info, n_shared_cores, util_last_bit(shader));\n\n  uint64_t l2_cache_features;\n  if (gpuinfo_panfrost_query_param(gpu_info->fd, DRM_PANFROST_PARAM_L2_FEATURES, &l2_cache_features) == 0)\n    SET_GPUINFO_STATIC(static_info, l2cache_size, l2_cache_features & (0xFF << 16));\n\n  if (GPUINFO_STATIC_FIELD_VALID(static_info, n_shared_cores)) {\n    uint64_t core_features, thread_features;\n    if (gpuinfo_panfrost_query_param(gpu_info->fd, DRM_PANFROST_PARAM_CORE_FEATURES, &core_features) != 0)\n      return;\n    if (gpuinfo_panfrost_query_param(gpu_info->fd, DRM_PANFROST_PARAM_THREAD_FEATURES, &thread_features) != 0)\n      return;\n\n    SET_GPUINFO_STATIC(static_info, n_exec_engines,\n\t\t       get_number_engines(gpuid, static_info->n_shared_cores,\n\t\t\t\t\t  core_features, thread_features));\n  }\n}\n\nvoid gpuinfo_panfrost_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  static const char *meminfo_total = \"MemTotal\";\n  static const char *meminfo_available = \"MemAvailable\";\n\n  struct gpu_info_mali *gpu_info = container_of(_gpu_info, struct gpu_info_mali, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  if (gpu_info->version != MALI_PANFROST) {\n    fprintf(stderr, \"Wrong device version: %u\\n\", gpu_info->version);\n    abort();\n  }\n\n  mali_common_refresh_dynamic_info(dynamic_info, &mali_state, meminfo_total, meminfo_available);\n}\n\nvoid gpuinfo_panfrost_get_running_processes(struct gpu_info *_gpu_info) {\n  mali_common_get_running_processes(_gpu_info, MALI_PANFROST);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_panfrost_utils.c",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <unistd.h>\n#include \"nvtop/interface_internal_common.h\"\n#include \"panfrost_utils.h\"\n\nstruct panfrost_model {\n\tconst char *name;\n\tunsigned int id;\n\tunsigned int (*nengines) (int32_t core_count, uint32_t core_features, uint32_t thread_features);\n};\n\nstatic uint32_t get_num_eng_g52(int core_count,\n\t\t\t\tuint32_t core_features,\n\t\t\t\tuint32_t thread_features)\n{\n  (void) core_count;\n  (void) thread_features;\n  return core_features & 0xF;\n}\n\n#define GPU_MODEL(_name, _id, _nengines)\t\\\n{\t\t\t\t\t\t\\\n\t.name = #_name,\t\t\t\t\\\n\t.id = _id,\t\t\t\t\\\n\t.nengines = _nengines,\t\t\t\\\n}\n\nstatic const struct panfrost_model gpu_models[] = {\n  GPU_MODEL(t600, 0x600, NULL),\n  GPU_MODEL(t620, 0x620, NULL),\n  GPU_MODEL(t720, 0x720, NULL),\n  GPU_MODEL(t760, 0x750, NULL),\n  GPU_MODEL(t820, 0x820, NULL),\n  GPU_MODEL(t830, 0x830, NULL),\n  GPU_MODEL(t860, 0x860, NULL),\n  GPU_MODEL(t880, 0x880, NULL),\n  GPU_MODEL(g71, 0x6000, NULL),\n  GPU_MODEL(g72, 0x6001, NULL),\n  GPU_MODEL(g51, 0x7000, NULL),\n  GPU_MODEL(g76, 0x7001, NULL),\n  GPU_MODEL(g52, 0x7002, get_num_eng_g52),\n  GPU_MODEL(g31, 0x7003, NULL),\n  GPU_MODEL(g57, 0x9001, NULL),\n  GPU_MODEL(g57, 0x9003, NULL),\n};\n\nstatic inline int panfrost_model_cmp(unsigned int match, unsigned int id)\n{\n  if (match & 0xf000)\n    match &= 0xf00f;\n  return match - id;\n}\n\nconst char * panfrost_parse_marketing_name(uint64_t gpu_id)\n{\n  for (unsigned i = 0; i < ARRAY_SIZE(gpu_models); i++) {\n    if (!panfrost_model_cmp(gpu_id, gpu_models[i].id)) {\n      return gpu_models[i].name;\n    }\n  }\n  return NULL;\n}\n\nunsigned int get_number_engines(uint32_t gpu_id,\n\t\t\t\tint core_count,\n\t\t\t\tuint32_t core_features,\n\t\t\t\tuint32_t thread_features)\n{\n  for (unsigned i = 0; i < ARRAY_SIZE(gpu_models); i++) {\n    if (!panfrost_model_cmp(gpu_id, gpu_models[i].id)) {\n      if (gpu_models[i].nengines)\n\treturn gpu_models[i].nengines(core_count, core_features, thread_features);\n      else\n\treturn 0;\n    }\n  }\n  return 0;\n}\n\nunsigned int util_last_bit(unsigned int u)\n{\n#if defined(HAVE___BUILTIN_CLZ)\n   return u == 0 ? 0 : 32 - __builtin_clz(u);\n#elif defined(_MSC_VER) && (_M_IX86 || _M_ARM || _M_AMD64 || _M_IA64)\n   unsigned long index;\n   if (_BitScanReverse(&index, u))\n      return index + 1;\n   else\n      return 0;\n#else\n   unsigned r = 0;\n   while (u) {\n      r++;\n      u >>= 1;\n   }\n   return r;\n#endif\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_panthor.c",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * This file is part of Nvtop and adapted from the msm implementation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n#include <xf86drm.h>\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include \"panthor_drm.h\"\n#include \"panthor_utils.h\"\n#include \"mali_common.h\"\n\nstatic bool gpuinfo_panthor_init(void);\nstatic void gpuinfo_panthor_shutdown(void);\nstatic const char *gpuinfo_panthor_last_error_string(void);\nstatic bool gpuinfo_panthor_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_panthor_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_panthor_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_panthor_get_running_processes(struct gpu_info *_gpu_info);\n\nstatic struct gpu_vendor gpu_vendor_panthor = {\n    .init = gpuinfo_panthor_init,\n    .shutdown = gpuinfo_panthor_shutdown,\n    .last_error_string = gpuinfo_panthor_last_error_string,\n    .get_device_handles = gpuinfo_panthor_get_device_handles,\n    .populate_static_info = gpuinfo_panthor_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_panthor_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_panthor_get_running_processes,\n    .refresh_utilisation_rate = gpuinfo_refresh_utilisation_rate,\n    .name = \"panthor\",\n};\n\nstatic struct drmFuncTable drmFuncs;\nstatic struct mali_gpu_state mali_state;\n\n__attribute__((constructor)) static void init_extract_gpuinfo_panthor(void) { register_gpu_vendor(&gpu_vendor_panthor); }\n\nbool gpuinfo_panthor_init(void) {\n  return mali_init_drm_funcs(&drmFuncs, &mali_state);\n}\n\nvoid gpuinfo_panthor_shutdown(void) {\n  mali_shutdown_common(&mali_state, &drmFuncs);\n}\n\nstatic const char *gpuinfo_panthor_last_error_string(void) {\n  static char driver_msg[MAX_ERR_STRING_LEN] = {0};\n\n  return mali_common_last_error_string(&mali_state,\n                                       gpu_vendor_panthor.name,\n                                       driver_msg);\n}\n\nstatic void panthor_check_fdinfo_keys (bool *is_engine, bool *is_cycles,\n                                        bool *is_maxfreq, bool *is_curfreq,\n                                        bool *is_resident, char *key)\n{\nstatic const char drm_panthor_engine[] = \"drm-engine-panthor\";\nstatic const char drm_panthor_cycles[] = \"drm-cycles-panthor\";\nstatic const char drm_panthor_maxfreq[] = \"drm-maxfreq-panthor\";\nstatic const char drm_panthor_curfreq[] = \"drm-curfreq-panthor\";\nstatic const char drm_panthor_resident_mem[] = \"drm-resident-memory\";\n\n  *is_engine = !strcmp(key, drm_panthor_engine);\n  *is_cycles = !strcmp(key, drm_panthor_cycles);\n  *is_maxfreq = !strcmp(key, drm_panthor_maxfreq);\n  *is_curfreq = !strcmp(key, drm_panthor_curfreq);\n  *is_resident = !strcmp(key, drm_panthor_resident_mem);\n}\n\nstatic bool parse_drm_fdinfo_panthor(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n\n  struct gpu_info_mali *gpu_info = container_of(info, struct gpu_info_mali, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n  struct fdinfo_data res = {0};\n\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n\n  if (!mali_common_parse_drm_fdinfo(info, fdinfo_file, process_info, dynamic_info,\n                                    panthor_check_fdinfo_keys, &res))\n    return false;\n\n  mali_common_parse_fdinfo_handle_cache(gpu_info, process_info, current_time, res.total_cycles,\n\t\t\t\t\tres.cid, res.engine_count >= 1 ? true : false);\n\n  return true;\n}\n\nstatic bool gpuinfo_panthor_get_device_handles(struct list_head *devices, unsigned *count) {\n        return mali_common_get_device_handles(&mali_state, &drmFuncs, &gpu_vendor_panthor,\n                                              parse_drm_fdinfo_panthor, devices, count,\n                                              NULL, MALI_PANTHOR);\n}\n\nvoid gpuinfo_panthor_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_mali *gpu_info = container_of(_gpu_info, struct gpu_info_mali, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n\n  if (gpu_info->version != MALI_PANTHOR) {\n    fprintf(stderr, \"Wrong device version: %u\\n\", gpu_info->version);\n    abort();\n  }\n\n  static_info->integrated_graphics = true;\n  static_info->encode_decode_shared = true;\n  RESET_ALL(static_info->valid);\n\n  struct drm_panthor_gpu_info gpu_dev_info = {0};\n  struct drm_panthor_dev_query query = {\n      .type = DRM_PANTHOR_DEV_QUERY_GPU_INFO,\n      .size = sizeof(gpu_dev_info),\n      .pointer = (uint64_t)(uintptr_t)&gpu_dev_info,\n   };\n\n  int ret = drmFuncs.drmIoctl(gpu_info->fd, DRM_IOCTL_PANTHOR_DEV_QUERY, &query);\n  if (ret) {\n          fprintf(stderr, \"Failed to query Panthor GPU device properties\\n\");\n          snprintf(static_info->device_name, sizeof(static_info->device_name),\n                   \"Unknown Panthor %x\", gpu_dev_info.gpu_id);\n          SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n          return;\n   }\n\n   const char *name = panthor_device_name(gpu_dev_info.gpu_id);\n   if (name)\n           strncpy(static_info->device_name, name, sizeof(static_info->device_name));\n   else\n           snprintf(static_info->device_name, sizeof(static_info->device_name),\n                    \"Unknown Panthor %x\", gpu_dev_info.gpu_id);\n\n   SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n}\n\nvoid gpuinfo_panthor_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  static const char *meminfo_total = \"MemTotal\";\n  static const char *meminfo_available = \"MemAvailable\";\n\n  struct gpu_info_mali *gpu_info = container_of(_gpu_info, struct gpu_info_mali, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  if (gpu_info->version != MALI_PANTHOR) {\n    fprintf(stderr, \"Wrong device version: %u\\n\", gpu_info->version);\n    abort();\n  }\n\n  mali_common_refresh_dynamic_info(dynamic_info, &mali_state, meminfo_total, meminfo_available);\n}\n\nvoid gpuinfo_panthor_get_running_processes(struct gpu_info *_gpu_info) {\n  mali_common_get_running_processes(_gpu_info, MALI_PANTHOR);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_panthor_utils.c",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <unistd.h>\n#include \"nvtop/interface_internal_common.h\"\n#include \"panthor_utils.h\"\n\n/**\n * struct panthor_model - GPU model description\n */\nstruct panthor_model {\n  /** @name: Model name. */\n  const char *name;\n\n  /** @arch_major: Major version number of architecture */\n  uint8_t arch_major;\n\n  /* @product_major: Major version number of product */\n  uint8_t product_major;\n};\n\n/**\n * GPU_MODEL() - Define a GPU model. A GPU product can be uniquely identified\n * by a combination of the major architecture version and the major product\n * version.\n */\n#define GPU_MODEL(_name, _arch_major, _product_major)\t\\\n  {\t\t\t\t\t\t\t\\\n    .name = #_name,\t\t\t\t\t\\\n      .arch_major = _arch_major,\t\t\t\\\n      .product_major = _product_major,\t\t\t\\\n      }\n\nstatic const struct panthor_model gpu_models[] = {\n  GPU_MODEL(g610, 10, 7),\n  GPU_MODEL(g310, 10, 4),\n  {0},\n};\n\nconst char * panthor_device_name(uint32_t gpu_id)\n{\n  uint32_t arch_major, product_major;\n  const struct panthor_model *model;\n\n  arch_major = (gpu_id >> 28) & 0xf;\n  product_major = (gpu_id >> 16) & 0xf;\n\n  for (model = gpu_models; model->name; model++) {\n    if (model->arch_major == arch_major &&\n\tmodel->product_major == product_major)\n      return model->name;\n  }\n\n  return NULL;\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_tpu.c",
    "content": "/*\n *\n * Copyright (C) 2025 Robert Dyro <robert.dyro@gmail.com>\n *\n * This file is part of Nvtop\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/time.h\"\n\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n#include <math.h>\n#include <dlfcn.h>\n#include <sys/time.h>\n\nstruct gpu_info_tpu {\n  struct gpu_info base;\n  int device_id;\n};\n\nstruct tpu_chip_usage_data {\n  char name[8];\n  int64_t device_id;\n  int64_t memory_usage;\n  int64_t total_memory;\n  double duty_cycle_pct;\n  int64_t pid;\n};\n\nstatic bool gpuinfo_tpu_init(void);\nstatic void gpuinfo_tpu_shutdown(void);\nstatic const char *gpuinfo_tpu_last_error_string(void);\nstatic bool gpuinfo_tpu_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_tpu_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_tpu_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_tpu_get_running_processes(struct gpu_info *_gpu_info);\nstatic bool is_cache_valid(void);\nstatic bool refresh_tpu_cache(void);\nstatic void reset_tpu_cache(bool);\nstatic void free_ptr(void **ptr);\n\nstruct gpu_vendor gpu_vendor_tpu = {\n    .init = gpuinfo_tpu_init,\n    .shutdown = gpuinfo_tpu_shutdown,\n    .last_error_string = gpuinfo_tpu_last_error_string,\n    .get_device_handles = gpuinfo_tpu_get_device_handles,\n    .populate_static_info = gpuinfo_tpu_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_tpu_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_tpu_get_running_processes,\n    .name = \"TPU\",\n};\n\n__attribute__((constructor)) static void init_extract_gpuinfo_tpu(void) { \n  register_gpu_vendor(&gpu_vendor_tpu);\n}\n\nint64_t tpu_chip_count = -1;\nstatic struct gpu_info_tpu *gpu_infos;\n\n#define STRINGIFY(x) STRINGIFY_HELPER_(x)\n#define STRINGIFY_HELPER_(x) #x\n\n#define VENDOR_TPU 0x1ae0\n#define VENDOR_TPU_STR STRINGIFY(VENDOR_TPU)\n\n#define MAX(x, y) ((x >= y) ? (x) : (y))\n#define MIN(x, y) ((x <= y) ? (x) : (y))\n\n#define int64 long long\n\nint (*_tpu_chip_count)(void);\nint (*_tpu_metrics)(int port, int64 *device_ids, int64 *memory_usage, \n                    int64 *total_memory, double *duty_cycle_pct, int n);\nint (*_tpu_pids)(int64 *pids, int n);\n\nchar *libname = \"libtpuinfo.so\";\n// -1 means allowing libtpuinfo to select the default port\n// env LIBTPUINFO_GRPC_PORT={int} allows setting the port via an environment variable\n// $ env LIBTPUINFO_GRPC_PORT=8431 nvtop\nint tpu_runtime_monitoring_port = -1;  \n\n/* TPU info cache ------------------------------------------------------------------------------- */\nstruct tpu_chip_usage_data *latest_chips_usage_data = NULL;\nnvtop_time last_cache_refresh;\nint64 *_pids, *_device_ids, *_memory_usage, *_total_memory;\ndouble* _duty_cycle_pct;\n\nbool is_cache_valid(void) {\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n  uint64_t t_diff_ns = nvtop_difftime_u64(last_cache_refresh, current_time);\n  return t_diff_ns < 900 * 1000 * 1000; // 900ms\n}\n\nbool refresh_tpu_cache(void) {\n  if (is_cache_valid()) return true;\n  nvtop_get_current_time(&last_cache_refresh);\n  if (tpu_chip_count <= 0) return false;\n  if (_tpu_pids(_pids, tpu_chip_count) != 0) {\n    reset_tpu_cache(false);\n    return false;\n  }\n  for (int64_t i = 0; i < tpu_chip_count; i++) latest_chips_usage_data[i].pid = _pids[i];\n\n  if (_tpu_metrics(tpu_runtime_monitoring_port, _device_ids, _memory_usage, _total_memory,\n                   _duty_cycle_pct, tpu_chip_count) != 0) return false;\n  for (int64_t i = 0; i < tpu_chip_count; i++) {\n    latest_chips_usage_data[i].device_id = _device_ids[i];\n    latest_chips_usage_data[i].memory_usage = _memory_usage[i];\n    latest_chips_usage_data[i].total_memory = _total_memory[i];\n    latest_chips_usage_data[i].duty_cycle_pct = _duty_cycle_pct[i];\n  }\n  return true;\n}\n\nvoid reset_tpu_cache(bool fully) {\n  for (int64_t i = 0; i < tpu_chip_count; i++) {\n    latest_chips_usage_data[i].memory_usage = 0;\n    latest_chips_usage_data[i].duty_cycle_pct = 0;\n    latest_chips_usage_data[i].pid = -1;\n    if (fully) {\n      snprintf(latest_chips_usage_data[i].name, sizeof(latest_chips_usage_data[i].name), \"%s\", \"N/A\");\n      latest_chips_usage_data[i].device_id = 0;\n      latest_chips_usage_data[i].total_memory = 0;\n    }\n  }\n}\n/* TPU info cache ------------------------------------------------------------------------------- */\n\nbool gpuinfo_tpu_init(void) {\n  char* error_msg;\n  nvtop_get_current_time(&last_cache_refresh);\n  // invalidate cache by putting it in the past\n  last_cache_refresh = nvtop_substract_time(last_cache_refresh, (nvtop_time){10, 0}); \n\n  // Load dynamic library symbols\n  void *handle = dlopen(libname, RTLD_LAZY);\n  if (!handle) {\n      error_msg = dlerror();\n#ifndef NDEBUG\n      if (error_msg != NULL) fprintf(stderr, \"TPU support error: %s\\n\", error_msg);\n#endif\n      return false;\n  }\n\n  // Resolve the necessary symbols within the library\n  _tpu_chip_count = dlsym(handle, \"tpu_chip_count\");\n  error_msg = dlerror();\n  if (error_msg != NULL) {\n#ifndef NDEBUG\n      fprintf(stderr, \"libtpuinfo can't resolve symbol `tpu_chip_count` with error: %s\\n\", error_msg);\n#endif\n      return false;\n  }\n  _tpu_pids = dlsym(handle, \"tpu_pids\");\n  error_msg = dlerror();\n  if (error_msg != NULL) {\n#ifndef NDEBUG\n      fprintf(stderr, \"libtpuinfo can't resolve symbol `tpu_pids` with error: %s\\n\", error_msg);\n#endif\n      return false;\n  }\n  _tpu_metrics = dlsym(handle, \"tpu_metrics\");\n  error_msg = dlerror();\n  if (error_msg != NULL) {\n#ifndef NDEBUG\n      fprintf(stderr, \"libtpuinfo can't resolve symbol `tpu_metrics` with error: %s\\n\", error_msg);\n#endif\n      return false;\n  }\n\n  // Discover TPU devices\n  tpu_chip_count = _tpu_chip_count();\n  if (tpu_chip_count == 0) {\n#ifndef NDEBUG\n    fprintf(stderr, \"Found 0 TPU devices on the system.\\n\");\n#endif\n    return false;\n  }\n\n  // Allocate memory for TPU device data cache\n  latest_chips_usage_data = (struct tpu_chip_usage_data*)malloc(tpu_chip_count*sizeof(struct tpu_chip_usage_data));\n  _pids = (int64*)malloc(sizeof(int64) * tpu_chip_count);\n  _device_ids = (int64*)malloc(sizeof(int64) * tpu_chip_count);\n  _memory_usage = (int64*)malloc(sizeof(int64) * tpu_chip_count);\n  _total_memory = (int64*)malloc(sizeof(int64) * tpu_chip_count);\n  _duty_cycle_pct = (double*)malloc(sizeof(double) * tpu_chip_count);\n  reset_tpu_cache(true);\n  return true;\n}\n\nvoid free_ptr(void **ptr) {\n  if (ptr != NULL && *ptr != NULL) {\n    free(*ptr);\n    *ptr = NULL;\n  }\n}\n\nvoid gpuinfo_tpu_shutdown(void) {\n  free_ptr((void **)&gpu_infos);\n  free_ptr((void **)&latest_chips_usage_data);\n  free_ptr((void **)&_pids);\n  free_ptr((void **)&_device_ids);\n  free_ptr((void **)&_memory_usage);\n  free_ptr((void **)&_total_memory);\n  free_ptr((void **)&_duty_cycle_pct);\n  tpu_chip_count = -1;\n}\n\nconst char *gpuinfo_tpu_last_error_string(void) { return \"Err\"; }\n\nstatic void add_tpu_chip(struct list_head *devices, unsigned *count) {\n  struct gpu_info_tpu *this_tpu = &gpu_infos[*count];\n  this_tpu->base.vendor = &gpu_vendor_tpu;\n  this_tpu->device_id = *count;\n  snprintf(this_tpu->base.pdev, PDEV_LEN, \"TPU%u\", *count);\n  list_add_tail(&this_tpu->base.list, devices);\n\n  this_tpu->base.processes_count = 0;\n  this_tpu->base.processes = NULL;\n  this_tpu->base.processes_array_size = 0;\n\n  *count = *count + 1;\n}\n\nbool gpuinfo_tpu_get_device_handles(struct list_head *devices_list, unsigned *count) {\n  *count = 0;\n  if (tpu_chip_count <= 0) return false;\n  gpu_infos = (struct gpu_info_tpu *)calloc(tpu_chip_count, sizeof(*gpu_infos));\n  if (!gpu_infos) return false;\n  for (int64_t i = 0; i < tpu_chip_count; i++) add_tpu_chip(devices_list, count);\n  return true;\n}\n\nvoid gpuinfo_tpu_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_tpu *gpu_info = container_of(_gpu_info, struct gpu_info_tpu, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  static_info->integrated_graphics = false;\n  static_info->encode_decode_shared = false;\n  RESET_ALL(static_info->valid);\n  snprintf(static_info->device_name, MIN(sizeof(static_info->device_name), PDEV_LEN), \"%s\", gpu_info->base.pdev);\n  SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n}\n\nvoid gpuinfo_tpu_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_tpu *gpu_info = container_of(_gpu_info, struct gpu_info_tpu, base);\n  // struct gpuinfo_static_info *static_info = &gpu_info->base.static_info; // unused\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  refresh_tpu_cache();\n\n  if (gpu_info->device_id >= tpu_chip_count) return;\n  struct tpu_chip_usage_data usage_data = latest_chips_usage_data[gpu_info->device_id];\n  double mem_util = round(1e2 * (double)(usage_data.memory_usage) / (double)MAX(1, usage_data.total_memory));\n  double tpu_util = round(usage_data.duty_cycle_pct);\n  SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, (int)tpu_util);\n  SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, (int)mem_util);\n  SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, usage_data.total_memory);\n  SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, usage_data.memory_usage);\n  SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, usage_data.total_memory - usage_data.memory_usage);\n\n  return;\n}\n\nvoid gpuinfo_tpu_get_running_processes(struct gpu_info *_gpu_info) {\n  struct gpu_info_tpu *gpu_info = container_of(_gpu_info, struct gpu_info_tpu, base);\n  if (gpu_info->device_id >= tpu_chip_count) return;\n  if (tpu_chip_count <= 0 || latest_chips_usage_data[gpu_info->device_id].pid < 0) {\n    _gpu_info->processes_count = 0;\n    return;\n  }\n  _gpu_info->processes_count = 1;\n  if (_gpu_info->processes_array_size == 0) {\n    _gpu_info->processes_array_size = 1;\n    _gpu_info->processes = (struct gpu_process*)malloc(1 * sizeof(struct gpu_process));\n    memset(_gpu_info->processes, 0, _gpu_info->processes_count * sizeof(*_gpu_info->processes));\n  }\n  _gpu_info->processes[0].type = gpu_process_compute;\n  _gpu_info->processes[0].pid = latest_chips_usage_data[gpu_info->device_id].pid;\n  _gpu_info->processes[0].gpu_memory_usage = _gpu_info->dynamic_info.used_memory;\n\n  SET_VALID(gpuinfo_process_gpu_memory_usage_valid, _gpu_info->processes[0].valid);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_v3d.c",
    "content": "/*\n *\n * Copyright (C) 2022 Hoream Xiao <horeamx@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <uthash.h>\n\nint mbox_open(void);\nvoid mbox_close(int mb);\nvoid set_debug_files(int card_id);\nvoid set_gpuinfo_from_vcio(struct gpuinfo_dynamic_info *dynamic_info, int mb);\nvoid set_memory_gpuinfo(struct gpuinfo_dynamic_info *dynamic_info);\nvoid set_init_max_memory(int mb);\n\n#define HASH_FIND_CLIENT(head, key_ptr, out_ptr) HASH_FIND(hh, head, key_ptr, sizeof(struct unique_cache_id), out_ptr)\n#define HASH_ADD_CLIENT(head, in_ptr) HASH_ADD(hh, head, client_id, sizeof(struct unique_cache_id), in_ptr)\n\n#define SET_V3D_CACHE(cachePtr, field, value) SET_VALUE(cachePtr, field, value, v3d_cache_)\n#define RESET_V3D_CACHE(cachePtr, field) INVALIDATE_VALUE(cachePtr, field, v3d_cache_)\n#define V3D_CACHE_FIELD_VALID(cachePtr, field) VALUE_IS_VALID(cachePtr, field, v3d_cache_)\n\nenum v3d_process_info_cache_valid { v3d_cache_engine_render_valid = 0, v3d_cache_process_info_cache_valid_count };\n\nstruct __attribute__((__packed__)) unique_cache_id {\n  unsigned client_id;\n  pid_t pid;\n};\n\nstruct v3d_process_info_cache {\n  struct unique_cache_id client_id;\n  uint64_t engine_render;\n  nvtop_time last_measurement_tstamp;\n  unsigned char valid[(v3d_cache_process_info_cache_valid_count + CHAR_BIT - 1) / CHAR_BIT];\n  UT_hash_handle hh;\n};\n\nstruct gpu_info_v3d {\n  struct gpu_info base;\n  int mb;\n  int card_id;\n\n  struct nvtop_device *card_device;\n  struct nvtop_device *driver_device;\n  struct v3d_process_info_cache *last_update_process_cache, *current_update_process_cache; // Cached processes info\n};\n\nstatic bool gpuinfo_v3d_init(void);\nstatic void gpuinfo_v3d_shutdown(void);\nstatic const char *gpuinfo_v3d_last_error_string(void);\nstatic bool gpuinfo_v3d_get_device_handles(struct list_head *devices, unsigned *count);\nstatic void gpuinfo_v3d_populate_static_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_v3d_refresh_dynamic_info(struct gpu_info *_gpu_info);\nstatic void gpuinfo_v3d_get_running_processes(struct gpu_info *_gpu_info);\n\nstruct gpu_vendor gpu_vendor_v3d = {\n    .init = gpuinfo_v3d_init,\n    .shutdown = gpuinfo_v3d_shutdown,\n    .last_error_string = gpuinfo_v3d_last_error_string,\n    .get_device_handles = gpuinfo_v3d_get_device_handles,\n    .populate_static_info = gpuinfo_v3d_populate_static_info,\n    .refresh_dynamic_info = gpuinfo_v3d_refresh_dynamic_info,\n    .refresh_running_processes = gpuinfo_v3d_get_running_processes,\n    .name = \"v3d\",\n};\n\nunsigned v3d_gpu_count;\nstatic struct gpu_info_v3d *gpu_infos;\n\n__attribute__((constructor)) static void init_extract_gpuinfo_v3d(void) { register_gpu_vendor(&gpu_vendor_v3d); }\n\nbool gpuinfo_v3d_init(void) { return true; }\nvoid gpuinfo_v3d_shutdown(void) {\n  for (unsigned i = 0; i < v3d_gpu_count; ++i) {\n    struct gpu_info_v3d *current = &gpu_infos[i];\n    nvtop_device_unref(current->card_device);\n    nvtop_device_unref(current->driver_device);\n    if (current->mb >= 0)\n      mbox_close(current->mb);\n  }\n}\n\nconst char *gpuinfo_v3d_last_error_string(void) { return \"Err\"; }\nstatic const char v3d_drm_engine_render[] = \"drm-engine-render\";\nstatic const char v3d_drm_total_memory[] = \"drm-total-memory\";\n\nstatic bool parse_drm_fdinfo_v3d(struct gpu_info *info, FILE *fdinfo_file, struct gpu_process *process_info) {\n  struct gpu_info_v3d *gpu_info = container_of(info, struct gpu_info_v3d, base);\n\n  static char *line = NULL;\n  static size_t line_buf_size = 0;\n  ssize_t count = 0;\n\n  bool client_id_set = false;\n  unsigned cid;\n  nvtop_time current_time;\n  nvtop_get_current_time(&current_time);\n\n  while ((count = getline(&line, &line_buf_size, fdinfo_file)) != -1) {\n    char *key, *val;\n    // Get rid of the newline if present\n    if (line[count - 1] == '\\n') {\n      line[--count] = '\\0';\n    }\n\n    if (!extract_drm_fdinfo_key_value(line, &key, &val))\n      continue;\n\n    if (!strcmp(key, drm_client_id)) {\n      char *endptr;\n      cid = strtoul(val, &endptr, 10);\n      if (*endptr)\n        continue;\n      client_id_set = true;\n    } else if (!strcmp(key, v3d_drm_total_memory)) {\n      unsigned long mem_int;\n      char *endptr;\n      mem_int = strtoul(val, &endptr, 10);\n      if (endptr == val || (strcmp(endptr, \" kB\") && strcmp(endptr, \" KiB\")))\n        continue;\n      SET_GPUINFO_PROCESS(process_info, gpu_memory_usage, mem_int * 1024);\n    } else if (!strcmp(key, v3d_drm_engine_render)) {\n      char *endptr;\n      uint64_t time_spent = strtoull(val, &endptr, 10);\n      if (endptr == val || strcmp(endptr, \" ns\"))\n        continue;\n      SET_GPUINFO_PROCESS(process_info, gfx_engine_used, time_spent);\n    }\n  }\n\n  if (!client_id_set)\n    return false;\n\n  process_info->type |= gpu_process_graphical;\n\n  struct unique_cache_id ucid = {.client_id = cid, .pid = process_info->pid};\n  struct v3d_process_info_cache *cache_entry;\n  HASH_FIND_CLIENT(gpu_info->last_update_process_cache, &ucid, cache_entry);\n  if (cache_entry) {\n    uint64_t time_elapsed = nvtop_difftime_u64(cache_entry->last_measurement_tstamp, current_time);\n    HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n    if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used) &&\n        V3D_CACHE_FIELD_VALID(cache_entry, engine_render) &&\n        process_info->gfx_engine_used >= cache_entry->engine_render &&\n        process_info->gfx_engine_used - cache_entry->engine_render <= time_elapsed) {\n      SET_GPUINFO_PROCESS(\n          process_info, gpu_usage,\n          busy_usage_from_time_usage_round(process_info->gfx_engine_used, cache_entry->engine_render, time_elapsed));\n    }\n  } else {\n    cache_entry = calloc(1, sizeof(*cache_entry));\n    if (!cache_entry)\n      goto parse_fdinfo_exit;\n    cache_entry->client_id.client_id = cid;\n    cache_entry->client_id.pid = process_info->pid;\n  }\n\n  RESET_ALL(cache_entry->valid);\n  if (GPUINFO_PROCESS_FIELD_VALID(process_info, gfx_engine_used))\n    SET_V3D_CACHE(cache_entry, engine_render, process_info->gfx_engine_used);\n\n  cache_entry->last_measurement_tstamp = current_time;\n  HASH_ADD_CLIENT(gpu_info->current_update_process_cache, cache_entry);\n\nparse_fdinfo_exit:\n  return true;\n}\n\nstatic void add_v3d_cards(struct nvtop_device *dev, const char *devname, struct list_head *devices, unsigned *count) {\n  struct nvtop_device *parent;\n  if (nvtop_device_get_parent(dev, &parent) < 0)\n    return;\n\n  const char *driver;\n  nvtop_device_get_driver(parent, &driver);\n  if (strcmp(driver, \"v3d\"))\n    return;\n\n  struct gpu_info_v3d *thisGPU = &gpu_infos[v3d_gpu_count++];\n  thisGPU->base.vendor = &gpu_vendor_v3d;\n  thisGPU->card_device = nvtop_device_ref(dev);\n  thisGPU->driver_device = nvtop_device_ref(parent);\n  list_add_tail(&thisGPU->base.list, devices);\n  // Register a fdinfo callback for this GPU\n  processinfo_register_fdinfo_callback(parse_drm_fdinfo_v3d, &thisGPU->base);\n  thisGPU->mb = mbox_open();\n  if (sscanf(devname, \"/dev/dri/card%d\", &thisGPU->card_id) != 1)\n    thisGPU->card_id = 0;\n  set_debug_files(thisGPU->card_id);\n\n  (*count)++;\n}\n\nbool gpuinfo_v3d_get_device_handles(struct list_head *devices_list, unsigned *count) {\n  *count = 0;\n  nvtop_device_enumerator *enumerator;\n  if (nvtop_enumerator_new(&enumerator) < 0)\n    return false;\n\n  if (nvtop_device_enumerator_add_match_subsystem(enumerator, \"drm\", true) < 0)\n    return false;\n\n  if (nvtop_device_enumerator_add_match_property(enumerator, \"DEVNAME\", \"/dev/dri/*\") < 0)\n    return false;\n\n  unsigned num_devices = 0;\n  for (nvtop_device *device = nvtop_enumerator_get_device_first(enumerator); device;\n       device = nvtop_enumerator_get_device_next(enumerator)) {\n    num_devices++;\n  }\n\n  gpu_infos = calloc(num_devices, sizeof(*gpu_infos));\n  if (!gpu_infos)\n    return false;\n\n  for (nvtop_device *device = nvtop_enumerator_get_device_first(enumerator); device;\n       device = nvtop_enumerator_get_device_next(enumerator)) {\n    num_devices++;\n    const char *devname;\n    if (nvtop_device_get_devname(device, &devname) < 0)\n      continue;\n    if (strstr(devname, \"/dev/dri/card\")) {\n      add_v3d_cards(device, devname, devices_list, count);\n    }\n  }\n\n  nvtop_enumerator_unref(enumerator);\n  return true;\n}\n\nvoid gpuinfo_v3d_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_v3d *gpu_info = container_of(_gpu_info, struct gpu_info_v3d, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n  const char *dev_name = \"VIDEO CORE\";\n\n  static_info->integrated_graphics = true;\n  static_info->encode_decode_shared = false;\n  RESET_ALL(static_info->valid);\n\n  snprintf(static_info->device_name, sizeof(static_info->device_name), \"%s\", dev_name);\n  SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n  if (gpu_info->mb >= 0)\n    set_init_max_memory(gpu_info->mb);\n}\n\nvoid gpuinfo_v3d_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_v3d *gpu_info = container_of(_gpu_info, struct gpu_info_v3d, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  RESET_ALL(dynamic_info->valid);\n\n  nvtop_device *card_dev_copy;\n  const char *syspath;\n  nvtop_device_get_syspath(gpu_info->card_device, &syspath);\n  nvtop_device_new_from_syspath(&card_dev_copy, syspath);\n\n  set_memory_gpuinfo(dynamic_info);\n  if (gpu_info->mb >= 0)\n    set_gpuinfo_from_vcio(dynamic_info, gpu_info->mb);\n  nvtop_device_unref(card_dev_copy);\n}\n\nstatic void swap_process_cache_for_next_update(struct gpu_info_v3d *gpu_info) {\n  // Free old cache data and set the cache for the next update\n  if (gpu_info->last_update_process_cache) {\n    struct v3d_process_info_cache *cache_entry, *tmp;\n    HASH_ITER(hh, gpu_info->last_update_process_cache, cache_entry, tmp) {\n      HASH_DEL(gpu_info->last_update_process_cache, cache_entry);\n      free(cache_entry);\n    }\n  }\n  gpu_info->last_update_process_cache = gpu_info->current_update_process_cache;\n  gpu_info->current_update_process_cache = NULL;\n}\n\nvoid gpuinfo_v3d_get_running_processes(struct gpu_info *_gpu_info) {\n  // For v3d, we register a fdinfo callback that will fill the gpu_process datastructure of the gpu_info structure\n  // for us. This avoids going through /proc multiple times per update for multiple GPUs.\n  struct gpu_info_v3d *gpu_info = container_of(_gpu_info, struct gpu_info_v3d, base);\n  swap_process_cache_for_next_update(gpu_info);\n}\n"
  },
  {
    "path": "src/extract_gpuinfo_v3d_utils.c",
    "content": "/*\n *\n * Copyright (C) 2022 Hoream Xiao <horeamx@gmail.com>\n *\n * This file is part of Nvtop and adapted from the vcgencmd implementation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include <dirent.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <sys/types.h>\n#include <unistd.h>\n\n/*\n * use ioctl to send mbox property message\n */\n#define DEVICE_FILE_NAME \"/dev/vcio\"\n#define MAJOR_NUM 100\n#define IOCTL_MBOX_PROPERTY _IOWR(MAJOR_NUM, 0, char *)\n#define MAX_STRING 1024\n#define GET_GENCMD_RESULT 0x00030080\n#define MAX_DECODER_FREQUENCE 550006336\n\nint mbox_open(void);\nvoid mbox_close(int mb);\nvoid set_debug_files(int card_id);\nvoid set_gpuinfo_from_vcio(struct gpuinfo_dynamic_info *dynamic_info, int mb);\nvoid set_memory_gpuinfo(struct gpuinfo_dynamic_info *dynamic_info);\nvoid set_init_max_memory(int mb);\n\nstatic uint64_t max_gpu_memory_bytes = 128 << 20;\n\nstatic const char measure_temp[] = \"measure_temp\";\nstatic const char measure_clock_v3d[] = \"measure_clock v3d\";\nstatic const char measure_clock_h264[] = \"measure_clock h264\";\nstatic const char get_mem_gpu[] = \"get_mem gpu\";\n\nstatic char bo_stats_file[50];\n\nvoid set_debug_files(int card_id) {\n  snprintf(bo_stats_file, sizeof(bo_stats_file), \"/sys/kernel/debug/dri/%d/bo_stats\", card_id);\n  if (access(bo_stats_file, F_OK))\n    printf(\"%s is not available.\\n\", bo_stats_file);\n}\n\nstatic int mbox_property(int mb, void *buf) {\n  int ret_val = ioctl(mb, IOCTL_MBOX_PROPERTY, buf);\n\n  if (ret_val < 0) {\n    printf(\"ioctl_set_msg failed:%d\\n\", ret_val);\n  }\n  return ret_val;\n}\n\nint mbox_open(void) {\n  int mb;\n\n  // open a char device file used for communicating with kernel mbox driver\n  mb = open(DEVICE_FILE_NAME, 0);\n  if (mb < 0) {\n    printf(\"Can't open device file: %s\\n\", DEVICE_FILE_NAME);\n    printf(\"Try creating a device file with: sudo mknod %s c %d 0\\n\", DEVICE_FILE_NAME, MAJOR_NUM);\n  }\n  return mb;\n}\n\nvoid mbox_close(int mb) { close(mb); }\n\nstatic unsigned gencmd(int mb, const char *command, char *result, int result_len) {\n  int i = 0;\n  unsigned p[(MAX_STRING >> 2) + 7];\n  int len = strlen(command);\n  // maximum length for command or response\n  if (len + 1 >= MAX_STRING) {\n    fprintf(stderr, \"gencmd length too long : %d\\n\", len);\n    return -1;\n  }\n  p[i++] = 0;          // size\n  p[i++] = 0x00000000; // process request\n\n  p[i++] = GET_GENCMD_RESULT; // (the tag id)\n  p[i++] = MAX_STRING;        // buffer_len\n  p[i++] = 0;                 // request_len (set to response length)\n  p[i++] = 0;                 // error response\n\n  memcpy(p + i, command, len + 1);\n  i += MAX_STRING >> 2;\n\n  p[i++] = 0x00000000;  // end tag\n  p[0] = i * sizeof *p; // actual size\n\n  mbox_property(mb, p);\n  result[0] = 0;\n\n  size_t available_space = result_len - strlen(result) - 1;\n  strncat(result, (const char *)(p + 6), available_space);\n\n  return p[5];\n}\n\nvoid set_init_max_memory(int mb) {\n  char result[MAX_STRING] = {};\n\n  int ret = gencmd(mb, get_mem_gpu, result, sizeof result);\n  if (!ret) {\n    if (sscanf(result, \"gpu=%luM\", &max_gpu_memory_bytes) == 1) {\n      max_gpu_memory_bytes <<= 20;\n    }\n  }\n}\n\nstatic unsigned cal_percentage_usage(unsigned usage, unsigned all) { return (unsigned)(100.0 * usage / all + 0.5); }\n\nstatic void set_gpuinfo_decode(struct gpuinfo_dynamic_info *dynamic_info, int mb) {\n  unsigned int decode_usage = 0;\n  char result[MAX_STRING] = {};\n\n  int ret = gencmd(mb, measure_clock_h264, result, sizeof result);\n  if (!ret) {\n    if (sscanf(result, \"frequency(28)=%u\", &decode_usage) == 1)\n      // divide current frequency by max frequency; usage rate might not be accurate.\n      SET_GPUINFO_DYNAMIC(dynamic_info, decoder_rate, cal_percentage_usage(decode_usage, MAX_DECODER_FREQUENCE));\n  }\n}\n\nstatic void set_gpuinfo_temp(struct gpuinfo_dynamic_info *dynamic_info, int mb) {\n  float temperature = 0;\n  char result[MAX_STRING] = {};\n\n  int ret = gencmd(mb, measure_temp, result, sizeof result);\n  if (!ret) {\n    if (sscanf(result, \"temp=%f'C\", &temperature) == 1) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, gpu_temp, (unsigned)temperature);\n    }\n  }\n}\n\nstatic void set_gpuinfo_clock(struct gpuinfo_dynamic_info *dynamic_info, int mb) {\n  unsigned int clock = 0;\n  char result[MAX_STRING] = {};\n\n  int ret = gencmd(mb, measure_clock_v3d, result, sizeof result);\n  if (!ret) {\n    if (sscanf(result, \"frequency(46)=%u\", &clock) == 1) {\n      SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, clock >> 20);\n    }\n  }\n}\n\nvoid set_gpuinfo_from_vcio(struct gpuinfo_dynamic_info *dynamic_info, int mb) {\n  set_gpuinfo_temp(dynamic_info, mb);\n  set_gpuinfo_clock(dynamic_info, mb);\n  set_gpuinfo_decode(dynamic_info, mb);\n}\n\nvoid set_memory_gpuinfo(struct gpuinfo_dynamic_info *dynamic_info) {\n  FILE *fp = fopen(bo_stats_file, \"rb\");\n  if (fp == NULL) {\n    return;\n  }\n\n  char line[256];\n  uint64_t allocated_bo_size_kb = 0;\n\n  while (fgets(line, sizeof(line), fp)) {\n    if (sscanf(line, \"allocated bo size (kb): %lu\", &allocated_bo_size_kb) == 1) {\n      break;\n    }\n  }\n\n  fclose(fp);\n\n  uint64_t allocated_bo_size_bytes = allocated_bo_size_kb << 10;\n\n  SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, allocated_bo_size_bytes);\n  if (allocated_bo_size_bytes >= max_gpu_memory_bytes)\n    max_gpu_memory_bytes = allocated_bo_size_bytes;\n  SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, max_gpu_memory_bytes);\n  SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate, cal_percentage_usage(allocated_bo_size_bytes, max_gpu_memory_bytes));\n}\n"
  },
  {
    "path": "src/extract_npuinfo_rockchip.c",
    "content": "/*\n *\n * Copyright (C) 2025 YuLong Yao <feilongphone@gmail.com>\n *\n * This file is part of Nvtop and adapted from igt-gpu-tools from Intel Corporation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/time.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <fcntl.h>\n\nstruct gpu_info_rknpu {\n  struct gpu_info base;\n};\n\nstatic struct gpu_info_rknpu *rknpu_info = NULL;\n\nstatic bool gpuinfo_rknpu_init(void) {\n  if (access(\"/sys/kernel/debug/rknpu/load\", R_OK) != 0) {\n    return false;\n  }\n  return true;\n}\n\nstatic void gpuinfo_rknpu_shutdown(void) {\n  if (rknpu_info) {\n    free(rknpu_info);\n    rknpu_info = NULL;\n  }\n}\n\nstatic const char *gpuinfo_rknpu_last_error_string(void) {\n  return \"RK-NPU error\";\n}\n\nstatic void add_rknpu_chip(struct list_head *devices, unsigned *count) {\n  extern struct gpu_vendor gpu_vendor_rknpu;\n  struct gpu_info_rknpu *this_npu = &rknpu_info[*count];\n  this_npu->base.vendor = &gpu_vendor_rknpu;\n  snprintf(this_npu->base.pdev, PDEV_LEN, \"RK-NPU%d\", *count);\n  list_add_tail(&this_npu->base.list, devices);\n\n  this_npu->base.processes_count = 0;\n  this_npu->base.processes = NULL;\n  this_npu->base.processes_array_size = 0;\n\n  *count += 1;\n}\n\nstatic bool gpuinfo_rknpu_get_device_handles(struct list_head *devices_list, unsigned *count) {\n  *count = 0;\n  rknpu_info = calloc(1, sizeof(struct gpu_info_rknpu));\n  if (!rknpu_info) return false;\n  add_rknpu_chip(devices_list, count);\n  return true;\n}\n\nstatic void gpuinfo_rknpu_populate_static_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_rknpu *gpu_info = container_of(_gpu_info, struct gpu_info_rknpu, base);\n  struct gpuinfo_static_info *static_info = &gpu_info->base.static_info;\n\n  static_info->integrated_graphics = true;\n  static_info->encode_decode_shared = false;\n\n  RESET_ALL(static_info->valid);\n  snprintf(static_info->device_name, sizeof(static_info->device_name), \"%s\", gpu_info->base.pdev);\n  SET_VALID(gpuinfo_device_name_valid, static_info->valid);\n}\n\nstatic int read_int_from_file(const char *path) {\n  int value = 0;\n  FILE *fp = fopen(path, \"r\");\n  if (fp) {\n    fscanf(fp, \"%d\", &value);\n    fclose(fp);\n  }\n  return value;\n}\n\nstatic int read_npu_load(const char *file) {\n  FILE *fp = fopen(file, \"r\");\n  if (!fp) return -1;\n\n  char line[256]; int sum = 0, load=0, count = 0;\n  if (fgets(line, sizeof(line), fp))\n      for (char *p = line; (p = strstr(p, \"Core\")); p++)\n          if (sscanf(p, \"Core%*d: %d%%\", &load) == 1) {\n            sum += load;\n            count++;\n          }\n\n  fclose(fp);\n  return count ? sum / count : -1;\n}\n\nstatic int set_gpuinfo_dynamic_memory(struct gpuinfo_dynamic_info *dynamic_info) {\n  FILE *fp = fopen(\"/proc/meminfo\", \"r\");\n  if (!fp) return -1;\n  char line[256];\n  unsigned long mem_total = 0, mem_available = 0;\n  while (fgets(line, sizeof(line), fp)) {\n    if (sscanf(line, \"MemTotal: %lu kB\", &mem_total) == 1) {\n      mem_total *= 1024;\n      SET_GPUINFO_DYNAMIC(dynamic_info, total_memory, mem_total);\n    } else if (sscanf(line, \"MemAvailable: %lu kB\", &mem_available) == 1) {\n      mem_available *= 1024;\n      SET_GPUINFO_DYNAMIC(dynamic_info, free_memory, mem_available);\n    }\n  }\n  fclose(fp);\n  if (mem_total > 0 && mem_available > 0) {\n    SET_GPUINFO_DYNAMIC(dynamic_info, used_memory, mem_total - mem_available);\n    SET_GPUINFO_DYNAMIC(dynamic_info, mem_util_rate,\n                        (dynamic_info->total_memory - dynamic_info->free_memory) * 100 / dynamic_info->total_memory);\n  }\n  return 0; \n}\n\nstatic void gpuinfo_rknpu_refresh_dynamic_info(struct gpu_info *_gpu_info) {\n  struct gpu_info_rknpu *gpu_info = container_of(_gpu_info, struct gpu_info_rknpu, base);\n  struct gpuinfo_dynamic_info *dynamic_info = &gpu_info->base.dynamic_info;\n\n  int gpu_clock_speed = read_int_from_file(\"/sys/class/devfreq/fdab0000.npu/cur_freq\") / 1000000;\n  int gpu_clock_speed_max = read_int_from_file(\"/sys/class/devfreq/fdab0000.npu/max_freq\") / 1000000;\n  int gpu_util_rate = read_npu_load(\"/sys/kernel/debug/rknpu/load\");\n  if (gpu_util_rate >= 0) \n    SET_GPUINFO_DYNAMIC(dynamic_info, gpu_util_rate, gpu_util_rate);\n\n  SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed, gpu_clock_speed);\n  SET_GPUINFO_DYNAMIC(dynamic_info, gpu_clock_speed_max, gpu_clock_speed_max);\n\n  int gpu_temp = read_int_from_file(\"/sys/class/thermal/thermal_zone6/temp\") / 1000;\n  SET_GPUINFO_DYNAMIC(dynamic_info, gpu_temp, gpu_temp);\n\n  set_gpuinfo_dynamic_memory(dynamic_info);\n}\n\nstatic void gpuinfo_rknpu_get_running_processes(struct gpu_info *_gpu_info) {\n  _gpu_info->processes_count = 0;\n}\n\nstruct gpu_vendor gpu_vendor_rknpu = {\n  .init = gpuinfo_rknpu_init,\n  .shutdown = gpuinfo_rknpu_shutdown,\n  .last_error_string = gpuinfo_rknpu_last_error_string,\n  .get_device_handles = gpuinfo_rknpu_get_device_handles,\n  .populate_static_info = gpuinfo_rknpu_populate_static_info,\n  .refresh_dynamic_info = gpuinfo_rknpu_refresh_dynamic_info,\n  .refresh_running_processes = gpuinfo_rknpu_get_running_processes,\n  .name = \"RK-NPU\"\n};\n\n__attribute__((constructor)) static void init_extract_gpuinfo_rknpu(void) {\n  register_gpu_vendor(&gpu_vendor_rknpu);\n}\n"
  },
  {
    "path": "src/extract_processinfo_fdinfo.c",
    "content": "/*\n * Copyright (C) 2022 YiFei Zhu <zhuyifei1999@gmail.com>\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop and adapted from radeontop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/common.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n\n#include <ctype.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/syscall.h>\n#ifdef __linux__\n// for major() on linux (available in sys/types.h on BSD)\n#include <sys/sysmacros.h>\n#endif\n#include <sys/types.h>\n#include <unistd.h>\n\n#ifndef KCMP_FILE\n#define KCMP_FILE 0\n#endif\n\nstruct callback_entry {\n  struct gpu_info *gpu_info;\n  processinfo_fdinfo_callback callback;\n  bool active;\n};\n\nstatic unsigned registered_callback_entries;\n#define FDINFO_CALLBACK_ARRAY_INCREMENT 4\nstatic unsigned callback_entries_size;\nstatic struct callback_entry *callback_entries;\n\nvoid processinfo_drop_callback(const struct gpu_info *info) {\n  for (unsigned index = 0; index < registered_callback_entries; ++index) {\n    if (callback_entries[index].gpu_info == info) {\n      memmove(&callback_entries[index], &callback_entries[index + 1],\n              (registered_callback_entries - index) * sizeof(*callback_entries));\n      return;\n    }\n  }\n}\n\nvoid processinfo_register_fdinfo_callback(processinfo_fdinfo_callback callback, struct gpu_info *info) {\n  if (callback_entries_size == registered_callback_entries) {\n    callback_entries_size += FDINFO_CALLBACK_ARRAY_INCREMENT;\n    callback_entries = reallocarray(callback_entries, callback_entries_size, sizeof(*callback_entries));\n    if (!callback_entries) {\n      perror(\"Could not re-allocate memory: \");\n      exit(EXIT_FAILURE);\n    }\n  }\n  callback_entries[registered_callback_entries].gpu_info = info;\n  callback_entries[registered_callback_entries].callback = callback;\n  callback_entries[registered_callback_entries].active = true;\n  registered_callback_entries++;\n}\n\nvoid processinfo_enable_disable_callback_for(const struct gpu_info *info, bool enable) {\n  for (unsigned index = 0; index < registered_callback_entries; ++index) {\n    if (callback_entries[index].gpu_info == info) {\n      callback_entries[index].active = enable;\n    }\n  }\n}\n\nstatic bool is_drm_fd(int fd_dir_fd, const char *name) {\n  struct stat stat;\n  int ret;\n\n  ret = fstatat(fd_dir_fd, name, &stat, 0);\n\n  return ret == 0 && (stat.st_mode & S_IFMT) == S_IFCHR && major(stat.st_rdev) == 226;\n}\n\n// Increment for the number DRM FD tracked per process\n// 8 has been experimentally selected for being small while avoiding multiple allocations in most common cases\n#define DRM_FD_LINEAR_REALLOC_INC 8\n\nvoid processinfo_sweep_fdinfos(void) {\n  bool anyActiveCallback = false;\n  for (unsigned callback_idx = 0; !anyActiveCallback && callback_idx < registered_callback_entries; ++callback_idx) {\n    struct callback_entry *current_callback = &callback_entries[callback_idx];\n    anyActiveCallback = anyActiveCallback || current_callback->active;\n  }\n  if (!anyActiveCallback)\n    return;\n\n  DIR *proc_dir = opendir(\"/proc\");\n  if (!proc_dir)\n    return;\n\n  static unsigned seen_fds_capacity = 0;\n  static int *seen_fds = NULL;\n\n  struct dirent *proc_dent;\n  while ((proc_dent = readdir(proc_dir)) != NULL) {\n    int pid_dir_fd = -1, fd_dir_fd = -1, fdinfo_dir_fd = -1;\n    DIR *fdinfo_dir = NULL;\n    unsigned int seen_fds_len = 0;\n    struct dirent *fdinfo_dent;\n    unsigned int client_pid;\n\n    if (proc_dent->d_type != DT_DIR)\n      continue;\n    if (!isdigit(proc_dent->d_name[0]))\n      continue;\n\n    pid_dir_fd = openat(dirfd(proc_dir), proc_dent->d_name, O_DIRECTORY);\n    if (pid_dir_fd < 0)\n      continue;\n\n    client_pid = atoi(proc_dent->d_name);\n    if (!client_pid)\n      goto next;\n\n    fd_dir_fd = openat(pid_dir_fd, \"fd\", O_DIRECTORY);\n    if (fd_dir_fd < 0)\n      goto next;\n\n    fdinfo_dir_fd = openat(pid_dir_fd, \"fdinfo\", O_DIRECTORY);\n    if (fdinfo_dir_fd < 0)\n      goto next;\n\n    fdinfo_dir = fdopendir(fdinfo_dir_fd);\n    if (!fdinfo_dir) {\n      close(fdinfo_dir_fd);\n      goto next;\n    }\n\n  next_fd:\n    while ((fdinfo_dent = readdir(fdinfo_dir)) != NULL) {\n      struct gpu_process processes_info_local = {0};\n      int fd_num;\n\n      if (fdinfo_dent->d_type != DT_REG)\n        continue;\n      if (!isdigit(fdinfo_dent->d_name[0]))\n        continue;\n\n      if (!is_drm_fd(fd_dir_fd, fdinfo_dent->d_name))\n        continue;\n\n      fd_num = atoi(fdinfo_dent->d_name);\n\n      // check if this fd refers to the same open file as any seen ones.\n      // we only care about unique opens\n      for (unsigned i = 0; i < seen_fds_len; i++) {\n        if (syscall(SYS_kcmp, client_pid, client_pid, KCMP_FILE, fd_num, seen_fds[i]) <= 0)\n          goto next_fd;\n      }\n\n      if (seen_fds_len == seen_fds_capacity) {\n        seen_fds_capacity += DRM_FD_LINEAR_REALLOC_INC;\n        seen_fds = reallocarray(seen_fds, seen_fds_capacity, sizeof(*seen_fds));\n        if (!seen_fds) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n      }\n      seen_fds[seen_fds_len++] = fd_num;\n\n      int fdinfo_fd = openat(fdinfo_dir_fd, fdinfo_dent->d_name, O_RDONLY);\n      if (fdinfo_fd < 0)\n        continue;\n      FILE *fdinfo_file = fdopen(fdinfo_fd, \"r\");\n      if (!fdinfo_file) {\n        close(fdinfo_fd);\n        continue;\n      }\n\n      bool callback_success = false;\n      struct callback_entry *current_callback = NULL;\n      processes_info_local.pid = client_pid;\n      for (unsigned callback_idx = 0; !callback_success && callback_idx < registered_callback_entries; ++callback_idx) {\n        rewind(fdinfo_file);\n        fflush(fdinfo_file);\n        RESET_ALL(processes_info_local.valid);\n        processes_info_local.type = gpu_process_unknown;\n        current_callback = &callback_entries[callback_idx];\n        if (current_callback->active)\n          callback_success = current_callback->callback(current_callback->gpu_info, fdinfo_file, &processes_info_local);\n        else\n          callback_success = false;\n      }\n      fclose(fdinfo_file);\n      if (!callback_success)\n        continue;\n      // Default to graphical type\n      if (processes_info_local.type == gpu_process_unknown)\n        processes_info_local.type = gpu_process_graphical;\n\n      unsigned process_index =\n          current_callback->gpu_info->processes_count ? current_callback->gpu_info->processes_count - 1 : 0;\n      // Alloc when array is empty or realloc when this pid does not correspond to the last entry and the array is full\n      if ((current_callback->gpu_info->processes_count == 0 ||\n           current_callback->gpu_info->processes[process_index].pid != (pid_t)client_pid) &&\n          current_callback->gpu_info->processes_count == current_callback->gpu_info->processes_array_size) {\n        current_callback->gpu_info->processes_array_size += COMMON_PROCESS_LINEAR_REALLOC_INC;\n        current_callback->gpu_info->processes =\n            reallocarray(current_callback->gpu_info->processes, current_callback->gpu_info->processes_array_size,\n                         sizeof(*current_callback->gpu_info->processes));\n        if (!current_callback->gpu_info->processes) {\n          perror(\"Could not re-allocate memory: \");\n          exit(EXIT_FAILURE);\n        }\n      new_empty_process_entry:\n        process_index = current_callback->gpu_info->processes_count++;\n        memset(&current_callback->gpu_info->processes[process_index], 0,\n               sizeof(*current_callback->gpu_info->processes));\n        current_callback->gpu_info->processes[process_index].pid = client_pid;\n      }\n      // No alloc/realloc with different pid case\n      if (current_callback->gpu_info->processes_count == 0 ||\n          current_callback->gpu_info->processes[process_index].pid != (pid_t)client_pid) {\n        goto new_empty_process_entry;\n      }\n      struct gpu_process *process_info = &current_callback->gpu_info->processes[process_index];\n\n      process_info->type |= processes_info_local.type;\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, gpu_memory_usage)) {\n        SET_GPUINFO_PROCESS(process_info, gpu_memory_usage,\n                            process_info->gpu_memory_usage + processes_info_local.gpu_memory_usage);\n      }\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, gpu_usage)) {\n        SET_GPUINFO_PROCESS(process_info, gpu_usage, process_info->gpu_usage + processes_info_local.gpu_usage);\n      }\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, encode_usage)) {\n        SET_GPUINFO_PROCESS(process_info, encode_usage, process_info->encode_usage + processes_info_local.encode_usage);\n      }\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, decode_usage)) {\n        SET_GPUINFO_PROCESS(process_info, decode_usage, process_info->decode_usage + processes_info_local.decode_usage);\n      }\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, gfx_engine_used)) {\n        SET_GPUINFO_PROCESS(process_info, gfx_engine_used,\n                            process_info->gfx_engine_used + processes_info_local.gfx_engine_used);\n      }\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, compute_engine_used)) {\n        SET_GPUINFO_PROCESS(process_info, compute_engine_used,\n                            process_info->compute_engine_used + processes_info_local.compute_engine_used);\n      }\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, enc_engine_used)) {\n        SET_GPUINFO_PROCESS(process_info, enc_engine_used,\n                            process_info->enc_engine_used + processes_info_local.enc_engine_used);\n      }\n\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, dec_engine_used)) {\n        SET_GPUINFO_PROCESS(process_info, dec_engine_used,\n                            process_info->dec_engine_used + processes_info_local.dec_engine_used);\n      }\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, gpu_cycles)) {\n        SET_GPUINFO_PROCESS(process_info, gpu_cycles,\n                            process_info->gpu_cycles + processes_info_local.gpu_cycles);\n      }\n      if (GPUINFO_PROCESS_FIELD_VALID(&processes_info_local, sample_delta)) {\n        SET_GPUINFO_PROCESS(process_info, sample_delta,\n                            process_info->sample_delta + processes_info_local.sample_delta);\n      }\n    }\n\n  next:\n    if (fdinfo_dir)\n      closedir(fdinfo_dir);\n\n    if (fd_dir_fd >= 0)\n      close(fd_dir_fd);\n    close(pid_dir_fd);\n  }\n\n  closedir(proc_dir);\n  return;\n}\n"
  },
  {
    "path": "src/extract_processinfo_mac.c",
    "content": "/*\n * Copyright (C) 2023 Robin Voetter <robin@voetter.nl>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n\nvoid processinfo_drop_callback(const struct gpu_info *info) {\n  (void) info;\n}\n\nvoid processinfo_register_fdinfo_callback(processinfo_fdinfo_callback callback, struct gpu_info *info) {\n  (void) callback;\n  (void) info;\n}\n\nvoid processinfo_sweep_fdinfos(void) {\n}\n\nvoid processinfo_enable_disable_callback_for(const struct gpu_info *info, bool enable) {\n  (void)info;\n  (void)enable;\n}\n"
  },
  {
    "path": "src/get_process_info_linux.c",
    "content": "/*\n *\n * Copyright (C) 2017-2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/get_process_info.h\"\n\n#include <inttypes.h>\n#include <pwd.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n\n#define pid_path_size 1024\nstatic char pid_path[pid_path_size];\n\nvoid get_username_from_pid(pid_t pid, char **buffer) {\n  int written = snprintf(pid_path, pid_path_size, \"/proc/%\" PRIdMAX, (intmax_t)pid);\n  if (written == pid_path_size) {\n    *buffer = NULL;\n    return;\n  }\n  struct stat folder_stat;\n  int starval = stat(pid_path, &folder_stat);\n  if (starval == -1) {\n    *buffer = NULL;\n    return;\n  }\n  uid_t user_id = folder_stat.st_uid;\n  struct passwd *user_info = getpwuid(user_id);\n  if (user_info == NULL) {\n    *buffer = NULL;\n    return;\n  }\n  size_t namelen = strlen(user_info->pw_name) + 1;\n  *buffer = malloc(namelen * sizeof(**buffer));\n\n  strncpy(*buffer, user_info->pw_name, namelen);\n}\n\n#define command_line_increment 32\n\nvoid get_command_from_pid(pid_t pid, char **buffer) {\n  int written = snprintf(pid_path, pid_path_size, \"/proc/%\" PRIdMAX \"/cmdline\", (intmax_t)pid);\n  if (written == pid_path_size) {\n    *buffer = NULL;\n    return;\n  }\n  FILE *pid_file = fopen(pid_path, \"r\");\n  if (!pid_file) {\n    *buffer = NULL;\n    return;\n  }\n\n  size_t size_buffer = command_line_increment;\n  *buffer = malloc(size_buffer);\n  char *current_buffer = *buffer;\n  current_buffer[0] = '\\0';\n\n  size_t total_read = 0;\n  do {\n    size_t num_read = fread(current_buffer, 1, command_line_increment, pid_file);\n    total_read += num_read;\n    if (num_read == command_line_increment) {\n      size_buffer += command_line_increment;\n      *buffer = realloc(*buffer, size_buffer);\n      current_buffer = &((*buffer)[total_read]);\n    }\n  } while (!feof(pid_file) && !ferror(pid_file));\n  if (ferror(pid_file)) {\n    fclose(pid_file);\n    free(*buffer);\n    *buffer = NULL;\n    return;\n  }\n  fclose(pid_file);\n\n  for (size_t i = 0; total_read && i < total_read - 1; ++i) {\n    if ((*buffer)[i] == '\\0')\n      (*buffer)[i] = ' ';\n  }\n}\n\n/*\n *\n * From man 5 proc of /proc/<pid>/stat\n * For clock ticks per second use sysconf(_SC_CLK_TCK)\n *\n *  enum process_state {\n *   process_running = 'R',\n *   process_sleeping = 'S',\n *   process_sleeping_disk = 'D',\n *   process_zombie = 'Z',\n *   process_stopped = 'T',\n *   process_stopped_tracing = 't',\n *   process_dead = 'X',\n *   process_dead2 = 'x',\n *   process_wake_kill = 'K',\n *   process_waking = 'W',\n *   process_parked = 'P',\n * };\n *\n * struct stat_parse {\n *   int process_id;\n *   char *executable_filename;\n *   enum process_state process_state;\n *   int parent_pid;\n *   int process_group_id;\n *   int process_session_id;\n *   int process_tty;\n *   int foreground_process_group_id;\n *   unsigned kernel_flag;\n *   unsigned long num_minor_fault;\n *   unsigned long num_minor_fault_children;\n *   unsigned long num_major_fault;\n *   unsigned long num_major_fault_children;\n *   unsigned long user_time;           // in clock ticks\n *   unsigned long kernel_time;         // in clock ticks\n *   long children_user_time;   // in clock ticks\n *   long children_kernel_time; // in clock ticks\n *   long process_priority;\n *   long process_niceness;\n *   long process_num_threads;\n *   long next_sigalarm_time;\n *   unsigned long long process_start_time;\n *   unsigned long process_virt_mem_usage;\n *   long process_resident_mem_usage;\n *   long process_resident_mem_limit;\n *   unsigned long process_text_address_start;\n *   unsigned long process_text_address_end;\n *   unsigned long process_stack_address_start;\n *   unsigned long process_stack_address_current;\n *   unsigned long process_instruction_pointer;\n *   unsigned long process_signals; // Obsolete\n *   unsigned long process_signals_blocked; // Obsolete\n *   unsigned long process_signals_ignored; // Obsolete\n *   unsigned long process_signals_caught; // Obsolete\n *   unsigned long wait_channel_id;\n *   unsigned long process_num_page_swapped;\n *   unsigned long process_and_child_num_page_swapped;\n *   int process_exit_signal_to_parent;\n *   int process_processor;\n *   unsigned process_real_time_priority;\n *   unsigned policy;\n *   long long unsigned total_io_delays;\n *   long unsigned process_guest_time;\n *   long process_children_guest_time;\n *   unsigned long process_data_address_start;\n *   unsigned long process_data_address_end;\n *   unsigned long process_brk_start;\n *   unsigned long process_arguments_address_start;\n *   unsigned long process_arguments_address_end;\n *   unsigned long process_env_vars_address_start;\n *   unsigned long process_env_vars_address_end;\n *   int thread_exit_code;\n * };\n *\n */\n\nbool get_process_info(pid_t pid, struct process_cpu_usage *usage) {\n  double clock_ticks_per_second = sysconf(_SC_CLK_TCK);\n  size_t page_size = (size_t)sysconf(_SC_PAGESIZE);\n  int written = snprintf(pid_path, pid_path_size, \"/proc/%\" PRIdMAX \"/stat\", (intmax_t)pid);\n  if (written == pid_path_size) {\n    return false;\n  }\n  FILE *stat_file = fopen(pid_path, \"r\");\n  if (!stat_file) {\n    return false;\n  }\n  nvtop_get_current_time(&usage->timestamp);\n  unsigned long total_user_time;   // in clock_ticks\n  unsigned long total_kernel_time; // in clock_ticks\n  unsigned long virtual_memory;    // In bytes\n  long resident_memory;            // In page number?\n\n  int retval = fscanf(stat_file,\n                      \"%*d %*[^)]) %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u \"\n                      \"%*u %lu %lu %*d %*d %*d %*d %*d %*d %*u %lu %ld\",\n                      &total_user_time, &total_kernel_time, &virtual_memory, &resident_memory);\n  fclose(stat_file);\n  if (retval != 4)\n    return false;\n  usage->total_user_time = total_user_time / clock_ticks_per_second;\n  usage->total_kernel_time = total_kernel_time / clock_ticks_per_second;\n  usage->virtual_memory = virtual_memory;\n  usage->resident_memory = (size_t)resident_memory * page_size;\n  return true;\n}\n"
  },
  {
    "path": "src/get_process_info_mac.c",
    "content": "/*\n *\n * Copyright (C) 2023 Robin Voetter <robin@voetter.nl>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/get_process_info.h\"\n\n#include <libproc.h>\n#include <sys/sysctl.h>\n#include <pwd.h>\n#include <mach/mach_time.h>\n\n#include <string.h>\n#include <stdio.h>\n\nvoid get_username_from_pid(pid_t pid, char **buffer) {\n  struct proc_bsdshortinfo proc;\n  const int st = proc_pidinfo(pid, PROC_PIDT_SHORTBSDINFO, 0, &proc, PROC_PIDT_SHORTBSDINFO_SIZE);\n  if (st != PROC_PIDT_SHORTBSDINFO_SIZE) {\n    goto error;\n  }\n\n  struct passwd *user_info = getpwuid(proc.pbsi_uid);\n  if (user_info == NULL) {\n    goto error;\n  }\n\n  const size_t namelen = strlen(user_info->pw_name) + 1;\n  *buffer = malloc(namelen * sizeof(**buffer));\n  strncpy(*buffer, user_info->pw_name, namelen);\n  return;\nerror:\n  *buffer = NULL;\n}\n\nvoid get_command_from_pid(pid_t pid, char **buffer) {\n  // See https://chromium.googlesource.com/crashpad/crashpad/+/360e441c53ab4191a6fd2472cc57c3343a2f6944/util/posix/process_util_mac.cc\n  size_t argmax;\n  size_t argmax_estimate;\n  char *procargs = NULL;\n  int tries = 3;\n  do {\n    int mib[] = {CTL_KERN, KERN_PROCARGS2, pid};\n    if (sysctl(mib, 3, NULL, &argmax_estimate, NULL, 0) != 0) {\n      goto error_free_procargs;\n    }\n\n    argmax = argmax_estimate + 1;\n    procargs = realloc(procargs, argmax);\n    if (sysctl(mib, 3, procargs, &argmax, NULL, 0) != 0) {\n      goto error_free_procargs;\n    }\n  } while (argmax == argmax_estimate + 1 && --tries != 0);\n\n  unsigned argc;\n  memcpy(&argc, procargs, sizeof(argc));\n\n  size_t i = sizeof(argc);\n  // Skip executable path.\n  while (i < argmax && procargs[i] != 0) {\n    ++i;\n  }\n  // Find the first string\n  while (i < argmax && procargs[i] == 0) {\n    ++i;\n  }\n\n  const size_t argv0 = i;\n  // Count the total size of the args by finding the end.\n  for (unsigned int arg = 0; arg < argc && i < argmax; ++arg) {\n    while (i < argmax && procargs[i] != 0) {\n      ++i;\n    }\n    ++i; // We are going to replace this null character with a space (or a null in the case of the last).\n  }\n  const size_t args_size = i - argv0;\n  if (args_size == 0) {\n    goto error_free_procargs;\n  }\n  char* args = malloc(args_size);\n  *buffer = args;\n\n  i = argv0;\n  for (unsigned int arg = 0; arg < argc && i < argmax; ++arg) {\n    while (i < argmax && procargs[i] != 0) {\n      *args++ = procargs[i++];\n    }\n    *args++ = ' ';\n    ++i;\n  }\n  args[-1] = 0;\n\n  free(procargs);\n  return;\nerror_free_procargs:\n  free(procargs);\n  *buffer = NULL;\n  return;\n}\n\nbool get_process_info(pid_t pid, struct process_cpu_usage *usage) {\n  struct proc_taskinfo proc;\n  const int st = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &proc, PROC_PIDTASKINFO_SIZE);\n  if (st != PROC_PIDTASKINFO_SIZE) {\n    return false;\n  }\n\n  nvtop_get_current_time(&usage->timestamp);\n\n  // TODO: Should we implement this workaround?\n  // https://github.com/htop-dev/htop/blob/main/darwin/PlatformHelpers.c#L98\n  mach_timebase_info_data_t info;\n  mach_timebase_info(&info);\n  const double nanoseconds_per_tick = (double)info.numer / (double)info.denom;\n\n  usage->total_user_time = (proc.pti_total_user * nanoseconds_per_tick) / 1000000000.0;\n  usage->total_kernel_time = (proc.pti_total_system * nanoseconds_per_tick) / 1000000000.0;\n  usage->virtual_memory = proc.pti_virtual_size;\n  usage->resident_memory = proc.pti_resident_size;\n  return true;\n}\n"
  },
  {
    "path": "src/info_messages_linux.c",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"list.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/info_messages.h\"\n\n#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/utsname.h>\n\nstatic int get_linux_kernel_release(unsigned *major, unsigned *minor, unsigned *patch) {\n  struct utsname uname_str;\n  int retval = uname(&uname_str);\n  if (retval)\n    return retval;\n  int nmatch = sscanf(uname_str.release, \"%u.%u.%u\", major, minor, patch);\n  return nmatch != 3;\n}\n\nenum messages {\n  AMD_GPU_514,\n  INTEL_GPU_519,\n  MSM_GPU,\n};\n\nstatic const char *allMessages[] = {\n    \"Nvtop won't be able to show AMD GPU processes on your kernel version (requires Linux >= 5.14)\",\n    \"Nvtop won't be able to show Intel GPU utilization and processes on your kernel version (requires Linux >= 5.19)\",\n    \"This version of Nvtop does not yet support reporting all data for MSM GPUs, such as power, fan and temperature information\",\n};\nstatic const char *message_array[sizeof(allMessages) / sizeof(*allMessages)];\n\nvoid get_info_messages(struct list_head *devices, unsigned *num_messages, const char ***messages) {\n  *num_messages = 0;\n  unsigned linux_major, linux_minor, linux_patch;\n  if (get_linux_kernel_release(&linux_major, &linux_minor, &linux_patch))\n    return;\n\n  *messages = message_array;\n  bool hasIntel = false;\n  bool hasMSM = false;\n  bool hasAMD = false;\n  struct gpu_info *gpuinfo;\n  list_for_each_entry(gpuinfo, devices, list) {\n    if (strcmp(gpuinfo->vendor->name, \"Intel\") == 0) {\n      hasIntel = true;\n    }\n    if (strcmp(gpuinfo->vendor->name, \"msm\") == 0) {\n      hasMSM = true;\n    }\n    if (strcmp(gpuinfo->vendor->name, \"AMD\") == 0) {\n      hasAMD = true;\n    }\n  }\n  if (hasAMD) {\n    if (linux_major < 5 || (linux_major == 5 && linux_minor < 14)) {\n      message_array[(*num_messages)++] = allMessages[AMD_GPU_514];\n    }\n  }\n  if (hasIntel) {\n    if (linux_major < 5 || (linux_major == 5 && linux_minor < 19)) {\n      message_array[(*num_messages)++] = allMessages[INTEL_GPU_519];\n    }\n  }\n  if (hasMSM) {\n    message_array[(*num_messages)++] = allMessages[MSM_GPU];\n  }\n}\n"
  },
  {
    "path": "src/info_messages_mac.c",
    "content": "/*\n *\n * Copyright (C) 2023 Robin Voetter <robin@voetter.nl>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"list.h\"\n#include \"nvtop/info_messages.h\"\n\nvoid get_info_messages(struct list_head *devices, unsigned *num_messages, const char ***messages) {\n  (void) devices;\n  (void) messages;\n  *num_messages = 0;\n}\n"
  },
  {
    "path": "src/ini.c",
    "content": "/* inih -- simple .INI file parser\n\nSPDX-License-Identifier: BSD-3-Clause\n\nCopyright (C) 2009-2020, Ben Hoyt\n\ninih is released under the New BSD license (see LICENSE.txt). Go to the project\nhome page for more info:\n\nhttps://github.com/benhoyt/inih\n\n*/\n\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include <ctype.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"ini.h\"\n\n#if !INI_USE_STACK\n#if INI_CUSTOM_ALLOCATOR\n#include <stddef.h>\nvoid *ini_malloc(size_t size);\nvoid ini_free(void *ptr);\nvoid *ini_realloc(void *ptr, size_t size);\n#else\n#include <stdlib.h>\n#define ini_malloc malloc\n#define ini_free free\n#define ini_realloc realloc\n#endif\n#endif\n\n#define MAX_SECTION 50\n#define MAX_NAME 50\n\n/* Used by ini_parse_string() to keep track of string parsing state. */\ntypedef struct {\n  const char *ptr;\n  size_t num_left;\n} ini_parse_string_ctx;\n\n/* Strip whitespace chars off end of given string, in place. Return s. */\nstatic char *rstrip(char *s) {\n  char *p = s + strlen(s);\n  while (p > s && isspace((unsigned char)(*--p)))\n    *p = '\\0';\n  return s;\n}\n\n/* Return pointer to first non-whitespace char in given string. */\nstatic char *lskip(const char *s) {\n  while (*s && isspace((unsigned char)(*s)))\n    s++;\n  return (char *)s;\n}\n\n/* Return pointer to first char (of chars) or inline comment in given string,\n   or pointer to NUL at end of string if neither found. Inline comment must\n   be prefixed by a whitespace character to register as a comment. */\nstatic char *find_chars_or_comment(const char *s, const char *chars) {\n#if INI_ALLOW_INLINE_COMMENTS\n  int was_space = 0;\n  while (*s && (!chars || !strchr(chars, *s)) && !(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) {\n    was_space = isspace((unsigned char)(*s));\n    s++;\n  }\n#else\n  while (*s && (!chars || !strchr(chars, *s))) {\n    s++;\n  }\n#endif\n  return (char *)s;\n}\n\n/* Similar to strncpy, but ensures dest (size bytes) is\n   NUL-terminated, and doesn't pad with NULs. */\nstatic char *strncpy0(char *dest, const char *src, size_t size) {\n  /* Could use strncpy internally, but it causes gcc warnings (see issue #91) */\n  size_t i;\n  for (i = 0; i < size - 1 && src[i]; i++)\n    dest[i] = src[i];\n  dest[i] = '\\0';\n  return dest;\n}\n\n/* See documentation in header file. */\nint ini_parse_stream(ini_reader reader, void *stream, ini_handler handler, void *user) {\n  /* Uses a fair bit of stack (use heap instead if you need to) */\n#if INI_USE_STACK\n  char line[INI_MAX_LINE];\n  int max_line = INI_MAX_LINE;\n#else\n  char *line;\n  size_t max_line = INI_INITIAL_ALLOC;\n#endif\n#if INI_ALLOW_REALLOC && !INI_USE_STACK\n  char *new_line;\n  size_t offset;\n#endif\n  char section[MAX_SECTION] = \"\";\n  char prev_name[MAX_NAME] = \"\";\n\n  char *start;\n  char *end;\n  char *name;\n  char *value;\n  int lineno = 0;\n  int error = 0;\n\n#if !INI_USE_STACK\n  line = (char *)ini_malloc(INI_INITIAL_ALLOC);\n  if (!line) {\n    return -2;\n  }\n#endif\n\n#if INI_HANDLER_LINENO\n#define HANDLER(u, s, n, v) handler(u, s, n, v, lineno)\n#else\n#define HANDLER(u, s, n, v) handler(u, s, n, v)\n#endif\n\n  /* Scan through stream line by line */\n  while (reader(line, (int)max_line, stream) != NULL) {\n#if INI_ALLOW_REALLOC && !INI_USE_STACK\n    offset = strlen(line);\n    while (offset == max_line - 1 && line[offset - 1] != '\\n') {\n      max_line *= 2;\n      if (max_line > INI_MAX_LINE)\n        max_line = INI_MAX_LINE;\n      new_line = ini_realloc(line, max_line);\n      if (!new_line) {\n        ini_free(line);\n        return -2;\n      }\n      line = new_line;\n      if (reader(line + offset, (int)(max_line - offset), stream) == NULL)\n        break;\n      if (max_line >= INI_MAX_LINE)\n        break;\n      offset += strlen(line + offset);\n    }\n#endif\n\n    lineno++;\n\n    start = line;\n#if INI_ALLOW_BOM\n    if (lineno == 1 && (unsigned char)start[0] == 0xEF && (unsigned char)start[1] == 0xBB &&\n        (unsigned char)start[2] == 0xBF) {\n      start += 3;\n    }\n#endif\n    start = lskip(rstrip(start));\n\n    if (strchr(INI_START_COMMENT_PREFIXES, *start)) {\n      /* Start-of-line comment */\n    }\n#if INI_ALLOW_MULTILINE\n    else if (*prev_name && *start && start > line) {\n      /* Non-blank line with leading whitespace, treat as continuation\n         of previous name's value (as per Python configparser). */\n      if (!HANDLER(user, section, prev_name, start) && !error)\n        error = lineno;\n    }\n#endif\n    else if (*start == '[') {\n      /* A \"[section]\" line */\n      end = find_chars_or_comment(start + 1, \"]\");\n      if (*end == ']') {\n        *end = '\\0';\n        strncpy0(section, start + 1, sizeof(section));\n        *prev_name = '\\0';\n#if INI_CALL_HANDLER_ON_NEW_SECTION\n        if (!HANDLER(user, section, NULL, NULL) && !error)\n          error = lineno;\n#endif\n      } else if (!error) {\n        /* No ']' found on section line */\n        error = lineno;\n      }\n    } else if (*start) {\n      /* Not a comment, must be a name[=:]value pair */\n      end = find_chars_or_comment(start, \"=:\");\n      if (*end == '=' || *end == ':') {\n        *end = '\\0';\n        name = rstrip(start);\n        value = end + 1;\n#if INI_ALLOW_INLINE_COMMENTS\n        end = find_chars_or_comment(value, NULL);\n        if (*end)\n          *end = '\\0';\n#endif\n        value = lskip(value);\n        rstrip(value);\n\n        /* Valid name[=:]value pair found, call handler */\n        strncpy0(prev_name, name, sizeof(prev_name));\n        if (!HANDLER(user, section, name, value) && !error)\n          error = lineno;\n      } else if (!error) {\n        /* No '=' or ':' found on name[=:]value line */\n#if INI_ALLOW_NO_VALUE\n        *end = '\\0';\n        name = rstrip(start);\n        if (!HANDLER(user, section, name, NULL) && !error)\n          error = lineno;\n#else\n        error = lineno;\n#endif\n      }\n    }\n\n#if INI_STOP_ON_FIRST_ERROR\n    if (error)\n      break;\n#endif\n  }\n\n#if !INI_USE_STACK\n  ini_free(line);\n#endif\n\n  return error;\n}\n\n/* See documentation in header file. */\nint ini_parse_file(FILE *file, ini_handler handler, void *user) {\n  return ini_parse_stream((ini_reader)fgets, file, handler, user);\n}\n\n/* See documentation in header file. */\nint ini_parse(const char *filename, ini_handler handler, void *user) {\n  FILE *file;\n  int error;\n\n  file = fopen(filename, \"r\");\n  if (!file)\n    return -1;\n  error = ini_parse_file(file, handler, user);\n  fclose(file);\n  return error;\n}\n\n/* An ini_reader function to read the next line from a string buffer. This\n   is the fgets() equivalent used by ini_parse_string(). */\nstatic char *ini_reader_string(char *str, int num, void *stream) {\n  ini_parse_string_ctx *ctx = (ini_parse_string_ctx *)stream;\n  const char *ctx_ptr = ctx->ptr;\n  size_t ctx_num_left = ctx->num_left;\n  char *strp = str;\n  char c;\n\n  if (ctx_num_left == 0 || num < 2)\n    return NULL;\n\n  while (num > 1 && ctx_num_left != 0) {\n    c = *ctx_ptr++;\n    ctx_num_left--;\n    *strp++ = c;\n    if (c == '\\n')\n      break;\n    num--;\n  }\n\n  *strp = '\\0';\n  ctx->ptr = ctx_ptr;\n  ctx->num_left = ctx_num_left;\n  return str;\n}\n\n/* See documentation in header file. */\nint ini_parse_string(const char *string, ini_handler handler, void *user) {\n  ini_parse_string_ctx ctx;\n\n  ctx.ptr = string;\n  ctx.num_left = strlen(string);\n  return ini_parse_stream((ini_reader)ini_reader_string, &ctx, handler, user);\n}\n"
  },
  {
    "path": "src/interface.c",
    "content": "/*\n *\n * Copyright (C) 2017-2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/common.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/interface.h\"\n#include \"nvtop/interface_common.h\"\n#include \"nvtop/interface_internal_common.h\"\n#include \"nvtop/interface_layout_selection.h\"\n#include \"nvtop/interface_options.h\"\n#include \"nvtop/interface_ring_buffer.h\"\n#include \"nvtop/interface_setup_win.h\"\n#include \"nvtop/plot.h\"\n#include \"nvtop/time.h\"\n\n#include <assert.h>\n#include <inttypes.h>\n#include <ncurses.h>\n#include <signal.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <tgmath.h>\n#include <unistd.h>\n\nstatic unsigned int sizeof_device_field[device_field_count] = {\n    [device_name] = 11,       [device_fan_speed] = 11,   [device_temperature] = 10, [device_power] = 15,\n    [device_clock] = 11,      [device_mem_clock] = 12,   [device_pcie] = 46,        [device_shadercores] = 7,\n    [device_l2features] = 11, [device_execengines] = 11,\n};\n\nstatic unsigned int sizeof_process_field[process_field_count] = {\n    [process_pid] = 7,       [process_user] = 4,          [process_gpu_id] = 3,   [process_type] = 8,\n    [process_gpu_rate] = 4,  [process_enc_rate] = 4,      [process_dec_rate] = 4,\n    [process_memory] = 14, // 9 for mem 5 for %\n    [process_cpu_usage] = 6, [process_cpu_mem_usage] = 9, [process_command] = 0,\n};\n\nstatic void alloc_device_window(unsigned int start_row, unsigned int start_col, unsigned int totalcol,\n                                struct device_window *dwin) {\n\n  const unsigned int spacer = 1;\n\n  // Line 1 = Name | PCIe info\n\n  dwin->name_win = newwin(1, sizeof_device_field[device_name], start_row, start_col);\n  if (dwin->name_win == NULL)\n    goto alloc_error;\n  dwin->pcie_info =\n      newwin(1, sizeof_device_field[device_pcie], start_row, start_col + spacer + sizeof_device_field[device_name]);\n  if (dwin->pcie_info == NULL)\n    goto alloc_error;\n\n  // Line 2 = GPU clk | MEM clk | Temp | Fan | Power\n  dwin->gpu_clock_info = newwin(1, sizeof_device_field[device_clock], start_row + 1, start_col);\n  if (dwin->gpu_clock_info == NULL)\n    goto alloc_error;\n  dwin->mem_clock_info = newwin(1, sizeof_device_field[device_mem_clock], start_row + 1,\n                                start_col + spacer + sizeof_device_field[device_clock]);\n  if (dwin->mem_clock_info == NULL)\n    goto alloc_error;\n  dwin->temperature =\n      newwin(1, sizeof_device_field[device_temperature], start_row + 1,\n             start_col + spacer * 2 + sizeof_device_field[device_clock] + sizeof_device_field[device_mem_clock]);\n  if (dwin->temperature == NULL)\n    goto alloc_error;\n  dwin->fan_speed = newwin(1, sizeof_device_field[device_fan_speed], start_row + 1,\n                           start_col + spacer * 3 + sizeof_device_field[device_clock] +\n                               sizeof_device_field[device_mem_clock] + sizeof_device_field[device_temperature]);\n  if (dwin->fan_speed == NULL)\n    goto alloc_error;\n  dwin->power_info =\n      newwin(1, sizeof_device_field[device_power], start_row + 1,\n             start_col + spacer * 4 + sizeof_device_field[device_clock] + sizeof_device_field[device_mem_clock] +\n                 sizeof_device_field[device_temperature] + sizeof_device_field[device_fan_speed]);\n  if (dwin->power_info == NULL)\n    goto alloc_error;\n\n  // Line 3 = GPU used | MEM used | Encoder | Decoder\n\n  int remaining_cols = totalcol - 3 * spacer;\n  int size_gpu, size_mem, size_encode, size_decode;\n  int quot, rem;\n  quot = remaining_cols / 3;\n  rem = remaining_cols % 3;\n  size_gpu = size_mem = size_encode = quot;\n  switch (rem) {\n  case 2:\n    if (size_encode % 2 == 1)\n      size_encode += 1;\n    else\n      size_mem += 1;\n    /* Falls through */\n  case 1:\n    size_gpu += 1;\n    break;\n  }\n\n  if (size_encode % 2 == 1) {\n    size_mem += 1;\n    size_encode -= 1;\n  }\n\n  if (size_encode / 2 < 14) {\n    size_encode += 2;\n    size_gpu -= 1;\n    size_mem -= 1;\n  }\n\n  size_decode = size_encode / 2;\n  if (size_encode % 2 == 1)\n    size_encode += 1;\n  size_encode /= 2;\n\n  dwin->gpu_util_enc_dec = newwin(1, size_gpu, start_row + 2, start_col);\n  if (dwin->gpu_util_enc_dec == NULL)\n    goto alloc_error;\n  dwin->mem_util_enc_dec = newwin(1, size_mem, start_row + 2, start_col + spacer + size_gpu);\n  if (dwin->mem_util_enc_dec == NULL)\n    goto alloc_error;\n  dwin->encode_util = newwin(1, size_encode, start_row + 2, start_col + spacer * 2 + size_gpu + size_mem);\n  if (dwin->encode_util == NULL)\n    goto alloc_error;\n  dwin->decode_util = newwin(1, size_decode, start_row + 2, start_col + spacer * 3 + size_gpu + size_mem + size_encode);\n  if (dwin->decode_util == NULL)\n    goto alloc_error;\n  dwin->encdec_util = newwin(1, size_encode * 2, start_row + 2, start_col + spacer * 2 + size_gpu + size_mem);\n  if (dwin->encdec_util == NULL)\n    goto alloc_error;\n  // For auto-hide encode / decode window\n  dwin->gpu_util_no_enc_or_dec = newwin(1, size_gpu + size_encode / 2 + 1, start_row + 2, start_col);\n  if (dwin->gpu_util_no_enc_or_dec == NULL)\n    goto alloc_error;\n  dwin->mem_util_no_enc_or_dec =\n      newwin(1, size_mem + size_encode / 2, start_row + 2, start_col + spacer + size_gpu + size_encode / 2 + 1);\n  if (dwin->mem_util_no_enc_or_dec == NULL)\n    goto alloc_error;\n  dwin->gpu_util_no_enc_and_dec = newwin(1, size_gpu + size_encode + 1, start_row + 2, start_col);\n  if (dwin->gpu_util_no_enc_and_dec == NULL)\n    goto alloc_error;\n  dwin->mem_util_no_enc_and_dec =\n      newwin(1, size_mem + size_encode + 1, start_row + 2, start_col + spacer + size_gpu + size_encode + 1);\n  if (dwin->mem_util_no_enc_and_dec == NULL)\n    goto alloc_error;\n  dwin->enc_was_visible = false;\n  dwin->dec_was_visible = false;\n\n  // Line 4 = Number of shading cores | L2 Features\n  dwin->shader_cores = newwin(1, sizeof_device_field[device_shadercores], start_row + 3, start_col);\n  if (dwin->shader_cores == NULL)\n    goto alloc_error;\n  dwin->l2_cache_size = newwin(1, sizeof_device_field[device_l2features], start_row + 3,\n                               start_col + spacer + sizeof_device_field[device_shadercores]);\n  if (dwin->l2_cache_size == NULL)\n    goto alloc_error;\n  dwin->exec_engines =\n      newwin(1, sizeof_device_field[device_execengines], start_row + 3,\n             start_col + spacer * 2 + sizeof_device_field[device_shadercores] + sizeof_device_field[device_l2features]);\n  if (dwin->exec_engines == NULL)\n    goto alloc_error;\n\n  return;\nalloc_error:\n  endwin();\n  fprintf(stderr, \"Error: Not enough columns to draw device information\\n\");\n  exit(EXIT_FAILURE);\n}\n\nstatic void free_device_windows(struct device_window *dwin) {\n  delwin(dwin->name_win);\n  delwin(dwin->gpu_util_enc_dec);\n  delwin(dwin->mem_util_enc_dec);\n  delwin(dwin->gpu_util_no_enc_or_dec);\n  delwin(dwin->mem_util_no_enc_or_dec);\n  delwin(dwin->gpu_util_no_enc_and_dec);\n  delwin(dwin->mem_util_no_enc_and_dec);\n  delwin(dwin->encode_util);\n  delwin(dwin->decode_util);\n  delwin(dwin->encdec_util);\n  delwin(dwin->gpu_clock_info);\n  delwin(dwin->mem_clock_info);\n  delwin(dwin->power_info);\n  delwin(dwin->temperature);\n  delwin(dwin->fan_speed);\n  delwin(dwin->pcie_info);\n}\n\nstatic void alloc_process_with_option(struct nvtop_interface *interface, unsigned posX, unsigned posY, unsigned sizeX,\n                                      unsigned sizeY) {\n  if (sizeY > 0) {\n    interface->process.process_win = newwin(sizeY, sizeX, posY, posX);\n    interface->process.process_with_option_win =\n        newwin(sizeY, sizeX - option_window_size, posY, posX + option_window_size);\n  } else {\n    interface->process.process_win = NULL;\n    interface->process.process_with_option_win = NULL;\n  }\n  interface->process.selected_row = 0;\n  interface->process.selected_pid = -1;\n  interface->process.offset_column = 0;\n  interface->process.offset = 0;\n\n  interface->process.option_window.option_win = newwin(sizeY, option_window_size, posY, posX);\n\n  interface->process.option_window.state = nvtop_option_state_hidden;\n  interface->process.option_window.previous_state = nvtop_option_state_sort_by;\n  interface->process.option_window.offset = 0;\n  interface->process.option_window.selected_row = 0;\n}\n\nstatic void initialize_gpu_mem_plot(struct plot_window *plot, struct window_position *position,\n                                    nvtop_interface_option *options) {\n  unsigned rows = position->sizeY;\n  unsigned cols = position->sizeX;\n  cols -= 5;\n  rows -= 2;\n  plot->plot_window = newwin(rows, cols, position->posY + 1, position->posX + 4);\n  draw_rectangle(plot->win, 3, 0, cols + 2, rows + 2);\n  mvwprintw(plot->win, 1 + rows * 3 / 4, 0, \" 25\");\n  mvwprintw(plot->win, 1 + rows / 4, 0, \" 75\");\n  mvwprintw(plot->win, 1 + rows / 2, 0, \" 50\");\n  mvwprintw(plot->win, 1, 0, \"100\");\n  mvwprintw(plot->win, rows, 0, \"  0\");\n  plot->data = calloc(cols, sizeof(*plot->data));\n  plot->num_data = cols;\n\n  unsigned column_divisor = 0;\n  for (unsigned i = 0; i < plot->num_devices_to_plot; ++i) {\n    unsigned dev_id = plot->devices_ids[i];\n    plot_info_to_draw to_draw = options->gpu_specific_opts[dev_id].to_draw;\n    column_divisor += plot_count_draw_info(to_draw);\n  }\n  assert(column_divisor > 0);\n  char elapsedSeconds[5];\n  char *err = \"err\";\n  char *zeroSec = \"0s\";\n  if (options->plot_left_to_right) {\n    char *toPrint = zeroSec;\n    mvwprintw(plot->win, position->sizeY - 1, 4, \"%s\", toPrint);\n\n    int retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols / 4 / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols / 4 - strlen(toPrint) / 2, \"%s\", toPrint);\n\n    retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols / 2 / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols / 2 - strlen(toPrint) / 2, \"%s\", toPrint);\n\n    retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols * 3 / 4 / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols * 3 / 4 - strlen(toPrint) / 2, \"%s\", toPrint);\n\n    retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols - strlen(toPrint), \"%s\", toPrint);\n  } else {\n    char *toPrint;\n    int retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4, \"%s\", toPrint);\n\n    retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols * 3 / 4 / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols / 4 - strlen(toPrint) / 2, \"%s\", toPrint);\n\n    retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols / 2 / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols / 2 - strlen(toPrint) / 2, \"%s\", toPrint);\n\n    retval = snprintf(elapsedSeconds, 5, \"%ds\", options->update_interval * cols / 4 / column_divisor / 1000);\n    if (retval > 4)\n      toPrint = err;\n    else\n      toPrint = elapsedSeconds;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols * 3 / 4 - strlen(toPrint) / 2, \"%s\", toPrint);\n\n    toPrint = zeroSec;\n    mvwprintw(plot->win, position->sizeY - 1, 4 + cols - strlen(toPrint), \"%s\", toPrint);\n  }\n  wnoutrefresh(plot->win);\n}\n\nstatic void alloc_plot_window(unsigned devices_count, struct window_position *plot_positions,\n                              unsigned map_device_to_plot[devices_count], struct nvtop_interface *interface) {\n  if (!interface->num_plots) {\n    interface->plots = NULL;\n    return;\n  }\n  interface->plots = malloc(interface->num_plots * sizeof(*interface->plots));\n  for (size_t i = 0; i < interface->num_plots; ++i) {\n    interface->plots[i].num_devices_to_plot = 0;\n    for (unsigned dev_id = 0; dev_id < devices_count; ++dev_id) {\n      if (map_device_to_plot[dev_id] == i) {\n        interface->plots[i].devices_ids[interface->plots[i].num_devices_to_plot] = dev_id;\n        interface->plots[i].num_devices_to_plot++;\n      }\n    }\n    interface->plots[i].win =\n        newwin(plot_positions[i].sizeY, plot_positions[i].sizeX, plot_positions[i].posY, plot_positions[i].posX);\n    initialize_gpu_mem_plot(&interface->plots[i], &plot_positions[i], &interface->options);\n  }\n}\n\nstatic unsigned device_length(void) {\n  return max(sizeof_device_field[device_name] + sizeof_device_field[device_pcie] + 1,\n             sizeof_device_field[device_clock] + sizeof_device_field[device_mem_clock] +\n                 sizeof_device_field[device_temperature] + sizeof_device_field[device_fan_speed] +\n                 sizeof_device_field[device_power] + 5);\n}\n\nstatic pid_t nvtop_pid;\n\nstatic void initialize_all_windows(struct nvtop_interface *dwin) {\n  int rows, cols;\n  getmaxyx(stdscr, rows, cols);\n\n  unsigned int devices_count = dwin->monitored_dev_count;\n\n  struct window_position device_positions[devices_count];\n  unsigned map_device_to_plot[devices_count];\n  struct window_position process_position;\n  struct window_position plot_positions[MAX_CHARTS];\n  struct window_position setup_position;\n\n  compute_sizes_from_layout(devices_count, dwin->options.has_gpu_info_bar ? 4 : 3, device_length(), rows - 1, cols,\n                            dwin->options.gpu_specific_opts, dwin->options.process_fields_displayed, device_positions,\n                            &dwin->num_plots, plot_positions, map_device_to_plot, &process_position, &setup_position,\n                            dwin->options.hide_processes_list);\n\n  alloc_plot_window(devices_count, plot_positions, map_device_to_plot, dwin);\n\n  for (unsigned int i = 0; i < devices_count; ++i) {\n    alloc_device_window(device_positions[i].posY, device_positions[i].posX, device_positions[i].sizeX,\n                        &dwin->devices_win[i]);\n  }\n\n  alloc_process_with_option(dwin, process_position.posX, process_position.posY, process_position.sizeX,\n                            process_position.sizeY);\n\n  dwin->shortcut_window = newwin(1, cols, rows - 1, 0);\n\n  alloc_setup_window(&setup_position, &dwin->setup_win);\n  nvtop_pid = getpid();\n}\n\nstatic void delete_all_windows(struct nvtop_interface *dwin) {\n  for (unsigned int i = 0; i < dwin->monitored_dev_count; ++i) {\n    free_device_windows(&dwin->devices_win[i]);\n  }\n  delwin(dwin->process.process_win);\n  delwin(dwin->process.process_with_option_win);\n  dwin->process.process_win = NULL;\n  dwin->process.process_with_option_win = NULL;\n  delwin(dwin->shortcut_window);\n  delwin(dwin->process.option_window.option_win);\n  for (size_t i = 0; i < dwin->num_plots; ++i) {\n    delwin(dwin->plots[i].win);\n    free(dwin->plots[i].data);\n  }\n  free_setup_window(&dwin->setup_win);\n  free(dwin->plots);\n}\n\nstatic void initialize_colors(void) {\n  start_color();\n  short background_color;\n#ifdef NCURSES_VERSION\n  if (use_default_colors() == OK)\n    background_color = -1;\n  else\n    background_color = COLOR_BLACK;\n#else\n  background_color = COLOR_BLACK;\n#endif\n  init_pair(cyan_color, COLOR_CYAN, background_color);\n  init_pair(red_color, COLOR_RED, background_color);\n  init_pair(green_color, COLOR_GREEN, background_color);\n  init_pair(yellow_color, COLOR_YELLOW, background_color);\n  init_pair(blue_color, COLOR_BLUE, background_color);\n  init_pair(magenta_color, COLOR_MAGENTA, background_color);\n}\n\nstruct nvtop_interface *initialize_curses(unsigned total_devices, unsigned devices_count, unsigned largest_device_name,\n                                          nvtop_interface_option options) {\n  struct nvtop_interface *interface = calloc(1, sizeof(*interface));\n  interface->options = options;\n  interface->devices_win = calloc(devices_count, sizeof(*interface->devices_win));\n  interface->total_dev_count = total_devices;\n  interface->monitored_dev_count = devices_count;\n  sizeof_device_field[device_name] = largest_device_name + 11;\n  initscr();\n  refresh();\n  if (interface->options.use_color && has_colors() == TRUE) {\n    initialize_colors();\n  }\n  cbreak();\n  noecho();\n  keypad(stdscr, TRUE);\n  curs_set(0);\n\n  // Hide decode and encode if not active for some time\n  if (interface->options.encode_decode_hiding_timer > 0.) {\n    nvtop_time time_now, some_time_in_past;\n    some_time_in_past =\n        nvtop_hmns_to_time(0, (unsigned int)(interface->options.encode_decode_hiding_timer / 60.) + 1, 0);\n\n    nvtop_get_current_time(&time_now);\n    some_time_in_past = nvtop_substract_time(time_now, some_time_in_past);\n    for (size_t i = 0; i < devices_count; ++i) {\n      interface->devices_win[i].last_encode_seen = some_time_in_past;\n      interface->devices_win[i].last_decode_seen = some_time_in_past;\n    }\n  }\n\n  interface_alloc_ring_buffer(devices_count, 4, 10 * 60 * 1000, &interface->saved_data_ring);\n  initialize_all_windows(interface);\n  return interface;\n}\n\nvoid clean_ncurses(struct nvtop_interface *interface) {\n  endwin();\n  delete_all_windows(interface);\n  free(interface->options.gpu_specific_opts);\n  free(interface->options.config_file_location);\n  free(interface->devices_win);\n  interface_free_ring_buffer(&interface->saved_data_ring);\n  free(interface);\n}\n\nstatic void draw_percentage_meter(WINDOW *win, const char *prelude, unsigned int new_percentage,\n                                  const char inside_braces_right[1024]) {\n  int rows, cols;\n  getmaxyx(win, rows, cols);\n  (void)rows;\n  size_t size_prelude = strlen(prelude);\n  wcolor_set(win, cyan_color, NULL);\n  mvwprintw(win, 0, 0, \"%s\", prelude);\n  wstandend(win);\n  waddch(win, '[');\n  int curx, cury;\n  curx = getcurx(win);\n  cury = getcury(win);\n  int between_sbraces = cols - size_prelude - 2;\n  float usage = round((float)between_sbraces * new_percentage / 100.f);\n  int represent_usage = (int)usage;\n  whline(win, '|', (int)represent_usage);\n  mvwhline(win, cury, curx + represent_usage, ' ', between_sbraces - represent_usage);\n  mvwaddch(win, cury, curx + between_sbraces, ']');\n  unsigned int right_side_braces_space_required = strlen(inside_braces_right);\n  wmove(win, cury, curx + between_sbraces - right_side_braces_space_required);\n  wprintw(win, \"%s\", inside_braces_right);\n  mvwchgat(win, cury, curx, represent_usage, 0, green_color, NULL);\n  wnoutrefresh(win);\n}\n\n// Draw percentage with a yellow highlight percentage (yellow percentage <= new_percentage)\nstatic void draw_percentage_meter_with_yellow_highlight(WINDOW *win, const char *prelude, unsigned int new_percentage,\n                                                        unsigned int yellow_percentage,\n                                                        const char inside_braces_right[1024]) {\n  draw_percentage_meter(win, prelude, new_percentage, inside_braces_right);\n  if (yellow_percentage > new_percentage)\n    yellow_percentage = new_percentage;\n  int rows, cols;\n  getmaxyx(win, rows, cols);\n  (void)rows;\n  size_t size_prelude = strlen(prelude);\n  int between_sbraces = cols - size_prelude - 2;\n  float usage = round((float)between_sbraces * yellow_percentage / 100.f);\n  mvwchgat(win, 0, size_prelude + 1, (int)usage, 0, yellow_color, NULL);\n  wnoutrefresh(win);\n}\n\nstatic const char *memory_prefix[] = {\" B\", \"Ki\", \"Mi\", \"Gi\", \"Ti\", \"Pi\"};\n\nstatic void draw_temp_color(WINDOW *win, unsigned int temp, unsigned int temp_slowdown, bool celsius) {\n  unsigned int temp_convert;\n  if (celsius)\n    temp_convert = temp;\n  else\n    temp_convert = (unsigned)(32 + nearbyint(temp * 1.8));\n  wcolor_set(win, cyan_color, NULL);\n  mvwprintw(win, 0, 0, \"TEMP\");\n\n  if (temp >= temp_slowdown - 5) {\n    if (temp >= temp_slowdown)\n      wcolor_set(win, red_color, NULL);\n    else\n      wcolor_set(win, yellow_color, NULL);\n  } else {\n    wcolor_set(win, green_color, NULL);\n  }\n  wprintw(win, \" %3u\", temp_convert);\n  wstandend(win);\n\n  waddch(win, ACS_DEGREE);\n  if (celsius)\n    waddch(win, 'C');\n  else\n    waddch(win, 'F');\n  wnoutrefresh(win);\n}\n\nstatic void print_pcie_at_scale(WINDOW *win, unsigned int value) {\n  int prefix_off;\n  double val_d = value;\n  for (prefix_off = 1; prefix_off < 5 && val_d >= 1000.; ++prefix_off) {\n    val_d = val_d / 1024.;\n  }\n  if (val_d >= 100.) {\n    wprintw(win, \"%.1f\", val_d);\n  } else {\n    if (val_d >= 10.) {\n      wprintw(win, \"%.2f\", val_d);\n    } else {\n      wprintw(win, \"%.3f\", val_d);\n    }\n  }\n  wprintw(win, \" %sB/s\", memory_prefix[prefix_off]);\n}\n\nstatic inline void werase_and_wnoutrefresh(WINDOW *w) {\n  werase(w);\n  wnoutrefresh(w);\n}\n\nstatic bool cleaned_enc_window(struct device_window *dev, double encode_decode_hiding_timer, nvtop_time tnow) {\n  if (encode_decode_hiding_timer > 0. && nvtop_difftime(dev->last_encode_seen, tnow) > encode_decode_hiding_timer) {\n    if (dev->enc_was_visible) {\n      dev->enc_was_visible = false;\n      if (dev->dec_was_visible) {\n        werase_and_wnoutrefresh(dev->gpu_util_enc_dec);\n        werase_and_wnoutrefresh(dev->mem_util_enc_dec);\n      } else {\n        werase_and_wnoutrefresh(dev->gpu_util_no_enc_or_dec);\n        werase_and_wnoutrefresh(dev->mem_util_no_enc_or_dec);\n      }\n    }\n    return true;\n  } else {\n    return false;\n  }\n}\n\nstatic bool cleaned_dec_window(struct device_window *dev, double encode_decode_hiding_timer, nvtop_time tnow) {\n  if (encode_decode_hiding_timer > 0. && nvtop_difftime(dev->last_decode_seen, tnow) > encode_decode_hiding_timer) {\n    if (dev->dec_was_visible) {\n      dev->dec_was_visible = false;\n      if (dev->enc_was_visible) {\n        werase_and_wnoutrefresh(dev->gpu_util_enc_dec);\n        werase_and_wnoutrefresh(dev->mem_util_enc_dec);\n      } else {\n        werase_and_wnoutrefresh(dev->gpu_util_no_enc_or_dec);\n        werase_and_wnoutrefresh(dev->mem_util_no_enc_or_dec);\n      }\n    }\n    return true;\n  } else {\n    return false;\n  }\n}\n\nstatic void encode_decode_show_select(struct device_window *dev, bool encode_valid, bool decode_valid,\n                                      unsigned encode_rate, unsigned decode_rate, double encode_decode_hiding_timer,\n                                      bool encode_decode_shared, bool *display_encode, bool *display_decode) {\n  nvtop_time tnow;\n  nvtop_get_current_time(&tnow);\n  if (encode_valid && encode_rate > 0) {\n    *display_encode = true;\n    dev->last_encode_seen = tnow;\n    if (!dev->enc_was_visible) {\n      dev->enc_was_visible = true;\n      if (!dev->dec_was_visible) {\n        werase_and_wnoutrefresh(dev->gpu_util_no_enc_and_dec);\n        werase_and_wnoutrefresh(dev->mem_util_no_enc_and_dec);\n      } else {\n        werase_and_wnoutrefresh(dev->gpu_util_no_enc_or_dec);\n        werase_and_wnoutrefresh(dev->mem_util_no_enc_or_dec);\n      }\n    }\n  } else {\n    *display_encode = !cleaned_enc_window(dev, encode_decode_hiding_timer, tnow);\n  }\n  // If shared, rely on decode\n  *display_encode = *display_encode && !encode_decode_shared;\n  if (decode_valid && decode_rate > 0) {\n    *display_decode = true;\n    dev->last_decode_seen = tnow;\n    if (!dev->dec_was_visible) {\n      dev->dec_was_visible = true;\n      if (!dev->enc_was_visible) {\n        werase_and_wnoutrefresh(dev->gpu_util_no_enc_and_dec);\n        werase_and_wnoutrefresh(dev->mem_util_no_enc_and_dec);\n      } else {\n        werase_and_wnoutrefresh(dev->gpu_util_no_enc_or_dec);\n        werase_and_wnoutrefresh(dev->mem_util_no_enc_or_dec);\n      }\n    }\n  } else {\n    *display_decode = !cleaned_dec_window(dev, encode_decode_hiding_timer, tnow);\n  }\n}\n\nstatic void draw_devices(struct list_head *devices, struct nvtop_interface *interface) {\n  struct gpu_info *device;\n  unsigned dev_id = 0;\n\n  list_for_each_entry(device, devices, list) {\n    struct device_window *dev = &interface->devices_win[dev_id];\n\n    wcolor_set(dev->name_win, cyan_color, NULL);\n    mvwprintw(dev->name_win, 0, 0, \"Device %-2u\", dev_id);\n    wstandend(dev->name_win);\n    if (GPUINFO_STATIC_FIELD_VALID(&device->static_info, device_name)) {\n      wprintw(dev->name_win, \"[%s]\", device->static_info.device_name);\n      wnoutrefresh(dev->name_win);\n    } else {\n      wprintw(dev->name_win, \"[N/A]\");\n      wnoutrefresh(dev->name_win);\n    }\n    bool display_encode = false;\n    bool display_decode = false;\n    encode_decode_show_select(dev, GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, encoder_rate),\n                              GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, decoder_rate),\n                              device->dynamic_info.encoder_rate, device->dynamic_info.decoder_rate,\n                              interface->options.encode_decode_hiding_timer, device->static_info.encode_decode_shared,\n                              &display_encode, &display_decode);\n\n    WINDOW *gpu_util_win;\n    WINDOW *mem_util_win;\n    WINDOW *encode_win = dev->encode_util;\n    WINDOW *decode_win = dev->decode_util;\n    if ((display_encode && display_decode) || (display_decode && device->static_info.encode_decode_shared)) {\n      gpu_util_win = dev->gpu_util_enc_dec;\n      mem_util_win = dev->mem_util_enc_dec;\n      if (device->static_info.encode_decode_shared)\n        decode_win = dev->encdec_util;\n    } else {\n      if (display_encode || display_decode) {\n        // If encode only, place at decode location\n        encode_win = dev->decode_util;\n        gpu_util_win = dev->gpu_util_no_enc_or_dec;\n        mem_util_win = dev->mem_util_no_enc_or_dec;\n      } else {\n        gpu_util_win = dev->gpu_util_no_enc_and_dec;\n        mem_util_win = dev->mem_util_no_enc_and_dec;\n      }\n    }\n    char buff[1024];\n    if (display_encode) {\n      unsigned rate =\n          GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, encoder_rate) ? device->dynamic_info.encoder_rate : 0;\n      snprintf(buff, 1024, \"%u%%\", rate);\n      draw_percentage_meter(encode_win, \"ENC\", rate, buff);\n    }\n    if (display_decode) {\n      unsigned rate =\n          GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, decoder_rate) ? device->dynamic_info.decoder_rate : 0;\n      snprintf(buff, 1024, \"%u%%\", rate);\n      if (device->static_info.encode_decode_shared)\n        draw_percentage_meter(decode_win, \"ENC/DEC\", rate, buff);\n      else\n        draw_percentage_meter(decode_win, \"DEC\", rate, buff);\n    }\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_util_rate)) {\n      if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, effective_load_rate)) {\n        snprintf(buff, 1024, \"%u%%(eff %u%%)\", device->dynamic_info.gpu_util_rate,\n                 device->dynamic_info.effective_load_rate);\n        draw_percentage_meter_with_yellow_highlight(gpu_util_win, \"GPU\", device->dynamic_info.gpu_util_rate,\n                                                    device->dynamic_info.effective_load_rate, buff);\n      } else {\n        snprintf(buff, 1024, \"%u%%\", device->dynamic_info.gpu_util_rate);\n        draw_percentage_meter(gpu_util_win, \"GPU\", device->dynamic_info.gpu_util_rate, buff);\n      }\n    } else {\n      snprintf(buff, 1024, \"N/A\");\n      draw_percentage_meter(gpu_util_win, \"GPU\", 0, buff);\n    }\n\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, total_memory) &&\n        GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, used_memory)) {\n      double total_mem = device->dynamic_info.total_memory;\n      double used_mem = device->dynamic_info.used_memory;\n      double total_prefixed = total_mem, used_prefixed = used_mem;\n      size_t prefix_off;\n      for (prefix_off = 0; prefix_off < 5 && total_prefixed >= 1000.; ++prefix_off) {\n        total_prefixed /= 1024.;\n        used_prefixed /= 1024.;\n      }\n      snprintf(buff, 1024, \"%.3f%s/%.3f%s\", used_prefixed, memory_prefix[prefix_off], total_prefixed,\n               memory_prefix[prefix_off]);\n      draw_percentage_meter(mem_util_win, \"MEM\", (unsigned int)(100. * used_mem / total_mem), buff);\n    } else if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, total_memory)) {\n      double total_mem = device->dynamic_info.total_memory;\n      double total_prefixed = total_mem;\n      size_t prefix_off;\n      for (prefix_off = 0; prefix_off < 5 && total_prefixed >= 1000.; ++prefix_off) {\n        total_prefixed /= 1024.;\n      }\n      snprintf(buff, 1024, \"N/A/%.3f%s\", total_prefixed, memory_prefix[prefix_off]);\n      draw_percentage_meter(mem_util_win, \"MEM\", 0, buff);\n    } else {\n      snprintf(buff, 1024, \"N/A\");\n      draw_percentage_meter(mem_util_win, \"MEM\", 0, buff);\n    }\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_temp)) {\n      if (!GPUINFO_STATIC_FIELD_VALID(&device->static_info, temperature_slowdown_threshold))\n        device->static_info.temperature_slowdown_threshold = 0;\n      draw_temp_color(dev->temperature, device->dynamic_info.gpu_temp,\n                      device->static_info.temperature_slowdown_threshold,\n                      !interface->options.temperature_in_fahrenheit);\n    } else {\n      mvwprintw(dev->temperature, 0, 0, \"TEMP N/A\");\n      waddch(dev->temperature, ACS_DEGREE);\n      if (interface->options.temperature_in_fahrenheit)\n        waddch(dev->temperature, 'F');\n      else\n        waddch(dev->temperature, 'C');\n      mvwchgat(dev->temperature, 0, 0, 4, 0, cyan_color, NULL);\n      wnoutrefresh(dev->temperature);\n    }\n\n    // FAN\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, fan_speed)) {\n      mvwprintw(dev->fan_speed, 0, 0, \" FAN %3u%%  \",\n                device->dynamic_info.fan_speed > 100 ? 100 : device->dynamic_info.fan_speed);\n      mvwchgat(dev->fan_speed, 0, 1, 3, 0, cyan_color, NULL);\n    } else if (device->static_info.integrated_graphics) {\n      mvwprintw(dev->fan_speed, 0, 0, \"  CPU-FAN  \");\n      mvwchgat(dev->fan_speed, 0, 2, 7, 0, cyan_color, NULL);\n    } else if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, fan_rpm)) {\n      mvwprintw(dev->fan_speed, 0, 0, \"FAN %4uRPM\",\n                device->dynamic_info.fan_rpm > 9999 ? 9999 : device->dynamic_info.fan_rpm);\n      mvwchgat(dev->fan_speed, 0, 0, 3, 0, cyan_color, NULL);\n    } else {\n      mvwprintw(dev->fan_speed, 0, 0, \"  FAN N/A  \");\n      mvwchgat(dev->fan_speed, 0, 2, 3, 0, cyan_color, NULL);\n    }\n    wnoutrefresh(dev->fan_speed);\n\n    // GPU CLOCK\n    werase(dev->gpu_clock_info);\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_clock_speed))\n      mvwprintw(dev->gpu_clock_info, 0, 0, \"GPU %uMHz\", device->dynamic_info.gpu_clock_speed);\n    else\n      mvwprintw(dev->gpu_clock_info, 0, 0, \"GPU N/A MHz\");\n\n    mvwchgat(dev->gpu_clock_info, 0, 0, 3, 0, cyan_color, NULL);\n    wnoutrefresh(dev->gpu_clock_info);\n\n    // MEM CLOCK\n    werase(dev->mem_clock_info);\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, mem_clock_speed))\n      mvwprintw(dev->mem_clock_info, 0, 0, \"MEM %uMHz\", device->dynamic_info.mem_clock_speed);\n    else\n      mvwprintw(dev->mem_clock_info, 0, 0, \"MEM N/A MHz\");\n    mvwchgat(dev->mem_clock_info, 0, 0, 3, 0, cyan_color, NULL);\n    wnoutrefresh(dev->mem_clock_info);\n\n    // POWER\n    werase(dev->power_info);\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw) &&\n        GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw_max))\n      mvwprintw(dev->power_info, 0, 0, \"POW %3u / %3u W\", device->dynamic_info.power_draw / 1000,\n                device->dynamic_info.power_draw_max / 1000);\n    else if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw) &&\n             !GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw_max))\n      mvwprintw(dev->power_info, 0, 0, \"POW %3u W\", device->dynamic_info.power_draw / 1000);\n    else if (!GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw) &&\n             GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw_max))\n      mvwprintw(dev->power_info, 0, 0, \"POW N/A / %3u W\", device->dynamic_info.power_draw_max / 1000);\n    else\n      mvwprintw(dev->power_info, 0, 0, \"POW N/A W\");\n    mvwchgat(dev->power_info, 0, 0, 3, 0, cyan_color, NULL);\n    wnoutrefresh(dev->power_info);\n\n    // PICe throughput\n    werase(dev->pcie_info);\n    if (device->static_info.integrated_graphics) {\n      wcolor_set(dev->pcie_info, cyan_color, NULL);\n      mvwprintw(dev->pcie_info, 0, 0, \"Integrated GPU\");\n    } else {\n      wcolor_set(dev->pcie_info, cyan_color, NULL);\n      mvwprintw(dev->pcie_info, 0, 0, \"PCIe \");\n      wcolor_set(dev->pcie_info, magenta_color, NULL);\n      wprintw(dev->pcie_info, \"GEN \");\n      wstandend(dev->pcie_info);\n      if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, pcie_link_gen) &&\n          GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, pcie_link_width))\n        wprintw(dev->pcie_info, \"%u@%2ux\", device->dynamic_info.pcie_link_gen, device->dynamic_info.pcie_link_width);\n      else\n        wprintw(dev->pcie_info, \"N/A\");\n    }\n\n    wcolor_set(dev->pcie_info, magenta_color, NULL);\n    wprintw(dev->pcie_info, \" RX: \");\n    wstandend(dev->pcie_info);\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, pcie_rx))\n      print_pcie_at_scale(dev->pcie_info, device->dynamic_info.pcie_rx);\n    else\n      wprintw(dev->pcie_info, \"N/A\");\n    wcolor_set(dev->pcie_info, magenta_color, NULL);\n    wprintw(dev->pcie_info, \" TX: \");\n    wstandend(dev->pcie_info);\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, pcie_tx))\n      print_pcie_at_scale(dev->pcie_info, device->dynamic_info.pcie_tx);\n    else\n      wprintw(dev->pcie_info, \"N/A\");\n\n    wnoutrefresh(dev->pcie_info);\n\n    if (interface->options.has_gpu_info_bar) {\n      // Number of shader cores\n      werase(dev->shader_cores);\n      wcolor_set(dev->shader_cores, cyan_color, NULL);\n      mvwprintw(dev->shader_cores, 0, 0, \"NSHC \");\n      wstandend(dev->shader_cores);\n      if (GPUINFO_STATIC_FIELD_VALID(&device->static_info, n_shared_cores))\n        wprintw(dev->shader_cores, \"%u\", device->static_info.n_shared_cores);\n      else\n        wprintw(dev->shader_cores, \"N/A\");\n\n      wnoutrefresh(dev->shader_cores);\n\n      // L2 cache information\n      werase(dev->l2_cache_size);\n      wcolor_set(dev->l2_cache_size, cyan_color, NULL);\n      mvwprintw(dev->l2_cache_size, 0, 0, \"L2CF \");\n      wstandend(dev->l2_cache_size);\n      if (GPUINFO_STATIC_FIELD_VALID(&device->static_info, l2cache_size))\n        wprintw(dev->l2_cache_size, \"%u\", device->static_info.l2cache_size);\n      else\n        wprintw(dev->l2_cache_size, \"N/A\");\n\n      wnoutrefresh(dev->l2_cache_size);\n\n      // Number of execution engines\n      werase(dev->exec_engines);\n      wcolor_set(dev->exec_engines, cyan_color, NULL);\n      mvwprintw(dev->exec_engines, 0, 0, \"NEXC \");\n      wstandend(dev->exec_engines);\n      if (GPUINFO_STATIC_FIELD_VALID(&device->static_info, n_exec_engines))\n        wprintw(dev->exec_engines, \"%u\", device->static_info.n_exec_engines);\n      else\n        wprintw(dev->exec_engines, \"N/A\");\n\n      wnoutrefresh(dev->exec_engines);\n    }\n\n    dev_id++;\n  }\n}\n\ntypedef struct {\n  unsigned processes_count;\n  struct gpuid_and_process {\n    unsigned gpu_id;\n    struct gpu_process *process;\n  } *processes;\n} all_processes;\n\nstatic all_processes all_processes_array(struct list_head *devices) {\n  unsigned total_processes_count = 0;\n  struct gpu_info *device;\n  unsigned dev_id = 0;\n\n  list_for_each_entry(device, devices, list) { total_processes_count += device->processes_count; }\n\n  all_processes merged_devices_processes;\n  merged_devices_processes.processes_count = total_processes_count;\n  if (total_processes_count) {\n    merged_devices_processes.processes = malloc(total_processes_count * sizeof(*merged_devices_processes.processes));\n    if (!merged_devices_processes.processes) {\n      perror(\"Cannot allocate memory: \");\n      exit(EXIT_FAILURE);\n    }\n  } else {\n    merged_devices_processes.processes = NULL;\n  }\n\n  size_t offset = 0;\n  list_for_each_entry(device, devices, list) {\n    for (unsigned int j = 0; j < device->processes_count; ++j) {\n      merged_devices_processes.processes[offset].gpu_id = dev_id;\n      merged_devices_processes.processes[offset++].process = &device->processes[j];\n    }\n\n    dev_id++;\n  }\n\n  return merged_devices_processes;\n}\n\nstatic int compare_pid_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  return p1->process->pid >= p2->process->pid ? -1 : 1;\n}\n\nstatic int compare_pid_asc(const void *pp1, const void *pp2) { return compare_pid_desc(pp2, pp1); }\n\nstatic int compare_username_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, user_name) && GPUINFO_PROCESS_FIELD_VALID(p2->process, user_name))\n    return -strcmp(p1->process->user_name, p2->process->user_name);\n  else\n    return 0;\n}\n\nstatic int compare_username_asc(const void *pp1, const void *pp2) { return compare_username_desc(pp2, pp1); }\n\nstatic int compare_process_name_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, cmdline) && GPUINFO_PROCESS_FIELD_VALID(p2->process, cmdline))\n    return -strcmp(p1->process->cmdline, p2->process->cmdline);\n  else\n    return 0;\n}\n\nstatic int compare_process_name_asc(const void *pp1, const void *pp2) { return compare_process_name_desc(pp2, pp1); }\n\nstatic int compare_mem_usage_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, gpu_memory_usage) &&\n      GPUINFO_PROCESS_FIELD_VALID(p2->process, gpu_memory_usage))\n    return p1->process->gpu_memory_usage >= p2->process->gpu_memory_usage ? -1 : 1;\n  else\n    return 0;\n}\n\nstatic int compare_mem_usage_asc(const void *pp1, const void *pp2) { return compare_mem_usage_desc(pp2, pp1); }\n\nstatic int compare_cpu_usage_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, cpu_usage) && GPUINFO_PROCESS_FIELD_VALID(p2->process, cpu_usage))\n    return p1->process->cpu_usage >= p2->process->cpu_usage ? -1 : 1;\n  else\n    return 0;\n}\n\nstatic int compare_cpu_usage_asc(const void *pp1, const void *pp2) { return compare_cpu_usage_desc(pp2, pp1); }\n\nstatic int compare_cpu_mem_usage_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, cpu_memory_res) &&\n      GPUINFO_PROCESS_FIELD_VALID(p2->process, cpu_memory_res))\n    return p1->process->cpu_memory_res >= p2->process->cpu_memory_res ? -1 : 1;\n  else\n    return 0;\n}\n\nstatic int compare_cpu_mem_usage_asc(const void *pp1, const void *pp2) { return compare_cpu_mem_usage_desc(pp2, pp1); }\n\nstatic int compare_gpu_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  return p1->gpu_id >= p2->gpu_id ? -1 : 1;\n}\n\nstatic int compare_gpu_asc(const void *pp1, const void *pp2) { return -compare_gpu_desc(pp1, pp2); }\n\nstatic int compare_process_type_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  return (p1->process->type == gpu_process_graphical) != (p2->process->type == gpu_process_graphical);\n}\n\nstatic int compare_process_type_asc(const void *pp1, const void *pp2) { return -compare_process_name_desc(pp1, pp2); }\n\nstatic int compare_process_gpu_rate_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, gpu_usage) && GPUINFO_PROCESS_FIELD_VALID(p2->process, gpu_usage)) {\n    return p1->process->gpu_usage > p2->process->gpu_usage ? -1 : 1;\n  } else {\n    if (GPUINFO_PROCESS_FIELD_VALID(p1->process, gpu_usage)) {\n      return p1->process->gpu_usage > 0 ? -1 : 0;\n    } else if (GPUINFO_PROCESS_FIELD_VALID(p2->process, gpu_usage)) {\n      return p2->process->gpu_usage > 0 ? 1 : 0;\n    } else {\n      return 0;\n    }\n  }\n}\n\nstatic int compare_process_gpu_rate_asc(const void *pp1, const void *pp2) {\n  return -compare_process_gpu_rate_desc(pp1, pp2);\n}\n\nstatic int compare_process_enc_rate_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, encode_usage) &&\n      GPUINFO_PROCESS_FIELD_VALID(p2->process, encode_usage)) {\n    return p1->process->encode_usage >= p2->process->encode_usage ? -1 : 1;\n  } else {\n    if (GPUINFO_PROCESS_FIELD_VALID(p1->process, encode_usage)) {\n      return p1->process->encode_usage > 0 ? -1 : 0;\n    } else if (GPUINFO_PROCESS_FIELD_VALID(p2->process, encode_usage)) {\n      return p2->process->encode_usage > 0 ? 1 : 0;\n    } else {\n      return 0;\n    }\n  }\n}\n\nstatic int compare_process_enc_rate_asc(const void *pp1, const void *pp2) {\n  return -compare_process_enc_rate_desc(pp1, pp2);\n}\n\nstatic int compare_process_dec_rate_desc(const void *pp1, const void *pp2) {\n  const struct gpuid_and_process *p1 = (const struct gpuid_and_process *)pp1;\n  const struct gpuid_and_process *p2 = (const struct gpuid_and_process *)pp2;\n  if (GPUINFO_PROCESS_FIELD_VALID(p1->process, decode_usage) &&\n      GPUINFO_PROCESS_FIELD_VALID(p2->process, decode_usage)) {\n    return p1->process->decode_usage >= p2->process->decode_usage ? -1 : 1;\n  } else {\n    if (GPUINFO_PROCESS_FIELD_VALID(p1->process, decode_usage)) {\n      return p1->process->decode_usage > 0 ? -1 : 0;\n    } else if (GPUINFO_PROCESS_FIELD_VALID(p2->process, decode_usage)) {\n      return p2->process->decode_usage > 0 ? 1 : 0;\n    } else {\n      return 0;\n    }\n  }\n}\nstatic int compare_process_dec_rate_asc(const void *pp1, const void *pp2) {\n  return -compare_process_dec_rate_desc(pp1, pp2);\n}\n\nstatic void sort_process(all_processes all_procs, enum process_field criterion, bool asc_sort) {\n  if (all_procs.processes_count == 0 || !all_procs.processes)\n    return;\n  int (*sort_fun)(const void *, const void *);\n  switch (criterion) {\n  case process_pid:\n    if (asc_sort)\n      sort_fun = compare_pid_asc;\n    else\n      sort_fun = compare_pid_desc;\n    break;\n  case process_user:\n    if (asc_sort)\n      sort_fun = compare_username_asc;\n    else\n      sort_fun = compare_username_desc;\n    break;\n  case process_gpu_id:\n    if (asc_sort)\n      sort_fun = compare_gpu_asc;\n    else\n      sort_fun = compare_gpu_desc;\n    break;\n  case process_type:\n    if (asc_sort)\n      sort_fun = compare_process_type_asc;\n    else\n      sort_fun = compare_process_type_desc;\n    break;\n  case process_memory:\n    if (asc_sort)\n      sort_fun = compare_mem_usage_asc;\n    else\n      sort_fun = compare_mem_usage_desc;\n    break;\n  case process_command:\n    if (asc_sort)\n      sort_fun = compare_process_name_asc;\n    else\n      sort_fun = compare_process_name_desc;\n    break;\n  case process_cpu_usage:\n    if (asc_sort)\n      sort_fun = compare_cpu_usage_asc;\n    else\n      sort_fun = compare_cpu_usage_desc;\n    break;\n  case process_cpu_mem_usage:\n    if (asc_sort)\n      sort_fun = compare_cpu_mem_usage_asc;\n    else\n      sort_fun = compare_cpu_mem_usage_desc;\n    break;\n  case process_gpu_rate:\n    if (asc_sort)\n      sort_fun = compare_process_gpu_rate_asc;\n    else\n      sort_fun = compare_process_gpu_rate_desc;\n    break;\n  case process_enc_rate:\n    if (asc_sort)\n      sort_fun = compare_process_enc_rate_asc;\n    else\n      sort_fun = compare_process_enc_rate_desc;\n    break;\n  case process_dec_rate:\n    if (asc_sort)\n      sort_fun = compare_process_dec_rate_asc;\n    else\n      sort_fun = compare_process_dec_rate_desc;\n    break;\n  case process_field_count:\n    return;\n  }\n  qsort(all_procs.processes, all_procs.processes_count, sizeof(*all_procs.processes), sort_fun);\n}\n\nstatic void filter_out_nvtop_pid(all_processes *all_procs, struct nvtop_interface *interface) {\n  if (interface->options.filter_nvtop_pid) {\n    for (unsigned procId = 0; procId < all_procs->processes_count; ++procId) {\n      if (all_procs->processes[procId].process->pid == nvtop_pid) {\n        memmove(&all_procs->processes[procId], &all_procs->processes[procId + 1],\n                (all_procs->processes_count - procId - 1) * sizeof(*all_procs->processes));\n        all_procs->processes_count = all_procs->processes_count - 1;\n        break;\n      }\n    }\n  }\n}\n\nstatic const char *columnName[process_field_count] = {\n    \"PID\", \"USER\", \"DEV\", \"TYPE\", \"GPU\", \"ENC\", \"DEC\", \"GPU MEM\", \"CPU\", \"HOST MEM\", \"Command\",\n};\n\nstatic void update_selected_offset_with_window_size(unsigned int *selected_row, unsigned int *offset,\n                                                    unsigned int row_available_to_draw, unsigned int num_to_draw) {\n\n  if (!num_to_draw)\n    return;\n\n  if (*selected_row > num_to_draw - 1)\n    *selected_row = num_to_draw - 1;\n\n  if (*offset > *selected_row)\n    *offset = *selected_row;\n\n  if (*offset + row_available_to_draw - 1 < *selected_row)\n    *offset = *selected_row - row_available_to_draw + 1;\n\n  while (row_available_to_draw > num_to_draw - *offset && *offset != 0)\n    *offset -= 1;\n}\n\n#define process_buffer_line_size 8192\nstatic char process_print_buffer[process_buffer_line_size];\n\nstatic void print_processes_on_screen(all_processes all_procs, struct process_window *process,\n                                      enum process_field sort_criterion, process_field_displayed fields_to_display) {\n  WINDOW *win = process->option_window.state == nvtop_option_state_hidden ? process->process_win\n                                                                          : process->process_with_option_win;\n  struct gpuid_and_process *processes = all_procs.processes;\n\n  unsigned int rows, cols;\n  getmaxyx(win, rows, cols);\n  rows -= 1;\n\n  update_selected_offset_with_window_size(&process->selected_row, &process->offset, rows, all_procs.processes_count);\n  if (process->offset_column + cols >= process_buffer_line_size)\n    process->offset_column = process_buffer_line_size - cols - 1;\n\n  size_t special_row = process->selected_row;\n\n  char pid_str[sizeof_process_field[process_pid] + 1];\n  char guid_str[sizeof_process_field[process_gpu_id] + 1];\n  char memory[sizeof_process_field[process_memory] + 1];\n  char cpu_percent[sizeof_process_field[process_cpu_usage] + 1];\n  char cpu_mem[sizeof_process_field[process_cpu_mem_usage] + 1];\n\n  unsigned int start_at_process = process->offset;\n  unsigned int end_at_process = start_at_process + rows;\n\n  int printed = 0;\n  int column_sort_start = 0, column_sort_end = sizeof_process_field[0];\n  memset(process_print_buffer, 0, sizeof(process_print_buffer));\n  for (enum process_field i = process_pid; i < process_field_count; ++i) {\n    if (i == sort_criterion) {\n      column_sort_start = printed;\n      column_sort_end =\n          i == process_command ? process_buffer_line_size - 4 : column_sort_start + sizeof_process_field[i];\n    }\n    if (process_is_field_displayed(i, fields_to_display))\n      printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                          sizeof_process_field[i], columnName[i]);\n  }\n\n  mvwprintw(win, 0, 0, \"%.*s\", cols, &process_print_buffer[process->offset_column]);\n  wclrtoeol(win);\n  mvwchgat(win, 0, 0, -1, A_STANDOUT, green_color, NULL);\n  set_attribute_between(win, 0, column_sort_start - (int)process->offset_column,\n                        column_sort_end - (int)process->offset_column, A_STANDOUT, cyan_color);\n\n  int start_col_process_type = 0;\n  for (enum process_field i = process_pid; i < process_type; ++i) {\n    if (process_is_field_displayed(i, fields_to_display))\n      start_col_process_type += sizeof_process_field[i] + 1;\n  }\n  int end_col_process_type = start_col_process_type + sizeof_process_field[process_type];\n\n  static unsigned printed_last_call = 0;\n  unsigned last_line_printed = 0;\n  for (unsigned int i = start_at_process; i < end_at_process && i < all_procs.processes_count; ++i) {\n    memset(process_print_buffer, 0, sizeof(process_print_buffer));\n\n    printed = 0;\n    if (process_is_field_displayed(process_pid, fields_to_display)) {\n      size_t size =\n          snprintf(pid_str, sizeof_process_field[process_pid] + 1, \"%\" PRIdMAX, (intmax_t)processes[i].process->pid);\n      if (size == sizeof_process_field[process_pid] + 1)\n        pid_str[sizeof_process_field[process_pid]] = '\\0';\n      printed += snprintf(&process_print_buffer[printed], process_buffer_line_size, \"%*s \",\n                          sizeof_process_field[process_pid], pid_str);\n    }\n\n    if (process_is_field_displayed(process_user, fields_to_display)) {\n      const char *username;\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, user_name)) {\n        username = processes[i].process->user_name;\n      } else {\n        username = \"N/A\";\n      }\n\n      printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                          sizeof_process_field[process_user], username);\n    }\n\n    if (process_is_field_displayed(process_gpu_id, fields_to_display)) {\n      size_t size = snprintf(guid_str, sizeof_process_field[process_gpu_id] + 1, \"%u\", processes[i].gpu_id);\n      if (size >= sizeof_process_field[process_gpu_id] + 1)\n        pid_str[sizeof_process_field[process_gpu_id]] = '\\0';\n      printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                          sizeof_process_field[process_gpu_id], guid_str);\n    }\n\n    if (process_is_field_displayed(process_type, fields_to_display)) {\n      if (processes[i].process->type == gpu_process_graphical_compute) {\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                            sizeof_process_field[process_type], \"Both G+C\");\n      } else if (processes[i].process->type == gpu_process_graphical) {\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                            sizeof_process_field[process_type], \"Graphic\");\n      } else {\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                            sizeof_process_field[process_type], \"Compute\");\n      }\n    }\n\n    if (process_is_field_displayed(process_gpu_rate, fields_to_display)) {\n      unsigned gpu_usage = 0;\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, gpu_usage)) {\n        gpu_usage = processes[i].process->gpu_usage;\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%3u%% \", gpu_usage);\n      } else {\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"N/A  \");\n      }\n    }\n\n    if (process_is_field_displayed(process_enc_rate, fields_to_display)) {\n      unsigned encoder_rate = 0;\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, encode_usage)) {\n        encoder_rate = processes[i].process->encode_usage;\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%3u%% \", encoder_rate);\n      } else {\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"N/A  \");\n      }\n    }\n\n    if (process_is_field_displayed(process_dec_rate, fields_to_display)) {\n      unsigned decode_rate = 0;\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, decode_usage)) {\n        decode_rate = processes[i].process->decode_usage;\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%3u%% \", decode_rate);\n      } else {\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"N/A  \");\n      }\n    }\n\n    if (process_is_field_displayed(process_memory, fields_to_display)) {\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, gpu_memory_usage)) {\n        if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, gpu_memory_percentage)) {\n          snprintf(memory, 9 + 1, \"%6uMiB\", (unsigned)(processes[i].process->gpu_memory_usage / 1048576));\n          snprintf(memory + 9, sizeof_process_field[process_memory] - 9 + 1, \" %3u%%\",\n                   processes[i].process->gpu_memory_percentage);\n        } else {\n          snprintf(memory, sizeof_process_field[process_memory], \"%6uMiB\",\n                   (unsigned)(processes[i].process->gpu_memory_usage / 1048576));\n        }\n      } else {\n        snprintf(memory, sizeof_process_field[process_memory], \"%s\", \"N/A\");\n      }\n      printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                          sizeof_process_field[process_memory], memory);\n    }\n\n    if (process_is_field_displayed(process_cpu_usage, fields_to_display)) {\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, cpu_usage))\n        snprintf(cpu_percent, sizeof_process_field[process_cpu_usage] + 1, \"%u%%\", processes[i].process->cpu_usage);\n      else\n        snprintf(cpu_percent, sizeof_process_field[process_cpu_usage] + 1, \"   N/A\");\n      printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                          sizeof_process_field[process_cpu_usage], cpu_percent);\n    }\n\n    if (process_is_field_displayed(process_cpu_mem_usage, fields_to_display)) {\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, cpu_memory_res))\n        snprintf(cpu_mem, sizeof_process_field[process_cpu_mem_usage] + 1, \"%zuMiB\",\n                 processes[i].process->cpu_memory_res / 1048576);\n      else\n        snprintf(cpu_mem, sizeof_process_field[process_cpu_mem_usage] + 1, \"N/A\");\n      printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%*s \",\n                          sizeof_process_field[process_cpu_mem_usage], cpu_mem);\n    }\n\n    if (process_is_field_displayed(process_command, fields_to_display)) {\n      if (GPUINFO_PROCESS_FIELD_VALID(processes[i].process, cmdline))\n        printed += snprintf(&process_print_buffer[printed], process_buffer_line_size - printed, \"%.*s\",\n                            process_buffer_line_size - printed, processes[i].process->cmdline);\n    }\n\n    unsigned int write_at = i - start_at_process + 1;\n    mvwprintw(win, write_at, 0, \"%.*s\", cols, &process_print_buffer[process->offset_column]);\n    unsigned row, col;\n    getyx(win, row, col);\n    (void)col;\n    if (row == write_at)\n      wclrtoeol(win);\n    last_line_printed = write_at;\n    if (i == special_row) {\n      mvwchgat(win, write_at, 0, -1, A_STANDOUT, cyan_color, NULL);\n    } else {\n      if (process_is_field_displayed(process_type, fields_to_display)) {\n        if (processes[i].process->type == gpu_process_graphical_compute) {\n          set_attribute_between(win, write_at, start_col_process_type - (int)process->offset_column,\n                                start_col_process_type - (int)process->offset_column + 4, 0, cyan_color);\n          set_attribute_between(win, write_at, end_col_process_type - (int)process->offset_column - 3,\n                                end_col_process_type - (int)process->offset_column - 2, 0, yellow_color);\n          set_attribute_between(win, write_at, end_col_process_type - (int)process->offset_column - 1,\n                                end_col_process_type - (int)process->offset_column, 0, magenta_color);\n        } else if (processes[i].process->type == gpu_process_graphical) {\n          set_attribute_between(win, write_at, start_col_process_type - (int)process->offset_column,\n                                end_col_process_type - (int)process->offset_column, 0, yellow_color);\n        } else {\n          set_attribute_between(win, write_at, start_col_process_type - (int)process->offset_column,\n                                end_col_process_type - (int)process->offset_column, 0, magenta_color);\n        }\n      }\n    }\n  }\n  if (printed_last_call > last_line_printed) {\n    for (unsigned i = last_line_printed + 1; i <= rows && i <= printed_last_call; ++i) {\n      wmove(win, i, 0);\n      wclrtoeol(win);\n    }\n  }\n  printed_last_call = last_line_printed;\n  wnoutrefresh(win);\n}\n\nstatic void update_process_option_win(struct nvtop_interface *interface);\n\nstatic void draw_processes(struct list_head *devices, struct nvtop_interface *interface) {\n  if (interface->options.hide_processes_list)\n    return;\n\n  if (interface->process.process_win == NULL)\n    return;\n\n  if (interface->process.option_window.state != interface->process.option_window.previous_state) {\n    werase(interface->process.option_window.option_win);\n    wclear(interface->process.process_win);\n    wclear(interface->process.process_with_option_win);\n    wnoutrefresh(interface->process.option_window.option_win);\n  }\n  if (interface->process.option_window.state != nvtop_option_state_hidden)\n    update_process_option_win(interface);\n\n  all_processes all_procs = all_processes_array(devices);\n  filter_out_nvtop_pid(&all_procs, interface);\n  sort_process(all_procs, interface->options.sort_processes_by, !interface->options.sort_descending_order);\n\n  if (all_procs.processes_count > 0) {\n    if (interface->process.selected_row >= all_procs.processes_count)\n      interface->process.selected_row = all_procs.processes_count - 1;\n    interface->process.selected_pid = all_procs.processes[interface->process.selected_row].process->pid;\n  } else {\n    interface->process.selected_row = 0;\n    interface->process.selected_pid = -1;\n  }\n\n  unsigned largest_username = 4;\n  for (unsigned i = 0; i < all_procs.processes_count; ++i) {\n    if (GPUINFO_PROCESS_FIELD_VALID(all_procs.processes[i].process, user_name)) {\n      unsigned length = strlen(all_procs.processes[i].process->user_name);\n      if (length > largest_username)\n        largest_username = length;\n    }\n  }\n  sizeof_process_field[process_user] = largest_username;\n\n  print_processes_on_screen(all_procs, &interface->process, interface->options.sort_processes_by,\n                            interface->options.process_fields_displayed);\n  free(all_procs.processes);\n}\n\nstatic const char *signalNames[] = {\n    \"Cancel\",  \"SIGHUP\",    \"SIGINT\",  \"SIGQUIT\",  \"SIGILL\",  \"SIGTRAP\", \"SIGABRT\", \"SIGBUS\",\n    \"SIGFPE\",  \"SIGKILL\",   \"SIGUSR1\", \"SIGSEGV\",  \"SIGUSR2\", \"SIGPIPE\", \"SIGALRM\", \"SIGTERM\",\n    \"SIGCHLD\", \"SIGCONT\",   \"SIGSTOP\", \"SIGTSTP\",  \"SIGTTIN\", \"SIGTTOU\", \"SIGURG\",  \"SIGXCPU\",\n    \"SIGXFSZ\", \"SIGVTALRM\", \"SIGPROF\", \"SIGWINCH\", \"SIGIO\",   \"SIGPWR\",  \"SIGSYS\",\n};\n\n// SIGPWR does not exist on FreeBSD or Apple, while it is a synonym for SIGINFO on Linux\n#if defined(__FreeBSD__) || defined(__APPLE__)\n#define SIGPWR SIGINFO\n#endif\n\nstatic const int signalValues[ARRAY_SIZE(signalNames)] = {\n    -1,      SIGHUP,  SIGINT,  SIGQUIT,   SIGILL,  SIGTRAP,  SIGABRT, SIGBUS,  SIGFPE,  SIGKILL, SIGUSR1,\n    SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM,   SIGTERM, SIGCHLD,  SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU,\n    SIGURG,  SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO,   SIGPWR,  SIGSYS,\n};\n\nstatic const size_t nvtop_num_signals = ARRAY_SIZE(signalNames) - 1;\n\nstatic void draw_kill_option(struct nvtop_interface *interface) {\n  WINDOW *win = interface->process.option_window.option_win;\n  wattr_set(win, A_REVERSE, green_color, NULL);\n  mvwprintw(win, 0, 0, \"Send signal:\");\n  wstandend(win);\n  wprintw(win, \" \");\n  int rows, cols;\n  getmaxyx(win, rows, cols);\n\n  size_t start_at_option = interface->process.option_window.offset;\n  size_t end_at_option = start_at_option + rows - 1;\n\n  for (size_t i = start_at_option; i < end_at_option && i <= nvtop_num_signals; ++i) {\n    if (i == interface->process.option_window.selected_row) {\n      wattr_set(win, A_STANDOUT, cyan_color, NULL);\n    }\n    wprintw(win, \"%*zu %s\", 2, i, signalNames[i]);\n    getyx(win, rows, cols);\n\n    for (unsigned int j = cols; j < option_window_size; ++j)\n      wprintw(win, \" \");\n    if (i == interface->process.option_window.selected_row) {\n      wstandend(win);\n      mvwprintw(win, rows, option_window_size - 1, \" \");\n    }\n  }\n  wnoutrefresh(win);\n}\n\nstatic void draw_sort_option(struct nvtop_interface *interface) {\n  WINDOW *win = interface->process.option_window.option_win;\n  wattr_set(win, A_REVERSE, green_color, NULL);\n  mvwprintw(win, 0, 0, \"Sort by     \");\n  wstandend(win);\n  wprintw(win, \" \");\n  int rows, cols;\n  if (interface->process.option_window.offset == 0) {\n    if (interface->process.option_window.selected_row == 0) {\n      wattr_set(win, A_STANDOUT, cyan_color, NULL);\n    }\n    wprintw(win, \"Cancel\");\n    getyx(win, rows, cols);\n    for (unsigned int j = cols; j < option_window_size; ++j)\n      wprintw(win, \" \");\n    if (interface->process.option_window.selected_row == 0) {\n      wstandend(win);\n      mvwprintw(win, rows, option_window_size - 1, \" \");\n    }\n  }\n  getmaxyx(win, rows, cols);\n\n  size_t start_at_option = interface->process.option_window.offset == 0 ? interface->process.option_window.offset\n                                                                        : interface->process.option_window.offset - 1;\n  size_t end_at_option =\n      interface->process.option_window.offset == 0 ? start_at_option + rows - 2 : start_at_option + rows - 1;\n\n  unsigned option_index = 0;\n  for (enum process_field field = process_pid; field < process_field_count; ++field) {\n    if (process_is_field_displayed(field, interface->options.process_fields_displayed)) {\n      if (option_index >= start_at_option && option_index < end_at_option) {\n        if (option_index + 1 == interface->process.option_window.selected_row) {\n          wattr_set(win, A_STANDOUT, cyan_color, NULL);\n        }\n        wprintw(win, \"%s\", columnName[field]);\n        getyx(win, rows, cols);\n        for (unsigned int j = cols; j < option_window_size; ++j)\n          wprintw(win, \" \");\n\n        if (option_index + 1 == interface->process.option_window.selected_row) {\n          wstandend(win);\n          mvwprintw(win, rows, option_window_size - 1, \" \");\n        }\n      }\n      option_index++;\n    }\n  }\n  wnoutrefresh(win);\n}\n\nstatic void update_process_option_win(struct nvtop_interface *interface) {\n  unsigned int rows, cols;\n  getmaxyx(interface->process.option_window.option_win, rows, cols);\n  rows -= 1;\n  (void)cols;\n  unsigned int num_options = 0;\n  switch (interface->process.option_window.state) {\n  case nvtop_option_state_kill:\n    num_options = nvtop_num_signals + 1; // Option + Cancel\n    break;\n  case nvtop_option_state_sort_by:\n    num_options = process_field_displayed_count(interface->options.process_fields_displayed) + 1; // Option + Cancel\n    break;\n  case nvtop_option_state_hidden:\n  default:\n    break;\n  }\n\n  update_selected_offset_with_window_size(&interface->process.option_window.selected_row,\n                                          &interface->process.option_window.offset, rows, num_options);\n\n  switch (interface->process.option_window.state) {\n  case nvtop_option_state_kill:\n    draw_kill_option(interface);\n    break;\n  case nvtop_option_state_sort_by:\n    draw_sort_option(interface);\n    break;\n  case nvtop_option_state_hidden:\n  default:\n    break;\n  }\n}\n\nstatic const char *option_selection_hidden[] = {\n    \"Setup\", \"Sort\", \"Kill\", \"Quit\", \"Save Config\",\n};\nstatic const char *option_selection_hidden_num[] = {\n    \"2\", \"6\", \"9\", \"10\", \"12\",\n};\n\nstatic const char *option_selection_sort[][2] = {\n    {\"Enter\", \"Sort\"},\n    {\"ESC\", \"Cancel\"},\n    {\"+\", \"Ascending\"},\n    {\"-\", \"Descending\"},\n};\n\nstatic const char *option_selection_kill[][2] = {\n    {\"Enter\", \"Send\"},\n    {\"ESC\", \"Cancel\"},\n};\n\nstatic const unsigned int option_selection_width = 8;\n\nstatic void draw_process_shortcuts(struct nvtop_interface *interface) {\n  if (interface->process.option_window.state == interface->process.option_window.previous_state)\n    return;\n  WINDOW *win = interface->shortcut_window;\n  enum nvtop_option_window_state current_state = interface->process.option_window.state;\n  wmove(win, 0, 0);\n  switch (current_state) {\n  case nvtop_option_state_hidden:\n    for (size_t i = 0; i < ARRAY_SIZE(option_selection_hidden); ++i) {\n      if (interface->options.hide_processes_list &&\n          (strcmp(option_selection_hidden_num[i], \"6\") == 0 || strcmp(option_selection_hidden_num[i], \"9\") == 0))\n        continue;\n\n      if (process_field_displayed_count(interface->options.process_fields_displayed) > 0 || (i != 1 && i != 2)) {\n        wprintw(win, \"F%s\", option_selection_hidden_num[i]);\n        wattr_set(win, A_STANDOUT, cyan_color, NULL);\n        wprintw(win, \"%-*s\", option_selection_width, option_selection_hidden[i]);\n        wstandend(win);\n      }\n    }\n    break;\n  case nvtop_option_state_kill:\n    for (size_t i = 0; i < ARRAY_SIZE(option_selection_kill); ++i) {\n      wprintw(win, \"%s\", option_selection_kill[i][0]);\n      wattr_set(win, A_STANDOUT, cyan_color, NULL);\n      wprintw(win, \"%-*s\", option_selection_width, option_selection_kill[i][1]);\n      wstandend(win);\n    }\n    break;\n  case nvtop_option_state_sort_by:\n    for (size_t i = 0; i < ARRAY_SIZE(option_selection_sort); ++i) {\n      wprintw(win, \"%s\", option_selection_sort[i][0]);\n      wattr_set(win, A_STANDOUT, cyan_color, NULL);\n      wprintw(win, \"%-*s\", option_selection_width, option_selection_sort[i][1]);\n      wstandend(win);\n    }\n    break;\n  default:\n    break;\n  }\n  wclrtoeol(win);\n  unsigned int cur_col, tmp;\n  (void)tmp;\n  getyx(win, tmp, cur_col);\n  mvwchgat(win, 0, cur_col, -1, A_STANDOUT, cyan_color, NULL);\n  wnoutrefresh(win);\n  interface->process.option_window.previous_state = current_state;\n}\n\nstatic void draw_shortcuts(struct nvtop_interface *interface) {\n  if (interface->setup_win.visible) {\n    draw_setup_window_shortcuts(interface);\n  } else {\n    draw_process_shortcuts(interface);\n  }\n}\n\nvoid save_current_data_to_ring(struct list_head *devices, struct nvtop_interface *interface) {\n  struct gpu_info *device;\n  unsigned dev_id = 0;\n\n  list_for_each_entry(device, devices, list) {\n    unsigned data_index = 0;\n    for (enum plot_information info = plot_gpu_rate; info < plot_information_count; ++info) {\n      if (plot_isset_draw_info(info, interface->options.gpu_specific_opts[dev_id].to_draw)) {\n        unsigned data_val = 0;\n        switch (info) {\n        case plot_gpu_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_util_rate))\n            data_val = device->dynamic_info.gpu_util_rate;\n          break;\n        case plot_gpu_mem_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, mem_util_rate))\n            data_val = device->dynamic_info.mem_util_rate;\n          break;\n        case plot_encoder_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, encoder_rate))\n            data_val = device->dynamic_info.encoder_rate;\n          break;\n        case plot_decoder_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, decoder_rate))\n            data_val = device->dynamic_info.decoder_rate;\n          break;\n        case plot_gpu_temperature:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_temp)) {\n            data_val = device->dynamic_info.gpu_temp;\n            if (data_val > 100)\n              data_val = 100u;\n          }\n          break;\n        case plot_gpu_power_draw_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw) &&\n              GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw_max)) {\n            data_val = device->dynamic_info.power_draw * 100 / device->dynamic_info.power_draw_max;\n            if (data_val > 100)\n              data_val = 100u;\n          }\n          break;\n        case plot_fan_speed:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, fan_speed)) {\n            data_val = device->dynamic_info.fan_speed;\n          }\n          break;\n        case plot_gpu_clock_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_clock_speed) &&\n              GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_clock_speed_max)) {\n            data_val = device->dynamic_info.gpu_clock_speed * 100 / device->dynamic_info.gpu_clock_speed_max;\n          }\n          break;\n        case plot_gpu_mem_clock_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, mem_clock_speed) &&\n              GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, mem_clock_speed_max)) {\n            data_val = device->dynamic_info.mem_clock_speed * 100 / device->dynamic_info.mem_clock_speed_max;\n          }\n          break;\n        case plot_effective_load_rate:\n          if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, effective_load_rate)) {\n            data_val = device->dynamic_info.effective_load_rate;\n          }\n          break;\n        case plot_information_count:\n          break;\n        }\n        interface_ring_buffer_push(&interface->saved_data_ring, dev_id, data_index, data_val);\n        data_index++;\n      }\n    }\n\n    dev_id++;\n  }\n}\n\nstatic unsigned populate_plot_data_from_ring_buffer(const struct nvtop_interface *interface,\n                                                    struct plot_window *plot_win, unsigned size_data_buff,\n                                                    double data[size_data_buff],\n                                                    char plot_legend[MAX_LINES_PER_PLOT][PLOT_MAX_LEGEND_SIZE]) {\n\n  memset(data, 0, size_data_buff * sizeof(*data));\n  unsigned total_to_draw = 0;\n  for (unsigned i = 0; i < plot_win->num_devices_to_plot; ++i) {\n    unsigned dev_id = plot_win->devices_ids[i];\n    plot_info_to_draw to_draw = interface->options.gpu_specific_opts[dev_id].to_draw;\n    total_to_draw += plot_count_draw_info(to_draw);\n  }\n\n  assert(total_to_draw > 0);\n  assert(size_data_buff % total_to_draw == 0);\n  unsigned max_data_to_copy = size_data_buff / total_to_draw;\n  double (*data_split)[total_to_draw] = (double (*)[total_to_draw])data;\n\n  unsigned in_processing = 0;\n  for (unsigned i = 0; i < plot_win->num_devices_to_plot; ++i) {\n    unsigned dev_id = plot_win->devices_ids[i];\n    plot_info_to_draw to_draw = interface->options.gpu_specific_opts[dev_id].to_draw;\n    unsigned data_ring_index = 0;\n    for (enum plot_information info = plot_gpu_rate; info < plot_information_count; ++info) {\n      if (plot_isset_draw_info(info, to_draw)) {\n        // Populate the legend\n        switch (info) {\n        case plot_gpu_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u %%\", dev_id);\n          break;\n        case plot_gpu_mem_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u mem%%\", dev_id);\n          break;\n        case plot_encoder_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u encode%%\", dev_id);\n          break;\n        case plot_decoder_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u decode%%\", dev_id);\n          break;\n        case plot_gpu_temperature:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u temp(c)\", dev_id);\n          break;\n        case plot_gpu_power_draw_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u power%%\", dev_id);\n          break;\n        case plot_fan_speed:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u fan%%\", dev_id);\n          break;\n        case plot_gpu_clock_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u clock%%\", dev_id);\n          break;\n        case plot_gpu_mem_clock_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u mem clock%%\", dev_id);\n          break;\n        case plot_effective_load_rate:\n          snprintf(plot_legend[in_processing], PLOT_MAX_LEGEND_SIZE, \"GPU%u eff. load%%\", dev_id);\n          break;\n        case plot_information_count:\n          break;\n        }\n        // Copy the data\n        unsigned data_in_ring = interface_ring_buffer_data_stored(&interface->saved_data_ring, dev_id, data_ring_index);\n        if (interface->options.plot_left_to_right) {\n          for (unsigned j = 0; j < data_in_ring && j < max_data_to_copy; ++j) {\n            data_split[j][in_processing] =\n                interface_ring_buffer_get(&interface->saved_data_ring, dev_id, data_ring_index, data_in_ring - j - 1);\n          }\n        } else {\n          for (unsigned j = 0; j < data_in_ring && j < max_data_to_copy; ++j) {\n            data_split[max_data_to_copy - j - 1][in_processing] =\n                interface_ring_buffer_get(&interface->saved_data_ring, dev_id, data_ring_index, data_in_ring - j - 1);\n          }\n        }\n        data_ring_index++;\n        in_processing++;\n      }\n    }\n  }\n  return total_to_draw;\n}\n\nstatic void draw_plots(struct nvtop_interface *interface) {\n  for (unsigned plot_id = 0; plot_id < interface->num_plots; ++plot_id) {\n    werase(interface->plots[plot_id].plot_window);\n\n    char plot_legend[MAX_LINES_PER_PLOT][PLOT_MAX_LEGEND_SIZE];\n\n    unsigned num_lines =\n        populate_plot_data_from_ring_buffer(interface, &interface->plots[plot_id], interface->plots[plot_id].num_data,\n                                            interface->plots[plot_id].data, plot_legend);\n\n    nvtop_line_plot(interface->plots[plot_id].plot_window, interface->plots[plot_id].num_data,\n                    interface->plots[plot_id].data, num_lines, !interface->options.plot_left_to_right, plot_legend);\n\n    wnoutrefresh(interface->plots[plot_id].plot_window);\n  }\n}\n\nvoid draw_gpu_info_ncurses(unsigned devices_count, struct list_head *devices, struct nvtop_interface *interface) {\n\n  draw_devices(devices, interface);\n  if (!interface->setup_win.visible) {\n    draw_plots(interface);\n    draw_processes(devices, interface);\n  } else {\n    draw_setup_window(devices_count, devices, interface);\n  }\n  draw_shortcuts(interface);\n  doupdate();\n}\n\nvoid update_window_size_to_terminal_size(struct nvtop_interface *inter) {\n  endwin();\n  erase();\n  refresh();\n  refresh();\n  delete_all_windows(inter);\n  initialize_all_windows(inter);\n}\n\nbool is_escape_for_quit(struct nvtop_interface *interface) {\n  if (interface->process.option_window.state == nvtop_option_state_hidden && !interface->setup_win.visible)\n    return true;\n  else\n    return false;\n}\n\nstatic void option_do_kill(struct nvtop_interface *interface) {\n  if (interface->process.option_window.selected_row == 0)\n    return;\n  pid_t pid = interface->process.selected_pid;\n  int sig = signalValues[interface->process.option_window.selected_row];\n  if (pid > 0) {\n    kill(pid, sig);\n  }\n}\n\nstatic void option_change_sort(struct nvtop_interface *interface) {\n  if (interface->process.option_window.selected_row == 0)\n    return;\n  unsigned index = 0;\n  for (enum process_field i = process_pid; i < process_field_count; ++i) {\n    if (process_is_field_displayed(i, interface->options.process_fields_displayed)) {\n      if (index == interface->process.option_window.selected_row - 1) {\n        interface->options.sort_processes_by = i;\n        return;\n      }\n      index++;\n    }\n  }\n}\n\nvoid interface_key(int keyId, struct nvtop_interface *interface) {\n  if (interface->setup_win.visible) {\n    handle_setup_win_keypress(keyId, interface);\n    return;\n  }\n  switch (keyId) {\n  case KEY_F(2):\n    if (interface->process.option_window.state == nvtop_option_state_hidden && !interface->setup_win.visible) {\n      show_setup_window(interface);\n    }\n    break;\n  case KEY_F(12):\n    save_interface_options_to_config_file(interface->total_dev_count, &interface->options);\n    break;\n  case KEY_F(9):\n    if (process_field_displayed_count(interface->options.process_fields_displayed) > 0 &&\n        interface->process.option_window.state == nvtop_option_state_hidden) {\n      interface->process.option_window.state = nvtop_option_state_kill;\n      interface->process.option_window.selected_row = 0;\n    }\n    break;\n  case KEY_F(6):\n    if (process_field_displayed_count(interface->options.process_fields_displayed) > 0 &&\n        interface->process.option_window.state == nvtop_option_state_hidden) {\n      interface->process.option_window.state = nvtop_option_state_sort_by;\n      interface->process.option_window.selected_row = 0;\n    }\n    break;\n  case 'l':\n  case KEY_RIGHT:\n    if (interface->process.option_window.state == nvtop_option_state_hidden)\n      interface->process.offset_column += 4;\n    break;\n  case 'h':\n  case KEY_LEFT:\n    if (interface->process.option_window.state == nvtop_option_state_hidden && interface->process.offset_column >= 4)\n      interface->process.offset_column -= 4;\n    break;\n  case 'k':\n  case KEY_UP:\n    switch (interface->process.option_window.state) {\n    case nvtop_option_state_kill:\n    case nvtop_option_state_sort_by:\n      if (interface->process.option_window.selected_row != 0)\n        interface->process.option_window.selected_row--;\n      break;\n    case nvtop_option_state_hidden:\n      if (interface->process.selected_row != 0)\n        interface->process.selected_row--;\n      break;\n    default:\n      break;\n    }\n    break;\n  case 'j':\n  case KEY_DOWN:\n    switch (interface->process.option_window.state) {\n    case nvtop_option_state_kill:\n    case nvtop_option_state_sort_by:\n      interface->process.option_window.selected_row++;\n      break;\n    case nvtop_option_state_hidden:\n      interface->process.selected_row++;\n      break;\n    default:\n      break;\n    }\n    break;\n  case '+':\n    interface->options.sort_descending_order = false;\n    break;\n  case '-':\n    interface->options.sort_descending_order = true;\n    break;\n  case '\\n':\n  case KEY_ENTER:\n    switch (interface->process.option_window.state) {\n    case nvtop_option_state_kill:\n      option_do_kill(interface);\n      interface->process.option_window.state = nvtop_option_state_hidden;\n      break;\n    case nvtop_option_state_sort_by:\n      option_change_sort(interface);\n      interface->process.option_window.state = nvtop_option_state_hidden;\n      break;\n    case nvtop_option_state_hidden:\n    default:\n      break;\n    }\n    break;\n  case 27:\n    interface->process.option_window.state = nvtop_option_state_hidden;\n    break;\n  case KEY_F(5):\n  case 12: // Ctrl+L\n    update_window_size_to_terminal_size(interface);\n    break;\n  default:\n    break;\n  }\n}\n\nbool interface_freeze_processes(struct nvtop_interface *interface) {\n  return interface->process.option_window.state == nvtop_option_state_kill;\n}\n\nextern inline void set_attribute_between(WINDOW *win, int startY, int startX, int endX, attr_t attr, short pair);\n\nint interface_update_interval(const struct nvtop_interface *interface) { return interface->options.update_interval; }\n\nunsigned interface_largest_gpu_name(struct list_head *devices) {\n  struct gpu_info *gpuinfo;\n  unsigned max_size = 4;\n  list_for_each_entry(gpuinfo, devices, list) {\n    if (GPUINFO_STATIC_FIELD_VALID(&gpuinfo->static_info, device_name)) {\n      unsigned name_len = strlen(gpuinfo->static_info.device_name);\n      max_size = name_len > max_size ? name_len : max_size;\n    }\n  }\n  return max_size;\n}\n\nvoid interface_check_monitored_gpu_change(struct nvtop_interface **interface, unsigned allDevCount,\n                                          unsigned *num_monitored_gpus, struct list_head *monitoredGpus,\n                                          struct list_head *nonMonitoredGpus) {\n  if (!(*interface)->setup_win.visible && (*interface)->options.has_monitored_set_changed) {\n    nvtop_interface_option options_copy = (*interface)->options;\n    options_copy.has_monitored_set_changed = false;\n    memset(&(*interface)->options, 0, sizeof(options_copy));\n    *num_monitored_gpus =\n        interface_check_and_fix_monitored_gpus(allDevCount, monitoredGpus, nonMonitoredGpus, &options_copy);\n    clean_ncurses(*interface);\n    *interface =\n        initialize_curses(allDevCount, *num_monitored_gpus, interface_largest_gpu_name(monitoredGpus), options_copy);\n    timeout(interface_update_interval(*interface));\n  }\n}\n\nstatic char dontShowAgain[] = \"<Don't Show Again>\";\nstatic char okay[] = \"<Ok>\";\nstatic char interactKeys[] = \"Press Enter to select, arrows \\\">\\\" and \\\"<\\\" to switch options\";\n\nstatic unsigned message_lines(unsigned message_size, unsigned cols) { return (message_size + cols - 1) / cols; }\n\nbool show_information_messages(unsigned num_messages, const char **messages) {\n  if (!num_messages)\n    return false;\n  bool exit = false;\n  bool dontShowAgainOption = false;\n\n  while (!exit) {\n    initscr();\n    clear();\n    refresh();\n    initialize_colors();\n    cbreak();\n    noecho();\n    keypad(stdscr, TRUE);\n    curs_set(0);\n    int rows, cols;\n    getmaxyx(stdscr, rows, cols);\n    unsigned messages_lines = num_messages / 2;\n    for (unsigned i = 0; i < num_messages; ++i) {\n      messages_lines += message_lines(strlen(messages[i]), cols) + 1;\n    }\n    int row = (rows - messages_lines + 1) / 2;\n    for (unsigned i = 0; i < num_messages; ++i) {\n      int col = (cols - strlen(messages[i]) - 1) / 2;\n      col = col < 0 ? 0 : col;\n      mvprintw(row, col, \"%s\", messages[i]);\n      row += message_lines(strlen(messages[i]), cols) + 1;\n    }\n    size_t sizeQuitOptions = sizeof(dontShowAgain) + sizeof(okay);\n    int quitOptionsRow = row;\n    int quitOptionsCol = (cols - sizeQuitOptions) / 2;\n    quitOptionsCol = quitOptionsCol < 0 ? 0 : quitOptionsCol;\n    mvprintw(quitOptionsRow, quitOptionsCol, \"%s %s\", dontShowAgain, okay);\n    refresh();\n    if (dontShowAgainOption) {\n      mvchgat(quitOptionsRow, quitOptionsCol, sizeof(dontShowAgain) - 1, 0, green_color, NULL);\n      mvchgat(quitOptionsRow, quitOptionsCol + sizeof(dontShowAgain), sizeof(okay) - 1, 0, 0, NULL);\n    } else {\n      mvchgat(quitOptionsRow, quitOptionsCol, sizeof(dontShowAgain) - 1, 0, 0, NULL);\n      mvchgat(quitOptionsRow, quitOptionsCol + sizeof(dontShowAgain), sizeof(okay) - 1, 0, green_color, NULL);\n    }\n    int interactKeyCol = (cols - sizeof(interactKeys) - 1) / 2;\n    interactKeyCol = interactKeyCol < 0 ? 0 : interactKeyCol;\n    mvprintw(quitOptionsRow + 1, interactKeyCol, \"%s\", interactKeys);\n\n    int input_char = getch();\n    switch (input_char) {\n    case 27: // ESC\n    case 'q':\n    case KEY_ENTER:\n    case '\\n':\n      exit = true;\n      break;\n    case KEY_RIGHT:\n      dontShowAgainOption = false;\n      break;\n    case KEY_LEFT:\n      dontShowAgainOption = true;\n      break;\n    default:\n      break;\n    }\n    endwin();\n  }\n  return dontShowAgainOption;\n}\n\nvoid print_snapshot(struct list_head *devices, bool use_fahrenheit_option) {\n  struct gpu_info *device;\n\n  printf(\"[\\n\");\n  list_for_each_entry(device, devices, list) {\n    const char *indent_level_two = \"  \";\n    const char *indent_level_four = \"   \";\n    const char *indent_level_six = \"     \";\n    const char *indent_level_eight = \"       \";\n\n    const char *device_name_field = \"device_name\";\n    const char *gpu_clock_field = \"gpu_clock\";\n    const char *mem_clock_field = \"mem_clock\";\n    const char *temp_field = \"temp\";\n    const char *fan_field = \"fan_speed\";\n    const char *power_field = \"power_draw\";\n    const char *gpu_util_field = \"gpu_util\";\n    const char *mem_util_field = \"mem_util\";\n    const char *mem_total_field = \"mem_total\";\n    const char *mem_used_field = \"mem_used\";\n    const char *mem_free_field = \"mem_free\";\n\n    printf(\"%s{\\n\", indent_level_two);\n\n    // Device Name\n    if (GPUINFO_STATIC_FIELD_VALID(&device->static_info, device_name))\n      printf(\"%s\\\"%s\\\": \\\"%s\\\",\\n\", indent_level_four, device_name_field, device->static_info.device_name);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, device_name_field);\n\n    // GPU Clock Speed\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_clock_speed))\n      printf(\"%s\\\"%s\\\": \\\"%uMHz\\\",\\n\", indent_level_four, gpu_clock_field, device->dynamic_info.gpu_clock_speed);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, gpu_clock_field);\n\n    // MEM Clock Speed\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, mem_clock_speed))\n      printf(\"%s\\\"%s\\\": \\\"%uMHz\\\",\\n\", indent_level_four, mem_clock_field, device->dynamic_info.mem_clock_speed);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, mem_clock_field);\n\n    // GPU Temperature\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_temp)) {\n      unsigned int temp_convert;\n      if (!use_fahrenheit_option)\n        temp_convert = device->dynamic_info.gpu_temp;\n      else\n        temp_convert = (unsigned)(32 + nearbyint(device->dynamic_info.gpu_temp * 1.8));\n\n      printf(\"%s\\\"%s\\\": \\\"%u%s\\\",\\n\", indent_level_four, temp_field, temp_convert, use_fahrenheit_option ? \"F\" : \"C\");\n    } else {\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, temp_field);\n    }\n\n    // Fan speed\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, fan_speed))\n      printf(\"%s\\\"%s\\\": \\\"%u%%\\\",\\n\", indent_level_four, fan_field,\n             device->dynamic_info.fan_speed > 100 ? 100 : device->dynamic_info.fan_speed);\n    else if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, fan_rpm))\n      printf(\"%s\\\"%s\\\": \\\"%uRPM\\\",\\n\", indent_level_four, fan_field,\n             device->dynamic_info.fan_rpm > 9999 ? 9999 : device->dynamic_info.fan_rpm);\n    else if (device->static_info.integrated_graphics)\n      printf(\"%s\\\"%s\\\": \\\"CPU Fan\\\",\\n\", indent_level_four, fan_field);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, fan_field);\n\n    // Power draw\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, power_draw))\n      printf(\"%s\\\"%s\\\": \\\"%uW\\\",\\n\", indent_level_four, power_field, device->dynamic_info.power_draw / 1000);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, power_field);\n\n    // GPU Utilization\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, gpu_util_rate))\n      printf(\"%s\\\"%s\\\": \\\"%u%%\\\",\\n\", indent_level_four, gpu_util_field, device->dynamic_info.gpu_util_rate);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, gpu_util_field);\n\n    // Encode / Decode\n    if (device->static_info.encode_decode_shared) {\n      printf(\"%s\\\"encode_decode\\\": \", indent_level_four);\n      if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, decoder_rate))\n        printf(\"\\\"%u%%\\\",\\n\", device->dynamic_info.decoder_rate);\n      else\n        printf(\"null,\\n\");\n    } else {\n      printf(\"%s\\\"encode\\\": \", indent_level_four);\n      if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, encoder_rate))\n        printf(\"\\\"%u%%\\\",\\n\", device->dynamic_info.encoder_rate);\n      else\n        printf(\"null,\\n\");\n      printf(\"%s\\\"decode\\\": \", indent_level_four);\n      if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, decoder_rate))\n        printf(\"\\\"%u%%\\\",\\n\", device->dynamic_info.decoder_rate);\n      else\n        printf(\"null,\\n\");\n    }\n\n    // Memory Utilization\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, mem_util_rate))\n      printf(\"%s\\\"%s\\\": \\\"%u%%\\\",\\n\", indent_level_four, mem_util_field, device->dynamic_info.mem_util_rate);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, mem_util_field);\n    // Memory Total\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, total_memory))\n      printf(\"%s\\\"%s\\\": \\\"%llu\\\",\\n\", indent_level_four, mem_total_field, device->dynamic_info.total_memory);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, mem_total_field);\n    // Memory Used\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, used_memory))\n      printf(\"%s\\\"%s\\\": \\\"%llu\\\",\\n\", indent_level_four, mem_used_field, device->dynamic_info.used_memory);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, mem_used_field);\n    // Memory Available\n    if (GPUINFO_DYNAMIC_FIELD_VALID(&device->dynamic_info, free_memory))\n      printf(\"%s\\\"%s\\\": \\\"%llu\\\",\\n\", indent_level_four, mem_free_field, device->dynamic_info.free_memory);\n    else\n      printf(\"%s\\\"%s\\\": null,\\n\", indent_level_four, mem_free_field);\n\n    // Processes\n    printf(\"%s\\\"processes\\\" : [\\n\", indent_level_four);\n    for (unsigned i = 0; i < device->processes_count; ++i) {\n      struct gpu_process *proc = &device->processes[i];\n      printf(\"%s{\\n\", indent_level_six);\n\n      // PID\n      printf(\"%s\\\"pid\\\": \\\"%d\\\",\\n\", indent_level_eight, proc->pid);\n\n      printf(\"%s\\\"cmdline\\\": \\\"\", indent_level_eight);\n      for (char *li = proc->cmdline; *li != '\\0'; li++) {\n        // We need to escape some characters for for json strings\n        if (*li == '\\n') {\n          printf(\"\\\\n\");\n          continue;\n        } else if (*li == '\\b') {\n          printf(\"\\\\b\");\n          continue;\n        } else if (*li == '\\f') {\n          printf(\"\\\\f\");\n          continue;\n        } else if (*li == '\\r') {\n          printf(\"\\\\r\");\n          continue;\n        } else if (*li == '\\t') {\n          printf(\"\\\\t\");\n          continue;\n        }\n        // escaping backslash and quotes\n        if (*li == '\\\\' || *li == '\"')\n          printf(\"\\\\\");\n        printf(\"%c\", *li);\n      }\n      printf(\"\\\",\\n\");\n\n      printf(\"%s\\\"kind\\\": \", indent_level_eight);\n      if (proc->type != gpu_process_unknown) {\n        printf(\"\\\"\");\n        switch (proc->type) {\n        case gpu_process_graphical:\n          printf(\"graphic\");\n          break;\n        case gpu_process_compute:\n          printf(\"compute\");\n          break;\n        case gpu_process_graphical_compute:\n          printf(\"graphic & compute\");\n          break;\n        default:\n          printf(\"N/A\");\n          break;\n        }\n        printf(\"\\\"\");\n      } else {\n        printf(\"null\");\n      }\n      printf(\",\\n\");\n\n      // GPU memory usage\n      printf(\"%s\\\"user\\\": \", indent_level_eight);\n      if (GPUINFO_PROCESS_FIELD_VALID(proc, user_name))\n        printf(\"\\\"%s\\\",\\n\", proc->user_name);\n      else\n        printf(\"null,\\n\");\n\n      // GPU usage\n      printf(\"%s\\\"gpu_usage\\\": \", indent_level_eight);\n      if (GPUINFO_PROCESS_FIELD_VALID(proc, gpu_usage))\n        printf(\"\\\"%u%%\\\",\\n\", proc->gpu_usage);\n      else\n        printf(\"null,\\n\");\n\n      // GPU memory usage\n      printf(\"%s\\\"gpu_mem_bytes_alloc\\\": \", indent_level_eight);\n      if (GPUINFO_PROCESS_FIELD_VALID(proc, gpu_memory_usage))\n        printf(\"\\\"%llu\\\",\\n\", proc->gpu_memory_usage);\n      else\n        printf(\"null,\\n\");\n\n      // GPU memory usage\n      printf(\"%s\\\"gpu_mem_usage\\\": \", indent_level_eight);\n      if (GPUINFO_PROCESS_FIELD_VALID(proc, gpu_memory_percentage))\n        printf(\"\\\"%u%%\\\",\\n\", proc->gpu_memory_percentage);\n      else\n        printf(\"null,\\n\");\n\n      // Encode usage\n      if (device->static_info.encode_decode_shared) {\n        // (Notice: no comma at the end as it's the last field here)\n        printf(\"%s\\\"encode_decode\\\": \", indent_level_eight);\n        if (GPUINFO_PROCESS_FIELD_VALID(proc, decode_usage))\n          printf(\"\\\"%u%%\\\"\\n\", proc->decode_usage);\n        else\n          printf(\"null\\n\");\n      } else {\n        printf(\"%s\\\"encode\\\": \", indent_level_eight);\n        if (GPUINFO_PROCESS_FIELD_VALID(proc, encode_usage))\n          printf(\"\\\"%u%%\\\",\\n\", proc->encode_usage);\n        else\n          printf(\"null,\\n\");\n        // (Notice: no comma at the end as it's the last field here)\n        printf(\"%s\\\"decode\\\": \", indent_level_eight);\n        if (GPUINFO_PROCESS_FIELD_VALID(proc, decode_usage))\n          printf(\"\\\"%u%%\\\"\\n\", proc->decode_usage);\n        else\n          printf(\"null\\n\");\n      }\n\n      printf(\"%s}\", indent_level_six);\n      if (i != device->processes_count - 1)\n        printf(\",\");\n      printf(\"\\n\");\n    }\n    // (Notice: no comma at the end as it's the last field here)\n    printf(\"%s]\\n\", indent_level_four);\n\n    if (device->list.next == devices)\n      printf(\"%s}\\n\", indent_level_two);\n    else\n      printf(\"%s},\\n\", indent_level_two);\n  }\n  printf(\"]\\n\");\n  fflush(stdout);\n}\n"
  },
  {
    "path": "src/interface_layout_selection.c",
    "content": "#include \"nvtop/interface_layout_selection.h\"\n#include \"nvtop/interface.h\"\n#include \"nvtop/interface_options.h\"\n\n#include <assert.h>\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\nstatic unsigned min_rows_taken_by_process(unsigned rows, unsigned num_devices) {\n  return 1 + max(5, min(rows / 4, num_devices * 3));\n}\n\nstatic const unsigned cols_needed_box_drawing = 5;\nstatic const unsigned min_plot_rows = 7;\nstatic unsigned min_plot_cols(unsigned num_data_info_to_plot) {\n  return cols_needed_box_drawing + 10 * num_data_info_to_plot;\n}\n\n// If true, returns two plot indices that yields to the lowest number of info in\n// a plot when merged.\n// In case of ties, plots at the end of the list are prioritized.\nstatic bool who_to_merge(unsigned max_merge_size, unsigned plot_count, unsigned num_info_per_plot[plot_count],\n                         unsigned merge_ids[2]) {\n  unsigned smallest_merge = UINT_MAX;\n  for (unsigned notEmptyPlotIdx = plot_count - 1; notEmptyPlotIdx < plot_count; --notEmptyPlotIdx) {\n    if (!num_info_per_plot[notEmptyPlotIdx])\n      continue;\n    // We want to preserve the devices order when merging, hence we only look\n    // for the closest non empty neighbor for each plot.\n    unsigned merge_with = notEmptyPlotIdx;\n    for (unsigned j = notEmptyPlotIdx - 1; j < notEmptyPlotIdx; --j) {\n      if (num_info_per_plot[j]) {\n        merge_with = j;\n        break;\n      }\n    }\n    unsigned num_info_merged = num_info_per_plot[notEmptyPlotIdx] + num_info_per_plot[merge_with];\n    if (merge_with < notEmptyPlotIdx && num_info_merged <= max_merge_size && num_info_merged < smallest_merge) {\n      smallest_merge = num_info_merged;\n      merge_ids[0] = merge_with;\n      merge_ids[1] = notEmptyPlotIdx;\n    }\n  }\n  return smallest_merge != UINT_MAX;\n}\n\nstatic bool move_plot_to_stack(unsigned stack_max_cols, unsigned plot_id, unsigned destination_stack,\n                               unsigned plot_count, unsigned stack_count, const unsigned num_info_per_plot[plot_count],\n                               unsigned cols_allocated_in_stacks[stack_count], unsigned plot_in_stack[plot_count]) {\n  if (plot_in_stack[plot_id] == destination_stack)\n    return false;\n  unsigned cols_used_by_plot_id = min_plot_cols(num_info_per_plot[plot_id]);\n  unsigned cols_after_merge = cols_allocated_in_stacks[destination_stack] + cols_used_by_plot_id;\n  if (cols_after_merge > stack_max_cols) {\n    return false;\n  } else {\n    cols_allocated_in_stacks[plot_in_stack[plot_id]] -= cols_used_by_plot_id;\n    cols_allocated_in_stacks[destination_stack] += cols_used_by_plot_id;\n    plot_in_stack[plot_id] = destination_stack;\n    return true;\n  }\n}\n\nstatic unsigned info_in_plot(unsigned plot_id, unsigned devices_count, const unsigned map_device_to_plot[devices_count],\n                             const nvtop_interface_gpu_opts gpuOpts[devices_count]) {\n  unsigned sum = 0;\n  for (unsigned dev_id = 0; dev_id < devices_count; ++dev_id) {\n    if (map_device_to_plot[dev_id] == plot_id)\n      sum += plot_count_draw_info(gpuOpts[dev_id].to_draw);\n  }\n  assert(sum > 0);\n  return sum;\n}\n\nstatic unsigned cols_used_by_stack(unsigned stack_id, unsigned plot_count, const unsigned num_info_per_plot[plot_count],\n                                   const unsigned plot_in_stack[plot_count]) {\n  unsigned sum = 0;\n  for (unsigned plot_id = 0; plot_id < plot_count; ++plot_id) {\n    if (plot_in_stack[plot_id] == stack_id)\n      sum += min_plot_cols(num_info_per_plot[plot_id]);\n  }\n  return sum;\n}\n\nstatic unsigned size_differences_between_stacks(unsigned plot_count, unsigned stack_count,\n                                                unsigned cols_allocated_in_stacks[plot_count]) {\n  unsigned sum = 0;\n  for (unsigned i = 0; i < stack_count; ++i) {\n    for (unsigned j = i + 1; j < stack_count; ++j) {\n      if (cols_allocated_in_stacks[i] > cols_allocated_in_stacks[j]) {\n        sum += cols_allocated_in_stacks[i] - cols_allocated_in_stacks[j];\n      } else {\n        sum += cols_allocated_in_stacks[j] - cols_allocated_in_stacks[i];\n      }\n    }\n  }\n  return sum;\n}\n\nstatic void preliminary_plot_positioning(unsigned rows_for_plots, unsigned plot_total_cols, unsigned devices_count,\n                                         const nvtop_interface_gpu_opts gpuOpts[devices_count],\n                                         unsigned map_device_to_plot[devices_count],\n                                         unsigned plot_in_stack[devices_count], unsigned *num_plots,\n                                         unsigned *plot_stack_count) {\n\n  // Used to handle the merging process\n  unsigned num_info_per_plot[MAX_CHARTS];\n\n  bool plot_anything = false;\n  for (unsigned i = 0; i < devices_count; ++i) {\n    num_info_per_plot[i] = plot_count_draw_info(gpuOpts[i].to_draw);\n    map_device_to_plot[i] = i;\n    if (num_info_per_plot[i])\n      plot_anything = true;\n  }\n\n  // Get the most packed configuration possible with one chart per device if\n  // possible.\n  // If there is not enough place, merge the charts and retry.\n  unsigned num_plot_stacks = 0;\n  bool search_a_window_configuration = plot_anything && rows_for_plots >= min_plot_rows;\n  while (search_a_window_configuration) {\n    search_a_window_configuration = false;\n    unsigned plot_id = 0;\n    num_plot_stacks = 1;\n    unsigned cols_used_in_stack = 0;\n    unsigned rows_left_to_allocate = rows_for_plots - min_plot_rows;\n\n    for (unsigned i = 0; i < devices_count; ++i) {\n      unsigned num_info_for_this_plot = num_info_per_plot[i];\n      if (num_info_for_this_plot == 0)\n        continue;\n\n      unsigned cols_this_plot = min_plot_cols(num_info_for_this_plot);\n      // If there is enough horizontal space left, allocate side by side\n      if (plot_total_cols >= cols_this_plot + cols_used_in_stack) {\n        cols_used_in_stack += cols_this_plot;\n        plot_in_stack[plot_id] = num_plot_stacks - 1;\n        plot_id++;\n      } else {\n        // This plot is too wide for an empty stack, abort\n        if (cols_used_in_stack == 0) {\n          num_plot_stacks = 0;\n          break;\n        }\n        // Else allocate a new stack and retry\n        if (rows_left_to_allocate >= min_plot_rows) {\n          rows_left_to_allocate -= min_plot_rows;\n          num_plot_stacks++;\n          cols_used_in_stack = 0;\n          i--;\n        } else { // Not enough space for a stack: retry and merge one more\n          unsigned to_merge[2];\n          if (who_to_merge(MAX_LINES_PER_PLOT, devices_count, num_info_per_plot, to_merge)) {\n            num_info_per_plot[to_merge[0]] += num_info_per_plot[to_merge[1]];\n            num_info_per_plot[to_merge[1]] = 0;\n            unsigned oldLocation = map_device_to_plot[to_merge[1]];\n            for (unsigned devId = 0; devId < devices_count; ++devId) {\n              if (map_device_to_plot[devId] == oldLocation)\n                map_device_to_plot[devId] = map_device_to_plot[to_merge[0]];\n            }\n            search_a_window_configuration = true;\n          } else { // No merge left\n            num_plot_stacks = 0;\n          }\n          break;\n        }\n      }\n    }\n  }\n\n  // Compute the number of plots, the mapping and the size\n  *num_plots = 0;\n  *plot_stack_count = num_plot_stacks;\n  if (num_plot_stacks > 0) {\n    // Move non-empty plots over empty ones caused by merges\n    for (unsigned idx = 0; idx < devices_count; ++idx) {\n      if (!num_info_per_plot[idx]) {\n        // Search next non-empty and move it here\n        for (unsigned nextIdx = idx + 1; nextIdx < devices_count; ++nextIdx) {\n          if (num_info_per_plot[nextIdx]) {\n            num_info_per_plot[idx] = num_info_per_plot[nextIdx];\n            num_info_per_plot[nextIdx] = 0;\n            for (unsigned devId = 0; devId < devices_count; ++devId) {\n              if (map_device_to_plot[devId] == nextIdx)\n                map_device_to_plot[devId] = idx;\n            }\n            (*num_plots)++;\n            break;\n          }\n        }\n      } else {\n        (*num_plots)++;\n      }\n    }\n  }\n}\n\nstatic void balance_info_on_stacks_preserving_plot_order(unsigned stack_max_cols, unsigned stack_count,\n                                                         unsigned plot_count, unsigned num_info_per_plot[plot_count],\n                                                         unsigned cols_allocated_in_stacks[stack_count],\n                                                         unsigned plot_in_stack[plot_count]) {\n  if (stack_count > plot_count) {\n    stack_count = plot_count;\n  }\n  unsigned moving_plot_id = plot_count - 1;\n  while (moving_plot_id < plot_count) {\n    unsigned to_stack = plot_in_stack[moving_plot_id] + 1;\n    if (to_stack < stack_count) {\n      unsigned diff_sum_before = size_differences_between_stacks(plot_count, stack_count, cols_allocated_in_stacks);\n      unsigned stack_before = plot_in_stack[moving_plot_id];\n      if (move_plot_to_stack(stack_max_cols, moving_plot_id, to_stack, plot_count, stack_count, num_info_per_plot,\n                             cols_allocated_in_stacks, plot_in_stack)) {\n        unsigned diff_sum_after = size_differences_between_stacks(plot_count, stack_count, cols_allocated_in_stacks);\n        if (diff_sum_after <= diff_sum_before) {\n          moving_plot_id = plot_count;\n        } else {\n          // Move back\n          move_plot_to_stack(stack_max_cols, moving_plot_id, stack_before, plot_count, stack_count, num_info_per_plot,\n                             cols_allocated_in_stacks, plot_in_stack);\n        }\n      }\n    }\n    moving_plot_id--;\n  }\n}\nvoid compute_sizes_from_layout(unsigned devices_count, unsigned device_header_rows, unsigned device_header_cols,\n                               unsigned rows, unsigned cols, const nvtop_interface_gpu_opts *gpuOpts,\n                               process_field_displayed process_displayed, struct window_position *device_positions,\n                               unsigned *num_plots, struct window_position plot_positions[MAX_CHARTS],\n                               unsigned *map_device_to_plot, struct window_position *process_position,\n                               struct window_position *setup_position, bool process_win_hide) {\n\n  unsigned min_rows_for_header = 0, header_stacks = 0, num_device_per_row = 0;\n  num_device_per_row = max(1, cols / device_header_cols);\n  header_stacks = max(1, devices_count / num_device_per_row + ((devices_count % num_device_per_row) > 0));\n  if (devices_count % header_stacks == 0)\n    num_device_per_row = devices_count / header_stacks;\n  min_rows_for_header = header_stacks * device_header_rows;\n\n  unsigned min_rows_for_process =\n      process_field_displayed_count(process_displayed) ? min_rows_taken_by_process(rows, devices_count) : 0;\n\n  // Not enough room for the header and process\n  if (rows < min_rows_for_header + min_rows_for_process) {\n    if (rows >= min_rows_for_header + 2 && process_field_displayed_count(process_displayed)) { // Shrink process\n      min_rows_for_process = rows - min_rows_for_header;\n    } else { // Only header if possible\n      min_rows_for_header = rows;\n      min_rows_for_process = 0;\n    }\n  }\n\n  if (process_win_hide)\n    min_rows_for_process = 0;\n\n  unsigned rows_for_header = min_rows_for_header;\n  unsigned rows_for_process = min_rows_for_process;\n  unsigned rows_for_plots = rows - min_rows_for_header - min_rows_for_process;\n\n  unsigned num_plot_stacks = 0;\n  unsigned plot_in_stack[MAX_CHARTS];\n  preliminary_plot_positioning(rows_for_plots, cols, devices_count, gpuOpts, map_device_to_plot, plot_in_stack,\n                               num_plots, &num_plot_stacks);\n\n  // Transfer some lines to the header to separate the devices\n  unsigned transferable_lines = rows_for_plots - num_plot_stacks * min_plot_rows;\n  unsigned space_for_header = header_stacks == 0 ? 0 : header_stacks - 1;\n  bool space_between_header_stack = false;\n  if (transferable_lines >= space_for_header) {\n    rows_for_header += space_for_header;\n    rows_for_plots -= space_for_header;\n    space_between_header_stack = true;\n  }\n\n  // Allocate additional plot stacks if there is enough vertical room\n  if (num_plot_stacks > 0) {\n    while (num_plot_stacks < *num_plots && rows_for_plots / (num_plot_stacks + 1) >= 11 &&\n           (num_plot_stacks + 1) * min_plot_rows <= rows_for_plots)\n      num_plot_stacks++;\n  }\n\n  // Compute the cols used in each stacks to prepare balancing\n  unsigned num_info_per_plot[MAX_CHARTS];\n  for (unsigned i = 0; i < *num_plots; ++i) {\n    num_info_per_plot[i] = info_in_plot(i, devices_count, map_device_to_plot, gpuOpts);\n  }\n  unsigned cols_allocated_in_stacks[MAX_CHARTS];\n  for (unsigned i = 0; i < num_plot_stacks; ++i) {\n    cols_allocated_in_stacks[i] = cols_used_by_stack(i, *num_plots, num_info_per_plot, plot_in_stack);\n  }\n\n  // Keep the plot order of apparition, but spread the plot on different stacks\n  balance_info_on_stacks_preserving_plot_order(cols, num_plot_stacks, *num_plots, num_info_per_plot,\n                                               cols_allocated_in_stacks, plot_in_stack);\n\n  // Device Information Header\n  unsigned cols_header_left = cols - num_device_per_row * device_header_cols;\n  bool space_between_header_col = false;\n  bool space_before_header = false;\n  if (cols_header_left > num_device_per_row) {\n    space_between_header_col = true;\n    cols_header_left -= num_device_per_row - 1;\n  }\n  if (cols_header_left > 0)\n    space_before_header = true;\n\n  unsigned num_this_row = 0;\n  unsigned headerPosX = space_before_header;\n  unsigned headerPosY = 0;\n  for (unsigned i = 0; i < devices_count; ++i) {\n    device_positions[i].posX = headerPosX;\n    device_positions[i].posY = headerPosY;\n    device_positions[i].sizeX = device_header_cols;\n    device_positions[i].sizeY = device_header_rows;\n    num_this_row++;\n    if (num_this_row == num_device_per_row) {\n      headerPosX = space_before_header;\n      headerPosY += device_header_rows + space_between_header_stack;\n      num_this_row = 0;\n    } else {\n      headerPosX += device_header_cols + space_between_header_col;\n    }\n  }\n\n  unsigned rows_left_for_process = 0;\n  if (*num_plots > 0) {\n    unsigned rows_per_stack = rows_for_plots / num_plot_stacks;\n    if (!process_win_hide && rows_per_stack > 23)\n      rows_per_stack = 23;\n    unsigned num_plot_done = 0;\n    unsigned currentPosX = 0, currentPosY = rows_for_header;\n    for (unsigned stack_id = 0; stack_id < num_plot_stacks; ++stack_id) {\n      unsigned plot_in_this_stack = 0;\n      unsigned lines_to_draw = 0;\n      for (unsigned j = 0; j < *num_plots; ++j) {\n        if (plot_in_stack[j] == stack_id) {\n          plot_in_this_stack++;\n          lines_to_draw += num_info_per_plot[j];\n        }\n      }\n      unsigned cols_for_line_drawing = cols - plot_in_this_stack * cols_needed_box_drawing;\n      for (unsigned j = 0; j < *num_plots; ++j) {\n        if (plot_in_stack[j] == stack_id) {\n          unsigned max_plot_cols =\n              cols_needed_box_drawing + cols_for_line_drawing * num_info_per_plot[j] / lines_to_draw;\n          unsigned plot_cols = max_plot_cols - (max_plot_cols - cols_needed_box_drawing) % num_info_per_plot[j];\n          plot_positions[num_plot_done].posX = currentPosX;\n          plot_positions[num_plot_done].posY = currentPosY;\n          plot_positions[num_plot_done].sizeX = plot_cols;\n          plot_positions[num_plot_done].sizeY = rows_per_stack;\n          currentPosX += max_plot_cols;\n          num_plot_done++;\n        }\n      }\n      currentPosY += rows_per_stack;\n      currentPosX = 0;\n    }\n    if (process_field_displayed_count(process_displayed) > 0)\n      rows_left_for_process = rows_for_plots - rows_per_stack * num_plot_stacks;\n  } else {\n    // No plot displayed, allocate the leftover space to the processes\n    if (process_field_displayed_count(process_displayed) > 0 && rows_for_plots > 0)\n      rows_for_process += rows_for_plots - 1;\n  }\n\n  process_position->posX = 0;\n  process_position->posY = rows - rows_for_process - rows_left_for_process;\n  process_position->sizeY = rows_for_process + rows_left_for_process;\n  process_position->sizeX = cols;\n\n  setup_position->posX = 0;\n  setup_position->posY = rows_for_header;\n  setup_position->sizeY = rows - rows_for_header;\n  setup_position->sizeX = cols;\n}\n"
  },
  {
    "path": "src/interface_options.c",
    "content": "/*\n *\n * Copyright (C) 2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/interface_options.h\"\n#include \"ini.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/interface_common.h\"\n\n#include <assert.h>\n#include <errno.h>\n#include <libgen.h>\n#include <limits.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n\nchar config_file_path[PATH_MAX];\nconst char config_file_location[] = \"nvtop/interface.ini\";\nconst char config_conf_path[] = \".config\";\n\nstatic const char *default_config_path(void) {\n  char *xdg_config_dir = getenv(\"XDG_CONFIG_HOME\");\n  size_t conf_path_length = 0;\n  if (!xdg_config_dir) {\n    // XDG config dir not set, default to $HOME/.config\n    xdg_config_dir = getenv(\"HOME\");\n    if (!xdg_config_dir)\n            return NULL;\n    conf_path_length = sizeof(config_conf_path);\n  }\n  size_t xdg_path_length = strlen(xdg_config_dir);\n  if (xdg_path_length < PATH_MAX - conf_path_length - sizeof(config_file_location)) {\n    strcpy(config_file_path, xdg_config_dir);\n    config_file_path[xdg_path_length] = '/';\n    if (conf_path_length) {\n      strcpy(config_file_path + xdg_path_length + 1, config_conf_path);\n      config_file_path[xdg_path_length + conf_path_length] = '/';\n    }\n    strcpy(config_file_path + xdg_path_length + 1 + conf_path_length, config_file_location);\n    return config_file_path;\n  } else {\n    return NULL;\n  }\n}\n\nunsigned interface_check_and_fix_monitored_gpus(unsigned num_devices, struct list_head *monitoredGpu,\n                                                struct list_head *nonMonitoredGpu, nvtop_interface_option *options) {\n  // The array in options->gpu_specifi_opts is kept in sync with the lists\n  unsigned idx = 0;\n  struct gpu_info *device, *list_tmp;\n  list_for_each_entry_safe(device, list_tmp, monitoredGpu, list) {\n    assert(idx <= num_devices);\n    if (options->gpu_specific_opts[idx].doNotMonitor) {\n      list_move_tail(&device->list, nonMonitoredGpu);\n      nvtop_interface_gpu_opts saveInfo = options->gpu_specific_opts[idx];\n      memmove(&options->gpu_specific_opts[idx], &options->gpu_specific_opts[idx + 1],\n              (num_devices - idx - 1) * sizeof(*options->gpu_specific_opts));\n      options->gpu_specific_opts[num_devices - 1] = saveInfo;\n    } else {\n      idx++;\n    }\n  }\n  unsigned numMonitored = idx;\n  list_for_each_entry_safe(device, list_tmp, nonMonitoredGpu, list) {\n    assert(idx <= num_devices);\n    if (!options->gpu_specific_opts[idx].doNotMonitor) {\n      list_move_tail(&device->list, monitoredGpu);\n      nvtop_interface_gpu_opts saveInfo = options->gpu_specific_opts[idx];\n      for (unsigned nonMonPred = idx; nonMonPred > numMonitored; --nonMonPred) {\n        options->gpu_specific_opts[nonMonPred] = options->gpu_specific_opts[nonMonPred - 1];\n      }\n      options->gpu_specific_opts[numMonitored] = saveInfo;\n      numMonitored++;\n    }\n    idx++;\n  }\n  assert(idx == num_devices);\n  // We keep at least one monitored gpu at all times\n  if (num_devices > 0 && numMonitored == 0) {\n    assert(list_empty(monitoredGpu));\n    list_move(&list_first_entry(nonMonitoredGpu, struct gpu_info, list)->list, monitoredGpu);\n    options->gpu_specific_opts[0].doNotMonitor = false;\n    numMonitored++;\n  }\n  list_for_each_entry(device, monitoredGpu, list) { processinfo_enable_disable_callback_for(device, true); }\n  list_for_each_entry(device, nonMonitoredGpu, list) { processinfo_enable_disable_callback_for(device, false); }\n  return numMonitored;\n}\n\nvoid alloc_interface_options_internals(char *config_location, unsigned num_devices, struct list_head *devices,\n                                       nvtop_interface_option *options) {\n  options->gpu_specific_opts = calloc(num_devices, sizeof(*options->gpu_specific_opts));\n  if (!options->gpu_specific_opts) {\n    perror(\"Cannot allocate memory: \");\n    exit(EXIT_FAILURE);\n  }\n  unsigned idx = 0;\n  struct gpu_info *device;\n  list_for_each_entry(device, devices, list) { options->gpu_specific_opts[idx++].linkedGpu = device; }\n  options->plot_left_to_right = false;\n  options->use_color = true;\n  options->encode_decode_hiding_timer = 30.;\n  options->temperature_in_fahrenheit = false;\n  options->config_file_location = NULL;\n  options->sort_processes_by = process_memory;\n  options->sort_descending_order = true;\n  options->update_interval = 1000;\n  options->process_fields_displayed = 0;\n  options->has_monitored_set_changed = false;\n  options->show_startup_messages = true;\n  options->filter_nvtop_pid = true;\n  options->has_gpu_info_bar = false;\n  if (config_location) {\n    options->config_file_location = malloc(strlen(config_location) + 1);\n    if (!options->config_file_location) {\n      perror(\"Cannot allocate memory: \");\n      exit(EXIT_FAILURE);\n    }\n    strcpy(options->config_file_location, config_location);\n  } else {\n    const char *default_path = default_config_path();\n    if (default_path) {\n      options->config_file_location = malloc(strlen(default_path) + 1);\n      if (!options->config_file_location) {\n\tperror(\"Cannot allocate memory: \");\n\texit(EXIT_FAILURE);\n      }\n      strcpy(options->config_file_location, default_path);\n    }\n  }\n}\n\nstruct nvtop_option_ini_data {\n  unsigned num_devices;\n  unsigned selectedGpu;\n  nvtop_interface_option *options;\n};\n\nstatic const char do_not_modify_notice[] = \"; Please do not edit this file.\\n\"\n                                           \"; The file is automatically generated and modified by nvtop by pressing \"\n                                           \"F12.\\n\"\n                                           \"; If you wish to modify an option, use nvtop's setup window (F2) and \"\n                                           \"follow \"\n                                           \"up by saving the preference (F12).\\n\";\n\nstatic const char general_section[] = \"GeneralOption\";\nstatic const char general_value_use_color[] = \"UseColor\";\nstatic const char general_value_update_interval[] = \"UpdateInterval\";\nstatic const char general_show_messages[] = \"ShowInfoMessages\";\n\nstatic const char header_section[] = \"HeaderOption\";\nstatic const char header_value_use_fahrenheit[] = \"UseFahrenheit\";\nstatic const char header_value_encode_decode_timer[] = \"EncodeHideTimer\";\nstatic const char header_value_gpu_info_bar[] = \"GPUInfoBar\";\n\nstatic const char chart_section[] = \"ChartOption\";\nstatic const char chart_value_reverse[] = \"ReverseChart\";\n\nstatic const char process_list_section[] = \"ProcessListOption\";\nstatic const char process_hide_nvtop_process_list[] = \"HideNvtopProcessList\";\nstatic const char process_hide_nvtop_process[] = \"HideNvtopProcess\";\nstatic const char process_value_sortby[] = \"SortBy\";\nstatic const char process_value_display_field[] = \"DisplayField\";\nstatic const char *process_sortby_vals[process_field_count + 1] = {\n    \"pId\", \"user\", \"gpuId\", \"type\", \"gpuRate\", \"encRate\", \"decRate\", \"memory\", \"cpuUsage\", \"cpuMem\", \"cmdline\", \"none\"};\nstatic const char process_value_sort_order[] = \"SortOrder\";\nstatic const char process_sort_descending[] = \"descending\";\nstatic const char process_sort_ascending[] = \"ascending\";\n\nstatic const char device_section[] = \"Device\";\nstatic const char device_pdev[] = \"Pdev\";\nstatic const char device_monitor[] = \"Monitor\";\nstatic const char device_shown_value[] = \"ShownInfo\";\nstatic const char *device_draw_vals[plot_information_count + 1] = {\n    \"gpuRate\",       \"gpuMemRate\", \"encodeRate\",   \"decodeRate\",      \"temperature\",\n    \"powerDrawRate\", \"fanSpeed\",   \"gpuClockRate\", \"gpuMemClockRate\", \"effectiveLoadRate\", \"none\"};\n\nstatic int nvtop_option_ini_handler(void *user, const char *section, const char *name, const char *value) {\n  struct nvtop_option_ini_data *ini_data = (struct nvtop_option_ini_data *)user;\n  // General Options\n  if (strcmp(section, general_section) == 0) {\n    if (strcmp(name, general_value_use_color) == 0) {\n      if (strcmp(value, \"true\") == 0) {\n        ini_data->options->use_color = true;\n      }\n      if (strcmp(value, \"false\") == 0) {\n        ini_data->options->use_color = false;\n      }\n    }\n    if (strcmp(name, general_value_update_interval) == 0) {\n      int update_interval;\n      if (sscanf(value, \"%d\", &update_interval) == 1)\n        ini_data->options->update_interval = update_interval;\n    }\n    if (strcmp(name, general_show_messages) == 0) {\n      if (strcmp(value, \"true\") == 0) {\n        ini_data->options->show_startup_messages = true;\n      }\n      if (strcmp(value, \"false\") == 0) {\n        ini_data->options->show_startup_messages = false;\n      }\n    }\n  }\n  // Header Options\n  if (strcmp(section, header_section) == 0) {\n    if (strcmp(name, header_value_use_fahrenheit) == 0) {\n      if (strcmp(value, \"true\") == 0) {\n        ini_data->options->temperature_in_fahrenheit = true;\n      }\n      if (strcmp(value, \"false\") == 0) {\n        ini_data->options->temperature_in_fahrenheit = false;\n      }\n    }\n    if (strcmp(name, header_value_encode_decode_timer) == 0) {\n      double value_double;\n      if (sscanf(value, \"%le\", &value_double) == 1)\n        ini_data->options->encode_decode_hiding_timer = value_double;\n    }\n    if (strcmp(name, header_value_gpu_info_bar) == 0) {\n      if (strcmp(value, \"true\") == 0) {\n        ini_data->options->has_gpu_info_bar = true;\n      }\n      if (strcmp(value, \"false\") == 0) {\n        ini_data->options->has_gpu_info_bar = false;\n      }\n    }\n  }\n  // Chart Options\n  if (strcmp(section, chart_section) == 0) {\n    if (strcmp(name, chart_value_reverse) == 0) {\n      if (strcmp(value, \"true\") == 0) {\n        ini_data->options->plot_left_to_right = true;\n      }\n      if (strcmp(value, \"false\") == 0) {\n        ini_data->options->plot_left_to_right = false;\n      }\n    }\n  }\n  // Process List Options\n  if (strcmp(section, process_list_section) == 0) {\n    if (strcmp(name, process_hide_nvtop_process_list) == 0) {\n      if (strcmp(value, \"true\") == 0) {\n        ini_data->options->hide_processes_list = true;\n      }\n      if (strcmp(value, \"false\") == 0) {\n        ini_data->options->hide_processes_list = false;\n      }\n    }\n    if (strcmp(name, process_hide_nvtop_process) == 0) {\n      if (strcmp(value, \"true\") == 0) {\n        ini_data->options->filter_nvtop_pid = true;\n      }\n      if (strcmp(value, \"false\") == 0) {\n        ini_data->options->filter_nvtop_pid = false;\n      }\n    }\n    if (strcmp(name, process_value_sortby) == 0) {\n      for (enum process_field i = process_pid; i < process_field_count; ++i) {\n        if (strcmp(value, process_sortby_vals[i]) == 0) {\n          ini_data->options->sort_processes_by = i;\n        }\n      }\n    }\n    if (strcmp(name, process_value_display_field) == 0) {\n      for (enum process_field i = process_pid; i < process_field_count + 1; ++i) {\n        if (strcmp(value, process_sortby_vals[i]) == 0) {\n          ini_data->options->process_fields_displayed =\n              process_add_field_to_display(i, ini_data->options->process_fields_displayed);\n          ini_data->options->process_fields_displayed =\n              process_add_field_to_display(process_field_count, ini_data->options->process_fields_displayed);\n        }\n      }\n    }\n    if (strcmp(name, process_value_sort_order) == 0) {\n      if (strcmp(value, process_sort_descending) == 0) {\n        ini_data->options->sort_descending_order = true;\n      }\n      if (strcmp(value, process_sort_ascending) == 0) {\n        ini_data->options->sort_descending_order = false;\n      }\n    }\n  }\n  // Per-Device Sections\n  if (strcmp(section, device_section) == 0) {\n    if (strcmp(name, device_pdev) == 0) {\n      ini_data->selectedGpu = ini_data->num_devices;\n      for (unsigned i = 0; i < ini_data->num_devices; ++i) {\n        if (strcmp(ini_data->options->gpu_specific_opts[i].linkedGpu->pdev, value) == 0) {\n          ini_data->selectedGpu = i;\n          break;\n        }\n      }\n    }\n    if (ini_data->selectedGpu < ini_data->num_devices) {\n      if (strcmp(name, device_shown_value) == 0) {\n        for (enum plot_information j = plot_gpu_rate; j < plot_information_count + 1; ++j) {\n          if (strcmp(value, device_draw_vals[j]) == 0) {\n            ini_data->options->gpu_specific_opts[ini_data->selectedGpu].to_draw =\n                plot_add_draw_info(j, ini_data->options->gpu_specific_opts[ini_data->selectedGpu].to_draw);\n            ini_data->options->gpu_specific_opts[ini_data->selectedGpu].to_draw = plot_add_draw_info(\n                plot_information_count, ini_data->options->gpu_specific_opts[ini_data->selectedGpu].to_draw);\n          }\n        }\n      }\n      if (strcmp(name, device_monitor) == 0) {\n        if (strcmp(value, \"true\") == 0)\n          ini_data->options->gpu_specific_opts[ini_data->selectedGpu].doNotMonitor = false;\n        if (strcmp(value, \"false\") == 0)\n          ini_data->options->gpu_specific_opts[ini_data->selectedGpu].doNotMonitor = true;\n      }\n    }\n  }\n  return 1;\n}\n\nbool load_interface_options_from_config_file(unsigned num_devices, nvtop_interface_option *options) {\n  FILE *option_file = fopen(options->config_file_location, \"r\");\n  if (!option_file)\n    return false;\n  struct nvtop_option_ini_data ini_data = {num_devices, num_devices, options};\n  int retval = ini_parse_file(option_file, nvtop_option_ini_handler, &ini_data);\n  fclose(option_file);\n  if (!process_is_field_displayed(options->sort_processes_by, options->process_fields_displayed)) {\n    options->sort_processes_by = process_default_sort_by_from(options->process_fields_displayed);\n  }\n  return retval >= 0;\n}\n\nstatic bool create_config_directory_rec(char *config_directory) {\n  for (char *index = config_directory + 1; *index != '\\0'; ++index) {\n    if (*index == '/') {\n      *index = '\\0';\n      if (mkdir(config_directory, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {\n        if (errno != EEXIST) {\n          char *error_str = strerror(errno);\n          fprintf(stderr, \"Could not create directory \\\"%s\\\": %s\\n\", config_directory, error_str);\n          return false;\n        }\n      }\n      *index = '/';\n    }\n  }\n  if (mkdir(config_directory, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {\n    if (errno != EEXIST) {\n      char *error_str = strerror(errno);\n      fprintf(stderr, \"Could not create directory \\\"%s\\\": %s\\n\", config_directory, error_str);\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic const char *boolean_string(bool value) { return value ? \"true\" : \"false\"; }\n\nbool save_interface_options_to_config_file(unsigned total_dev_count, const nvtop_interface_option *options) {\n  if (!options->config_file_location)\n    return false;\n\n  char folder_path[PATH_MAX];\n  strcpy(folder_path, options->config_file_location);\n  char *config_directory = dirname(folder_path);\n  if (!create_config_directory_rec(config_directory))\n    return false;\n\n  FILE *config_file = fopen(options->config_file_location, \"w\");\n  if (!config_file) {\n    char *error_str = strerror(errno);\n    fprintf(stderr, \"Could not create config file \\\"%s\\\": %s\\n\", options->config_file_location, error_str);\n    return false;\n  }\n\n  fprintf(config_file, \"%s\", do_not_modify_notice);\n  // General Options\n  fprintf(config_file, \"[%s]\\n\", general_section);\n  fprintf(config_file, \"%s = %s\\n\", general_value_use_color, boolean_string(options->use_color));\n  fprintf(config_file, \"%s = %d\\n\", general_value_update_interval, options->update_interval);\n  fprintf(config_file, \"%s = %s\\n\", general_show_messages, boolean_string(options->show_startup_messages));\n\n  // Header Options\n  fprintf(config_file, \"\\n[%s]\\n\", header_section);\n  fprintf(config_file, \"%s = %s\\n\", header_value_use_fahrenheit, boolean_string(options->temperature_in_fahrenheit));\n  fprintf(config_file, \"%s = %e\\n\", header_value_encode_decode_timer, options->encode_decode_hiding_timer);\n  fprintf(config_file, \"%s = %s\\n\", header_value_gpu_info_bar, boolean_string(options->has_gpu_info_bar));\n\n  // Chart Options\n  fprintf(config_file, \"\\n[%s]\\n\", chart_section);\n  fprintf(config_file, \"%s = %s\\n\", chart_value_reverse, boolean_string(options->plot_left_to_right));\n\n  // Process Options\n  fprintf(config_file, \"\\n[%s]\\n\", process_list_section);\n  fprintf(config_file, \"%s = %s\\n\", process_hide_nvtop_process_list, boolean_string(options->hide_processes_list));\n  fprintf(config_file, \"%s = %s\\n\", process_hide_nvtop_process, boolean_string(options->filter_nvtop_pid));\n  fprintf(config_file, \"%s = %s\\n\", process_value_sort_order,\n          options->sort_descending_order ? process_sort_descending : process_sort_ascending);\n  fprintf(config_file, \"%s = %s\\n\", process_value_sortby, process_sortby_vals[options->sort_processes_by]);\n  bool display_any_field = false;\n  for (enum process_field field = process_pid; field < process_field_count; ++field) {\n    if (process_is_field_displayed(field, options->process_fields_displayed)) {\n      fprintf(config_file, \"%s = %s\\n\", process_value_display_field, process_sortby_vals[field]);\n      display_any_field = true;\n    }\n  }\n  if (!display_any_field)\n    fprintf(config_file, \"%s = %s\\n\", process_value_display_field, process_sortby_vals[process_field_count]);\n\n  // Per-Device Sections\n  for (unsigned i = 0; i < total_dev_count; ++i) {\n    fprintf(config_file, \"\\n[%s]\\n\", device_section);\n    fprintf(config_file, \"%s = %s\\n\", device_pdev, options->gpu_specific_opts[i].linkedGpu->pdev);\n    fprintf(config_file, \"%s = %s\\n\", device_monitor, boolean_string(!options->gpu_specific_opts[i].doNotMonitor));\n    bool draw_any = false;\n    for (enum plot_information j = plot_gpu_rate; j < plot_information_count; ++j) {\n      if (plot_isset_draw_info(j, options->gpu_specific_opts[i].to_draw)) {\n        fprintf(config_file, \"%s = %s\\n\", device_shown_value, device_draw_vals[j]);\n        draw_any = true;\n      }\n    }\n    if (!draw_any)\n      fprintf(config_file, \"%s = %s\\n\", device_shown_value, device_draw_vals[plot_information_count]);\n    fprintf(config_file, \"\\n\");\n  }\n\n  fclose(config_file);\n  return true;\n}\n\nextern inline plot_info_to_draw plot_add_draw_info(enum plot_information set_info, plot_info_to_draw to_draw);\n\nextern inline plot_info_to_draw plot_remove_draw_info(enum plot_information set_info, plot_info_to_draw to_draw);\n\nextern inline plot_info_to_draw plot_default_draw_info(void);\n\nextern inline bool plot_isset_draw_info(enum plot_information check_info, plot_info_to_draw to_draw);\n\nextern inline unsigned plot_count_draw_info(plot_info_to_draw to_draw);\n\nextern inline bool process_is_field_displayed(enum process_field field, process_field_displayed cols_displayed);\n\nextern inline process_field_displayed process_remove_field_to_display(enum process_field field,\n                                                                      process_field_displayed cols_displayed);\n\nextern inline process_field_displayed process_add_field_to_display(enum process_field field,\n                                                                   process_field_displayed cols_displayed);\n\nextern inline process_field_displayed process_default_displayed_field(void);\n\nextern inline unsigned process_field_displayed_count(process_field_displayed fields_displayed);\n\nenum process_field process_default_sort_by_from(process_field_displayed fields_displayed) {\n  if (process_is_field_displayed(process_memory, fields_displayed))\n    return process_memory;\n  if (process_is_field_displayed(process_cpu_mem_usage, fields_displayed))\n    return process_cpu_mem_usage;\n  if (process_is_field_displayed(process_gpu_rate, fields_displayed))\n    return process_gpu_rate;\n  if (process_is_field_displayed(process_cpu_usage, fields_displayed))\n    return process_cpu_usage;\n  if (process_is_field_displayed(process_command, fields_displayed))\n    return process_command;\n  if (process_is_field_displayed(process_type, fields_displayed))\n    return process_type;\n  if (process_is_field_displayed(process_enc_rate, fields_displayed))\n    return process_enc_rate;\n  if (process_is_field_displayed(process_dec_rate, fields_displayed))\n    return process_dec_rate;\n  if (process_is_field_displayed(process_user, fields_displayed))\n    return process_user;\n  if (process_is_field_displayed(process_gpu_id, fields_displayed))\n    return process_gpu_id;\n  if (process_is_field_displayed(process_pid, fields_displayed))\n    return process_pid;\n  return process_field_count;\n}\n"
  },
  {
    "path": "src/interface_ring_buffer.c",
    "content": "\n#include \"nvtop/interface_ring_buffer.h\"\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n\nvoid interface_alloc_ring_buffer(unsigned devices_count, unsigned per_device_data_saved, unsigned buffer_size,\n                                 interface_ring_buffer *ring_buffer) {\n  ring_buffer->ring_buffer[0] = calloc(1, sizeof(unsigned[devices_count][per_device_data_saved][2]));\n  if (!ring_buffer->ring_buffer[0]) {\n    perror(\"Cannot allocate memory: \");\n    exit(EXIT_FAILURE);\n  }\n  ring_buffer->ring_buffer[1] = malloc(sizeof(unsigned[devices_count][per_device_data_saved][buffer_size]));\n  if (!ring_buffer->ring_buffer[1]) {\n    perror(\"Cannot allocate memory: \");\n    exit(EXIT_FAILURE);\n  }\n  ring_buffer->buffer_size = buffer_size;\n  ring_buffer->per_device_data_saved = per_device_data_saved;\n  ring_buffer->monitored_dev_count = devices_count;\n}\n\nvoid interface_free_ring_buffer(interface_ring_buffer *buffer) {\n  free(buffer->ring_buffer[0]);\n  free(buffer->ring_buffer[1]);\n}\n\nextern inline unsigned interface_ring_buffer_data_stored(const interface_ring_buffer *buff, unsigned device,\n                                                         unsigned which_data);\n\nextern inline unsigned interface_index_in_ring(const interface_ring_buffer *buff, unsigned device, unsigned which_data,\n                                               unsigned index);\n\nextern inline unsigned interface_ring_buffer_get(const interface_ring_buffer *buff, unsigned device,\n                                                 unsigned which_data, unsigned index);\n\nextern inline void interface_ring_buffer_push(interface_ring_buffer *buff, unsigned device, unsigned which_data,\n                                              unsigned value);\n\nextern inline void interface_ring_buffer_pop(interface_ring_buffer *buff, unsigned device, unsigned which_data);\n\nextern inline void interface_ring_buffer_empty_select(interface_ring_buffer *buff, unsigned device,\n                                                      unsigned which_data);\n\nextern inline void interface_ring_buffer_empty(interface_ring_buffer *buff, unsigned device);\n"
  },
  {
    "path": "src/interface_setup_win.c",
    "content": "/*\n *\n * Copyright (C) 2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/interface_setup_win.h\"\n#include \"nvtop/interface.h\"\n#include \"nvtop/interface_internal_common.h\"\n#include \"nvtop/interface_options.h\"\n#include \"nvtop/interface_ring_buffer.h\"\n\n#include <ncurses.h>\n\nstatic char *setup_window_category_names[setup_window_selection_count] = {\"General\", \"Devices\", \"Chart\", \"Processes\",\n                                                                          \"GPU Select\"};\n\n// All the windows used to display the setup\nenum setup_window_type {\n  setup_window_type_setup,\n  setup_window_type_single,\n  setup_window_type_split_left,\n  setup_window_type_split_right,\n  setup_window_type_count\n};\n\n// General Options\n\nenum setup_general_options {\n  setup_general_color,\n  setup_general_show_startup_support_messages,\n  setup_general_update_interval,\n  setup_general_options_count\n};\n\nstatic const char *setup_general_option_description[setup_general_options_count] = {\n    \"Disable color (requires save and restart)\", \"Show support messages on startup\", \"Update interval (seconds)\"};\n\n// Header Options\n\nenum setup_header_options {\n  setup_header_toggle_fahrenheit,\n  setup_header_enc_dec_timer,\n  setup_header_gpu_info_bar,\n  setup_header_options_count\n};\n\nstatic const char *setup_header_option_descriptions[setup_header_options_count] = {\n    \"Temperature in fahrenheit\", \"Keep displaying Encoder/Decoder rate (after reaching an idle state)\",\n    \"Display extra GPU info bar\"};\n\n// Chart Options\n\nenum setup_chart_options {\n  setup_chart_reverse,\n  setup_chart_all_gpu,\n  setup_chart_start_gpu_list,\n  setup_chart_options_count\n};\n\nstatic const char *setup_chart_options_descriptions[setup_chart_options_count] = {\n    \"Reverse plot direction\", \"Displayed all GPUs\", \"Displayed GPU\"};\n\nstatic const char *setup_chart_gpu_value_descriptions[plot_information_count] = {\n    \"GPU utilization rate\", \"GPU memory utilization rate\",   \"GPU encoder rate\", \"GPU decoder rate\",\n    \"GPU temperature\",      \"Power draw rate (current/max)\", \"Fan speed\",        \"GPU clock rate\",\n    \"GPU memory clock rate\", \"Effective load rate\"};\n\n// Process List Options\n\nenum setup_proc_list_options {\n  setup_proc_list_hide_process_list,\n  setup_proc_list_hide_nvtop_process,\n  setup_proc_list_sort_ascending,\n  setup_proc_list_sort_by,\n  setup_proc_list_display,\n  setup_proc_list_options_count\n};\n\nstatic const char *setup_proc_list_option_description[setup_proc_list_options_count] = {\n    \"Don't display the process list\", \"Hide nvtop in the process list\", \"Sort Ascending\", \"Sort by\", \"Field Displayed\"};\n\nstatic const char *setup_proc_list_value_descriptions[process_field_count] = {\n    \"Process Id\",    \"User name\",        \"Device Id\", \"Workload type\",    \"GPU usage\", \"Encoder usage\",\n    \"Decoder usage\", \"GPU memory usage\", \"CPU usage\", \"CPU memory usage\", \"Command\"};\n\nstatic unsigned int sizeof_setup_windows[setup_window_type_count] = {[setup_window_type_setup] = 11,\n                                                                     [setup_window_type_single] = 0,\n                                                                     [setup_window_type_split_left] = 26,\n                                                                     [setup_window_type_split_right] = 0};\n\n// For toggle options\n// Show * if on, - if partial and nothing if off\nenum option_state {\n  option_off,\n  option_on,\n  option_partially_active,\n};\n\nstatic char option_state_char(enum option_state state) {\n  switch (state) {\n  case option_on:\n    return '*';\n  case option_partially_active:\n    return '-';\n  case option_off:\n    return ' ';\n  default:\n    return ' ';\n  }\n}\n\nvoid alloc_setup_window(struct window_position *position, struct setup_window *setup_win) {\n  setup_win->visible = false;\n  setup_win->clean_space = newwin(position->sizeY, position->sizeX, position->posY, position->posX);\n\n  sizeof_setup_windows[setup_window_type_single] = position->sizeX - sizeof_setup_windows[setup_window_type_setup] - 1;\n  if (sizeof_setup_windows[setup_window_type_single] > position->sizeX)\n    sizeof_setup_windows[setup_window_type_single] = 0;\n\n  sizeof_setup_windows[setup_window_type_split_right] = position->sizeX -\n                                                        sizeof_setup_windows[setup_window_type_setup] -\n                                                        sizeof_setup_windows[setup_window_type_split_left] - 2;\n  if (sizeof_setup_windows[setup_window_type_split_right] > position->sizeX)\n    sizeof_setup_windows[setup_window_type_split_right] = 0;\n\n  setup_win->setup =\n      newwin(position->sizeY, sizeof_setup_windows[setup_window_type_setup], position->posY, position->posX);\n\n  setup_win->single = newwin(position->sizeY, sizeof_setup_windows[setup_window_type_single], position->posY,\n                             position->posX + sizeof_setup_windows[setup_window_type_setup] + 1);\n\n  setup_win->split[0] = newwin(position->sizeY, sizeof_setup_windows[setup_window_type_split_left], position->posY,\n                               position->posX + sizeof_setup_windows[setup_window_type_setup] + 1);\n\n  setup_win->split[1] = newwin(position->sizeY, sizeof_setup_windows[setup_window_type_split_right], position->posY,\n                               position->posX + sizeof_setup_windows[setup_window_type_setup] +\n                                   sizeof_setup_windows[setup_window_type_split_left] + 2);\n}\n\nvoid free_setup_window(struct setup_window *setup_win) {\n  delwin(setup_win->clean_space);\n  delwin(setup_win->setup);\n  delwin(setup_win->single);\n  delwin(setup_win->split[0]);\n  delwin(setup_win->split[1]);\n}\n\nvoid show_setup_window(struct nvtop_interface *interface) {\n  interface->setup_win.visible = true;\n  touchwin(interface->setup_win.clean_space);\n  wnoutrefresh(interface->setup_win.clean_space);\n  interface->setup_win.selected_section = setup_general_selected;\n  interface->setup_win.indentation_level = 0;\n  interface->setup_win.options_selected[0] = 0;\n  interface->setup_win.options_selected[1] = 0;\n}\n\nvoid hide_setup_window(struct nvtop_interface *interface) { interface->setup_win.visible = false; }\n\nstatic void draw_setup_window_setup(struct nvtop_interface *interface) {\n  werase(interface->setup_win.setup);\n  mvwprintw(interface->setup_win.setup, 0, 0, \"Setup\");\n  mvwchgat(interface->setup_win.setup, 0, 0, sizeof_setup_windows[setup_window_type_setup], A_STANDOUT, green_color,\n           NULL);\n  for (enum setup_window_section category = setup_general_selected; category < setup_window_selection_count;\n       ++category) {\n    mvwprintw(interface->setup_win.setup, category + 1, 0, \"%s\", setup_window_category_names[category]);\n    if (interface->setup_win.selected_section == category) {\n      if (interface->setup_win.indentation_level == 0) {\n        set_attribute_between(interface->setup_win.setup, category + 1, 0,\n                              sizeof_setup_windows[setup_window_type_setup], A_STANDOUT, cyan_color);\n      } else {\n        mvwprintw(interface->setup_win.setup, category + 1, sizeof_setup_windows[setup_window_type_setup] - 1, \">\");\n        set_attribute_between(interface->setup_win.setup, category + 1, 0,\n                              sizeof_setup_windows[setup_window_type_setup], A_BOLD, cyan_color);\n      }\n    }\n  }\n  wnoutrefresh(interface->setup_win.setup);\n}\n\nstatic void draw_setup_window_general(struct nvtop_interface *interface) {\n  if (interface->setup_win.indentation_level > 1)\n    interface->setup_win.indentation_level = 1;\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] >= setup_general_options_count)\n    interface->setup_win.options_selected[0] = setup_general_options_count - 1;\n\n  wattr_set(interface->setup_win.single, A_STANDOUT, green_color, NULL);\n  mvwprintw(interface->setup_win.single, 0, 0, \"General Options\");\n  wstandend(interface->setup_win.single);\n\n  unsigned int cur_col, maxcols, tmp;\n  (void)tmp;\n  getmaxyx(interface->setup_win.single, tmp, maxcols);\n  getyx(interface->setup_win.single, tmp, cur_col);\n  mvwchgat(interface->setup_win.single, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n\n  enum option_state option_state = !interface->options.use_color;\n  mvwprintw(interface->setup_win.single, setup_general_color + 1, 0, \"[%c] %s\", option_state_char(option_state),\n            setup_general_option_description[setup_general_color]);\n  if (interface->setup_win.indentation_level == 1 && interface->setup_win.options_selected[0] == setup_general_color) {\n    mvwchgat(interface->setup_win.single, setup_general_color + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n  option_state = interface->options.show_startup_messages;\n  mvwprintw(interface->setup_win.single, setup_general_show_startup_support_messages + 1, 0, \"[%c] %s\",\n            option_state_char(option_state),\n            setup_general_option_description[setup_general_show_startup_support_messages]);\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_general_show_startup_support_messages) {\n    mvwchgat(interface->setup_win.single, setup_general_show_startup_support_messages + 1, 0, 3, A_STANDOUT, cyan_color,\n             NULL);\n  }\n\n  int update_deciseconds = (interface->options.update_interval / 100) % 10;\n  int update_seconds = interface->options.update_interval / 1000;\n  mvwprintw(interface->setup_win.single, setup_general_update_interval + 1, 0, \"[%2u.%u] %s\", update_seconds,\n            update_deciseconds, setup_general_option_description[setup_general_update_interval]);\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_general_update_interval) {\n    mvwchgat(interface->setup_win.single, setup_general_update_interval + 1, 0, 6, A_STANDOUT, cyan_color, NULL);\n  }\n  wnoutrefresh(interface->setup_win.single);\n}\n\nstatic void draw_setup_window_header(struct nvtop_interface *interface) {\n  if (interface->setup_win.indentation_level > 1)\n    interface->setup_win.indentation_level = 1;\n  if (interface->setup_win.options_selected[0] >= setup_header_options_count)\n    interface->setup_win.options_selected[0] = setup_header_options_count - 1;\n\n  WINDOW *options_win = interface->setup_win.single;\n\n  wattr_set(options_win, A_STANDOUT, green_color, NULL);\n  mvwprintw(options_win, 0, 0, \"Devices Display Options\");\n  wstandend(options_win);\n\n  unsigned int cur_col, maxcols, tmp;\n  (void)tmp;\n  getmaxyx(options_win, tmp, maxcols);\n  getyx(options_win, tmp, cur_col);\n  mvwchgat(options_win, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n\n  enum option_state option_state;\n\n  // Fahrenheit Option\n  option_state = interface->options.temperature_in_fahrenheit;\n  mvwprintw(options_win, setup_header_toggle_fahrenheit + 1, 0, \"[%c] %s\", option_state_char(option_state),\n            setup_header_option_descriptions[setup_header_toggle_fahrenheit]);\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_header_toggle_fahrenheit) {\n    mvwchgat(options_win, setup_header_toggle_fahrenheit + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n\n  // Encode/Decode hiding timer\n  if (interface->options.encode_decode_hiding_timer > 0) {\n    mvwprintw(options_win, setup_header_enc_dec_timer + 1, 0, \"[%3.0fsec] %s\",\n              interface->options.encode_decode_hiding_timer,\n              setup_header_option_descriptions[setup_header_enc_dec_timer]);\n  } else {\n    mvwprintw(options_win, setup_header_enc_dec_timer + 1, 0, \"[always] %s\",\n              setup_header_option_descriptions[setup_header_enc_dec_timer]);\n  }\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_header_enc_dec_timer) {\n    mvwchgat(options_win, setup_header_enc_dec_timer + 1, 0, 8, A_STANDOUT, cyan_color, NULL);\n  }\n\n  // Extra GPU info bar\n  option_state = interface->options.has_gpu_info_bar;\n  mvwprintw(options_win, setup_header_gpu_info_bar + 1, 0, \"[%c] %s\", option_state_char(option_state),\n            setup_header_option_descriptions[setup_header_gpu_info_bar]);\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_header_gpu_info_bar) {\n    mvwchgat(options_win, setup_header_gpu_info_bar + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n  wnoutrefresh(options_win);\n}\n\nstatic void draw_setup_window_chart(unsigned devices_count, struct list_head *devices,\n                                    struct nvtop_interface *interface) {\n  WINDOW *option_list_win;\n\n  // Fix indices for this window\n  if (interface->setup_win.options_selected[0] > devices_count + 1)\n    interface->setup_win.options_selected[0] = devices_count + 1;\n  if (interface->setup_win.options_selected[0] > 0) {\n    if (interface->setup_win.options_selected[1] >= plot_information_count)\n      interface->setup_win.options_selected[1] = plot_information_count - 1;\n    option_list_win = interface->setup_win.split[0];\n  } else {\n    if (interface->setup_win.indentation_level > 1)\n      interface->setup_win.indentation_level = 1;\n    option_list_win = interface->setup_win.single;\n  }\n  werase(interface->setup_win.single);\n  wnoutrefresh(interface->setup_win.single);\n  touchwin(interface->setup_win.split[0]);\n  touchwin(interface->setup_win.split[1]);\n\n  wattr_set(option_list_win, A_STANDOUT, green_color, NULL);\n  mvwprintw(option_list_win, 0, 0, \"Chart Options\");\n  wstandend(option_list_win);\n\n  unsigned int cur_col, maxcols, tmp;\n  (void)tmp;\n  getmaxyx(option_list_win, tmp, maxcols);\n  getyx(option_list_win, tmp, cur_col);\n  mvwchgat(option_list_win, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n\n  enum option_state option_state;\n\n  // Reverse plot\n  option_state = interface->options.plot_left_to_right;\n  mvwprintw(option_list_win, setup_chart_reverse + 1, 0, \"[%c] %s\", option_state_char(option_state),\n            setup_chart_options_descriptions[setup_chart_reverse]);\n  if (interface->setup_win.indentation_level == 1 && interface->setup_win.options_selected[0] == setup_chart_reverse) {\n    mvwchgat(option_list_win, setup_chart_reverse + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n\n  // Set for all GPUs at once\n  if (interface->setup_win.options_selected[0] == setup_chart_all_gpu) {\n    if (interface->setup_win.indentation_level == 1)\n      wattr_set(option_list_win, A_STANDOUT, cyan_color, NULL);\n    if (interface->setup_win.indentation_level == 2)\n      wattr_set(option_list_win, A_BOLD, cyan_color, NULL);\n  }\n  mvwaddch(option_list_win, setup_chart_all_gpu + 1, 1, ACS_HLINE);\n  waddch(option_list_win, '>');\n  wstandend(option_list_win);\n  wprintw(option_list_win, \" %s\", setup_chart_options_descriptions[setup_chart_all_gpu]);\n\n  // GPUs as a list\n  for (unsigned i = 0; i < devices_count; ++i) {\n    if (interface->setup_win.options_selected[0] == setup_chart_start_gpu_list + i) {\n      if (interface->setup_win.indentation_level == 1)\n        wattr_set(option_list_win, A_STANDOUT, cyan_color, NULL);\n      if (interface->setup_win.indentation_level == 2)\n        wattr_set(option_list_win, A_BOLD, cyan_color, NULL);\n    }\n    mvwaddch(option_list_win, setup_chart_start_gpu_list + 1 + i, 1, ACS_HLINE);\n    waddch(option_list_win, '>');\n    wstandend(option_list_win);\n    wprintw(option_list_win, \" %s %u\", setup_chart_options_descriptions[setup_chart_start_gpu_list], i);\n  }\n  wnoutrefresh(option_list_win);\n\n  // Window of list of metric to display in chart (4 maximum)\n  if (interface->setup_win.options_selected[0] >= setup_chart_all_gpu) {\n    WINDOW *value_list_win = interface->setup_win.split[1];\n    wattr_set(value_list_win, A_STANDOUT, green_color, NULL);\n    mvwprintw(value_list_win, 0, 0, \"Metric Displayed in Graph\");\n    getmaxyx(value_list_win, tmp, maxcols);\n    unsigned selected_gpu = interface->setup_win.options_selected[0] - setup_chart_start_gpu_list;\n    if (interface->setup_win.options_selected[0] == setup_chart_all_gpu) {\n      wprintw(value_list_win, \" (All GPUs)\");\n    } else {\n      // Get the selected device\n      struct gpu_info *device;\n      unsigned index = 0;\n      list_for_each_entry(device, devices, list) {\n        if (index == selected_gpu)\n          break;\n        index++;\n      }\n      if (IS_VALID(gpuinfo_device_name_valid, device->static_info.valid)) {\n        getyx(value_list_win, tmp, cur_col);\n        wprintw(value_list_win, \" (%.*s)\", maxcols - cur_col - 3, device->static_info.device_name);\n      } else\n        wprintw(value_list_win, \" (GPU %u)\", selected_gpu);\n    }\n    wclrtoeol(value_list_win);\n    getyx(value_list_win, tmp, cur_col);\n    mvwchgat(value_list_win, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n    wattr_set(value_list_win, A_NORMAL, magenta_color, NULL);\n    mvwprintw(value_list_win, 1, 0, \"Maximum of 4 metrics per GPU\");\n    wstandend(value_list_win);\n\n    for (enum plot_information i = plot_gpu_rate; i < plot_information_count; ++i) {\n      if (interface->setup_win.options_selected[0] == setup_chart_all_gpu) {\n        plot_info_to_draw draw_union = 0, draw_intersection = 0xffff;\n        for (unsigned j = 0; j < devices_count; ++j) {\n          draw_union |= interface->options.gpu_specific_opts[j].to_draw;\n          draw_intersection = draw_intersection & interface->options.gpu_specific_opts[j].to_draw;\n        }\n        if (plot_isset_draw_info(i, draw_intersection)) {\n          option_state = option_on;\n        } else {\n          if (plot_isset_draw_info(i, draw_union))\n            option_state = option_partially_active;\n          else\n            option_state = option_off;\n        }\n      } else {\n        option_state = plot_isset_draw_info(i, interface->options.gpu_specific_opts[selected_gpu].to_draw);\n      }\n      mvwprintw(value_list_win, i + 2, 0, \"[%c] %s\", option_state_char(option_state),\n                setup_chart_gpu_value_descriptions[i]);\n      if (interface->setup_win.indentation_level == 2 && interface->setup_win.options_selected[1] == i) {\n        mvwchgat(value_list_win, i + 2, 0, 3, A_STANDOUT, cyan_color, NULL);\n      }\n    }\n    wnoutrefresh(value_list_win);\n  }\n}\n\nstatic void draw_setup_window_proc_list(struct nvtop_interface *interface) {\n  WINDOW *option_list_win;\n  if (interface->setup_win.options_selected[0] >= setup_proc_list_options_count)\n    interface->setup_win.options_selected[0] = setup_proc_list_options_count - 1;\n  if (interface->setup_win.options_selected[0] < setup_proc_list_sort_by) {\n    option_list_win = interface->setup_win.single;\n    if (interface->setup_win.indentation_level > 1)\n      interface->setup_win.indentation_level = 1;\n  } else {\n    option_list_win = interface->setup_win.split[0];\n    if (interface->setup_win.options_selected[0] == setup_proc_list_sort_by) {\n      unsigned fields_count = process_field_displayed_count(interface->options.process_fields_displayed);\n      if (!fields_count) {\n        if (interface->setup_win.indentation_level > 1)\n          interface->setup_win.indentation_level = 1;\n      } else {\n        if (interface->setup_win.options_selected[1] >= fields_count)\n          interface->setup_win.options_selected[1] = fields_count - 1;\n      }\n    }\n    if (interface->setup_win.options_selected[0] == setup_proc_list_display) {\n      if (interface->setup_win.options_selected[1] >= process_field_count)\n        interface->setup_win.options_selected[1] = process_field_count - 1;\n    }\n  }\n\n  werase(interface->setup_win.single);\n  wnoutrefresh(interface->setup_win.single);\n  touchwin(interface->setup_win.split[0]);\n  touchwin(interface->setup_win.split[1]);\n\n  wattr_set(option_list_win, A_STANDOUT, green_color, NULL);\n  mvwprintw(option_list_win, 0, 0, \"Process List Options\");\n  wstandend(option_list_win);\n  unsigned int cur_col, maxcols, tmp;\n  (void)tmp;\n  getmaxyx(option_list_win, tmp, maxcols);\n  getyx(option_list_win, tmp, cur_col);\n  mvwchgat(option_list_win, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n\n  // Sort Ascending\n  enum option_state option_state = interface->options.hide_processes_list;\n  mvwprintw(option_list_win, setup_proc_list_hide_process_list + 1, 0, \"[%c] %s\", option_state_char(option_state),\n            setup_proc_list_option_description[setup_proc_list_hide_process_list]);\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_proc_list_hide_process_list) {\n    mvwchgat(option_list_win, setup_proc_list_hide_process_list + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n  option_state = interface->options.filter_nvtop_pid;\n  mvwprintw(option_list_win, setup_proc_list_hide_nvtop_process + 1, 0, \"[%c] %s\", option_state_char(option_state),\n            setup_proc_list_option_description[setup_proc_list_hide_nvtop_process]);\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_proc_list_hide_nvtop_process) {\n    mvwchgat(option_list_win, setup_proc_list_hide_nvtop_process + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n  option_state = !interface->options.sort_descending_order;\n  mvwprintw(option_list_win, setup_proc_list_sort_ascending + 1, 0, \"[%c] %s\", option_state_char(option_state),\n            setup_proc_list_option_description[setup_proc_list_sort_ascending]);\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] == setup_proc_list_sort_ascending) {\n    mvwchgat(option_list_win, setup_proc_list_sort_ascending + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n\n  for (enum setup_proc_list_options i = setup_proc_list_sort_by; i < setup_proc_list_options_count; ++i) {\n    if (interface->setup_win.options_selected[0] == i) {\n      if (interface->setup_win.indentation_level == 1)\n        wattr_set(option_list_win, A_STANDOUT, cyan_color, NULL);\n      if (interface->setup_win.indentation_level == 2)\n        wattr_set(option_list_win, A_BOLD, cyan_color, NULL);\n    }\n    mvwaddch(option_list_win, i + 1, 1, ACS_HLINE);\n    waddch(option_list_win, '>');\n    wstandend(option_list_win);\n    wprintw(option_list_win, \" %s\", setup_proc_list_option_description[i]);\n    wnoutrefresh(option_list_win);\n  }\n\n  if (interface->setup_win.options_selected[0] >= setup_proc_list_sort_by) {\n    WINDOW *value_list_win = interface->setup_win.split[1];\n    // Sort by\n    if (interface->setup_win.options_selected[0] == setup_proc_list_sort_by) {\n      wattr_set(value_list_win, A_STANDOUT, green_color, NULL);\n      mvwprintw(value_list_win, 0, 0, \"Processes are sorted by:\");\n      wstandend(value_list_win);\n      wclrtoeol(value_list_win);\n      getmaxyx(value_list_win, tmp, maxcols);\n      getyx(value_list_win, tmp, cur_col);\n      mvwchgat(value_list_win, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n      unsigned index = 0;\n      for (enum process_field field = process_pid; field < process_field_count; ++field) {\n        if (process_is_field_displayed(field, interface->options.process_fields_displayed)) {\n          option_state = interface->options.sort_processes_by == field;\n          mvwprintw(value_list_win, index + 1, 0, \"[%c] %s\", option_state_char(option_state),\n                    setup_proc_list_value_descriptions[field]);\n          wclrtoeol(value_list_win);\n          if (interface->setup_win.indentation_level == 2 && interface->setup_win.options_selected[1] == index) {\n            mvwchgat(value_list_win, index + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n            wmove(value_list_win, field + 2, 0);\n          }\n          index++;\n        }\n      }\n      if (!index) {\n        // Nothing displayed\n        wcolor_set(value_list_win, magenta_color, NULL);\n        mvwprintw(value_list_win, 1, 0, \"Nothing to sort: none of the process fields are displayed\");\n        wstandend(value_list_win);\n      }\n    }\n    // Process field displayed\n    if (interface->setup_win.options_selected[0] == setup_proc_list_display) {\n      wattr_set(value_list_win, A_STANDOUT, green_color, NULL);\n      mvwprintw(value_list_win, 0, 0, \"Process Field Displayed:\");\n      wstandend(value_list_win);\n      wclrtoeol(value_list_win);\n      getmaxyx(value_list_win, tmp, maxcols);\n      getyx(value_list_win, tmp, cur_col);\n      mvwchgat(value_list_win, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n      for (enum process_field field = process_pid; field < process_field_count; ++field) {\n        option_state = process_is_field_displayed(field, interface->options.process_fields_displayed);\n        mvwprintw(value_list_win, field + 1, 0, \"[%c] %s\", option_state_char(option_state),\n                  setup_proc_list_value_descriptions[field]);\n        wclrtoeol(value_list_win);\n        if (interface->setup_win.indentation_level == 2 && interface->setup_win.options_selected[1] == field) {\n          mvwchgat(value_list_win, field + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n          wmove(value_list_win, field + 2, 0);\n        }\n      }\n    }\n    wclrtobot(value_list_win);\n    wnoutrefresh(value_list_win);\n  }\n}\n\nstatic void draw_setup_window_gpu_select(struct nvtop_interface *interface) {\n  if (interface->setup_win.indentation_level > 1)\n    interface->setup_win.indentation_level = 1;\n  if (interface->setup_win.indentation_level == 1 &&\n      interface->setup_win.options_selected[0] >= interface->total_dev_count)\n    interface->setup_win.options_selected[0] = interface->total_dev_count - 1;\n\n  wattr_set(interface->setup_win.single, A_STANDOUT, green_color, NULL);\n  mvwprintw(interface->setup_win.single, 0, 0, \"Select Monitored GPUs\");\n  wstandend(interface->setup_win.single);\n  unsigned int cur_col, maxcols, tmp;\n  (void)tmp;\n  getmaxyx(interface->setup_win.single, tmp, maxcols);\n  getyx(interface->setup_win.single, tmp, cur_col);\n  mvwchgat(interface->setup_win.single, 0, cur_col, maxcols - cur_col, A_STANDOUT, green_color, NULL);\n\n  for (unsigned devId = 0; devId < interface->total_dev_count; ++devId) {\n    mvwprintw(interface->setup_win.single, devId + 1, 0, \"[%c] %s\",\n              option_state_char(!interface->options.gpu_specific_opts[devId].doNotMonitor),\n              interface->options.gpu_specific_opts[devId].linkedGpu->static_info.device_name);\n    if (interface->setup_win.indentation_level == 1 && interface->setup_win.options_selected[0] == devId)\n      mvwchgat(interface->setup_win.single, devId + 1, 0, 3, A_STANDOUT, cyan_color, NULL);\n  }\n\n  wnoutrefresh(interface->setup_win.single);\n}\n\nstatic const char *setup_window_shortcuts[] = {\"Enter\", \"ESC\", \"Arrow keys\", \"+/-\", \"F12\"};\n\nstatic const char *setup_window_shortcut_description[] = {\"Toggle\", \"Exit\", \"Navigate Menu\",\n                                                          \"Increment/Decrement Values\", \"Save Config\"};\n\nvoid draw_setup_window_shortcuts(struct nvtop_interface *interface) {\n  WINDOW *window = interface->shortcut_window;\n\n  wmove(window, 0, 0);\n  for (size_t i = 0; i < ARRAY_SIZE(setup_window_shortcuts); ++i) {\n    wprintw(window, \"%s\", setup_window_shortcuts[i]);\n    wattr_set(window, A_STANDOUT, cyan_color, NULL);\n    wprintw(window, \"%s \", setup_window_shortcut_description[i]);\n    wstandend(window);\n  }\n  wclrtoeol(window);\n  unsigned int cur_col, tmp;\n  (void)tmp;\n  getyx(window, tmp, cur_col);\n  mvwchgat(window, 0, cur_col, -1, A_STANDOUT, cyan_color, NULL);\n  wnoutrefresh(window);\n}\n\nvoid draw_setup_window(unsigned devices_count, struct list_head *devices, struct nvtop_interface *interface) {\n  draw_setup_window_setup(interface);\n  switch (interface->setup_win.selected_section) {\n  case setup_general_selected:\n    draw_setup_window_general(interface);\n    break;\n  case setup_header_selected:\n    draw_setup_window_header(interface);\n    break;\n  case setup_chart_selected:\n    draw_setup_window_chart(devices_count, devices, interface);\n    break;\n  case setup_process_list_selected:\n    draw_setup_window_proc_list(interface);\n    break;\n  case setup_monitored_gpu_list_selected:\n    draw_setup_window_gpu_select(interface);\n    break;\n  default:\n    break;\n  }\n}\n\nvoid handle_setup_win_keypress(int keyId, struct nvtop_interface *interface) {\n  if (interface->setup_win.visible) {\n    switch (keyId) {\n\n    case 'l':\n    case KEY_RIGHT:\n      if (interface->setup_win.indentation_level < 2)\n        interface->setup_win.indentation_level++;\n      break;\n\n    case 'h':\n    case KEY_LEFT:\n      if (interface->setup_win.indentation_level > 0)\n        interface->setup_win.indentation_level--;\n      break;\n\n    case 'k':\n    case KEY_UP:\n      if (interface->setup_win.indentation_level == 0) {\n        if (interface->setup_win.selected_section != setup_general_selected) {\n          interface->setup_win.selected_section--;\n          interface->setup_win.options_selected[0] = 0;\n          interface->setup_win.options_selected[1] = 0;\n          werase(interface->setup_win.single);\n          werase(interface->setup_win.split[0]);\n          werase(interface->setup_win.split[1]);\n          wnoutrefresh(interface->setup_win.single);\n        }\n      } else {\n        if (interface->setup_win.indentation_level == 1)\n          interface->setup_win.options_selected[1] = 0;\n        if (interface->setup_win.options_selected[interface->setup_win.indentation_level - 1] != 0)\n          interface->setup_win.options_selected[interface->setup_win.indentation_level - 1]--;\n      }\n      break;\n\n    case 'j':\n    case KEY_DOWN:\n      if (interface->setup_win.indentation_level == 0) {\n        if (interface->setup_win.selected_section + 1 != setup_window_selection_count) {\n\n          interface->setup_win.selected_section++;\n          interface->setup_win.options_selected[0] = 0;\n          interface->setup_win.options_selected[1] = 0;\n          werase(interface->setup_win.single);\n          werase(interface->setup_win.split[0]);\n          werase(interface->setup_win.split[1]);\n          wnoutrefresh(interface->setup_win.single);\n        }\n      } else {\n        if (interface->setup_win.indentation_level == 1)\n          interface->setup_win.options_selected[1] = 0;\n        interface->setup_win.options_selected[interface->setup_win.indentation_level - 1]++;\n      }\n      break;\n\n    case '+':\n      // General Options\n      if (interface->setup_win.selected_section == setup_general_selected) {\n        if (interface->setup_win.options_selected[0] == setup_general_update_interval) {\n          if (interface->options.update_interval <= 99800)\n            interface->options.update_interval += 100;\n        }\n      }\n      // Header options\n      if (interface->setup_win.selected_section == setup_header_selected) {\n        if (interface->setup_win.indentation_level == 1) {\n          if (interface->setup_win.options_selected[0] == setup_header_enc_dec_timer) {\n            interface->options.encode_decode_hiding_timer += 5.;\n          }\n        }\n      }\n      break;\n    case '-':\n      // General Options\n      if (interface->setup_win.selected_section == setup_general_selected) {\n        if (interface->setup_win.options_selected[0] == setup_general_update_interval) {\n          if (interface->options.update_interval >= 200)\n            interface->options.update_interval -= 100;\n        }\n      }\n      // Header options\n      if (interface->setup_win.selected_section == setup_header_selected) {\n        if (interface->setup_win.indentation_level == 1) {\n          if (interface->setup_win.options_selected[0] == setup_header_enc_dec_timer) {\n            interface->options.encode_decode_hiding_timer -= 5.;\n            if (interface->options.encode_decode_hiding_timer < 0.) {\n              interface->options.encode_decode_hiding_timer = 0.;\n            }\n          }\n        }\n      }\n      break;\n    case '\\n':\n    case KEY_ENTER:\n      if (interface->setup_win.indentation_level == 0) {\n        handle_setup_win_keypress(KEY_RIGHT, interface);\n        return;\n      }\n      // General Options\n      if (interface->setup_win.selected_section == setup_general_selected) {\n        if (interface->setup_win.options_selected[0] == setup_general_color) {\n          interface->options.use_color = !interface->options.use_color;\n        }\n        if (interface->setup_win.options_selected[0] == setup_general_show_startup_support_messages) {\n          interface->options.show_startup_messages = !interface->options.show_startup_messages;\n        }\n        if (interface->setup_win.options_selected[0] == setup_general_update_interval) {\n        }\n      }\n      // Header Options\n      if (interface->setup_win.selected_section == setup_header_selected) {\n        if (interface->setup_win.indentation_level == 1) {\n          if (interface->setup_win.options_selected[0] == setup_header_toggle_fahrenheit) {\n            interface->options.temperature_in_fahrenheit = !interface->options.temperature_in_fahrenheit;\n          }\n          if (interface->setup_win.options_selected[0] == setup_header_enc_dec_timer) {\n            if (interface->options.encode_decode_hiding_timer > 0.) {\n              interface->options.encode_decode_hiding_timer = 0.;\n            } else {\n              interface->options.encode_decode_hiding_timer = 30.;\n            }\n          }\n          if (interface->setup_win.options_selected[0] == setup_header_gpu_info_bar) {\n            interface->options.has_gpu_info_bar = !interface->options.has_gpu_info_bar;\n          }\n        }\n      }\n      // Chart Options\n      if (interface->setup_win.selected_section == setup_chart_selected) {\n        if (interface->setup_win.indentation_level == 1) {\n          if (interface->setup_win.options_selected[0] == setup_chart_reverse) {\n            interface->options.plot_left_to_right = !interface->options.plot_left_to_right;\n          }\n          if (interface->setup_win.options_selected[0] >= setup_chart_all_gpu) {\n            handle_setup_win_keypress(KEY_RIGHT, interface);\n          }\n        } else if (interface->setup_win.indentation_level == 2) {\n          if (interface->setup_win.options_selected[0] == setup_chart_all_gpu) {\n            plot_info_to_draw draw_intersection = 0xffff;\n            for (unsigned j = 0; j < interface->monitored_dev_count; ++j) {\n              draw_intersection = draw_intersection & interface->options.gpu_specific_opts[j].to_draw;\n            }\n            if (plot_isset_draw_info(interface->setup_win.options_selected[1], draw_intersection)) {\n              for (unsigned i = 0; i < interface->monitored_dev_count; ++i) {\n                interface->options.gpu_specific_opts[i].to_draw = plot_remove_draw_info(\n                    interface->setup_win.options_selected[1], interface->options.gpu_specific_opts[i].to_draw);\n                interface_ring_buffer_empty(&interface->saved_data_ring, i);\n              }\n            } else {\n              for (unsigned i = 0; i < interface->monitored_dev_count; ++i) {\n                interface->options.gpu_specific_opts[i].to_draw = plot_add_draw_info(\n                    interface->setup_win.options_selected[1], interface->options.gpu_specific_opts[i].to_draw);\n                interface_ring_buffer_empty(&interface->saved_data_ring, i);\n              }\n            }\n          }\n          if (interface->setup_win.options_selected[0] > setup_chart_all_gpu) {\n            unsigned selected_gpu = interface->setup_win.options_selected[0] - setup_chart_start_gpu_list;\n            if (plot_isset_draw_info(interface->setup_win.options_selected[1],\n                                     interface->options.gpu_specific_opts[selected_gpu].to_draw))\n              interface->options.gpu_specific_opts[selected_gpu].to_draw = plot_remove_draw_info(\n                  interface->setup_win.options_selected[1], interface->options.gpu_specific_opts[selected_gpu].to_draw);\n            else\n              interface->options.gpu_specific_opts[selected_gpu].to_draw = plot_add_draw_info(\n                  interface->setup_win.options_selected[1], interface->options.gpu_specific_opts[selected_gpu].to_draw);\n            interface_ring_buffer_empty(&interface->saved_data_ring, selected_gpu);\n          }\n        }\n      }\n      // Process List Options\n      if (interface->setup_win.selected_section == setup_process_list_selected) {\n        if (interface->setup_win.indentation_level == 1) {\n          if (interface->setup_win.options_selected[0] == setup_proc_list_sort_ascending) {\n            interface->options.sort_descending_order = !interface->options.sort_descending_order;\n          } else if (interface->setup_win.options_selected[0] == setup_proc_list_hide_nvtop_process) {\n            interface->options.filter_nvtop_pid = !interface->options.filter_nvtop_pid;\n          } else if (interface->setup_win.options_selected[0] == setup_proc_list_hide_process_list) {\n            interface->options.hide_processes_list = !interface->options.hide_processes_list;\n          } else if (interface->setup_win.options_selected[0] == setup_proc_list_sort_by) {\n            handle_setup_win_keypress(KEY_RIGHT, interface);\n          }\n        } else if (interface->setup_win.indentation_level == 2) {\n          if (interface->setup_win.options_selected[0] == setup_proc_list_sort_by) {\n            unsigned index = 0;\n            for (enum process_field field = process_pid; field < process_field_count; ++field) {\n              if (process_is_field_displayed(field, interface->options.process_fields_displayed)) {\n                if (index == interface->setup_win.options_selected[1])\n                  interface->options.sort_processes_by = field;\n                index++;\n              }\n            }\n          }\n          if (interface->setup_win.options_selected[0] == setup_proc_list_display) {\n            if (process_is_field_displayed(interface->setup_win.options_selected[1],\n                                           interface->options.process_fields_displayed)) {\n              interface->options.process_fields_displayed = process_remove_field_to_display(\n                  interface->setup_win.options_selected[1], interface->options.process_fields_displayed);\n            } else {\n              interface->options.process_fields_displayed = process_add_field_to_display(\n                  interface->setup_win.options_selected[1], interface->options.process_fields_displayed);\n            }\n            if (!process_is_field_displayed(interface->options.sort_processes_by,\n                                            interface->options.process_fields_displayed)) {\n              interface->options.sort_processes_by =\n                  process_default_sort_by_from(interface->options.process_fields_displayed);\n            }\n          }\n        }\n      }\n      if (interface->setup_win.selected_section == setup_monitored_gpu_list_selected) {\n        if (interface->setup_win.indentation_level == 1) {\n          interface->options.gpu_specific_opts[interface->setup_win.options_selected[0]].doNotMonitor =\n              !interface->options.gpu_specific_opts[interface->setup_win.options_selected[0]].doNotMonitor;\n          interface->options.has_monitored_set_changed = true;\n        }\n      }\n      break;\n    case KEY_F(2):\n    case 27:\n      interface->setup_win.visible = false;\n      update_window_size_to_terminal_size(interface);\n      break;\n    case KEY_F(12):\n      save_interface_options_to_config_file(interface->total_dev_count, &interface->options);\n      break;\n    default:\n      break;\n    }\n  }\n}\n"
  },
  {
    "path": "src/mali_common.h",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * This file is part of Nvtop and adapted from the msm implementation.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/device_discovery.h\"\n#include \"nvtop/extract_gpuinfo_common.h\"\n#include \"nvtop/extract_processinfo_fdinfo.h\"\n#include \"nvtop/time.h\"\n#include <uthash.h>\n#include <xf86drm.h>\n\n#define MAX_ERR_STRING_LEN 256\n\n// Declaration not present in xf86drm.h on Ubuntu 20.04\nextern int drmGetDeviceFromDevId(dev_t dev_id, uint32_t flags, drmDevicePtr *device);\n\nstruct drmFuncTable {\n  typeof(drmGetDevices) *drmGetDevices;\n  typeof(drmGetDevices2) *drmGetDevices2;\n  typeof(drmFreeDevices) *drmFreeDevices;\n  typeof(drmGetVersion) *drmGetVersion;\n  typeof(drmFreeVersion) *drmFreeVersion;\n  typeof(drmGetMagic) *drmGetMagic;\n  typeof(drmAuthMagic) *drmAuthMagic;\n  typeof(drmDropMaster) *drmDropMaster;\n  typeof(drmCommandWriteRead) *drmCommandWriteRead;\n  typeof(drmGetDeviceFromDevId) *drmGetDeviceFromDevId;\n  typeof(drmIoctl) *drmIoctl;\n};\n\nenum mali_version {\n\tMALI_PANFROST,\n\tMALI_PANTHOR,\n\tMALI_VERSIONS,\n};\n\nstruct mali_process_info_cache;\n\nstruct panfrost_driver_data {\n  bool original_profiling_state;\n  bool profiler_enabled;\n  char *sysfs_filename;\n};\nstruct panthor_driver_data {\n  uint32_t unused;\n};\n\nstruct gpu_info_mali {\n  drmVersionPtr drmVersion;\n  enum mali_version version;\n  struct gpu_info base;\n  int fd;\n\n   // Cached processes info\n  struct mali_process_info_cache *last_update_process_cache;\n  struct mali_process_info_cache *current_update_process_cache;\n\n  union {\n    struct panfrost_driver_data panfrost;\n    struct panthor_driver_data panthor;\n  } model;\n};\n\nstruct mali_gpu_state {\n  unsigned mali_gpu_count;\n  struct gpu_info_mali *gpu_infos;\n\n  void *libdrm_handle;\n  FILE *meminfo_file;\n\n  int last_libdrm_return_status;\n  char *didnt_call_gpuinfo_init;\n  char *local_error_string;\n};\n\ntypedef void (*check_fdinfo_keys)(bool *is_engine, bool *is_cycles,\n\t\t\t\t  bool *is_maxfreq, bool *is_curfreq,\n\t\t\t\t  bool *is_resident, char *key);\n\nstruct fdinfo_data {\n  uint64_t total_cycles;\n  bool client_id_set;\n  unsigned int engine_count;\n  unsigned cid;\n};\n\n#define HASH_FIND_CLIENT(head, key_ptr, out_ptr) HASH_FIND(hh, head, key_ptr, sizeof(struct unique_cache_id), out_ptr)\n#define HASH_ADD_CLIENT(head, in_ptr) HASH_ADD(hh, head, client_id, sizeof(struct unique_cache_id), in_ptr)\n\n#define SET_MALI_CACHE(cachePtr, field, value) SET_VALUE(cachePtr, field, value, mali_cache_)\n#define RESET_PANFROST_CACHE(cachePtr, field) INVALIDATE_VALUE(cachePtr, field, mali_cache_)\n#define MALI_CACHE_FIELD_VALID(cachePtr, field) VALUE_IS_VALID(cachePtr, field, mali_cache_)\n\nuint64_t parse_memory_multiplier(const char *str);\n\nbool mali_init_drm_funcs(struct drmFuncTable *drmFuncs, struct mali_gpu_state *state);\nvoid mali_deinit_drm(struct mali_gpu_state *state);\nvoid mali_shutdown_common(struct mali_gpu_state *state, struct drmFuncTable *funcs);\nconst char *mali_common_last_error_string(struct mali_gpu_state *state,\n\t\t\t\t\t  const char *drivername,\n\t\t\t\t\t  char error_str[]);\nbool mali_common_get_device_handles(struct mali_gpu_state *state,\n\t\t\t\t    struct drmFuncTable *funcs,\n\t\t\t\t    struct gpu_vendor *vendor,\n\t\t\t\t    processinfo_fdinfo_callback callback,\n\t\t\t\t    struct list_head *devices, unsigned *count,\n\t\t\t\t    bool (*handle_model) (struct gpu_info_mali *),\n\t\t\t\t    enum mali_version version);\nvoid mali_common_refresh_dynamic_info(struct gpuinfo_dynamic_info *dynamic_info,\n\t\t\t\t      struct mali_gpu_state *state,\n\t\t\t\t      const char *meminfo_total,\n\t\t\t\t      const char *meminfo_available);\nvoid mali_common_get_running_processes(struct gpu_info *_gpu_info, enum mali_version version);\n\nvoid mali_common_parse_fdinfo_handle_cache(struct gpu_info_mali *gpu_info,\n\t\t\t\t\t   struct gpu_process *process_info,\n\t\t\t\t\t   nvtop_time current_time,\n\t\t\t\t\t   uint64_t total_cycles,\n\t\t\t\t\t   unsigned cid,\n\t\t\t\t\t   bool engine_count);\n\nbool mali_common_parse_drm_fdinfo(struct gpu_info *info, FILE *fdinfo_file,\n\t\t\t\t  struct gpu_process *process_info,\n\t\t\t\t  struct gpuinfo_dynamic_info *dynamic_info,\n\t\t\t\t  check_fdinfo_keys match_keys,\n\t\t\t\t  struct fdinfo_data *fid);\n"
  },
  {
    "path": "src/nvtop.c",
    "content": "/*\n *\n * Copyright (C) 2017-2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/extract_gpuinfo.h\"\n#include \"nvtop/info_messages.h\"\n#include \"nvtop/interface.h\"\n#include \"nvtop/interface_common.h\"\n#include \"nvtop/interface_options.h\"\n#include \"nvtop/time.h\"\n#include \"nvtop/version.h\"\n\n#include <getopt.h>\n#include <ncurses.h>\n#include <signal.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <locale.h>\n\nstatic volatile sig_atomic_t signal_exit = 0;\nstatic volatile sig_atomic_t signal_resize_win = 0;\nstatic volatile sig_atomic_t signal_cont_received = 0;\n\nstatic void exit_handler(int signum) {\n  (void)signum;\n  signal_exit = 1;\n}\n\nstatic void resize_handler(int signum) {\n  (void)signum;\n  signal_resize_win = 1;\n}\n\nstatic void cont_handler(int signum) {\n  (void)signum;\n  signal_cont_received = 1;\n}\n\nstatic const char helpstring[] = \"Available options:\\n\"\n                                 \"  -d --delay        : Select the refresh rate (1 == 0.1s)\\n\"\n                                 \"  -v --version      : Print the version and exit\\n\"\n                                 \"  -c --config-file  : Provide a custom config file location to load/save \"\n                                 \"preferences\\n\"\n                                 \"  -p --no-plot      : Disable bar plot\\n\"\n                                 \"  -P --no-processes : Disable process list\\n\"\n                                 \"  -r --reverse-abs  : Reverse abscissa: plot the recent data left and \"\n                                 \"older on the right\\n\"\n                                 \"  -C --no-color     : No colors\\n\"\n                                 \"line information\\n\"\n                                 \"  -f --freedom-unit : Use fahrenheit\\n\"\n                                 \"  -i --gpu-info     : Show bar with additional GPU parameters\\n\"\n                                 \"  -E --encode-hide  : Set encode/decode auto hide time in seconds \"\n                                 \"(default 30s, negative = always on screen)\\n\"\n                                 \"  -h --help         : Print help and exit\\n\"\n                                 \"  -s --snapshot     : Output the current gpu stats without ncurses\"\n                                 \"(useful for scripting)\\n\"\n                                 \"  -l --loop         : Output the current gpu stats without ncurses in a loop\\n\";\n\nstatic const char versionString[] = \"nvtop version \" NVTOP_VERSION_STRING;\n\nstatic const struct option long_opts[] = {\n    {.name = \"delay\", .has_arg = required_argument, .flag = NULL, .val = 'd'},\n    {.name = \"version\", .has_arg = no_argument, .flag = NULL, .val = 'v'},\n    {.name = \"help\", .has_arg = no_argument, .flag = NULL, .val = 'h'},\n    {.name = \"config-file\", .has_arg = required_argument, .flag = NULL, .val = 'c'},\n    {.name = \"no-color\", .has_arg = no_argument, .flag = NULL, .val = 'C'},\n    {.name = \"no-colour\", .has_arg = no_argument, .flag = NULL, .val = 'C'},\n    {.name = \"freedom-unit\", .has_arg = no_argument, .flag = NULL, .val = 'f'},\n    {.name = \"gpu-info\", .has_arg = no_argument, .flag = NULL, .val = 'i'},\n    {.name = \"encode-hide\", .has_arg = required_argument, .flag = NULL, .val = 'E'},\n    {.name = \"no-plot\", .has_arg = no_argument, .flag = NULL, .val = 'p'},\n    {.name = \"no-processes\", .has_arg = no_argument, .flag = NULL, .val = 'P'},\n    {.name = \"reverse-abs\", .has_arg = no_argument, .flag = NULL, .val = 'r'},\n    {.name = \"snapshot\", .has_arg = no_argument, .flag = NULL, .val = 's'},\n    {.name = \"loop\", .has_arg = no_argument, .flag = NULL, .val = 'l'},\n    {0, 0, 0, 0},\n};\n\nstatic const char opts[] = \"hvd:c:CfE:pPrisl\";\n\nint main(int argc, char **argv) {\n  (void)setlocale(LC_CTYPE, \"\");\n\n  opterr = 0;\n  bool update_interval_option_set = false;\n  int update_interval_option;\n  bool no_color_option = false;\n  bool use_fahrenheit_option = false;\n  bool hide_plot_option = false;\n  bool hide_processes_option = false;\n  bool reverse_plot_direction_option = false;\n  bool encode_decode_timer_option_set = false;\n  bool show_gpu_info_bar = false;\n  bool show_snapshot = false;\n  bool loop_snapshot = false;\n  double encode_decode_hide_time = -1.;\n  char *custom_config_file_path = NULL;\n  while (true) {\n    int optchar = getopt_long(argc, argv, opts, long_opts, NULL);\n    if (optchar == -1)\n      break;\n    switch (optchar) {\n    case 'd': {\n      char *endptr = NULL;\n      long int delay_val = strtol(optarg, &endptr, 0);\n      if (endptr == optarg) {\n        fprintf(stderr, \"Error: The delay must be a positive value \"\n                        \"representing tenths of seconds\\n\");\n        exit(EXIT_FAILURE);\n      }\n      if (delay_val < 0) {\n        fprintf(stderr, \"Error: A negative delay requires a time machine!\\n\");\n        exit(EXIT_FAILURE);\n      }\n      update_interval_option_set = true;\n      update_interval_option = (int)delay_val * 100u;\n      if (update_interval_option > 99900)\n        update_interval_option = 99900;\n      if (update_interval_option < 100)\n        update_interval_option = 100;\n    } break;\n    case 'v':\n      printf(\"%s\\n\", versionString);\n      exit(EXIT_SUCCESS);\n    case 'h':\n      printf(\"%s\\n%s\", versionString, helpstring);\n      exit(EXIT_SUCCESS);\n    case 'c':\n      custom_config_file_path = optarg;\n      break;\n    case 'C':\n      no_color_option = true;\n      break;\n    case 'f':\n      use_fahrenheit_option = true;\n      break;\n    case 'i':\n      show_gpu_info_bar = true;\n      break;\n    case 'E': {\n      if (sscanf(optarg, \"%lf\", &encode_decode_hide_time) == EOF) {\n        fprintf(stderr, \"Invalid format for encode/decode hide time: %s\\n\", optarg);\n        exit(EXIT_FAILURE);\n      }\n      encode_decode_timer_option_set = true;\n    } break;\n    case 'p':\n      hide_plot_option = true;\n      break;\n    case 'P':\n      hide_processes_option = true;\n      break;\n    case 'r':\n      reverse_plot_direction_option = true;\n      break;\n    case 's':\n      show_snapshot = true;\n      break;\n    case 'l':\n      loop_snapshot = true;\n      break;\n    case ':':\n    case '?':\n      switch (optopt) {\n      case 'd':\n        fprintf(stderr, \"Error: The delay option takes a positive value \"\n                        \"representing tenths of seconds\\n\");\n        break;\n      default:\n        fprintf(stderr, \"Unhandled error in getopt missing argument\\n\");\n        exit(EXIT_FAILURE);\n        break;\n      }\n      exit(EXIT_FAILURE);\n    }\n  }\n\n  setenv(\"ESCDELAY\", \"10\", 1);\n\n  struct sigaction siga;\n  siga.sa_flags = 0;\n  sigemptyset(&siga.sa_mask);\n  siga.sa_handler = exit_handler;\n\n  if (sigaction(SIGINT, &siga, NULL) != 0) {\n    perror(\"Impossible to set signal handler for SIGINT: \");\n    exit(EXIT_FAILURE);\n  }\n  if (sigaction(SIGQUIT, &siga, NULL) != 0) {\n    perror(\"Impossible to set signal handler for SIGQUIT: \");\n    exit(EXIT_FAILURE);\n  }\n  siga.sa_handler = resize_handler;\n  if (sigaction(SIGWINCH, &siga, NULL) != 0) {\n    perror(\"Impossible to set signal handler for SIGWINCH: \");\n    exit(EXIT_FAILURE);\n  }\n  siga.sa_handler = cont_handler;\n  if (sigaction(SIGCONT, &siga, NULL) != 0) {\n    perror(\"Impossible to set signal handler for SIGCONT: \");\n    exit(EXIT_FAILURE);\n  }\n\n  unsigned allDevCount = 0;\n  LIST_HEAD(monitoredGpus);\n  LIST_HEAD(nonMonitoredGpus);\n  if (!gpuinfo_init_info_extraction(&allDevCount, &monitoredGpus))\n    return EXIT_FAILURE;\n  if (allDevCount == 0) {\n    fprintf(stdout, \"No GPU to monitor.\\n\");\n    return EXIT_SUCCESS;\n  }\n\n  if (show_snapshot || loop_snapshot) {\n    gpuinfo_populate_static_infos(&monitoredGpus);\n\n    // Always do a refresh followed by a short sleep to have valid cycle based\n    // metrics\n    gpuinfo_refresh_dynamic_info(&monitoredGpus);\n    gpuinfo_refresh_processes(&monitoredGpus);\n    gpuinfo_utilisation_rate(&monitoredGpus);\n    // Default to 0.1 sec\n    if (!update_interval_option_set)\n      update_interval_option = 100;\n\n    do {\n#if _POSIX_C_SOURCE >= 199309L\n      struct timespec tv = {.tv_sec = update_interval_option / 1000,\n                            .tv_nsec = (update_interval_option % 1000) * 1000000};\n      nanosleep(&tv, &tv);\n#else\n      int sec = update_interval_option / 1000;\n      sleep(sec > 0 ? sec : 1);\n#endif\n      gpuinfo_refresh_dynamic_info(&monitoredGpus);\n      gpuinfo_refresh_processes(&monitoredGpus);\n      gpuinfo_utilisation_rate(&monitoredGpus);\n      gpuinfo_fix_dynamic_info_from_process_info(&monitoredGpus);\n      print_snapshot(&monitoredGpus, use_fahrenheit_option);\n    } while (loop_snapshot && !signal_exit);\n\n    gpuinfo_shutdown_info_extraction(&monitoredGpus);\n    return EXIT_SUCCESS;\n  }\n\n  unsigned numWarningMessages = 0;\n  const char **warningMessages;\n  get_info_messages(&monitoredGpus, &numWarningMessages, &warningMessages);\n\n  nvtop_interface_option allDevicesOptions;\n  alloc_interface_options_internals(custom_config_file_path, allDevCount, &monitoredGpus, &allDevicesOptions);\n  load_interface_options_from_config_file(allDevCount, &allDevicesOptions);\n  for (unsigned i = 0; i < allDevCount; ++i) {\n    // Nothing specified in the file\n    if (!plot_isset_draw_info(plot_information_count, allDevicesOptions.gpu_specific_opts[i].to_draw)) {\n      allDevicesOptions.gpu_specific_opts[i].to_draw = plot_default_draw_info();\n    } else {\n      allDevicesOptions.gpu_specific_opts[i].to_draw =\n          plot_remove_draw_info(plot_information_count, allDevicesOptions.gpu_specific_opts[i].to_draw);\n    }\n  }\n  if (!process_is_field_displayed(process_field_count, allDevicesOptions.process_fields_displayed)) {\n    allDevicesOptions.process_fields_displayed = process_default_displayed_field();\n  } else {\n    allDevicesOptions.process_fields_displayed =\n        process_remove_field_to_display(process_field_count, allDevicesOptions.process_fields_displayed);\n  }\n  if (no_color_option)\n    allDevicesOptions.use_color = false;\n  if (hide_plot_option) {\n    for (unsigned i = 0; i < allDevCount; ++i) {\n      allDevicesOptions.gpu_specific_opts[i].to_draw = 0;\n    }\n  }\n  allDevicesOptions.hide_processes_list = hide_processes_option;\n  if (encode_decode_timer_option_set) {\n    allDevicesOptions.encode_decode_hiding_timer = encode_decode_hide_time;\n    if (allDevicesOptions.encode_decode_hiding_timer < 0.)\n      allDevicesOptions.encode_decode_hiding_timer = 0.;\n  }\n  if (reverse_plot_direction_option)\n    allDevicesOptions.plot_left_to_right = true;\n  if (use_fahrenheit_option)\n    allDevicesOptions.temperature_in_fahrenheit = true;\n  if (update_interval_option_set)\n    allDevicesOptions.update_interval = update_interval_option;\n  allDevicesOptions.has_gpu_info_bar = allDevicesOptions.has_gpu_info_bar || show_gpu_info_bar;\n\n  gpuinfo_populate_static_infos(&monitoredGpus);\n  unsigned numMonitoredGpus =\n      interface_check_and_fix_monitored_gpus(allDevCount, &monitoredGpus, &nonMonitoredGpus, &allDevicesOptions);\n\n  if (allDevicesOptions.show_startup_messages) {\n    bool dont_show_again = show_information_messages(numWarningMessages, warningMessages);\n    if (dont_show_again) {\n      allDevicesOptions.show_startup_messages = false;\n      save_interface_options_to_config_file(allDevCount, &allDevicesOptions);\n    }\n  }\n\n  struct nvtop_interface *interface =\n      initialize_curses(allDevCount, numMonitoredGpus, interface_largest_gpu_name(&monitoredGpus), allDevicesOptions);\n  timeout(interface_update_interval(interface));\n\n  double time_slept = interface_update_interval(interface);\n  while (!signal_exit) {\n    if (signal_resize_win) {\n      signal_resize_win = 0;\n      update_window_size_to_terminal_size(interface);\n    }\n    if (signal_cont_received) {\n      signal_cont_received = 0;\n      update_window_size_to_terminal_size(interface);\n    }\n    interface_check_monitored_gpu_change(&interface, allDevCount, &numMonitoredGpus, &monitoredGpus, &nonMonitoredGpus);\n    if (time_slept >= interface_update_interval(interface)) {\n      gpuinfo_refresh_dynamic_info(&monitoredGpus);\n      if (!interface_freeze_processes(interface)) {\n        gpuinfo_refresh_processes(&monitoredGpus);\n        gpuinfo_utilisation_rate(&monitoredGpus);\n        gpuinfo_fix_dynamic_info_from_process_info(&monitoredGpus);\n      }\n      save_current_data_to_ring(&monitoredGpus, interface);\n      timeout(interface_update_interval(interface));\n      time_slept = 0.;\n    } else {\n      int next_sleep = interface_update_interval(interface) - (int)time_slept;\n      timeout(next_sleep);\n    }\n    draw_gpu_info_ncurses(numMonitoredGpus, &monitoredGpus, interface);\n\n    nvtop_time time_before_sleep, time_after_sleep;\n    nvtop_get_current_time(&time_before_sleep);\n    int input_char = getch();\n    nvtop_get_current_time(&time_after_sleep);\n    time_slept += nvtop_difftime(time_before_sleep, time_after_sleep) * 1000;\n    switch (input_char) {\n    case 27: // ESC\n    {\n      timeout(0);\n      int in = getch();\n      if (in == ERR) { // ESC alone\n        if (is_escape_for_quit(interface))\n          signal_exit = 1;\n        else\n          interface_key(27, interface);\n      }\n      // else ALT key\n    } break;\n    case KEY_F(10):\n      if (is_escape_for_quit(interface))\n        signal_exit = 1;\n      break;\n    case 'q':\n      signal_exit = 1;\n      break;\n    case KEY_RESIZE:\n      update_window_size_to_terminal_size(interface);\n      break;\n    case KEY_F(2):\n    case KEY_F(5):\n    case KEY_F(9):\n    case KEY_F(6):\n    case KEY_F(12):\n    case '+':\n    case '-':\n    case 12: // Ctrl+L\n      interface_key(input_char, interface);\n      break;\n    case 'k':\n    case KEY_UP:\n    case 'j':\n    case KEY_DOWN:\n    case 'h':\n    case KEY_LEFT:\n    case 'l':\n    case KEY_RIGHT:\n    case KEY_ENTER:\n    case '\\n':\n      interface_key(input_char, interface);\n      break;\n    case ERR:\n    default:\n      break;\n    }\n  }\n\n  clean_ncurses(interface);\n  gpuinfo_shutdown_info_extraction(&monitoredGpus);\n\n  return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "src/panfrost_drm.h",
    "content": "/* SPDX-License-Identifier: MIT */\n/*\n * Copyright © 2014-2018 Broadcom\n * Copyright © 2019 Collabora ltd.\n */\n#ifndef _PANFROST_DRM_H_\n#define _PANFROST_DRM_H_\n\n#include \"drm.h\"\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n#define DRM_PANFROST_SUBMIT\t\t\t0x00\n#define DRM_PANFROST_WAIT_BO\t\t\t0x01\n#define DRM_PANFROST_CREATE_BO\t\t\t0x02\n#define DRM_PANFROST_MMAP_BO\t\t\t0x03\n#define DRM_PANFROST_GET_PARAM\t\t\t0x04\n#define DRM_PANFROST_GET_BO_OFFSET\t\t0x05\n#define DRM_PANFROST_PERFCNT_ENABLE\t\t0x06\n#define DRM_PANFROST_PERFCNT_DUMP\t\t0x07\n#define DRM_PANFROST_MADVISE\t\t\t0x08\n\n#define DRM_IOCTL_PANFROST_SUBMIT\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_PANFROST_SUBMIT, struct drm_panfrost_submit)\n#define DRM_IOCTL_PANFROST_WAIT_BO\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_PANFROST_WAIT_BO, struct drm_panfrost_wait_bo)\n#define DRM_IOCTL_PANFROST_CREATE_BO\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_PANFROST_CREATE_BO, struct drm_panfrost_create_bo)\n#define DRM_IOCTL_PANFROST_MMAP_BO\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_PANFROST_MMAP_BO, struct drm_panfrost_mmap_bo)\n#define DRM_IOCTL_PANFROST_GET_PARAM\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_PANFROST_GET_PARAM, struct drm_panfrost_get_param)\n#define DRM_IOCTL_PANFROST_GET_BO_OFFSET\tDRM_IOWR(DRM_COMMAND_BASE + DRM_PANFROST_GET_BO_OFFSET, struct drm_panfrost_get_bo_offset)\n#define DRM_IOCTL_PANFROST_MADVISE\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_PANFROST_MADVISE, struct drm_panfrost_madvise)\n\n/*\n * Unstable ioctl(s): only exposed when the unsafe unstable_ioctls module\n * param is set to true.\n * All these ioctl(s) are subject to deprecation, so please don't rely on\n * them for anything but debugging purpose.\n */\n#define DRM_IOCTL_PANFROST_PERFCNT_ENABLE\tDRM_IOW(DRM_COMMAND_BASE + DRM_PANFROST_PERFCNT_ENABLE, struct drm_panfrost_perfcnt_enable)\n#define DRM_IOCTL_PANFROST_PERFCNT_DUMP\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_PANFROST_PERFCNT_DUMP, struct drm_panfrost_perfcnt_dump)\n\n#define PANFROST_JD_REQ_FS (1 << 0)\n/**\n * struct drm_panfrost_submit - ioctl argument for submitting commands to the 3D\n * engine.\n *\n * This asks the kernel to have the GPU execute a render command list.\n */\nstruct drm_panfrost_submit {\n\n\t/** Address to GPU mapping of job descriptor */\n\t__u64 jc;\n\n\t/** An optional array of sync objects to wait on before starting this job. */\n\t__u64 in_syncs;\n\n\t/** Number of sync objects to wait on before starting this job. */\n\t__u32 in_sync_count;\n\n\t/** An optional sync object to place the completion fence in. */\n\t__u32 out_sync;\n\n\t/** Pointer to a u32 array of the BOs that are referenced by the job. */\n\t__u64 bo_handles;\n\n\t/** Number of BO handles passed in (size is that times 4). */\n\t__u32 bo_handle_count;\n\n\t/** A combination of PANFROST_JD_REQ_* */\n\t__u32 requirements;\n};\n\n/**\n * struct drm_panfrost_wait_bo - ioctl argument for waiting for\n * completion of the last DRM_PANFROST_SUBMIT on a BO.\n *\n * This is useful for cases where multiple processes might be\n * rendering to a BO and you want to wait for all rendering to be\n * completed.\n */\nstruct drm_panfrost_wait_bo {\n\t__u32 handle;\n\t__u32 pad;\n\t__s64 timeout_ns;\t/* absolute */\n};\n\n/* Valid flags to pass to drm_panfrost_create_bo */\n#define PANFROST_BO_NOEXEC\t1\n#define PANFROST_BO_HEAP\t2\n\n/**\n * struct drm_panfrost_create_bo - ioctl argument for creating Panfrost BOs.\n *\n * The flags argument is a bit mask of PANFROST_BO_* flags.\n */\nstruct drm_panfrost_create_bo {\n\t__u32 size;\n\t__u32 flags;\n\t/** Returned GEM handle for the BO. */\n\t__u32 handle;\n\t/* Pad, must be zero-filled. */\n\t__u32 pad;\n\t/**\n\t * Returned offset for the BO in the GPU address space.  This offset\n\t * is private to the DRM fd and is valid for the lifetime of the GEM\n\t * handle.\n\t *\n\t * This offset value will always be nonzero, since various HW\n\t * units treat 0 specially.\n\t */\n\t__u64 offset;\n};\n\n/**\n * struct drm_panfrost_mmap_bo - ioctl argument for mapping Panfrost BOs.\n *\n * This doesn't actually perform an mmap.  Instead, it returns the\n * offset you need to use in an mmap on the DRM device node.  This\n * means that tools like valgrind end up knowing about the mapped\n * memory.\n *\n * There are currently no values for the flags argument, but it may be\n * used in a future extension.\n */\nstruct drm_panfrost_mmap_bo {\n\t/** Handle for the object being mapped. */\n\t__u32 handle;\n\t__u32 flags;\n\t/** offset into the drm node to use for subsequent mmap call. */\n\t__u64 offset;\n};\n\nenum drm_panfrost_param {\n\tDRM_PANFROST_PARAM_GPU_PROD_ID,\n\tDRM_PANFROST_PARAM_GPU_REVISION,\n\tDRM_PANFROST_PARAM_SHADER_PRESENT,\n\tDRM_PANFROST_PARAM_TILER_PRESENT,\n\tDRM_PANFROST_PARAM_L2_PRESENT,\n\tDRM_PANFROST_PARAM_STACK_PRESENT,\n\tDRM_PANFROST_PARAM_AS_PRESENT,\n\tDRM_PANFROST_PARAM_JS_PRESENT,\n\tDRM_PANFROST_PARAM_L2_FEATURES,\n\tDRM_PANFROST_PARAM_CORE_FEATURES,\n\tDRM_PANFROST_PARAM_TILER_FEATURES,\n\tDRM_PANFROST_PARAM_MEM_FEATURES,\n\tDRM_PANFROST_PARAM_MMU_FEATURES,\n\tDRM_PANFROST_PARAM_THREAD_FEATURES,\n\tDRM_PANFROST_PARAM_MAX_THREADS,\n\tDRM_PANFROST_PARAM_THREAD_MAX_WORKGROUP_SZ,\n\tDRM_PANFROST_PARAM_THREAD_MAX_BARRIER_SZ,\n\tDRM_PANFROST_PARAM_COHERENCY_FEATURES,\n\tDRM_PANFROST_PARAM_TEXTURE_FEATURES0,\n\tDRM_PANFROST_PARAM_TEXTURE_FEATURES1,\n\tDRM_PANFROST_PARAM_TEXTURE_FEATURES2,\n\tDRM_PANFROST_PARAM_TEXTURE_FEATURES3,\n\tDRM_PANFROST_PARAM_JS_FEATURES0,\n\tDRM_PANFROST_PARAM_JS_FEATURES1,\n\tDRM_PANFROST_PARAM_JS_FEATURES2,\n\tDRM_PANFROST_PARAM_JS_FEATURES3,\n\tDRM_PANFROST_PARAM_JS_FEATURES4,\n\tDRM_PANFROST_PARAM_JS_FEATURES5,\n\tDRM_PANFROST_PARAM_JS_FEATURES6,\n\tDRM_PANFROST_PARAM_JS_FEATURES7,\n\tDRM_PANFROST_PARAM_JS_FEATURES8,\n\tDRM_PANFROST_PARAM_JS_FEATURES9,\n\tDRM_PANFROST_PARAM_JS_FEATURES10,\n\tDRM_PANFROST_PARAM_JS_FEATURES11,\n\tDRM_PANFROST_PARAM_JS_FEATURES12,\n\tDRM_PANFROST_PARAM_JS_FEATURES13,\n\tDRM_PANFROST_PARAM_JS_FEATURES14,\n\tDRM_PANFROST_PARAM_JS_FEATURES15,\n\tDRM_PANFROST_PARAM_NR_CORE_GROUPS,\n\tDRM_PANFROST_PARAM_THREAD_TLS_ALLOC,\n\tDRM_PANFROST_PARAM_AFBC_FEATURES,\n\tDRM_PANFROST_PARAM_MAX_FREQ,\n};\n\nstruct drm_panfrost_get_param {\n\t__u32 param;\n\t__u32 pad;\n\t__u64 value;\n};\n\n/**\n * Returns the offset for the BO in the GPU address space for this DRM fd.\n * This is the same value returned by drm_panfrost_create_bo, if that was called\n * from this DRM fd.\n */\nstruct drm_panfrost_get_bo_offset {\n\t__u32 handle;\n\t__u32 pad;\n\t__u64 offset;\n};\n\nstruct drm_panfrost_perfcnt_enable {\n\t__u32 enable;\n\t/*\n\t * On bifrost we have 2 sets of counters, this parameter defines the\n\t * one to track.\n\t */\n\t__u32 counterset;\n};\n\nstruct drm_panfrost_perfcnt_dump {\n\t__u64 buf_ptr;\n};\n\n/* madvise provides a way to tell the kernel in case a buffers contents\n * can be discarded under memory pressure, which is useful for userspace\n * bo cache where we want to optimistically hold on to buffer allocate\n * and potential mmap, but allow the pages to be discarded under memory\n * pressure.\n *\n * Typical usage would involve madvise(DONTNEED) when buffer enters BO\n * cache, and madvise(WILLNEED) if trying to recycle buffer from BO cache.\n * In the WILLNEED case, 'retained' indicates to userspace whether the\n * backing pages still exist.\n */\n#define PANFROST_MADV_WILLNEED 0\t/* backing pages are needed, status returned in 'retained' */\n#define PANFROST_MADV_DONTNEED 1\t/* backing pages not needed */\n\nstruct drm_panfrost_madvise {\n\t__u32 handle;         /* in, GEM handle */\n\t__u32 madv;           /* in, PANFROST_MADV_x */\n\t__u32 retained;       /* out, whether backing store still exists */\n};\n\n/* Definitions for coredump decoding in user space */\n#define PANFROSTDUMP_MAJOR 1\n#define PANFROSTDUMP_MINOR 0\n\n#define PANFROSTDUMP_MAGIC 0x464E4150 /* PANF */\n\n#define PANFROSTDUMP_BUF_REG 0\n#define PANFROSTDUMP_BUF_BOMAP (PANFROSTDUMP_BUF_REG + 1)\n#define PANFROSTDUMP_BUF_BO (PANFROSTDUMP_BUF_BOMAP + 1)\n#define PANFROSTDUMP_BUF_TRAILER (PANFROSTDUMP_BUF_BO + 1)\n\n/*\n * This structure is the native endianness of the dumping machine, tools can\n * detect the endianness by looking at the value in 'magic'.\n */\nstruct panfrost_dump_object_header {\n\t__u32 magic;\n\t__u32 type;\n\t__u32 file_size;\n\t__u32 file_offset;\n\n\tunion {\n\t\tstruct {\n\t\t\t__u64 jc;\n\t\t\t__u32 gpu_id;\n\t\t\t__u32 major;\n\t\t\t__u32 minor;\n\t\t\t__u64 nbos;\n\t\t} reghdr;\n\n\t\tstruct {\n\t\t\t__u32 valid;\n\t\t\t__u64 iova;\n\t\t\t__u32 data[2];\n\t\t} bomap;\n\n\t\t/*\n\t\t * Force same size in case we want to expand the header\n\t\t * with new fields and also keep it 512-byte aligned\n\t\t */\n\n\t\t__u32 sizer[496];\n\t};\n};\n\n/* Registers object, an array of these */\nstruct panfrost_dump_registers {\n\t__u32 reg;\n\t__u32 value;\n};\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif /* _PANFROST_DRM_H_ */\n"
  },
  {
    "path": "src/panfrost_utils.h",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n\nconst char * panfrost_parse_marketing_name(uint64_t gpu_id);\nunsigned int util_last_bit(unsigned int u);\nunsigned int get_number_engines(uint32_t gpu_id, int core_count, uint32_t core_features, uint32_t thread_features);\n"
  },
  {
    "path": "src/panthor_drm.h",
    "content": "/* SPDX-License-Identifier: MIT */\n/* Copyright (C) 2023 Collabora ltd. */\n#ifndef _PANTHOR_DRM_H_\n#define _PANTHOR_DRM_H_\n\n#include \"drm.h\"\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n/**\n * DOC: Introduction\n *\n * This documentation describes the Panthor IOCTLs.\n *\n * Just a few generic rules about the data passed to the Panthor IOCTLs:\n *\n * - Structures must be aligned on 64-bit/8-byte. If the object is not\n *   naturally aligned, a padding field must be added.\n * - Fields must be explicitly aligned to their natural type alignment with\n *   pad[0..N] fields.\n * - All padding fields will be checked by the driver to make sure they are\n *   zeroed.\n * - Flags can be added, but not removed/replaced.\n * - New fields can be added to the main structures (the structures\n *   directly passed to the ioctl). Those fields can be added at the end of\n *   the structure, or replace existing padding fields. Any new field being\n *   added must preserve the behavior that existed before those fields were\n *   added when a value of zero is passed.\n * - New fields can be added to indirect objects (objects pointed by the\n *   main structure), iff those objects are passed a size to reflect the\n *   size known by the userspace driver (see drm_panthor_obj_array::stride\n *   or drm_panthor_dev_query::size).\n * - If the kernel driver is too old to know some fields, those will be\n *   ignored if zero, and otherwise rejected (and so will be zero on output).\n * - If userspace is too old to know some fields, those will be zeroed\n *   (input) before the structure is parsed by the kernel driver.\n * - Each new flag/field addition must come with a driver version update so\n *   the userspace driver doesn't have to trial and error to know which\n *   flags are supported.\n * - Structures should not contain unions, as this would defeat the\n *   extensibility of such structures.\n * - IOCTLs can't be removed or replaced. New IOCTL IDs should be placed\n *   at the end of the drm_panthor_ioctl_id enum.\n */\n\n/**\n * DOC: MMIO regions exposed to userspace.\n *\n * .. c:macro:: DRM_PANTHOR_USER_MMIO_OFFSET\n *\n * File offset for all MMIO regions being exposed to userspace. Don't use\n * this value directly, use DRM_PANTHOR_USER_<name>_OFFSET values instead.\n * pgoffset passed to mmap2() is an unsigned long, which forces us to use a\n * different offset on 32-bit and 64-bit systems.\n *\n * .. c:macro:: DRM_PANTHOR_USER_FLUSH_ID_MMIO_OFFSET\n *\n * File offset for the LATEST_FLUSH_ID register. The Userspace driver controls\n * GPU cache flushing through CS instructions, but the flush reduction\n * mechanism requires a flush_id. This flush_id could be queried with an\n * ioctl, but Arm provides a well-isolated register page containing only this\n * read-only register, so let's expose this page through a static mmap offset\n * and allow direct mapping of this MMIO region so we can avoid the\n * user <-> kernel round-trip.\n */\n#define DRM_PANTHOR_USER_MMIO_OFFSET_32BIT\t(1ull << 43)\n#define DRM_PANTHOR_USER_MMIO_OFFSET_64BIT\t(1ull << 56)\n#define DRM_PANTHOR_USER_MMIO_OFFSET\t\t(sizeof(unsigned long) < 8 ? \\\n\t\t\t\t\t\t DRM_PANTHOR_USER_MMIO_OFFSET_32BIT : \\\n\t\t\t\t\t\t DRM_PANTHOR_USER_MMIO_OFFSET_64BIT)\n#define DRM_PANTHOR_USER_FLUSH_ID_MMIO_OFFSET\t(DRM_PANTHOR_USER_MMIO_OFFSET | 0)\n\n/**\n * DOC: IOCTL IDs\n *\n * enum drm_panthor_ioctl_id - IOCTL IDs\n *\n * Place new ioctls at the end, don't re-order, don't replace or remove entries.\n *\n * These IDs are not meant to be used directly. Use the DRM_IOCTL_PANTHOR_xxx\n * definitions instead.\n */\nenum drm_panthor_ioctl_id {\n\t/** @DRM_PANTHOR_DEV_QUERY: Query device information. */\n\tDRM_PANTHOR_DEV_QUERY = 0,\n\n\t/** @DRM_PANTHOR_VM_CREATE: Create a VM. */\n\tDRM_PANTHOR_VM_CREATE,\n\n\t/** @DRM_PANTHOR_VM_DESTROY: Destroy a VM. */\n\tDRM_PANTHOR_VM_DESTROY,\n\n\t/** @DRM_PANTHOR_VM_BIND: Bind/unbind memory to a VM. */\n\tDRM_PANTHOR_VM_BIND,\n\n\t/** @DRM_PANTHOR_BO_CREATE: Create a buffer object. */\n\tDRM_PANTHOR_BO_CREATE,\n\n\t/**\n\t * @DRM_PANTHOR_BO_MMAP_OFFSET: Get the file offset to pass to\n\t * mmap to map a GEM object.\n\t */\n\tDRM_PANTHOR_BO_MMAP_OFFSET,\n\n\t/** @DRM_PANTHOR_GROUP_CREATE: Create a scheduling group. */\n\tDRM_PANTHOR_GROUP_CREATE,\n\n\t/** @DRM_PANTHOR_GROUP_DESTROY: Destroy a scheduling group. */\n\tDRM_PANTHOR_GROUP_DESTROY,\n\n\t/**\n\t * @DRM_PANTHOR_GROUP_SUBMIT: Submit jobs to queues belonging\n\t * to a specific scheduling group.\n\t */\n\tDRM_PANTHOR_GROUP_SUBMIT,\n\n\t/** @DRM_PANTHOR_GROUP_GET_STATE: Get the state of a scheduling group. */\n\tDRM_PANTHOR_GROUP_GET_STATE,\n\n\t/** @DRM_PANTHOR_TILER_HEAP_CREATE: Create a tiler heap. */\n\tDRM_PANTHOR_TILER_HEAP_CREATE,\n\n\t/** @DRM_PANTHOR_TILER_HEAP_DESTROY: Destroy a tiler heap. */\n\tDRM_PANTHOR_TILER_HEAP_DESTROY,\n};\n\n/**\n * DRM_IOCTL_PANTHOR() - Build a Panthor IOCTL number\n * @__access: Access type. Must be R, W or RW.\n * @__id: One of the DRM_PANTHOR_xxx id.\n * @__type: Suffix of the type being passed to the IOCTL.\n *\n * Don't use this macro directly, use the DRM_IOCTL_PANTHOR_xxx\n * values instead.\n *\n * Return: An IOCTL number to be passed to ioctl() from userspace.\n */\n#define DRM_IOCTL_PANTHOR(__access, __id, __type) \\\n\tDRM_IO ## __access(DRM_COMMAND_BASE + DRM_PANTHOR_ ## __id, \\\n\t\t\t   struct drm_panthor_ ## __type)\n\n#define DRM_IOCTL_PANTHOR_DEV_QUERY \\\n\tDRM_IOCTL_PANTHOR(WR, DEV_QUERY, dev_query)\n#define DRM_IOCTL_PANTHOR_VM_CREATE \\\n\tDRM_IOCTL_PANTHOR(WR, VM_CREATE, vm_create)\n#define DRM_IOCTL_PANTHOR_VM_DESTROY \\\n\tDRM_IOCTL_PANTHOR(WR, VM_DESTROY, vm_destroy)\n#define DRM_IOCTL_PANTHOR_VM_BIND \\\n\tDRM_IOCTL_PANTHOR(WR, VM_BIND, vm_bind)\n#define DRM_IOCTL_PANTHOR_BO_CREATE \\\n\tDRM_IOCTL_PANTHOR(WR, BO_CREATE, bo_create)\n#define DRM_IOCTL_PANTHOR_BO_MMAP_OFFSET \\\n\tDRM_IOCTL_PANTHOR(WR, BO_MMAP_OFFSET, bo_mmap_offset)\n#define DRM_IOCTL_PANTHOR_GROUP_CREATE \\\n\tDRM_IOCTL_PANTHOR(WR, GROUP_CREATE, group_create)\n#define DRM_IOCTL_PANTHOR_GROUP_DESTROY \\\n\tDRM_IOCTL_PANTHOR(WR, GROUP_DESTROY, group_destroy)\n#define DRM_IOCTL_PANTHOR_GROUP_SUBMIT \\\n\tDRM_IOCTL_PANTHOR(WR, GROUP_SUBMIT, group_submit)\n#define DRM_IOCTL_PANTHOR_GROUP_GET_STATE \\\n\tDRM_IOCTL_PANTHOR(WR, GROUP_GET_STATE, group_get_state)\n#define DRM_IOCTL_PANTHOR_TILER_HEAP_CREATE \\\n\tDRM_IOCTL_PANTHOR(WR, TILER_HEAP_CREATE, tiler_heap_create)\n#define DRM_IOCTL_PANTHOR_TILER_HEAP_DESTROY \\\n\tDRM_IOCTL_PANTHOR(WR, TILER_HEAP_DESTROY, tiler_heap_destroy)\n\n/**\n * DOC: IOCTL arguments\n */\n\n/**\n * struct drm_panthor_obj_array - Object array.\n *\n * This object is used to pass an array of objects whose size is subject to changes in\n * future versions of the driver. In order to support this mutability, we pass a stride\n * describing the size of the object as known by userspace.\n *\n * You shouldn't fill drm_panthor_obj_array fields directly. You should instead use\n * the DRM_PANTHOR_OBJ_ARRAY() macro that takes care of initializing the stride to\n * the object size.\n */\nstruct drm_panthor_obj_array {\n\t/** @stride: Stride of object struct. Used for versioning. */\n\t__u32 stride;\n\n\t/** @count: Number of objects in the array. */\n\t__u32 count;\n\n\t/** @array: User pointer to an array of objects. */\n\t__u64 array;\n};\n\n/**\n * DRM_PANTHOR_OBJ_ARRAY() - Initialize a drm_panthor_obj_array field.\n * @cnt: Number of elements in the array.\n * @ptr: Pointer to the array to pass to the kernel.\n *\n * Macro initializing a drm_panthor_obj_array based on the object size as known\n * by userspace.\n */\n#define DRM_PANTHOR_OBJ_ARRAY(cnt, ptr) \\\n\t{ .stride = sizeof((ptr)[0]), .count = (cnt), .array = (__u64)(uintptr_t)(ptr) }\n\n/**\n * enum drm_panthor_sync_op_flags - Synchronization operation flags.\n */\nenum drm_panthor_sync_op_flags {\n\t/** @DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_MASK: Synchronization handle type mask. */\n\tDRM_PANTHOR_SYNC_OP_HANDLE_TYPE_MASK = 0xff,\n\n\t/** @DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_SYNCOBJ: Synchronization object type. */\n\tDRM_PANTHOR_SYNC_OP_HANDLE_TYPE_SYNCOBJ = 0,\n\n\t/**\n\t * @DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_TIMELINE_SYNCOBJ: Timeline synchronization\n\t * object type.\n\t */\n\tDRM_PANTHOR_SYNC_OP_HANDLE_TYPE_TIMELINE_SYNCOBJ = 1,\n\n\t/** @DRM_PANTHOR_SYNC_OP_WAIT: Wait operation. */\n\tDRM_PANTHOR_SYNC_OP_WAIT = 0 << 31,\n\n\t/** @DRM_PANTHOR_SYNC_OP_SIGNAL: Signal operation. */\n\tDRM_PANTHOR_SYNC_OP_SIGNAL = (int)(1u << 31),\n};\n\n/**\n * struct drm_panthor_sync_op - Synchronization operation.\n */\nstruct drm_panthor_sync_op {\n\t/** @flags: Synchronization operation flags. Combination of DRM_PANTHOR_SYNC_OP values. */\n\t__u32 flags;\n\n\t/** @handle: Sync handle. */\n\t__u32 handle;\n\n\t/**\n\t * @timeline_value: MBZ if\n\t * (flags & DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_MASK) !=\n\t * DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_TIMELINE_SYNCOBJ.\n\t */\n\t__u64 timeline_value;\n};\n\n/**\n * enum drm_panthor_dev_query_type - Query type\n *\n * Place new types at the end, don't re-order, don't remove or replace.\n */\nenum drm_panthor_dev_query_type {\n\t/** @DRM_PANTHOR_DEV_QUERY_GPU_INFO: Query GPU information. */\n\tDRM_PANTHOR_DEV_QUERY_GPU_INFO = 0,\n\n\t/** @DRM_PANTHOR_DEV_QUERY_CSIF_INFO: Query command-stream interface information. */\n\tDRM_PANTHOR_DEV_QUERY_CSIF_INFO,\n};\n\n/**\n * struct drm_panthor_gpu_info - GPU information\n *\n * Structure grouping all queryable information relating to the GPU.\n */\nstruct drm_panthor_gpu_info {\n\t/** @gpu_id : GPU ID. */\n\t__u32 gpu_id;\n#define DRM_PANTHOR_ARCH_MAJOR(x)\t\t((x) >> 28)\n#define DRM_PANTHOR_ARCH_MINOR(x)\t\t(((x) >> 24) & 0xf)\n#define DRM_PANTHOR_ARCH_REV(x)\t\t\t(((x) >> 20) & 0xf)\n#define DRM_PANTHOR_PRODUCT_MAJOR(x)\t\t(((x) >> 16) & 0xf)\n#define DRM_PANTHOR_VERSION_MAJOR(x)\t\t(((x) >> 12) & 0xf)\n#define DRM_PANTHOR_VERSION_MINOR(x)\t\t(((x) >> 4) & 0xff)\n#define DRM_PANTHOR_VERSION_STATUS(x)\t\t((x) & 0xf)\n\n\t/** @gpu_rev: GPU revision. */\n\t__u32 gpu_rev;\n\n\t/** @csf_id: Command stream frontend ID. */\n\t__u32 csf_id;\n#define DRM_PANTHOR_CSHW_MAJOR(x)\t\t(((x) >> 26) & 0x3f)\n#define DRM_PANTHOR_CSHW_MINOR(x)\t\t(((x) >> 20) & 0x3f)\n#define DRM_PANTHOR_CSHW_REV(x)\t\t\t(((x) >> 16) & 0xf)\n#define DRM_PANTHOR_MCU_MAJOR(x)\t\t(((x) >> 10) & 0x3f)\n#define DRM_PANTHOR_MCU_MINOR(x)\t\t(((x) >> 4) & 0x3f)\n#define DRM_PANTHOR_MCU_REV(x)\t\t\t((x) & 0xf)\n\n\t/** @l2_features: L2-cache features. */\n\t__u32 l2_features;\n\n\t/** @tiler_features: Tiler features. */\n\t__u32 tiler_features;\n\n\t/** @mem_features: Memory features. */\n\t__u32 mem_features;\n\n\t/** @mmu_features: MMU features. */\n\t__u32 mmu_features;\n#define DRM_PANTHOR_MMU_VA_BITS(x)\t\t((x) & 0xff)\n\n\t/** @thread_features: Thread features. */\n\t__u32 thread_features;\n\n\t/** @max_threads: Maximum number of threads. */\n\t__u32 max_threads;\n\n\t/** @thread_max_workgroup_size: Maximum workgroup size. */\n\t__u32 thread_max_workgroup_size;\n\n\t/**\n\t * @thread_max_barrier_size: Maximum number of threads that can wait\n\t * simultaneously on a barrier.\n\t */\n\t__u32 thread_max_barrier_size;\n\n\t/** @coherency_features: Coherency features. */\n\t__u32 coherency_features;\n\n\t/** @texture_features: Texture features. */\n\t__u32 texture_features[4];\n\n\t/** @as_present: Bitmask encoding the number of address-space exposed by the MMU. */\n\t__u32 as_present;\n\n\t/** @shader_present: Bitmask encoding the shader cores exposed by the GPU. */\n\t__u64 shader_present;\n\n\t/** @l2_present: Bitmask encoding the L2 caches exposed by the GPU. */\n\t__u64 l2_present;\n\n\t/** @tiler_present: Bitmask encoding the tiler units exposed by the GPU. */\n\t__u64 tiler_present;\n};\n\n/**\n * struct drm_panthor_csif_info - Command stream interface information\n *\n * Structure grouping all queryable information relating to the command stream interface.\n */\nstruct drm_panthor_csif_info {\n\t/** @csg_slot_count: Number of command stream group slots exposed by the firmware. */\n\t__u32 csg_slot_count;\n\n\t/** @cs_slot_count: Number of command stream slots per group. */\n\t__u32 cs_slot_count;\n\n\t/** @cs_reg_count: Number of command stream registers. */\n\t__u32 cs_reg_count;\n\n\t/** @scoreboard_slot_count: Number of scoreboard slots. */\n\t__u32 scoreboard_slot_count;\n\n\t/**\n\t * @unpreserved_cs_reg_count: Number of command stream registers reserved by\n\t * the kernel driver to call a userspace command stream.\n\t *\n\t * All registers can be used by a userspace command stream, but the\n\t * [cs_slot_count - unpreserved_cs_reg_count .. cs_slot_count] registers are\n\t * used by the kernel when DRM_PANTHOR_IOCTL_GROUP_SUBMIT is called.\n\t */\n\t__u32 unpreserved_cs_reg_count;\n\n\t/**\n\t * @pad: Padding field, set to zero.\n\t */\n\t__u32 pad;\n};\n\n/**\n * struct drm_panthor_dev_query - Arguments passed to DRM_PANTHOR_IOCTL_DEV_QUERY\n */\nstruct drm_panthor_dev_query {\n\t/** @type: the query type (see drm_panthor_dev_query_type). */\n\t__u32 type;\n\n\t/**\n\t * @size: size of the type being queried.\n\t *\n\t * If pointer is NULL, size is updated by the driver to provide the\n\t * output structure size. If pointer is not NULL, the driver will\n\t * only copy min(size, actual_structure_size) bytes to the pointer,\n\t * and update the size accordingly. This allows us to extend query\n\t * types without breaking userspace.\n\t */\n\t__u32 size;\n\n\t/**\n\t * @pointer: user pointer to a query type struct.\n\t *\n\t * Pointer can be NULL, in which case, nothing is copied, but the\n\t * actual structure size is returned. If not NULL, it must point to\n\t * a location that's large enough to hold size bytes.\n\t */\n\t__u64 pointer;\n};\n\n/**\n * struct drm_panthor_vm_create - Arguments passed to DRM_PANTHOR_IOCTL_VM_CREATE\n */\nstruct drm_panthor_vm_create {\n\t/** @flags: VM flags, MBZ. */\n\t__u32 flags;\n\n\t/** @id: Returned VM ID. */\n\t__u32 id;\n\n\t/**\n\t * @user_va_range: Size of the VA space reserved for user objects.\n\t *\n\t * The kernel will pick the remaining space to map kernel-only objects to the\n\t * VM (heap chunks, heap context, ring buffers, kernel synchronization objects,\n\t * ...). If the space left for kernel objects is too small, kernel object\n\t * allocation will fail further down the road. One can use\n\t * drm_panthor_gpu_info::mmu_features to extract the total virtual address\n\t * range, and chose a user_va_range that leaves some space to the kernel.\n\t *\n\t * If user_va_range is zero, the kernel will pick a sensible value based on\n\t * TASK_SIZE and the virtual range supported by the GPU MMU (the kernel/user\n\t * split should live enough VA space for userspace processes to support SVM,\n\t * while still allowing the kernel to map some amount of kernel objects in\n\t * the kernel VA range). The value chosen by the driver will be returned in\n\t * @user_va_range.\n\t *\n\t * User VA space always starts at 0x0, kernel VA space is always placed after\n\t * the user VA range.\n\t */\n\t__u64 user_va_range;\n};\n\n/**\n * struct drm_panthor_vm_destroy - Arguments passed to DRM_PANTHOR_IOCTL_VM_DESTROY\n */\nstruct drm_panthor_vm_destroy {\n\t/** @id: ID of the VM to destroy. */\n\t__u32 id;\n\n\t/** @pad: MBZ. */\n\t__u32 pad;\n};\n\n/**\n * enum drm_panthor_vm_bind_op_flags - VM bind operation flags\n */\nenum drm_panthor_vm_bind_op_flags {\n\t/**\n\t * @DRM_PANTHOR_VM_BIND_OP_MAP_READONLY: Map the memory read-only.\n\t *\n\t * Only valid with DRM_PANTHOR_VM_BIND_OP_TYPE_MAP.\n\t */\n\tDRM_PANTHOR_VM_BIND_OP_MAP_READONLY = 1 << 0,\n\n\t/**\n\t * @DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC: Map the memory not-executable.\n\t *\n\t * Only valid with DRM_PANTHOR_VM_BIND_OP_TYPE_MAP.\n\t */\n\tDRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC = 1 << 1,\n\n\t/**\n\t * @DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED: Map the memory uncached.\n\t *\n\t * Only valid with DRM_PANTHOR_VM_BIND_OP_TYPE_MAP.\n\t */\n\tDRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED = 1 << 2,\n\n\t/**\n\t * @DRM_PANTHOR_VM_BIND_OP_TYPE_MASK: Mask used to determine the type of operation.\n\t */\n\tDRM_PANTHOR_VM_BIND_OP_TYPE_MASK = (int)(0xfu << 28),\n\n\t/** @DRM_PANTHOR_VM_BIND_OP_TYPE_MAP: Map operation. */\n\tDRM_PANTHOR_VM_BIND_OP_TYPE_MAP = 0 << 28,\n\n\t/** @DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP: Unmap operation. */\n\tDRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP = 1 << 28,\n};\n\n/**\n * struct drm_panthor_vm_bind_op - VM bind operation\n */\nstruct drm_panthor_vm_bind_op {\n\t/** @flags: Combination of drm_panthor_vm_bind_op_flags flags. */\n\t__u32 flags;\n\n\t/**\n\t * @bo_handle: Handle of the buffer object to map.\n\t * MBZ for unmap operations.\n\t */\n\t__u32 bo_handle;\n\n\t/**\n\t * @bo_offset: Buffer object offset.\n\t * MBZ for unmap operations.\n\t */\n\t__u64 bo_offset;\n\n\t/**\n\t * @va: Virtual address to map/unmap.\n\t */\n\t__u64 va;\n\n\t/** @size: Size to map/unmap. */\n\t__u64 size;\n\n\t/**\n\t * @syncs: Array of struct drm_panthor_sync_op synchronization\n\t * operations.\n\t *\n\t * This array must be empty if %DRM_PANTHOR_VM_BIND_ASYNC is not set on\n\t * the drm_panthor_vm_bind object containing this VM bind operation.\n\t */\n\tstruct drm_panthor_obj_array syncs;\n\n};\n\n/**\n * enum drm_panthor_vm_bind_flags - VM bind flags\n */\nenum drm_panthor_vm_bind_flags {\n\t/**\n\t * @DRM_PANTHOR_VM_BIND_ASYNC: VM bind operations are queued to the VM\n\t * queue instead of being executed synchronously.\n\t */\n\tDRM_PANTHOR_VM_BIND_ASYNC = 1 << 0,\n};\n\n/**\n * struct drm_panthor_vm_bind - Arguments passed to DRM_IOCTL_PANTHOR_VM_BIND\n */\nstruct drm_panthor_vm_bind {\n\t/** @vm_id: VM targeted by the bind request. */\n\t__u32 vm_id;\n\n\t/** @flags: Combination of drm_panthor_vm_bind_flags flags. */\n\t__u32 flags;\n\n\t/** @ops: Array of struct drm_panthor_vm_bind_op bind operations. */\n\tstruct drm_panthor_obj_array ops;\n};\n\n/**\n * enum drm_panthor_bo_flags - Buffer object flags, passed at creation time.\n */\nenum drm_panthor_bo_flags {\n\t/** @DRM_PANTHOR_BO_NO_MMAP: The buffer object will never be CPU-mapped in userspace. */\n\tDRM_PANTHOR_BO_NO_MMAP = (1 << 0),\n};\n\n/**\n * struct drm_panthor_bo_create - Arguments passed to DRM_IOCTL_PANTHOR_BO_CREATE.\n */\nstruct drm_panthor_bo_create {\n\t/**\n\t * @size: Requested size for the object\n\t *\n\t * The (page-aligned) allocated size for the object will be returned.\n\t */\n\t__u64 size;\n\n\t/**\n\t * @flags: Flags. Must be a combination of drm_panthor_bo_flags flags.\n\t */\n\t__u32 flags;\n\n\t/**\n\t * @exclusive_vm_id: Exclusive VM this buffer object will be mapped to.\n\t *\n\t * If not zero, the field must refer to a valid VM ID, and implies that:\n\t *  - the buffer object will only ever be bound to that VM\n\t *  - cannot be exported as a PRIME fd\n\t */\n\t__u32 exclusive_vm_id;\n\n\t/**\n\t * @handle: Returned handle for the object.\n\t *\n\t * Object handles are nonzero.\n\t */\n\t__u32 handle;\n\n\t/** @pad: MBZ. */\n\t__u32 pad;\n};\n\n/**\n * struct drm_panthor_bo_mmap_offset - Arguments passed to DRM_IOCTL_PANTHOR_BO_MMAP_OFFSET.\n */\nstruct drm_panthor_bo_mmap_offset {\n\t/** @handle: Handle of the object we want an mmap offset for. */\n\t__u32 handle;\n\n\t/** @pad: MBZ. */\n\t__u32 pad;\n\n\t/** @offset: The fake offset to use for subsequent mmap calls. */\n\t__u64 offset;\n};\n\n/**\n * struct drm_panthor_queue_create - Queue creation arguments.\n */\nstruct drm_panthor_queue_create {\n\t/**\n\t * @priority: Defines the priority of queues inside a group. Goes from 0 to 15,\n\t * 15 being the highest priority.\n\t */\n\t__u8 priority;\n\n\t/** @pad: Padding fields, MBZ. */\n\t__u8 pad[3];\n\n\t/** @ringbuf_size: Size of the ring buffer to allocate to this queue. */\n\t__u32 ringbuf_size;\n};\n\n/**\n * enum drm_panthor_group_priority - Scheduling group priority\n */\nenum drm_panthor_group_priority {\n\t/** @PANTHOR_GROUP_PRIORITY_LOW: Low priority group. */\n\tPANTHOR_GROUP_PRIORITY_LOW = 0,\n\n\t/** @PANTHOR_GROUP_PRIORITY_MEDIUM: Medium priority group. */\n\tPANTHOR_GROUP_PRIORITY_MEDIUM,\n\n\t/** @PANTHOR_GROUP_PRIORITY_HIGH: High priority group. */\n\tPANTHOR_GROUP_PRIORITY_HIGH,\n};\n\n/**\n * struct drm_panthor_group_create - Arguments passed to DRM_IOCTL_PANTHOR_GROUP_CREATE\n */\nstruct drm_panthor_group_create {\n\t/** @queues: Array of drm_panthor_queue_create elements. */\n\tstruct drm_panthor_obj_array queues;\n\n\t/**\n\t * @max_compute_cores: Maximum number of cores that can be used by compute\n\t * jobs across CS queues bound to this group.\n\t *\n\t * Must be less or equal to the number of bits set in @compute_core_mask.\n\t */\n\t__u8 max_compute_cores;\n\n\t/**\n\t * @max_fragment_cores: Maximum number of cores that can be used by fragment\n\t * jobs across CS queues bound to this group.\n\t *\n\t * Must be less or equal to the number of bits set in @fragment_core_mask.\n\t */\n\t__u8 max_fragment_cores;\n\n\t/**\n\t * @max_tiler_cores: Maximum number of tilers that can be used by tiler jobs\n\t * across CS queues bound to this group.\n\t *\n\t * Must be less or equal to the number of bits set in @tiler_core_mask.\n\t */\n\t__u8 max_tiler_cores;\n\n\t/** @priority: Group priority (see enum drm_panthor_group_priority). */\n\t__u8 priority;\n\n\t/** @pad: Padding field, MBZ. */\n\t__u32 pad;\n\n\t/**\n\t * @compute_core_mask: Mask encoding cores that can be used for compute jobs.\n\t *\n\t * This field must have at least @max_compute_cores bits set.\n\t *\n\t * The bits set here should also be set in drm_panthor_gpu_info::shader_present.\n\t */\n\t__u64 compute_core_mask;\n\n\t/**\n\t * @fragment_core_mask: Mask encoding cores that can be used for fragment jobs.\n\t *\n\t * This field must have at least @max_fragment_cores bits set.\n\t *\n\t * The bits set here should also be set in drm_panthor_gpu_info::shader_present.\n\t */\n\t__u64 fragment_core_mask;\n\n\t/**\n\t * @tiler_core_mask: Mask encoding cores that can be used for tiler jobs.\n\t *\n\t * This field must have at least @max_tiler_cores bits set.\n\t *\n\t * The bits set here should also be set in drm_panthor_gpu_info::tiler_present.\n\t */\n\t__u64 tiler_core_mask;\n\n\t/**\n\t * @vm_id: VM ID to bind this group to.\n\t *\n\t * All submission to queues bound to this group will use this VM.\n\t */\n\t__u32 vm_id;\n\n\t/**\n\t * @group_handle: Returned group handle. Passed back when submitting jobs or\n\t * destroying a group.\n\t */\n\t__u32 group_handle;\n};\n\n/**\n * struct drm_panthor_group_destroy - Arguments passed to DRM_IOCTL_PANTHOR_GROUP_DESTROY\n */\nstruct drm_panthor_group_destroy {\n\t/** @group_handle: Group to destroy */\n\t__u32 group_handle;\n\n\t/** @pad: Padding field, MBZ. */\n\t__u32 pad;\n};\n\n/**\n * struct drm_panthor_queue_submit - Job submission arguments.\n *\n * This is describing the userspace command stream to call from the kernel\n * command stream ring-buffer. Queue submission is always part of a group\n * submission, taking one or more jobs to submit to the underlying queues.\n */\nstruct drm_panthor_queue_submit {\n\t/** @queue_index: Index of the queue inside a group. */\n\t__u32 queue_index;\n\n\t/**\n\t * @stream_size: Size of the command stream to execute.\n\t *\n\t * Must be 64-bit/8-byte aligned (the size of a CS instruction)\n\t *\n\t * Can be zero if stream_addr is zero too.\n\t */\n\t__u32 stream_size;\n\n\t/**\n\t * @stream_addr: GPU address of the command stream to execute.\n\t *\n\t * Must be aligned on 64-byte.\n\t *\n\t * Can be zero is stream_size is zero too.\n\t */\n\t__u64 stream_addr;\n\n\t/**\n\t * @latest_flush: FLUSH_ID read at the time the stream was built.\n\t *\n\t * This allows cache flush elimination for the automatic\n\t * flush+invalidate(all) done at submission time, which is needed to\n\t * ensure the GPU doesn't get garbage when reading the indirect command\n\t * stream buffers. If you want the cache flush to happen\n\t * unconditionally, pass a zero here.\n\t */\n\t__u32 latest_flush;\n\n\t/** @pad: MBZ. */\n\t__u32 pad;\n\n\t/** @syncs: Array of struct drm_panthor_sync_op sync operations. */\n\tstruct drm_panthor_obj_array syncs;\n};\n\n/**\n * struct drm_panthor_group_submit - Arguments passed to DRM_IOCTL_PANTHOR_VM_BIND\n */\nstruct drm_panthor_group_submit {\n\t/** @group_handle: Handle of the group to queue jobs to. */\n\t__u32 group_handle;\n\n\t/** @pad: MBZ. */\n\t__u32 pad;\n\n\t/** @queue_submits: Array of drm_panthor_queue_submit objects. */\n\tstruct drm_panthor_obj_array queue_submits;\n};\n\n/**\n * enum drm_panthor_group_state_flags - Group state flags\n */\nenum drm_panthor_group_state_flags {\n\t/**\n\t * @DRM_PANTHOR_GROUP_STATE_TIMEDOUT: Group had unfinished jobs.\n\t *\n\t * When a group ends up with this flag set, no jobs can be submitted to its queues.\n\t */\n\tDRM_PANTHOR_GROUP_STATE_TIMEDOUT = 1 << 0,\n\n\t/**\n\t * @DRM_PANTHOR_GROUP_STATE_FATAL_FAULT: Group had fatal faults.\n\t *\n\t * When a group ends up with this flag set, no jobs can be submitted to its queues.\n\t */\n\tDRM_PANTHOR_GROUP_STATE_FATAL_FAULT = 1 << 1,\n};\n\n/**\n * struct drm_panthor_group_get_state - Arguments passed to DRM_IOCTL_PANTHOR_GROUP_GET_STATE\n *\n * Used to query the state of a group and decide whether a new group should be created to\n * replace it.\n */\nstruct drm_panthor_group_get_state {\n\t/** @group_handle: Handle of the group to query state on */\n\t__u32 group_handle;\n\n\t/**\n\t * @state: Combination of DRM_PANTHOR_GROUP_STATE_* flags encoding the\n\t * group state.\n\t */\n\t__u32 state;\n\n\t/** @fatal_queues: Bitmask of queues that faced fatal faults. */\n\t__u32 fatal_queues;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n};\n\n/**\n * struct drm_panthor_tiler_heap_create - Arguments passed to DRM_IOCTL_PANTHOR_TILER_HEAP_CREATE\n */\nstruct drm_panthor_tiler_heap_create {\n\t/** @vm_id: VM ID the tiler heap should be mapped to */\n\t__u32 vm_id;\n\n\t/** @initial_chunk_count: Initial number of chunks to allocate. */\n\t__u32 initial_chunk_count;\n\n\t/** @chunk_size: Chunk size. Must be a power of two at least 256KB large. */\n\t__u32 chunk_size;\n\n\t/** @max_chunks: Maximum number of chunks that can be allocated. */\n\t__u32 max_chunks;\n\n\t/**\n\t * @target_in_flight: Maximum number of in-flight render passes.\n\t *\n\t * If the heap has more than tiler jobs in-flight, the FW will wait for render\n\t * passes to finish before queuing new tiler jobs.\n\t */\n\t__u32 target_in_flight;\n\n\t/** @handle: Returned heap handle. Passed back to DESTROY_TILER_HEAP. */\n\t__u32 handle;\n\n\t/** @tiler_heap_ctx_gpu_va: Returned heap GPU virtual address returned */\n\t__u64 tiler_heap_ctx_gpu_va;\n\n\t/**\n\t * @first_heap_chunk_gpu_va: First heap chunk.\n\t *\n\t * The tiler heap is formed of heap chunks forming a single-link list. This\n\t * is the first element in the list.\n\t */\n\t__u64 first_heap_chunk_gpu_va;\n};\n\n/**\n * struct drm_panthor_tiler_heap_destroy - Arguments passed to DRM_IOCTL_PANTHOR_TILER_HEAP_DESTROY\n */\nstruct drm_panthor_tiler_heap_destroy {\n\t/** @handle: Handle of the tiler heap to destroy */\n\t__u32 handle;\n\n\t/** @pad: Padding field, MBZ. */\n\t__u32 pad;\n};\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif /* _PANTHOR_DRM_H_ */\n"
  },
  {
    "path": "src/panthor_utils.h",
    "content": "/*\n *\n * Copyright (C) 2023 Adrian Larumbe <adrian.larumbe@collabora.com>\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n\nconst char * panthor_device_name(uint32_t gpu_id);\n"
  },
  {
    "path": "src/plot.c",
    "content": "/*\n *\n * Copyright (C) 2019-2021 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/plot.h\"\n#include \"nvtop/common.h\"\n\n#include <assert.h>\n#include <ncurses.h>\n#include <stdbool.h>\n#include <string.h>\n#include <tgmath.h>\n\nstatic inline int data_level(double rows, double data, double increment) {\n  return (int)(rows - round(data / increment));\n}\n\nvoid nvtop_line_plot(WINDOW *win, size_t num_data, const double *data, unsigned num_lines, bool legend_left,\n                     char legend[MAX_LINES_PER_PLOT][PLOT_MAX_LEGEND_SIZE]) {\n  if (num_data == 0)\n    return;\n  int rows, cols;\n  getmaxyx(win, rows, cols);\n  rows -= 1;\n  double increment = 100. / (double)(rows);\n\n  assert(num_lines <= MAX_LINES_PER_PLOT && \"Cannot plot more than \" EXPAND_AND_QUOTE(MAX_LINES_PER_PLOT) \" lines\");\n  unsigned lvl_before[MAX_LINES_PER_PLOT];\n  for (size_t k = 0; k < num_lines; ++k)\n    lvl_before[k] = data_level(rows, data[k], increment);\n\n  for (size_t i = 0; i < num_data || i < (size_t)cols; i += num_lines) {\n    for (unsigned k = 0; k < num_lines; ++k) {\n      unsigned lvl_now_k = data_level(rows, data[i + k], increment);\n      wcolor_set(win, k + 1, NULL);\n      // Three cases: has increased, has decreased and remained level\n      if (lvl_before[k] < lvl_now_k || lvl_before[k] > lvl_now_k) {\n        // Case 1 and 2: has increased/decreased\n\n        // An increase goes down on the plot because (0,0) is top left\n        bool drawing_down = lvl_before[k] < lvl_now_k;\n        unsigned bottom = drawing_down ? lvl_before[k] : lvl_now_k;\n        unsigned top = drawing_down ? lvl_now_k : lvl_before[k];\n\n        // Draw the vertical line corners\n        mvwaddch(win, bottom, i + k, drawing_down ? ACS_URCORNER : ACS_ULCORNER);\n        mvwaddch(win, top, i + k, drawing_down ? ACS_LLCORNER : ACS_LRCORNER);\n        // Draw the vertical line between the corners\n        if (top - bottom > 1) {\n          mvwvline(win, bottom + 1, i + k, 0, top - bottom - 1);\n        }\n\n        // Draw the continuation of the other metrics\n        for (unsigned j = 0; j < num_lines; ++j) {\n          if (j != k) {\n            if (lvl_before[j] == top)\n              // The continuation is at the same level as the bottom corner\n              mvwaddch(win, top, i + k, ACS_BTEE);\n            else if (lvl_before[j] == bottom)\n              // The continuation is at the same level as the top corner\n              mvwaddch(win, bottom, i + k, ACS_TTEE);\n            else if (lvl_before[j] > bottom && lvl_before[j] < top)\n              // The continuation lies on the vertical line\n              mvwaddch(win, lvl_before[j], i + k, ACS_PLUS);\n            else {\n              // The continuation lies outside the update interval so keep the\n              // color\n              wcolor_set(win, j + 1, NULL);\n              mvwaddch(win, lvl_before[j], i + k, ACS_HLINE);\n              wcolor_set(win, k + 1, NULL);\n            }\n          }\n        }\n      } else {\n        // Case 3: stayed level\n        mvwhline(win, lvl_now_k, i + k, 0, 1);\n        for (unsigned j = 0; j < num_lines; ++j) {\n          if (j != k) {\n            if (lvl_before[j] != lvl_now_k) {\n              // Add the continuation of other metric lines\n              wcolor_set(win, j + 1, NULL);\n              mvwaddch(win, lvl_before[j], i + k, ACS_HLINE);\n              wcolor_set(win, k + 1, NULL);\n            }\n          }\n        }\n      }\n      lvl_before[k] = lvl_now_k;\n    }\n  }\n  int plot_y_position = 0;\n  for (unsigned i = 0; i < num_lines && plot_y_position < rows; ++i) {\n    wcolor_set(win, i + 1, NULL);\n    if (legend_left) {\n      mvwprintw(win, plot_y_position, 0, \"%.*s\", cols, legend[i]);\n    } else {\n      size_t length = strlen(legend[i]);\n      if (length <= (size_t)cols) {\n        mvwprintw(win, plot_y_position, cols - length, \"%s\", legend[i]);\n      } else {\n        mvwprintw(win, plot_y_position, 0, \"%.*s\", (int)(length - cols), legend[i]);\n      }\n    }\n    plot_y_position++;\n  }\n}\n\nvoid draw_rectangle(WINDOW *win, unsigned startX, unsigned startY, unsigned sizeX, unsigned sizeY) {\n  mvwhline(win, startY, startX + 1, 0, sizeX - 2);\n  mvwhline(win, startY + sizeY - 1, startX + 1, 0, sizeX - 2);\n\n  mvwvline(win, startY + 1, startX, 0, sizeY - 2);\n  mvwvline(win, startY + 1, startX + sizeX - 1, 0, sizeY - 2);\n\n  mvwaddch(win, startY, startX, ACS_ULCORNER);\n  mvwaddch(win, startY, startX + sizeX - 1, ACS_URCORNER);\n  mvwaddch(win, startY + sizeY - 1, startX, ACS_LLCORNER);\n  mvwaddch(win, startY + sizeY - 1, startX + sizeX - 1, ACS_LRCORNER);\n}\n"
  },
  {
    "path": "src/time.c",
    "content": "/*\n *\n * Copyright (C) 2018-2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"nvtop/time.h\"\n\nextern inline void nvtop_get_current_time(nvtop_time *time);\nextern inline double nvtop_difftime(nvtop_time t0, nvtop_time t1);\nextern inline uint64_t nvtop_difftime_u64(nvtop_time t0, nvtop_time t1);\nextern inline uint64_t nvtop_time_u64(nvtop_time t0);\nextern inline nvtop_time nvtop_add_time(nvtop_time t0, nvtop_time t1);\nextern inline nvtop_time nvtop_substract_time(nvtop_time t0, nvtop_time t1);\nextern inline nvtop_time nvtop_hmns_to_time(unsigned hour, unsigned minutes, unsigned long nanosec);\n"
  },
  {
    "path": "tests/CMakeLists.txt",
    "content": "find_package(GTest)\nif (BUILD_TESTING AND GTest_FOUND)\n\n  option(THOROUGH_TESTING \"Enable extensive testing (takes hours, e.g., use once per release)\" OFF)\n\n  # Create a library for testing\n  add_library(testLib\n    ${PROJECT_SOURCE_DIR}/src/interface_layout_selection.c\n    ${PROJECT_SOURCE_DIR}/src/extract_processinfo_fdinfo.c\n    ${PROJECT_SOURCE_DIR}/src/interface_options.c\n    ${PROJECT_SOURCE_DIR}/src/ini.c\n  )\n  target_include_directories(testLib PUBLIC\n    ${PROJECT_SOURCE_DIR}/include\n    ${PROJECT_BINARY_DIR}/include)\n\n  # Tests\n  add_executable(\n    interfaceTests\n    interfaceTests.cpp\n  )\n  target_link_libraries(interfaceTests PRIVATE testLib GTest::gtest_main)\n  gtest_discover_tests(interfaceTests)\n\n  if (THOROUGH_TESTING)\n    target_compile_definitions(interfaceTests PRIVATE THOROUGH_TESTING)\n  endif()\n\n\nendif()\n"
  },
  {
    "path": "tests/interfaceTests.cpp",
    "content": "/*\n *\n * Copyright (C) 2022 Maxime Schmitt <maxime.schmitt91@gmail.com>\n *\n * This file is part of Nvtop.\n *\n * Nvtop is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Nvtop is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with nvtop.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <algorithm>\n#include <gtest/gtest.h>\n#include <iostream>\n#include <vector>\n\nextern \"C\" {\n#include \"nvtop/interface.h\"\n#include \"nvtop/interface_layout_selection.h\"\n}\n\nstatic std::ostream &operator<<(std::ostream &os, const struct window_position &win) {\n  os << \"Win (\" << win.posX << \", \" << win.posY << \")--(\" << win.posX + win.sizeX << \",\" << win.posY + win.sizeY << \")\";\n  return os;\n}\n\nnamespace {\n\n// Returns true if the two windows overlap, false otherwise.\nbool window_position_overlap(struct window_position &w1, struct window_position &w2) {\n  bool overlapX = w1.posX == w2.posX || (w1.posX < w2.posX && w1.posX + w1.sizeX - 1 >= w2.posX) ||\n                  (w1.posX > w2.posX && w2.posX + w2.sizeX - 1 >= w1.posX);\n  bool overlapY = w1.posY == w2.posY || (w1.posY < w2.posY && w1.posY + w1.sizeY - 1 >= w2.posY) ||\n                  (w1.posY > w2.posY && w2.posY + w2.sizeY - 1 >= w1.posY);\n  return overlapX && overlapY;\n}\n\nbool window_is_empty(const struct window_position &w1) { return w1.sizeX == 0 || w1.sizeY == 0; }\n\n// Check that the window is not empty\n// Returns true if the window is not empty\nbool check_non_empty_window(const struct window_position &w1) {\n  EXPECT_GT(w1.sizeX, 0) << \"Window \" << w1 << \" should not be empty\";\n  EXPECT_GT(w1.sizeY, 0) << \"Window \" << w1 << \" should not be empty\";\n  return not window_is_empty(w1);\n}\n\n// Check that the none of the windows overlap any other\nbool check_no_windows_overlap(std::vector<struct window_position> &windows) {\n  bool has_overlap = false;\n  for (unsigned winId = 0; winId < windows.size(); ++winId) {\n    struct window_position &currentWin = windows[winId];\n    for (unsigned winCompareId = winId + 1; winCompareId < windows.size(); ++winCompareId) {\n      struct window_position &compareTo = windows[winCompareId];\n      bool overlaps = window_position_overlap(currentWin, compareTo);\n      EXPECT_FALSE(overlaps) << \"Between \" << currentWin << \" and \" << compareTo;\n      has_overlap = has_overlap || overlaps;\n    }\n  }\n  return !has_overlap;\n}\n\n// Check that win does not extend past the container\n// Returns true if win is contained inside the container\nbool check_window_inside(const struct window_position &win, const struct window_position &container) {\n  bool insideX = win.posX >= container.posX && win.posX + win.sizeX - 1 <= container.posX + container.sizeX - 1;\n  EXPECT_TRUE(insideX) << win << \" is not inside \" << container;\n  bool insideY = win.posY >= container.posY && win.posY + win.sizeY - 1 <= container.posY + container.sizeY - 1;\n  EXPECT_TRUE(insideY) << win << \" is not inside \" << container;\n  return insideX && insideY;\n}\n\n// Check that w1 is below w2\nbool check_window_below(const struct window_position &w1, const struct window_position &w2) {\n  EXPECT_GT(w1.posY, w2.posY + w2.sizeY - 1) << w1 << \" is not below \" << w2;\n  return w1.posY > w2.posY + w2.sizeY - 1;\n}\n\n// Returns true if the layout is valid\nbool check_layout(struct window_position screen, std::vector<struct window_position> &dev_pos,\n                  std::vector<struct window_position> &plot_position, struct window_position process_position,\n                  struct window_position setup_position) {\n  bool layout_valid = true;\n\n  // Header\n  // A particularity of the header is that it can be bigger than the screen\n  for (auto const &dev_win : dev_pos) {\n    bool valid = check_non_empty_window(dev_win);\n    if (!valid)\n      std::cout << \"Error with header window: \" << dev_win << std::endl;\n    layout_valid = layout_valid && valid;\n  }\n  layout_valid = layout_valid && check_no_windows_overlap(dev_pos);\n\n  // Plots\n  for (auto const &plot_win : plot_position) {\n    bool valid = check_non_empty_window(plot_win);\n    if (!valid)\n      std::cout << \"Error with plot window: \" << plot_win << std::endl;\n    layout_valid = layout_valid && valid;\n  }\n  for (auto const &dev_win : dev_pos) {\n    for (auto const &plot_win : plot_position) {\n      layout_valid = layout_valid && check_window_below(plot_win, dev_win);\n      layout_valid = layout_valid && check_window_inside(plot_win, screen);\n    }\n  }\n  layout_valid = layout_valid && check_no_windows_overlap(plot_position);\n\n  // Processes\n  for (auto const &plot_win : plot_position) {\n    layout_valid = layout_valid && check_window_below(process_position, plot_win);\n  }\n  if (not window_is_empty(process_position))\n    layout_valid = layout_valid && check_window_inside(process_position, screen);\n\n  return layout_valid;\n}\n\nbool test_with_terminal_size(unsigned device_count, unsigned header_rows, unsigned header_cols, unsigned rows,\n                             unsigned cols) {\n  struct window_position screen = {.posX = 0, .posY = 0, .sizeX = cols, .sizeY = rows};\n\n  nvtop_interface_gpu_opts to_draw_default = {.to_draw = plot_default_draw_info()};\n  std::vector<nvtop_interface_gpu_opts> plot_display(device_count, to_draw_default);\n\n  process_field_displayed proc_display = process_default_displayed_field();\n\n  unsigned num_plots = 0;\n  std::vector<struct window_position> dev_positions(device_count);\n  std::vector<struct window_position> plot_positions(MAX_CHARTS);\n  struct window_position process_position;\n  struct window_position setup_position;\n  std::vector<unsigned> map_dev_to_plot(device_count);\n  compute_sizes_from_layout(device_count, header_rows, header_cols, rows, cols, plot_display.data(), proc_display,\n                            dev_positions.data(), &num_plots, plot_positions.data(), map_dev_to_plot.data(),\n                            &process_position, &setup_position, false);\n  plot_positions.resize(num_plots);\n\n  return check_layout(screen, dev_positions, plot_positions, process_position, setup_position);\n}\n\n} // namespace\n\nTEST(InterfaceLayout, LayoutSelection_issue_147) { test_with_terminal_size(8, 3, 78, 26, 189); }\n\nTEST(InterfaceLayout, CheckEmptyProcessWindow) {\n  unsigned device_count = 3, header_rows = 3, header_cols = 55, rows = 4, cols = 120;\n  struct window_position screen = {.posX = 0, .posY = 0, .sizeX = cols, .sizeY = rows};\n\n  nvtop_interface_gpu_opts to_draw_default = {.to_draw = plot_default_draw_info()};\n  std::vector<nvtop_interface_gpu_opts> plot_display(device_count, to_draw_default);\n\n  process_field_displayed proc_display = process_default_displayed_field();\n\n  unsigned num_plots = 0;\n  std::vector<struct window_position> dev_positions(device_count);\n  std::vector<struct window_position> plot_positions(MAX_CHARTS);\n  struct window_position process_position;\n  struct window_position setup_position;\n  std::vector<unsigned> map_dev_to_plot(device_count);\n  compute_sizes_from_layout(device_count, header_rows, header_cols, rows, cols, plot_display.data(), proc_display,\n                            dev_positions.data(), &num_plots, plot_positions.data(), map_dev_to_plot.data(),\n                            &process_position, &setup_position, false);\n  plot_positions.resize(num_plots);\n  EXPECT_EQ(num_plots, 0);\n  EXPECT_TRUE(window_is_empty(process_position));\n}\n\nTEST(InterfaceLayout, FixInfiniteLoop) {\n  unsigned device_count = 3, header_rows = 3, header_cols = 55, rows = 22, cols = 25;\n  struct window_position screen = {.posX = 0, .posY = 0, .sizeX = cols, .sizeY = rows};\n\n  nvtop_interface_gpu_opts to_draw_default = {.to_draw = plot_default_draw_info()};\n  std::vector<nvtop_interface_gpu_opts> plot_display(device_count, to_draw_default);\n\n  process_field_displayed proc_display = process_default_displayed_field();\n\n  unsigned num_plots = 0;\n  std::vector<struct window_position> dev_positions(device_count);\n  std::vector<struct window_position> plot_positions(MAX_CHARTS);\n  struct window_position process_position;\n  struct window_position setup_position;\n  std::vector<unsigned> map_dev_to_plot(device_count);\n  compute_sizes_from_layout(device_count, header_rows, header_cols, rows, cols, plot_display.data(), proc_display,\n                            dev_positions.data(), &num_plots, plot_positions.data(), map_dev_to_plot.data(),\n                            &process_position, &setup_position, false);\n  plot_positions.resize(num_plots);\n}\n\nTEST(InterfaceLayout, LayoutSelection_test_fail_case1) { test_with_terminal_size(32, 3, 55, 16, 1760); }\n\n#ifdef THOROUGH_TESTING\n\nTEST(InterfaceLayout, CheckManyTermSize) {\n  const std::array<unsigned, 8> dev_count_to_test = {0, 1, 2, 3, 6, 16, 32, 64};\n  const std::map<unsigned, unsigned> extra_increment = {{0, 0}, {1, 0},  {2, 0},  {3, 0},\n                                                        {6, 4}, {16, 6}, {32, 8}, {64, 17}};\n  for (unsigned dev_count : dev_count_to_test) {\n    for (unsigned screen_rows = 1; screen_rows < 2048; screen_rows += 1 + extra_increment.at(dev_count)) {\n      for (unsigned screen_cols = 1; screen_cols < 2048; screen_cols += 1 + extra_increment.at(dev_count)) {\n        for (unsigned header_cols = 55; header_cols < 120; header_cols += 1 + extra_increment.at(dev_count)) {\n          ASSERT_TRUE(test_with_terminal_size(dev_count, 3, header_cols, screen_rows, screen_cols))\n              << \"Problem found with \" << dev_count << \" devices, (\" << 3 << \", header \" << header_cols\n              << \"), terminal size (\" << screen_rows << \", \" << screen_cols << \")\";\n        }\n      }\n    }\n  }\n}\n\n#endif // THOROUGH_TESTING"
  }
]