├── .gitignore ├── LICENSE ├── README.md ├── install.sh ├── nvidia-dev-ctl.py ├── nvidia-dev-ctl.service └── nvidia-shlib.sh /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | .pybuilder/ 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | # For a library or package, you might want to ignore these files since the code is 88 | # intended to run in multiple environments; otherwise, check them in: 89 | # .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 99 | __pypackages__/ 100 | 101 | # Celery stuff 102 | celerybeat-schedule 103 | celerybeat.pid 104 | 105 | # SageMath parsed files 106 | *.sage.py 107 | 108 | # Environments 109 | .env 110 | .venv 111 | env/ 112 | venv/ 113 | ENV/ 114 | env.bak/ 115 | venv.bak/ 116 | 117 | # Spyder project settings 118 | .spyderproject 119 | .spyproject 120 | 121 | # Rope project settings 122 | .ropeproject 123 | 124 | # mkdocs documentation 125 | /site 126 | 127 | # mypy 128 | .mypy_cache/ 129 | .dmypy.json 130 | dmypy.json 131 | 132 | # Pyre type checker 133 | .pyre/ 134 | 135 | # pytype static type analyzer 136 | .pytype/ 137 | 138 | # Cython debug symbols 139 | cython_debug/ 140 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nvidia-dev-ctl.py 2 | 3 | Control tool for NVIDIA GPU and vGPU devices on GNU/Linux OS. 4 | 5 | ## Introduction 6 | 7 | The `nvidia-dev-ctl.py` tool is designed to simplify the runtime configuration of NVIDIA virtual and physical GPU devices along with KVM-only virtualization (i.e. through the virsh command.) on GNU/Linux OS. It is based on the official [NVIDIA vGPU user manual](https://docs.nvidia.com/grid/latest/grid-vgpu-user-guide/index.html) and attempts to reduce many of the manual steps described in the documentation, like [creating an NVIDIA vGPU on Red Hat Enterprise Linux KVM](https://docs.nvidia.com/grid/latest/grid-vgpu-user-guide/index.html#creating-vgpu-device-red-hat-el-kvm) using multiple shell commands. 8 | 9 | The following operations are provided by the tool via subcommands: 10 | 11 | * [list-pci](#list-pci-command) - list all NVIDIA PCI devices detected by the NVIDIA driver 12 | * [list-mdev](#list-mdev-command) - list all registered NVIDIA mediated devices (mdev) i.e. virtual GPUs (vGPUs) 13 | * [list-used-pci](#list-used-pci-command) - list all NVIDIA PCI devices used by virtual machines 14 | * [list-used-mdev](#list-used-mdev-command) - list all NVIDIA vGPUs (mdevs) used by virtual machines 15 | * [create-mdev](#create-mdev-command) - create new NVIDIA mdev device 16 | * [remove-mdev](#remove-mdev-command) - remove existing NVIDIA mdev device 17 | * [save](#save-command) - dump current NVIDIA device configuration for later loading using the restore` command. 18 | * [restore](#restore-command) - restore the NVIDIA device configuration dumped with the 'save' command. 19 | * [bind-driver](#bind-driver-command) - bind driver to devices 20 | * [unbind-driver](#unbind-driver-command) - unbind drivers from devices 21 | * [restart-services](#restart-services-command) - restart NVIDIA services 22 | * [attach-mdev](#attach-mdev-command) - attach NVIDIA mdev device to virsh domain (virtual machine) 23 | * [detach-mdev](#detach-mdev-command) - detach NVIDIA mdev device from virsh domain (virtual machine) 24 | * [attach-pci](#attach-pci-command) - attach NVIDIA GPU device to virsh domain (virtual machine) 25 | * [detach-pci](#detach-pci-command) - detach NVIDIA GPU device from virsh domain (virtual machine) 26 | 27 | Running `nvidia-dev-ctl.py` with the `--help` option will output the help information below. Details about subcommands can be output by using the `--help` option with the appropriate subcommand, e.g. `nvidia-dev-ctl.py save --help`: 28 | 29 | ``` 30 | usage: nvidia-dev-ctl.py [-h] [-l LOGLEVEL] [-c URL] [-w] [--trials N] 31 | [--delay SECONDS] [-p PCI_ADDRESSES] 32 | [-o {table,text}] [-O] 33 | ... 34 | 35 | optional arguments: 36 | -h, --help show this help message and exit 37 | -l LOGLEVEL, --log LOGLEVEL 38 | log level (use one of 39 | CRITICAL,ERROR,WARNING,INFO,DEBUG) 40 | -c URL, --connection URL 41 | virsh connection URL 42 | -w, --wait wait until mdev bus is available 43 | --trials N number of trials if waiting for device 44 | --delay SECONDS delay time in seconds between trials if waiting for 45 | device 46 | -p PCI_ADDRESSES, --pci-address PCI_ADDRESSES 47 | show only devices with specified pci addresses 48 | -o {table,text}, --output {table,text} 49 | output format 50 | -O, --output-all output all columns 51 | 52 | subcommands: 53 | 54 | list-pci list NVIDIA PCI devices 55 | list-mdev list registered mdev devices 56 | list-used-pci list used NVIDIA PCI devices 57 | list-used-mdev list used mdev devices 58 | create-mdev create new mdev device 59 | remove-mdev remove mdev device 60 | save dump registered mdev devices 61 | restore restore registered mdev devices 62 | bind-driver bind driver to devices 63 | unbind-driver unbind drivers from devices 64 | restart-services restart NVIDIA services 65 | attach-mdev attach mdev device to virsh domain (virtual machine) 66 | detach-mdev detach mdev device from virsh domain (virtual machine) 67 | attach-pci attach pci device to virsh domain (virtual machine) 68 | detach-pci detach pci device from virsh domain (virtual machine) 69 | ``` 70 | 71 | ## list-pci command 72 | 73 | `list-pci` outputs currently available NVIDIA devices on the PCI bus. The `-o` or `--output` option controls the mode of output. In the default table mode, the PCI device address, the name of the device driver loaded and the [sysfs](https://man7.org/linux/man-pages/man5/sysfs.5.html) device path are output: 74 | 75 | ``` 76 | $ nvidia-dev-ctl.py list-pci -o table 77 | PCI_ADDRESS DEVICE DEVICE_DRIVER 78 | 0000:43:00.0 GV100GL [Tesla V100 PCIe 32GB] nvidia 79 | 0000:44:00.0 GV100GL [Tesla V100 PCIe 32GB] nvidia 80 | 0000:45:00.0 GV100GL [Tesla V100 PCIe 32GB] vfio-pci 81 | 0000:46:00.0 GV100GL [Tesla V100 PCIe 32GB] nvidia 82 | 0000:47:00.0 GV100GL [Tesla V100 PCIe 32GB] nvidia 83 | 0000:83:00.0 GV100GL [Tesla V100 PCIe 32GB] vfio-pci 84 | 0000:84:00.0 GV100GL [Tesla V100 PCIe 32GB] vfio-pci 85 | 0000:85:00.0 GV100GL [Tesla V100 PCIe 32GB] vfio-pci 86 | 0000:86:00.0 GV100GL [Tesla V100 PCIe 32GB] vfio-pci 87 | 0000:87:00.0 GV100GL [Tesla V100 PCIe 32GB] vfio-pci 88 | ``` 89 | 90 | The output can be restricted to the PCI addresses specified by the `-p` or `--pci-address` option: 91 | 92 | ``` 93 | $ nvidia-dev-ctl.py list-pci -o table -p 0000:43:00.0 -p 0000:83:00.0 94 | PCI_ADDRESS DEVICE DEVICE_DRIVER 95 | 0000:43:00.0 GV100GL [Tesla V100 PCIe 32GB] nvidia 96 | 0000:83:00.0 GV100GL [Tesla V100 PCIe 32GB] vfio-pci 97 | ``` 98 | 99 | In text mode only PCI addresses are output: 100 | 101 | ``` 102 | $ nvidia-dev-ctl.py list-pci -o text 103 | 0000:43:00.0 0000:44:00.0 0000:45:00.0 0000:46:00.0 0000:47:00.0 0000:83:00.0 0000:84:00.0 0000:85:00.0 0000:86:00.0 0000:87:00.0 104 | ``` 105 | 106 | All `list-pci` command options: 107 | 108 | ``` 109 | usage: nvidia-dev-ctl.py list-pci [-h] [-p PCI_ADDRESSES] [-o {table,text}] 110 | [-O] 111 | 112 | optional arguments: 113 | -h, --help show this help message and exit 114 | -p PCI_ADDRESSES, --pci-address PCI_ADDRESSES 115 | show only devices with specified pci addresses 116 | -o {table,text}, --output {table,text} 117 | output format 118 | -O, --output-all output all columns 119 | ``` 120 | 121 | ## list-mdev command 122 | 123 | `list-mdev` outputs currently registered NVIDIA vGPU devices. By default, the device UUID, PCI device address, device type, device type name and virtual machine name, if vGPU is bound to the running virtual machine, are output: 124 | 125 | ``` 126 | $ nvidia-dev-ctl.py list-mdev 127 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME VM_NAME 128 | 45217cc2-a076-4d40-835f-a740d8d905df 0000:46:00.0 nvidia-313 GRID V100D-16C test-vm-5-node-01 129 | 5569c457-a0eb-448a-93b4-a15c5322243f 0000:47:00.0 nvidia-312 GRID V100D-8C 130 | 80129abf-2c41-4fa7-8280-84866112f31c 0000:43:00.0 nvidia-313 GRID V100D-16C test-vm-1-node-01 131 | 882f2c44-0f5c-4ed9-8bce-2a4a523519c4 0000:46:00.0 nvidia-313 GRID V100D-16C test-vm-6-node-01 132 | f9a58b28-009c-447d-b18f-29979e7ff857 0000:43:00.0 nvidia-313 GRID V100D-16C test-vm-4-node-01 133 | ``` 134 | 135 | The output can be limited to the PCI-addresses specified by the `-p` or `--pci-address` option in the same way as in the `list-pci` command. Use `-m` or `--mdev-type` to restrict output to devices of the specified vGPU type: 136 | 137 | ``` 138 | $ nvidia-dev-ctl.py list-mdev --mdev-type nvidia-312 139 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME VM_NAME 140 | 5569c457-a0eb-448a-93b4-a15c5322243f 0000:47:00.0 nvidia-312 GRID V100D-8C 141 | ``` 142 | 143 | If the `-O` or `--output-all` option is specified, the number of vGPU instances still available and the vGPU device description are also output. 144 | 145 | ``` 146 | $ nvidia-dev-ctl.py list-mdev --output-all 147 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME AVAILABLE_INSTANCES DESCRIPTION VM_NAME 148 | 45217cc2-a076-4d40-835f-a740d8d905df 0000:46:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 test-vm-5-node-01 149 | 80129abf-2c41-4fa7-8280-84866112f31c 0000:43:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 test-vm-1-node-01 150 | 882f2c44-0f5c-4ed9-8bce-2a4a523519c4 0000:46:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 test-vm-6-node-01 151 | f9a58b28-009c-447d-b18f-29979e7ff857 0000:43:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 test-vm-4-node-01 152 | ``` 153 | 154 | If the `-c` or `--classes` option is specified, a list of supported NVIDIA vGPU device classes is output for each PCI device. Only the device types output from the list can be created on the current hardware: 155 | 156 | ``` 157 | $ nvidia-dev-ctl.py list-mdev --classes -p 0000:47:00.0 158 | PCI_ADDRESS MDEV_TYPE NAME AVAILABLE_INSTANCES 159 | 0000:47:00.0 nvidia-180 GRID V100D-1Q 32 160 | 0000:47:00.0 nvidia-181 GRID V100D-2Q 16 161 | 0000:47:00.0 nvidia-182 GRID V100D-4Q 8 162 | 0000:47:00.0 nvidia-183 GRID V100D-8Q 4 163 | 0000:47:00.0 nvidia-184 GRID V100D-16Q 2 164 | 0000:47:00.0 nvidia-185 GRID V100D-32Q 1 165 | 0000:47:00.0 nvidia-186 GRID V100D-1A 32 166 | 0000:47:00.0 nvidia-187 GRID V100D-2A 16 167 | 0000:47:00.0 nvidia-188 GRID V100D-4A 8 168 | 0000:47:00.0 nvidia-189 GRID V100D-8A 4 169 | 0000:47:00.0 nvidia-190 GRID V100D-16A 2 170 | 0000:47:00.0 nvidia-191 GRID V100D-32A 1 171 | 0000:47:00.0 nvidia-192 GRID V100D-1B 32 172 | 0000:47:00.0 nvidia-193 GRID V100D-2B 16 173 | 0000:47:00.0 nvidia-218 GRID V100D-2B4 16 174 | 0000:47:00.0 nvidia-249 GRID V100D-1B4 32 175 | 0000:47:00.0 nvidia-311 GRID V100D-4C 8 176 | 0000:47:00.0 nvidia-312 GRID V100D-8C 4 177 | 0000:47:00.0 nvidia-313 GRID V100D-16C 2 178 | 0000:47:00.0 nvidia-314 GRID V100D-32C 1 179 | ``` 180 | 181 | Also in this case the option `-O` or `--output-all` will output more detailed information. 182 | 183 | All `list-mdev` command options: 184 | 185 | ``` 186 | usage: nvidia-dev-ctl.py list-mdev [-h] [-c] [-p PCI_ADDRESSES] 187 | [-m MDEV_TYPES] [-O] 188 | 189 | optional arguments: 190 | -h, --help show this help message and exit 191 | -c, --classes print mdev device classes 192 | -p PCI_ADDRESSES, --pci-address PCI_ADDRESSES 193 | show only devices with specified pci addresses 194 | -m MDEV_TYPES, --mdev-type MDEV_TYPES 195 | show only devices with specified mdev types 196 | -O, --output-all output all columns 197 | ``` 198 | 199 | ## list-used-pci command 200 | 201 | `list-used-pci` outputs NVIDIA devices on the PCI bus that are used by libvirt virtual machines (domains). The `-o` or `--output` option controls the mode of output. In the default table mode, the PCI device address and the name of the virtual machine are output: 202 | 203 | ``` 204 | $ nvidia-dev-ctl.py list-used-pci -o table 205 | PCI_ADDRESS VM_NAME 206 | 0000:43:00.0 test-vm-1-node-01 207 | 0000:86:00.0 test-vm-3-node-01 208 | ``` 209 | 210 | The output can be restricted to the PCI addresses specified by the `-p` or `--pci-address` option: 211 | 212 | ``` 213 | $ nvidia-dev-ctl.py list-used-pci -o table -p 0000:43:00.0 214 | PCI_ADDRESS VM_NAME 215 | 0000:43:00.0 test-vm-1-node-01 216 | ``` 217 | 218 | In text mode only PCI addresses are output: 219 | 220 | ``` 221 | $ nvidia-dev-ctl.py list-used-pci -o text 222 | 0000:43:00.0 0000:86:00.0 223 | ``` 224 | 225 | All `list-used-pci` command options: 226 | 227 | ``` 228 | usage: nvidia-dev-ctl.py list-used-pci [-h] [-p PCI_ADDRESSES] 229 | [-o {table,text}] 230 | 231 | optional arguments: 232 | -h, --help show this help message and exit 233 | -p PCI_ADDRESSES, --pci-address PCI_ADDRESSES 234 | show only devices with specified pci addresses 235 | -o {table,text}, --output {table,text} 236 | output format 237 | ``` 238 | 239 | ## list-used-mdev command 240 | 241 | `list-used-mdev` outputs NVIDIA vGPU devices that are used by libvirt virtual machines (domains). By default, the device UUID, PCI device address, device type, device type name and virtual machine name are output: 242 | 243 | ``` 244 | $ nvidia-dev-ctl.py -c qemu:///system list-used-mdev 245 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME VM_NAME 246 | 80129abf-2c41-4fa7-8280-84866112f31c 0000:43:00.0 nvidia-313 GRID V100D-16C foresight-vm-1-node-01 247 | 45217cc2-a076-4d40-835f-a740d8d905df 0000:46:00.0 nvidia-313 GRID V100D-16C foresight-vm-5-node-01 248 | f9a58b28-009c-447d-b18f-29979e7ff857 0000:43:00.0 nvidia-313 GRID V100D-16C foresight-vm-4-node-01 249 | 882f2c44-0f5c-4ed9-8bce-2a4a523519c4 0000:46:00.0 nvidia-313 GRID V100D-16C foresight-vm-6-node-01 250 | eb4fe85a-05d0-4f80-97e9-c099388387ba 0000:47:00.0 nvidia-312 GRID V100D-8C foresight-vm-6-node-01 251 | ``` 252 | 253 | The output can be limited to the PCI-addresses specified by the `-p` or `--pci-address` option in the same way as in the `list-used-pci` command. Use `-m` or `--mdev-type` to restrict output to devices of the specified vGPU type: 254 | 255 | ``` 256 | $ nvidia-dev-ctl.py -c qemu:///system list-used-mdev -m nvidia-312 257 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME VM_NAME 258 | eb4fe85a-05d0-4f80-97e9-c099388387ba 0000:47:00.0 nvidia-312 GRID V100D-8C foresight-vm-6-node-01 259 | ``` 260 | 261 | If the `-O` or `--output-all` option is specified, the number of vGPU instances still available and the vGPU device description are also output. 262 | 263 | ``` 264 | $ nvidia-dev-ctl.py -c qemu:///system list-used-mdev --output-all 265 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME AVAILABLE_INSTANCES DESCRIPTION VM_NAME 266 | 80129abf-2c41-4fa7-8280-84866112f31c 0000:43:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 foresight-vm-1-node-01 267 | 45217cc2-a076-4d40-835f-a740d8d905df 0000:46:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 foresight-vm-5-node-01 268 | f9a58b28-009c-447d-b18f-29979e7ff857 0000:43:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 foresight-vm-4-node-01 269 | 882f2c44-0f5c-4ed9-8bce-2a4a523519c4 0000:46:00.0 nvidia-313 GRID V100D-16C 0 num_heads=1, frl_config=60, framebuffer=16384M, max_resolution=4096x2160, max_instance=2 foresight-vm-6-node-01 270 | eb4fe85a-05d0-4f80-97e9-c099388387ba 0000:47:00.0 nvidia-312 GRID V100D-8C 3 num_heads=1, frl_config=60, framebuffer=8192M, max_resolution=4096x2160, max_instance=4 foresight-vm-6-node-01 271 | ``` 272 | 273 | All `list-used-mdev` command options: 274 | 275 | ``` 276 | usage: nvidia-dev-ctl.py list-used-mdev [-h] [-p PCI_ADDRESSES] 277 | [-m MDEV_TYPES] [-o {table,text}] [-O] 278 | 279 | optional arguments: 280 | -h, --help show this help message and exit 281 | -p PCI_ADDRESSES, --pci-address PCI_ADDRESSES 282 | show only devices with specified pci addresses 283 | -m MDEV_TYPES, --mdev-type MDEV_TYPES 284 | show only devices with specified mdev types 285 | -o {table,text}, --output {table,text} 286 | output format 287 | -O, --output-all output all columns 288 | ``` 289 | 290 | ## create-mdev command 291 | 292 | The `create-mdev` command is used to create a new vGPU by specifying the PCI address and MDEV type and optionally the UUID of the new vGPU. If no UUID is specified, it will be generated automatically. The UUID is printed if the operation was successful. In the following example we create a vGPU of type `nvidia-312` (named `GRID V100D-8C`) on PCI device `0000:47:00` : 293 | 294 | ``` 295 | $ sudo nvidia-dev-ctl.py -l INFO create-mdev 0000:47:00.0 nvidia-312 296 | 2020-10-14 19:15:10,396 INFO Do not change the driver on the device 0000:47:00.0, because it already has driver nvidia 297 | 2020-10-14 19:15:10,408 INFO Create Mdev device with UUID 5569c457-a0eb-448a-93b4-a15c5322243f and type nvidia-312 on PCI device with address 0000:47:00.0 298 | 2020-10-14 19:15:10,409 INFO Found device class 299 | 2020-10-14 19:15:10,414 INFO Found device type 300 | 2020-10-14 19:15:10,414 INFO Create mdev device with UUID 5569c457-a0eb-448a-93b4-a15c5322243f on PCI address 0000:47:00.0 and with type nvidia-312 301 | 5569c457-a0eb-448a-93b4-a15c5322243f 302 | ``` 303 | 304 | All log information is output to stderr and UUID to stdout. After successful execution of this command we should see a new mdev device using the `list-mdev` command: 305 | 306 | ``` 307 | $ nvidia-dev-ctl.py list-mdev -p 0000:47:00.0 308 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME VM_NAME 309 | 5569c457-a0eb-448a-93b4-a15c5322243f 0000:47:00.0 nvidia-312 GRID V100D-8C 310 | ``` 311 | 312 | With the `-n` or `--dry` option, the command does not make any changes. 313 | 314 | All `create-mdev` command options: 315 | 316 | ``` 317 | usage: nvidia-dev-ctl.py create-mdev [-h] [-u UUID] [-n] 318 | PCI_ADDRESS MDEV_TYPE_OR_NAME 319 | 320 | positional arguments: 321 | PCI_ADDRESS PCI address of the NVIDIA device where to create new 322 | mdev device 323 | MDEV_TYPE_OR_NAME mdev device type or type name 324 | 325 | optional arguments: 326 | -h, --help show this help message and exit 327 | -u UUID, --uuid UUID UUID of the mdev device, if not specified a new will 328 | be automatically generated 329 | -n, --dry-run Do everything except actually make changes 330 | ``` 331 | 332 | ## remove-mdev command 333 | 334 | The `remove-mdev` command does the opposite of the `create-mdev` command by deleting the mdev device specified with its UUID: 335 | 336 | ``` 337 | $ sudo nvidia-dev-ctl.py -l INFO remove-mdev 5569c457-a0eb-448a-93b4-a15c5322243f 338 | 2020-10-14 22:02:54,093 INFO Remove mdev device with UUID 5569c457-a0eb-448a-93b4-a15c5322243f on PCI address 0000:47:00.0 and with type nvidia-312 339 | ``` 340 | 341 | All `remove-mdev` command options: 342 | 343 | ``` 344 | usage: nvidia-dev-ctl.py remove-mdev [-h] [-n] UUID 345 | 346 | positional arguments: 347 | UUID UUID of the mdev device to remove 348 | 349 | optional arguments: 350 | -h, --help show this help message and exit 351 | -n, --dry-run Do everything except actually make changes 352 | ``` 353 | 354 | ## save command 355 | 356 | The `save` command outputs the current configuration of NVIDIA devices, including drivers bound to the device and registered vGPU devices, in text format that can be restored with the `restore` command. This makes it easy to restore the device configuration after a reboot, for example. 357 | 358 | Suppose we have the following configuration, which is displayed with the commands `list-pci` and `list-mdev`: 359 | 360 | ``` 361 | $ nvidia-dev-ctl.py list-pci 362 | PCI_ADDRESS DEVICE_DRIVER PCI_DEVICE_PATH 363 | 0000:43:00.0 nvidia /sys/bus/pci/devices/0000:43:00.0 364 | 0000:44:00.0 nvidia /sys/bus/pci/devices/0000:44:00.0 365 | 0000:45:00.0 nvidia /sys/bus/pci/devices/0000:45:00.0 366 | 0000:46:00.0 nvidia /sys/bus/pci/devices/0000:46:00.0 367 | 0000:47:00.0 nvidia /sys/bus/pci/devices/0000:47:00.0 368 | 0000:83:00.0 vfio-pci /sys/bus/pci/devices/0000:83:00.0 369 | 0000:84:00.0 vfio-pci /sys/bus/pci/devices/0000:84:00.0 370 | 0000:85:00.0 vfio-pci /sys/bus/pci/devices/0000:85:00.0 371 | 0000:86:00.0 vfio-pci /sys/bus/pci/devices/0000:86:00.0 372 | 0000:87:00.0 vfio-pci /sys/bus/pci/devices/0000:87:00.0 373 | $ nvidia-dev-ctl.py list-mdev 374 | MDEV_DEVICE_UUID PCI_ADDRESS TYPE NAME VM_NAME 375 | 45217cc2-a076-4d40-835f-a740d8d905df 0000:46:00.0 nvidia-313 GRID V100D-16C test-vm-5-node-01 376 | 80129abf-2c41-4fa7-8280-84866112f31c 0000:43:00.0 nvidia-313 GRID V100D-16C test-vm-1-node-01 377 | 882f2c44-0f5c-4ed9-8bce-2a4a523519c4 0000:46:00.0 nvidia-313 GRID V100D-16C test-vm-6-node-01 378 | eb4fe85a-05d0-4f80-97e9-c099388387ba 0000:47:00.0 nvidia-312 GRID V100D-8C 379 | f9a58b28-009c-447d-b18f-29979e7ff857 0000:43:00.0 nvidia-313 GRID V100D-16C test-vm-4-node-01 380 | ``` 381 | 382 | In this case the `save` command will produce the following output: 383 | 384 | ``` 385 | $ nvidia-dev-ctl.py save 386 | # NVIDIA Device Configuration 387 | # This file is auto-generated by nvidia-dev-ctl.py save command 388 | # pci_address driver_name mdev_uuid mdev_type 389 | 0000:43:00.0 nvidia 80129abf-2c41-4fa7-8280-84866112f31c nvidia-313 390 | 0000:43:00.0 nvidia f9a58b28-009c-447d-b18f-29979e7ff857 nvidia-313 391 | 0000:44:00.0 nvidia 392 | 0000:45:00.0 nvidia 393 | 0000:46:00.0 nvidia 45217cc2-a076-4d40-835f-a740d8d905df nvidia-313 394 | 0000:46:00.0 nvidia 882f2c44-0f5c-4ed9-8bce-2a4a523519c4 nvidia-313 395 | 0000:47:00.0 nvidia eb4fe85a-05d0-4f80-97e9-c099388387ba nvidia-312 396 | 0000:83:00.0 vfio-pci 397 | 0000:84:00.0 vfio-pci 398 | 0000:85:00.0 vfio-pci 399 | 0000:86:00.0 vfio-pci 400 | 0000:87:00.0 vfio-pci 401 | ``` 402 | 403 | All `save` command options: 404 | 405 | ``` 406 | usage: nvidia-dev-ctl.py save [-h] [-o FILE] 407 | 408 | optional arguments: 409 | -h, --help show this help message and exit 410 | -o FILE, --output FILE 411 | output mdev devices to file 412 | ``` 413 | 414 | ## restore command 415 | 416 | The `restore` command restores the configuration saved by the `save` command. Please note that `restore` only changes the state described in the configuration file. All devices that are not listed in the configuration file remain unchanged. 417 | 418 | Save and restore configuration: 419 | 420 | ``` 421 | $ nvidia-dev-ctl.py save > nvidia-devices.conf 422 | $ nvidia-dev-ctl.py restore < nvidia-devices.conf 423 | ``` 424 | 425 | Alternatively: 426 | 427 | ``` 428 | $ nvidia-dev-ctl.py save -o nvidia-devices.conf 429 | $ nvidia-dev-ctl.py restore -i nvidia-devices.conf 430 | ``` 431 | 432 | All `restore` command options: 433 | 434 | ``` 435 | usage: nvidia-dev-ctl.py restore [-h] [-i FILE] [-n] 436 | 437 | optional arguments: 438 | -h, --help show this help message and exit 439 | -i FILE, --input FILE 440 | load mdev devices from file 441 | -n, --dry-run Do everything except actually make changes 442 | ``` 443 | 444 | ## bind-driver command 445 | 446 | The `bind-driver` command allows you to bind drivers to one or multiple NVIDIA devices when no driver is loaded. This is useful if you want to switch the GPU from vGPU to PCI pass-through mode or vice versa by replacing the `nvidia` driver with the `vfio-pci` driver. If a driver is bound to the device, `bind-driver` will first unbind the driver. The command requires the name of the driver to be bound and one or more PCI addresses of the devices to which it should be bound: 447 | 448 | ``` 449 | $ nvidia-dev-ctl.py list-pci -p 0000:83:00.0 450 | PCI_ADDRESS DEVICE_DRIVER PCI_DEVICE_PATH 451 | 0000:83:00.0 vfio-pci /sys/bus/pci/devices/0000:83:00.0 452 | 453 | $ sudo nvidia-dev-ctl.py -l INFO bind-driver nvidia 0000:83:00.0 454 | 2020-10-15 09:28:27,063 INFO Unbind driver vfio-pci from PCI device 0000:83:00.0 455 | 2020-10-15 09:28:27,064 INFO Override driver nvidia for PCI device 0000:83:00.0 456 | 2020-10-15 09:28:27,064 INFO Bind driver nvidia to device 0000:83:00.0 457 | 458 | $ nvidia-dev-ctl.py list-pci -p 0000:83:00.0 459 | PCI_ADDRESS DEVICE_DRIVER PCI_DEVICE_PATH 460 | 0000:83:00.0 nvidia /sys/bus/pci/devices/0000:83:00.0 461 | ``` 462 | 463 | All `bind-driver` command options: 464 | 465 | ``` 466 | usage: nvidia-dev-ctl.py bind-driver [-h] [-n] 467 | DRIVER PCI_ADDRESS [PCI_ADDRESS ...] 468 | 469 | positional arguments: 470 | DRIVER bind driver to devices 471 | PCI_ADDRESS device PCI address 472 | 473 | optional arguments: 474 | -h, --help show this help message and exit 475 | -n, --dry-run Do everything except actually make changes 476 | ``` 477 | 478 | ## unbind-driver command 479 | 480 | The `unbind-driver` command does the opposite to the `bind-driver` by unbinding the driver from the device. 481 | Without specifying the name of the driver with the `-d` or `--driver` option, the command will unbind any driver bound to the device from the specified devices: 482 | 483 | ``` 484 | $ sudo nvidia-dev-ctl.py -l INFO unbind-driver 0000:83:00.0 485 | 2020-10-15 09:35:39,374 INFO Unbind driver vfio-pci from PCI device 0000:83:00.0 486 | 487 | $ nvidia-dev-ctl.py list-pci -p 0000:83:00.0 488 | PCI_ADDRESS DEVICE_DRIVER PCI_DEVICE_PATH 489 | 0000:83:00.0 no driver /sys/bus/pci/devices/0000:83:00.0 490 | ``` 491 | 492 | 493 | All `unbind-driver` command options: 494 | 495 | ``` 496 | usage: nvidia-dev-ctl.py unbind-driver [-h] [-d DRIVER] [-i] [-n] 497 | PCI_ADDRESS [PCI_ADDRESS ...] 498 | 499 | positional arguments: 500 | PCI_ADDRESS device PCI address 501 | 502 | optional arguments: 503 | -h, --help show this help message and exit 504 | -d DRIVER, --driver DRIVER 505 | unbind driver from devices (if not specified unbind 506 | any bound driver) 507 | -i, --ignore-others unbind only specified driver and ignore others 508 | -n, --dry-run Do everything except actually make changes 509 | ``` 510 | 511 | ## restart-services command 512 | 513 | The `restart-services` command will restart `nvidia-vgpud` and `nvidia-vgpu-mgr` NVIDIA vGPU services. 514 | 515 | All `restart-services` command options: 516 | 517 | ``` 518 | usage: nvidia-dev-ctl.py restart-services [-h] [-n] 519 | 520 | optional arguments: 521 | -h, --help show this help message and exit 522 | -n, --dry-run Do everything except actually make changes 523 | ``` 524 | 525 | ## attach-mdev command 526 | 527 | The `attach-mdev` command attaches the vGPU device specified by UUID to the libvirt domain (i.e., the virtual machine). 528 | By default, the change is only applied to the configuration and only takes effect after a restart. 529 | If the `--restart` option is specified, the domain is restarted after the change. 530 | If the `--hotplug` option is specified, the device is immediately available within the domain without restart. 531 | The `--restart` and `--hotplug` options cannot be used together. To display actions to be performed without actually making changes, 532 | use the `--n` or `--run-dry` option. 533 | 534 | All `attach-mdev` command options: 535 | 536 | ``` 537 | usage: nvidia-dev-ctl.py attach-mdev [-h] [--virsh-trials N] 538 | [--virsh-delay SECONDS] [-c URL] 539 | [--hotplug] [--restart] [-n] 540 | UUID DOMAIN 541 | 542 | positional arguments: 543 | UUID UUID of the mdev device to attach 544 | DOMAIN domain name, id or uuid 545 | 546 | optional arguments: 547 | -h, --help show this help message and exit 548 | --virsh-trials N number of trials if waiting for virsh 549 | --virsh-delay SECONDS 550 | delay time in seconds between trials if waiting for 551 | virsh 552 | -c URL, --connection URL 553 | virsh connection URL 554 | --hotplug affect the running domain and keep changes after 555 | reboot 556 | --restart shutdown and reboot the domain after the changes are 557 | made 558 | -n, --dry-run Do everything except actually make changes 559 | ``` 560 | 561 | ## detach-mdev command 562 | 563 | The `detach-mdev` command does the opposite of the `attach-mdev` command by detaching the vGPU device specified with 564 | its UUID from the domain (i.e., the virtual machine). 565 | By default, the change is only applied to the configuration and only takes effect after a restart. 566 | If the `--restart` option is specified, the domain is restarted after the change. 567 | If the `--hotplug` option is specified, the device is immediately available within the domain without restart. 568 | The `--restart` and `--hotplug` options cannot be used together. To display actions to be performed without actually making changes, 569 | use the `--n` or `--run-dry` option. 570 | 571 | All `detach-mdev` command options: 572 | 573 | ``` 574 | usage: nvidia-dev-ctl.py detach-mdev [-h] [--virsh-trials N] 575 | [--virsh-delay SECONDS] [-c URL] 576 | [--hotplug] [--restart] [-n] 577 | UUID DOMAIN 578 | 579 | positional arguments: 580 | UUID UUID of the mdev device to remove 581 | DOMAIN domain name, id or uuid 582 | 583 | optional arguments: 584 | -h, --help show this help message and exit 585 | --virsh-trials N number of trials if waiting for virsh 586 | --virsh-delay SECONDS 587 | delay time in seconds between trials if waiting for 588 | virsh 589 | -c URL, --connection URL 590 | virsh connection URL 591 | --hotplug affect the running domain and keep changes after 592 | reboot 593 | --restart shutdown and reboot the domain after the changes are 594 | made 595 | -n, --dry-run Do everything except actually make changes 596 | ``` 597 | 598 | ## attach-pci command 599 | 600 | The `attach-pci` command attaches the PCI device specified by its address to the libvirt domain (i.e., the virtual machine). 601 | By default, the change is only applied to the configuration and only takes effect after a restart. 602 | If the `--restart` option is specified, the domain is restarted after the change. 603 | If the `--hotplug` option is specified, the device is immediately available within the domain without restart. 604 | The `--restart` and `--hotplug` options cannot be used together. To display actions to be performed without actually making changes, 605 | use the `--n` or `--run-dry` option. 606 | 607 | All `attach-pci` command options: 608 | 609 | ``` 610 | usage: nvidia-dev-ctl.py attach-pci [-h] [--virsh-trials N] 611 | [--virsh-delay SECONDS] [-c URL] 612 | [--hotplug] [--restart] [-n] 613 | PCI_ADDRESS DOMAIN 614 | 615 | positional arguments: 616 | PCI_ADDRESS PCI address of the NVIDIA device to attach 617 | DOMAIN domain name, id or uuid 618 | 619 | optional arguments: 620 | -h, --help show this help message and exit 621 | --virsh-trials N number of trials if waiting for virsh 622 | --virsh-delay SECONDS 623 | delay time in seconds between trials if waiting for 624 | virsh 625 | -c URL, --connection URL 626 | virsh connection URL 627 | --hotplug affect the running domain and keep changes after 628 | reboot 629 | --restart shutdown and reboot the domain after the changes are 630 | made 631 | -n, --dry-run Do everything except actually make changes 632 | ``` 633 | 634 | ## detach-pci command 635 | 636 | The `detach-pci` command does the opposite of the `attach-pci` command by detaching the PCI device specified with 637 | its address from the domain (i.e., the virtual machine). 638 | By default, the change is only applied to the configuration and only takes effect after a restart. 639 | If the `--restart` option is specified, the domain is restarted after the change. 640 | If the `--hotplug` option is specified, the device is immediately available within the domain without restart. 641 | The `--restart` and `--hotplug` options cannot be used together. To display actions to be performed without actually making changes, 642 | use the `--n` or `--run-dry` option. 643 | 644 | All `detach-pci` command options: 645 | 646 | ``` 647 | usage: nvidia-dev-ctl.py detach-pci [-h] [--virsh-trials N] 648 | [--virsh-delay SECONDS] [-c URL] 649 | [--hotplug] [--restart] [-n] 650 | PCI_ADDRESS DOMAIN 651 | 652 | positional arguments: 653 | PCI_ADDRESS PCI address of the NVIDIA device to attach 654 | DOMAIN domain name, id or uuid 655 | 656 | optional arguments: 657 | -h, --help show this help message and exit 658 | --virsh-trials N number of trials if waiting for virsh 659 | --virsh-delay SECONDS 660 | delay time in seconds between trials if waiting for 661 | virsh 662 | -c URL, --connection URL 663 | virsh connection URL 664 | --hotplug affect the running domain and keep changes after 665 | reboot 666 | --restart shutdown and reboot the domain after the changes are 667 | made 668 | -n, --dry-run Do everything except actually make changes 669 | ``` 670 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -eo pipefail 4 | 5 | THIS_DIR=$( (cd "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) ) 6 | 7 | set -x 8 | sudo cp "$THIS_DIR/nvidia-dev-ctl.service" /usr/lib/systemd/system/ # /etc/systemd/system 9 | sudo cp "$THIS_DIR/nvidia-dev-ctl.py" /usr/bin/ 10 | [ ! -e "$THIS_DIR/nvidia-mdev-devices.conf" ] && touch "$THIS_DIR/nvidia-mdev-devices.conf" 11 | sudo cp "$THIS_DIR/nvidia-mdev-devices.conf" /etc/nvidia-mdev-devices.conf 12 | sudo systemctl daemon-reload 13 | sudo systemctl enable nvidia-dev-ctl.service 14 | -------------------------------------------------------------------------------- /nvidia-dev-ctl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (C) 2020 Dmitri Rubinstein, DFKI GmbH 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | # 18 | # Documentation 19 | # https://docs.nvidia.com/grid/10.0/grid-vgpu-user-guide/index.html#vgpu-information-in-sysfs-file-system 20 | # https://man7.org/linux/man-pages/man5/sysfs.5.html 21 | 22 | import argparse 23 | import grp 24 | import logging 25 | import os 26 | import os.path 27 | import re 28 | import shutil 29 | import subprocess 30 | import sys 31 | import tempfile 32 | import time 33 | import uuid 34 | import xml.etree.ElementTree as ET 35 | from collections import OrderedDict, defaultdict, namedtuple 36 | from subprocess import CalledProcessError 37 | from typing import Callable, Optional, Sequence, List, Union, NamedTuple, Dict 38 | 39 | LOG = logging.getLogger(__name__) 40 | 41 | MDEV_BUS_CLASS_PATH = "/sys/class/mdev_bus" 42 | 43 | MDEV_BUS_DEVICE_PATH = "/sys/bus/mdev/devices" 44 | 45 | PCI_BUS_DEVICE_PATH = "/sys/bus/pci/devices" 46 | 47 | PCI_BUS_DRIVER_PATH = "/sys/bus/pci/drivers" 48 | 49 | NVIDIA_VENDOR = "10de" 50 | 51 | TEXT_FORMAT = "text" 52 | TABLE_FORMAT = "table" 53 | 54 | PathWaiterFunc = Callable[[str], bool] 55 | PathWaiterCB = Optional[PathWaiterFunc] 56 | 57 | COMMANDS = {"virsh": "virsh", "lspci": "lspci", "systemctl": "systemctl", "modprobe": "modprobe"} 58 | 59 | 60 | class DevCtlException(Exception): 61 | pass 62 | 63 | 64 | class SysfsPathNotFoundError(DevCtlException): 65 | def __init__(self, path: str, message: str = None): 66 | super().__init__(message if message is not None else "Sysfs path '{}' not found".format(path)) 67 | self.path = path 68 | 69 | 70 | class DeviceDriverPathNotFound(SysfsPathNotFoundError): 71 | def __init__(self, path: str): 72 | super().__init__(path, "Device driver path '{}' not found".format(path)) 73 | 74 | 75 | class BindDriverPathNotFound(SysfsPathNotFoundError): 76 | def __init__(self, path: str): 77 | super().__init__(path, "Bind driver path '{}' not found".format(path)) 78 | 79 | 80 | class UnbindDriverPathNotFound(SysfsPathNotFoundError): 81 | def __init__(self, path: str): 82 | super().__init__(path, "Unbind driver path '{}' not found".format(path)) 83 | 84 | 85 | class DriverOverridePathNotFound(SysfsPathNotFoundError): 86 | def __init__(self, path: str): 87 | super().__init__(path, "Driver override path '{}' not found".format(path)) 88 | 89 | 90 | class MdevBusPathNotFound(SysfsPathNotFoundError): 91 | def __init__(self, path: str): 92 | super().__init__("MDEV path '{}' not found".format(path)) 93 | 94 | 95 | class InvalidPCIAddressError(DevCtlException): 96 | def __init__(self, pci_address: str): 97 | super().__init__("{} is not a PCI address".format(pci_address)) 98 | self.pci_address = pci_address 99 | 100 | 101 | class NoPCIAddressError(DevCtlException): 102 | def __init__(self, pci_address: str): 103 | super().__init__("No such PCI address: '{}'".format(pci_address)) 104 | self.pci_address = pci_address 105 | 106 | 107 | class NoMdevPCIAddressError(DevCtlException): 108 | def __init__(self, pci_address: str): 109 | super().__init__("No such MDEV PCI address: '{}'".format(pci_address)) 110 | self.pci_address = pci_address 111 | 112 | 113 | class NoMdevUUIDError(DevCtlException): 114 | def __init__(self, uuid: str): 115 | super().__init__("No such MDEV UUID: '{}'".format(uuid)) 116 | self.uuid = uuid 117 | 118 | 119 | class InvalidMdevFileFormat(DevCtlException): 120 | pass 121 | 122 | 123 | class InvalidCommandOutput(DevCtlException): 124 | pass 125 | 126 | 127 | def sysfs_pci_device_path(pci_address): 128 | return os.path.join(PCI_BUS_DEVICE_PATH, pci_address) 129 | 130 | 131 | def sysfs_pci_driver_path(driver): 132 | return os.path.join(PCI_BUS_DRIVER_PATH, driver) 133 | 134 | 135 | def sysfs_mdev_supported_types_path(pci_address): 136 | return os.path.join(MDEV_BUS_CLASS_PATH, pci_address, "mdev_supported_types") 137 | 138 | 139 | def sysfs_mdev_type_path(pci_address, mdev_type_name): 140 | return os.path.join(sysfs_mdev_supported_types_path(pci_address), mdev_type_name) 141 | 142 | 143 | def sysfs_mdev_path(pci_address, mdev_type_name, mdev_uuid): 144 | return os.path.join( 145 | sysfs_pci_device_path(pci_address), "mdev_supported_types", mdev_type_name, "devices", mdev_uuid 146 | ) 147 | 148 | 149 | def sysfs_mdev_remove_path(pci_address, mdev_type_name, mdev_uuid): 150 | return os.path.join( 151 | sysfs_pci_device_path(pci_address), "mdev_supported_types", mdev_type_name, "devices", mdev_uuid, "remove" 152 | ) 153 | 154 | 155 | RE_EXEC_MAIN_STATUS = re.compile(r"ExecMainStatus=(\d+)") 156 | 157 | RE_DOMAIN_STATE = re.compile(r"^State:\s*([^\s].*)$", re.MULTILINE) 158 | 159 | RE_PCI_ADDRESS = re.compile(r"([0-9a-fA-F]{4}):([0-9a-fA-F]{2}):([0-9a-fA-F]{2}).([0-9a-fA-F])") 160 | 161 | 162 | class PCIAddress(namedtuple("PCIAddress", ["domain", "bus", "slot", "function"])): 163 | __slots__ = () 164 | 165 | def __str__(self): 166 | return "{:04x}:{:02x}:{:02x}.{:01x}".format(self.domain, self.bus, self.slot, self.function) 167 | 168 | def __repr__(self): 169 | return "PCIAddress(domain=0x{:04x}, bus=0x{:02x}, slot=0x{:02x}, function=0x{:01x})".format( 170 | self.domain, self.bus, self.slot, self.function 171 | ) 172 | 173 | def __format__(self, format_spec): 174 | return format(str(self), format_spec) 175 | 176 | @classmethod 177 | def parse(cls, pci_address: str) -> "PCIAddress": 178 | m = RE_PCI_ADDRESS.match(pci_address) 179 | if not m: 180 | raise InvalidPCIAddressError(pci_address) 181 | 182 | return cls( 183 | domain=int(m.group(1), 16), bus=int(m.group(2), 16), slot=int(m.group(3), 16), function=int(m.group(4), 16) 184 | ) 185 | 186 | 187 | PCIAddressFilterFunc = Callable[[PCIAddress], bool] 188 | PCIAddressFilterCB = Optional[PCIAddressFilterFunc] 189 | 190 | 191 | class PCIDevice( 192 | NamedTuple( 193 | "PCIDevice", [("pci_address", PCIAddress), ("driver", str), ("name", str), ("vendor", str), ("tags", dict)] 194 | ) 195 | ): 196 | __slots__ = () 197 | 198 | def get_tag(self, tag_name, default=None): 199 | return self.tags.get(tag_name, default) 200 | 201 | @classmethod 202 | def from_tags(cls, tags: dict): 203 | slot = tags.get("Slot") 204 | if slot: 205 | pci_address = PCIAddress.parse(slot) 206 | else: 207 | raise InvalidPCIAddressError('No "Slot" tag in the lspci output') 208 | name = tags.get("Device", "") 209 | vendor = tags.get("Vendor", "") 210 | 211 | try: 212 | driver_name = get_driver_of_pci_device(pci_address) 213 | except NoPCIAddressError: 214 | driver_name = "no device" 215 | except DeviceDriverPathNotFound: 216 | driver_name = "no driver" 217 | 218 | return cls(pci_address=pci_address, driver=driver_name, name=name, vendor=vendor, tags=tags) 219 | 220 | 221 | PCIDeviceFilterFunc = Callable[[PCIDevice], bool] 222 | PCIDeviceFilterCB = Optional[PCIDeviceFilterFunc] 223 | 224 | 225 | class PCIDevices(object): 226 | def __init__(self, device_filter=None): 227 | self.device_filter = device_filter 228 | self.devices = [] 229 | self.parse() 230 | 231 | def filter_devices(self, pci_address: Union[str, PCIAddress]): 232 | if not isinstance(pci_address, PCIAddress): 233 | pci_address = PCIAddress.parse(pci_address) 234 | return [dev for dev in self.devices if dev.pci_address == pci_address] 235 | 236 | def find_device(self, pci_address: Union[str, PCIAddress]) -> "Optional[PCIDevice]": 237 | if not isinstance(pci_address, PCIAddress): 238 | pci_address = PCIAddress.parse(pci_address) 239 | for dev in self.devices: 240 | if dev.pci_address == pci_address: 241 | return dev 242 | return None 243 | 244 | def get_tag(self, pci_address: Union[str, PCIAddress], tag_name, default=None): 245 | dev = self.find_device(pci_address) 246 | if dev: 247 | return dev.get_tag(tag_name, default) 248 | return default 249 | 250 | def parse(self): 251 | global COMMANDS 252 | command = [COMMANDS["lspci"], "-D", "-vmm"] 253 | if self.device_filter: 254 | command.extend(("-d", self.device_filter)) 255 | LOG.debug("Run: %s", " ".join(command)) 256 | output = subprocess.check_output(command).decode("utf-8") 257 | entry = None 258 | for line in output.splitlines(): 259 | line = line.strip() 260 | if not line: 261 | if entry: 262 | self.devices.append(PCIDevice.from_tags(entry)) 263 | entry = None 264 | continue 265 | split_pos = line.find(":\t") 266 | if split_pos == -1: 267 | raise InvalidCommandOutput("Invalid line in lspci output: {}".format(line)) 268 | tag, value = line.split(":\t", 2) 269 | if not entry: 270 | entry = {} 271 | entry[tag] = value 272 | if entry: 273 | self.devices.append(PCIDevice.from_tags(entry)) 274 | 275 | 276 | PCI_DEVICES: Optional[PCIDevices] = None 277 | 278 | 279 | class UsedPCIDevice(NamedTuple("UsedPCIDevice", [("pci_device", PCIDevice), ("domain", str)])): 280 | __slots__ = () 281 | 282 | 283 | class UsedMdevDevice( 284 | NamedTuple("UsedMdevDevice", [("mdev_device", "MdevDevice"), ("pci_device", PCIDevice), ("domain", str)]) 285 | ): 286 | __slots__ = () 287 | 288 | 289 | def get_service_exit_code(service_name): 290 | global COMMANDS 291 | command = [COMMANDS["systemctl"], "show", "-p", "ExecMainStatus", service_name] 292 | LOG.debug("Run: %s", " ".join(command)) 293 | output = subprocess.check_output(command).decode("utf-8") 294 | m = RE_EXEC_MAIN_STATUS.match(output) 295 | if m: 296 | return int(m.group(1)) 297 | raise DevCtlException('Invalid output from "systemctl show -p ExecMainStatus {}": {}'.format(service_name, output)) 298 | 299 | 300 | def restart_nvidia_services(delay=5, dry_run=False): 301 | global COMMANDS 302 | for svc in ("nvidia-vgpud.service", "nvidia-vgpu-mgr.service"): 303 | LOG.info("restart-nvidia-services: Restartig service %s", svc) 304 | if not dry_run: 305 | command = [COMMANDS["systemctl"], "restart", svc] 306 | LOG.debug("Run: %s", " ".join(command)) 307 | subprocess.check_call(command) 308 | time.sleep(delay) 309 | if get_service_exit_code(svc) != 0: 310 | LOG.error("restart-nvidia-services: Service %s failed", svc) 311 | return False 312 | else: 313 | LOG.info("restart-nvidia-services: Service %s successfully restarted", svc) 314 | return True 315 | 316 | 317 | def load_driver(driver_name, dry_run=False): 318 | global COMMANDS 319 | if not dry_run: 320 | command = [COMMANDS["modprobe"], driver_name] 321 | LOG.debug("Run: %s", " ".join(command)) 322 | subprocess.check_call(command) 323 | if driver_name == "nvidia": 324 | if not dry_run: 325 | try: 326 | command = [COMMANDS["modprobe"], "nvidia_vgpu_vfio"] 327 | LOG.debug("Run: %s", " ".join(command)) 328 | subprocess.check_call(command) 329 | if not os.path.exists(MDEV_BUS_CLASS_PATH): 330 | restart_nvidia_services() 331 | except CalledProcessError: 332 | LOG.exception("Could not load nvidia_vgpu_vfio module") 333 | return False # FIXME What if we don't use nvidia_vgpu_vfio module ? 334 | driver_path = sysfs_pci_driver_path(driver_name) 335 | if not dry_run: 336 | if not os.path.exists(driver_path): 337 | raise DeviceDriverPathNotFound(driver_path) 338 | else: 339 | LOG.info("Loaded %s driver", driver_name) 340 | return True 341 | 342 | 343 | # https://stackoverflow.com/questions/9535954/printing-lists-as-tabular-data 344 | def print_table(table: Sequence): 345 | longest_cols = [(max([len(str(row[i])) for row in table]) + 1) for i in range(len(table[0]))] 346 | row_format = "".join(["{:<" + str(longest_col) + "}" for longest_col in longest_cols]) 347 | for row in table: 348 | print(row_format.format(*row)) 349 | 350 | 351 | def each_mdev_device_class_pci_address(path_waiter: PathWaiterCB = None): 352 | if path_waiter: 353 | path_waiter(MDEV_BUS_CLASS_PATH) 354 | for pci_address in sorted(os.listdir(MDEV_BUS_CLASS_PATH)): 355 | yield pci_address 356 | 357 | 358 | def each_supported_mdev_type_and_path(pci_address, path_waiter: PathWaiterCB = None): 359 | path = os.path.join(MDEV_BUS_CLASS_PATH, pci_address, "mdev_supported_types") 360 | if path_waiter: 361 | path_waiter(path) 362 | for mdev_type in sorted(os.listdir(path)): 363 | yield mdev_type, os.path.join(path, mdev_type) 364 | 365 | 366 | def each_mdev_device_uuid(path_waiter: PathWaiterCB = None): 367 | if path_waiter: 368 | path_waiter(MDEV_BUS_DEVICE_PATH) 369 | for mdev_uuid in sorted(os.listdir(MDEV_BUS_DEVICE_PATH)): 370 | yield mdev_uuid 371 | 372 | 373 | def each_pci_device_address_and_path(vendor=None, path_waiter: PathWaiterCB = None): 374 | if vendor and not vendor.startswith("0x"): 375 | vendor = "0x" + vendor 376 | 377 | if path_waiter: 378 | path_waiter(PCI_BUS_DEVICE_PATH) 379 | 380 | for dev in sorted(os.listdir(PCI_BUS_DEVICE_PATH)): 381 | dev_path = os.path.join(PCI_BUS_DEVICE_PATH, dev) 382 | 383 | if path_waiter: 384 | path_waiter(dev_path) 385 | 386 | vendor_path = os.path.join(dev_path, "vendor") 387 | 388 | if path_waiter: 389 | path_waiter(vendor_path) 390 | 391 | if vendor and os.path.exists(vendor_path): 392 | with open(vendor_path) as f: 393 | device_vendor = f.read().rstrip("\n") 394 | if device_vendor != vendor: 395 | continue 396 | yield dev, dev_path 397 | 398 | 399 | def unbind_driver_from_pci_devices( 400 | driver: str, devices: Sequence[str], path_waiter: PathWaiterCB = None, dry_run=False 401 | ): 402 | assert driver is not None, "driver should be not None" 403 | driver_path = "/sys/bus/pci/drivers/{}".format(driver) 404 | if path_waiter: 405 | path_waiter(driver_path) 406 | if not os.path.exists(driver_path): 407 | raise DeviceDriverPathNotFound(driver_path) 408 | driver_unbind_path = os.path.join(driver_path, "unbind") 409 | if path_waiter: 410 | path_waiter(driver_unbind_path) 411 | if not os.path.exists(driver_unbind_path): 412 | raise UnbindDriverPathNotFound(driver_unbind_path) 413 | for dev in devices: 414 | device_driver_path = os.path.join(driver_path, dev) 415 | if path_waiter: 416 | path_waiter(device_driver_path) 417 | if not os.path.exists(device_driver_path): 418 | raise DeviceDriverPathNotFound(device_driver_path) 419 | if not dry_run: 420 | with open(driver_unbind_path, "w") as f: 421 | LOG.info("Unbind driver %s from PCI device %s", driver, dev) 422 | print(dev, file=f) 423 | else: 424 | LOG.info("Dry run: Unbind driver %s from PCI device %s", driver, dev) 425 | 426 | 427 | def get_driver_of_pci_device( 428 | pci_device_address, empty_driver_name_if_no_driver=False, path_waiter: PathWaiterCB = None 429 | ): 430 | if not pci_device_address: 431 | raise NoPCIAddressError(pci_device_address) 432 | device_path = sysfs_pci_device_path(str(pci_device_address)) 433 | driver_path = os.path.join(device_path, "driver") 434 | if path_waiter: 435 | path_waiter(driver_path) 436 | if not os.path.exists(driver_path): 437 | if empty_driver_name_if_no_driver: 438 | return "" 439 | raise DeviceDriverPathNotFound(driver_path) 440 | driver_path = os.path.realpath(driver_path) 441 | driver_name = os.path.basename(driver_path) 442 | return driver_name 443 | 444 | 445 | def unbind_pci_device_drivers(devices: Sequence[str], path_waiter: PathWaiterCB = None, dry_run=False): 446 | for device in devices: 447 | device_driver = get_driver_of_pci_device(device, empty_driver_name_if_no_driver=True, path_waiter=path_waiter) 448 | if device_driver: 449 | unbind_driver_from_pci_devices(device_driver, [device], path_waiter=path_waiter, dry_run=dry_run) 450 | 451 | 452 | def bind_driver_to_pci_devices( 453 | driver_name: str, devices: Sequence[str], path_waiter: PathWaiterCB = None, dry_run=False 454 | ): 455 | assert driver_name is not None, "driver name should be not None" 456 | dry_run_prefix = "Dry run: " if dry_run else "" 457 | for dev in devices: 458 | current_driver_name = get_driver_of_pci_device( 459 | dev, empty_driver_name_if_no_driver=True, path_waiter=path_waiter 460 | ) 461 | if current_driver_name == driver_name: 462 | LOG.info( 463 | "Do not change the driver on the device %s, because it already has driver %s", 464 | dev, 465 | driver_name, 466 | ) 467 | continue 468 | if current_driver_name != "": 469 | # unbind driver first 470 | unbind_driver_from_pci_devices(current_driver_name, [dev], path_waiter=path_waiter, dry_run=dry_run) 471 | 472 | driver_override_path = "/sys/bus/pci/devices/{}/driver_override".format(dev) 473 | if path_waiter: 474 | path_waiter(driver_override_path) 475 | if not os.path.exists(driver_override_path): 476 | raise DriverOverridePathNotFound(driver_override_path) 477 | LOG.info(dry_run_prefix + "Override driver %s for PCI device %s", driver_name, dev) 478 | if not dry_run: 479 | with open(driver_override_path, "w") as f: 480 | print(driver_name, file=f) 481 | driver_path = sysfs_pci_driver_path(driver_name) 482 | if not os.path.exists(driver_path): 483 | LOG.info(dry_run_prefix + "Driver %s missing, try loading it first", driver_name) 484 | load_driver(driver_name) 485 | LOG.info(dry_run_prefix + "Bind driver %s to device %s", driver_name, dev) 486 | if not dry_run: 487 | driver_bind_path = "/sys/bus/pci/drivers/{}/bind".format(driver_name) 488 | if path_waiter: 489 | path_waiter(driver_bind_path) 490 | if not os.path.exists(driver_bind_path): 491 | raise BindDriverPathNotFound(driver_bind_path) 492 | try: 493 | with open(driver_bind_path, "w") as f: 494 | print(dev, file=f) 495 | except OSError: 496 | # Sometimes 'OSError: [Errno 19] No such device' appears, we check if it can be ignored. 497 | current_driver_name = get_driver_of_pci_device(dev, empty_driver_name_if_no_driver=True) 498 | if current_driver_name != driver_name: 499 | raise 500 | return True 501 | 502 | 503 | class MdevType: 504 | def __init__(self, path, path_waiter: PathWaiterCB = None): 505 | self.path = path 506 | self.path_waiter = path_waiter 507 | self.realpath = os.path.realpath(path) 508 | path_head, self.type = os.path.split(self.realpath) 509 | path_head_1, mdev_supported_types_sym = os.path.split(path_head) 510 | if mdev_supported_types_sym != "mdev_supported_types": 511 | raise DevCtlException("Path {} does not end with 'mdev_supported_types".format(path_head)) 512 | self.pci_address = os.path.basename(path_head_1) 513 | os.path.dirname(self.realpath) 514 | self.name = None 515 | self.description = None 516 | self.device_api = None 517 | self.available_instances: Optional[int] = None 518 | self.update() 519 | 520 | def create(self, uuid, dry_run=False): 521 | create_path = os.path.join(self.path, "create") 522 | if self.path_waiter: 523 | self.path_waiter(create_path) 524 | dry_run_prefix = "Dry run: " if dry_run else "" 525 | LOG.info( 526 | dry_run_prefix + "Create mdev device with UUID %s on PCI address %s and with type %s", 527 | uuid, 528 | self.pci_address, 529 | self.type, 530 | ) 531 | if not dry_run: 532 | with open(create_path, "w") as f: 533 | print(uuid, file=f) 534 | self.update() 535 | return dry_run or os.path.exists(sysfs_mdev_path(self.pci_address, self.type, uuid)) 536 | 537 | def remove(self, uuid, dry_run=False): 538 | remove_path = sysfs_mdev_remove_path(self.pci_address, self.type, uuid) 539 | if self.path_waiter: 540 | self.path_waiter(remove_path) 541 | dry_run_prefix = "Dry run: " if dry_run else "" 542 | LOG.info( 543 | dry_run_prefix + "Remove mdev device with UUID %s on PCI address %s and with type %s", 544 | uuid, 545 | self.pci_address, 546 | self.type, 547 | ) 548 | if not dry_run: 549 | with open(remove_path, "w") as f: 550 | print("1", file=f) 551 | # Wait until the path of the remote mdev device disappears 552 | counter = 10 553 | while os.path.exists(self.path) and counter > 0: 554 | time.sleep(0.001) 555 | counter -= 1 556 | # Reset path to realpath since path is not valid anymore 557 | self.path = self.realpath 558 | self.update() 559 | return dry_run or not os.path.exists(sysfs_mdev_path(self.pci_address, self.type, uuid)) 560 | 561 | def update(self): 562 | fields = ( 563 | ("name", str), 564 | ("description", str), 565 | ("device_api", str), 566 | ("available_instances", int), 567 | ) 568 | for field_name, field_type in fields: 569 | field_path = os.path.join(self.path, field_name) 570 | if self.path_waiter: 571 | self.path_waiter(field_path) 572 | with open(field_path, "r") as f: 573 | setattr(self, field_name, field_type(f.read().rstrip("\n"))) 574 | 575 | def __repr__(self): 576 | return "MdevType(path={!r})".format(self.path) 577 | 578 | def __str__(self): 579 | return ( 580 | "".format( 582 | self.path, 583 | self.realpath, 584 | self.type, 585 | self.name, 586 | self.description, 587 | self.device_api, 588 | self.available_instances, 589 | ) 590 | ) 591 | 592 | @classmethod 593 | def from_path(cls, path: str, path_waiter: PathWaiterCB = None) -> "MdevType": 594 | return cls(path, path_waiter=path_waiter) 595 | 596 | 597 | MdevTypeFilterFunc = Callable[[MdevType], bool] 598 | MdevTypeFilterCB = Optional[MdevTypeFilterFunc] 599 | 600 | 601 | class MdevDeviceClass: 602 | def __init__(self, pci_address, path, path_waiter: PathWaiterCB = None): 603 | self.pci_address = pci_address # PCI address 604 | self.path = path # device path 605 | self.path_waiter = path_waiter 606 | self._supported_mdev_types: Optional[OrderedDict[str, MdevType]] = None # maps mdev_type to MdevType 607 | 608 | def find_supported_mdev_type(self, name_or_type: str): 609 | mdev_type = self.supported_mdev_types.get(name_or_type) 610 | if mdev_type: 611 | return mdev_type 612 | for mdev_type in self.supported_mdev_types.values(): 613 | if mdev_type.name == name_or_type: 614 | return mdev_type 615 | return None 616 | 617 | @property 618 | def supported_mdev_types(self) -> "OrderedDict[str, MdevType]": 619 | if self._supported_mdev_types is None: 620 | self._supported_mdev_types = OrderedDict() 621 | for mdev_type, mdev_type_path in each_supported_mdev_type_and_path( 622 | self.pci_address, path_waiter=self.path_waiter 623 | ): 624 | self._supported_mdev_types[mdev_type] = MdevType.from_path(mdev_type_path, path_waiter=self.path_waiter) 625 | return self._supported_mdev_types 626 | 627 | def __repr__(self): 628 | return "MdevDeviceClass(pci_address={!r}, path={!r})".format(self.pci_address, self.path) 629 | 630 | def __str__(self): 631 | return "".format( 632 | self.pci_address, self.path, list(self.supported_mdev_types.keys()) 633 | ) 634 | 635 | @classmethod 636 | def from_pci_address(cls, pci_address, path_waiter: PathWaiterCB = None): 637 | if path_waiter: 638 | path_waiter(MDEV_BUS_CLASS_PATH) 639 | if not os.path.exists(MDEV_BUS_CLASS_PATH): 640 | raise MdevBusPathNotFound(MDEV_BUS_CLASS_PATH) 641 | path = os.path.join(MDEV_BUS_CLASS_PATH, pci_address) 642 | if path_waiter: 643 | path_waiter(path) 644 | if not os.path.exists(path): 645 | raise NoMdevPCIAddressError(pci_address) 646 | return cls(pci_address=pci_address, path=path, path_waiter=path_waiter) 647 | 648 | @classmethod 649 | def from_pci_address_unchecked(cls, pci_address, path_waiter: PathWaiterCB = None): 650 | path = os.path.join(MDEV_BUS_CLASS_PATH, pci_address) 651 | if path_waiter: 652 | path_waiter(path) 653 | return cls(pci_address=pci_address, path=path, path_waiter=path_waiter) 654 | 655 | 656 | class MdevNvidia: 657 | def __init__(self, path, vm_name, vgpu_params): 658 | self.path = path 659 | self.vm_name = vm_name 660 | self.vgpu_params = vgpu_params 661 | 662 | def __str__(self): 663 | return "mdev_nvidia path={} vm_name={} vgpu_params={}".format(self.path, self.vm_name, self.vgpu_params) 664 | 665 | def __repr__(self): 666 | return "MdevNvidia(path={!r}, vm_name={!r}, vgpu_params={!r})".format(self.path, self.vm_name, self.vgpu_params) 667 | 668 | @classmethod 669 | def from_path(cls, path): 670 | fields = ("vm_name", "vgpu_params") 671 | kwargs = {"path": path} 672 | for field in fields: 673 | with open(os.path.join(path, field)) as f: 674 | kwargs[field] = f.read().rstrip("\n") 675 | return cls(**kwargs) 676 | 677 | 678 | class MdevDevice: 679 | def __init__(self, uuid, path): 680 | self.uuid = uuid # mdev device UUID 681 | self.path = path # device path 682 | self.realpath = os.path.realpath(path) 683 | self.pci_address = os.path.basename(os.path.dirname(self.realpath)) 684 | self._mdev_type = None 685 | self._nvidia = None 686 | 687 | @property 688 | def mdev_type(self) -> MdevType: 689 | if self._mdev_type is None: 690 | self._mdev_type = MdevType.from_path(os.path.join(self.path, "mdev_type")) 691 | return self._mdev_type 692 | 693 | @property 694 | def nvidia(self) -> MdevNvidia: 695 | if self._nvidia is None: 696 | nvidia_path = os.path.join(self.path, "nvidia") 697 | if os.path.exists(nvidia_path): 698 | self._nvidia = MdevNvidia.from_path(nvidia_path) 699 | return self._nvidia 700 | 701 | @classmethod 702 | def from_uuid(cls, uuid): 703 | if not os.path.exists(MDEV_BUS_DEVICE_PATH): 704 | raise MdevBusPathNotFound(MDEV_BUS_DEVICE_PATH) 705 | device_path = os.path.join(MDEV_BUS_DEVICE_PATH, uuid) 706 | if not os.path.exists(device_path): 707 | raise NoMdevUUIDError(uuid) 708 | 709 | return cls(uuid=uuid, path=device_path) 710 | 711 | @classmethod 712 | def from_uuid_unchecked(cls, uuid): 713 | path = os.path.join(MDEV_BUS_DEVICE_PATH, uuid) 714 | return cls(uuid=uuid, path=path) 715 | 716 | 717 | class Waiter: 718 | def __init__(self, check_func, message, num_trials=3, wait_delay=1): 719 | self.check_func = check_func 720 | self.message = message 721 | self.num_trials = num_trials 722 | self.wait_delay = wait_delay 723 | 724 | def wait(self): 725 | trial = 0 726 | result = False 727 | while not result: 728 | result = self.check_func() 729 | if result: 730 | break 731 | if self.num_trials > 0: 732 | trial += 1 733 | if trial > self.num_trials: 734 | break 735 | LOG.info("[Trial %d / %d] %s", trial, self.num_trials, self.message) 736 | else: 737 | LOG.info("[Trying] %s", self.message) 738 | time.sleep(self.wait_delay) 739 | return result 740 | 741 | 742 | class PathWaiter(Waiter): 743 | def __init__(self, path, num_trials=3, wait_delay=1): 744 | super().__init__( 745 | check_func=lambda: os.path.exists(path), 746 | message="Wait for path {}".format(path), 747 | num_trials=num_trials, 748 | wait_delay=wait_delay, 749 | ) 750 | 751 | 752 | class DevCtl: 753 | def __init__( 754 | self, 755 | wait_for_device=False, 756 | num_trials=3, 757 | wait_delay=1, 758 | virsh_connection="qemu:///system", 759 | dry_run=False, 760 | debug=False, 761 | ): 762 | global COMMANDS 763 | self.wait_for_device = wait_for_device 764 | self.num_trials = num_trials 765 | self.wait_delay = wait_delay 766 | self.virsh_connection = virsh_connection 767 | self._virsh_list_all_cache = None 768 | self._virsh_dumpxml_cache = {} 769 | self._virsh_domain_state_cache = {} 770 | self.dry_run = dry_run 771 | self.debug = debug 772 | self._mdev_device_classes: Optional[ 773 | OrderedDict[str, MdevDeviceClass] 774 | ] = None # maps PCI address to MdevDeviceClass 775 | self._mdev_devices: Optional[OrderedDict[str, MdevDevice]] = None # maps UUID to MdevDevice 776 | 777 | # Check virsh 778 | self._has_virsh = False 779 | self._virsh_version = None 780 | try: 781 | self._virsh_version = self.run_virsh(("--version",)).strip() 782 | self._has_virsh = True 783 | except FileNotFoundError as e: 784 | if e.filename in ("virsh", COMMANDS["virsh"]): 785 | LOG.warning("Could not run '%s --version', libvirt is not installed", COMMANDS["virsh"]) 786 | else: 787 | raise e 788 | 789 | def wait_for_device_path(self, device_path): 790 | if self.wait_for_device: 791 | LOG.debug("wait_for_device_path(%r)", device_path) # ??? DEBUG 792 | w = PathWaiter(device_path, num_trials=self.num_trials, wait_delay=self.wait_delay) 793 | result = w.wait() 794 | del w 795 | else: 796 | result = os.path.exists(device_path) 797 | return result 798 | 799 | @property 800 | def wait_for_device_enabled(self): 801 | return self.wait_for_device 802 | 803 | @property 804 | def mdev_device_classes(self) -> "OrderedDict[str, MdevDeviceClass]": 805 | if self._mdev_device_classes is None: 806 | self._mdev_device_classes = OrderedDict() 807 | for pci_address in each_mdev_device_class_pci_address(path_waiter=self.wait_for_device_path): 808 | self._mdev_device_classes[pci_address] = MdevDeviceClass.from_pci_address_unchecked(pci_address) 809 | return self._mdev_device_classes 810 | 811 | @property 812 | def mdev_devices(self) -> "OrderedDict[str, MdevDevice]": 813 | if self._mdev_devices is None: 814 | self._mdev_devices = OrderedDict() 815 | for mdev_uuid in each_mdev_device_uuid(path_waiter=self.wait_for_device_path): 816 | self._mdev_devices[mdev_uuid] = MdevDevice.from_uuid_unchecked(mdev_uuid) 817 | return self._mdev_devices 818 | 819 | def print_mdev_device_classes( 820 | self, 821 | pci_address_filter: PCIAddressFilterCB, 822 | mdev_type_filter: MdevTypeFilterCB, 823 | all_classes=False, 824 | output_all_columns=False, 825 | ): 826 | def column_filter(row): 827 | if output_all_columns: 828 | return row 829 | else: 830 | return row[0], row[1], row[2], row[3] 831 | 832 | mdev_types = [ 833 | column_filter( 834 | ( 835 | "PCI_ADDRESS", 836 | "MDEV_TYPE", 837 | "MDEV_NAME", 838 | "AVAILABLE_INSTANCES", 839 | "DESCRIPTION", 840 | "MDEV_DEVICE_CLASS_PATH", 841 | ) 842 | ) 843 | ] 844 | for mdev_device_class in self.mdev_device_classes.values(): 845 | pci_address_obj = PCIAddress.parse(mdev_device_class.pci_address) 846 | if pci_address_filter and not pci_address_filter(pci_address_obj): 847 | continue 848 | 849 | for mdev_type in mdev_device_class.supported_mdev_types.values(): 850 | if mdev_type_filter and not mdev_type_filter(mdev_type): 851 | continue 852 | if mdev_type.available_instances is not None and mdev_type.available_instances > 0 or all_classes: 853 | mdev_types.append( 854 | column_filter( 855 | ( 856 | mdev_device_class.pci_address, 857 | mdev_type.type, 858 | mdev_type.name, 859 | mdev_type.available_instances, 860 | mdev_type.description, 861 | mdev_device_class.path, 862 | ) 863 | ) 864 | ) 865 | 866 | print_table(mdev_types) 867 | return True 868 | 869 | def print_mdev_devices( 870 | self, pci_address_filter: PCIAddressFilterCB, mdev_type_filter: MdevTypeFilterCB, output_all_columns=False 871 | ): 872 | global PCI_DEVICES 873 | assert PCI_DEVICES is not None 874 | 875 | def column_filter(row): 876 | if output_all_columns: 877 | return row 878 | else: 879 | return row[0], row[1], row[2], row[4], row[7] 880 | 881 | mdev_devices_tbl = [ 882 | column_filter( 883 | ( 884 | "MDEV_DEVICE_UUID", 885 | "PCI_ADDRESS", 886 | "DEVICE", 887 | "MDEV_TYPE", 888 | "MDEV_NAME", 889 | "AVAILABLE_INSTANCES", 890 | "DESCRIPTION", 891 | "VM_NAME", 892 | ) 893 | ) 894 | ] 895 | for mdev_device in self.mdev_devices.values(): 896 | pci_address_obj = PCIAddress.parse(mdev_device.pci_address) 897 | if pci_address_filter and not pci_address_filter(pci_address_obj): 898 | continue 899 | if mdev_type_filter and not mdev_type_filter(mdev_device.mdev_type): 900 | continue 901 | 902 | pci_device = PCI_DEVICES.find_device(mdev_device.pci_address) 903 | 904 | if pci_device is not None: 905 | mdev_devices_tbl.append( 906 | column_filter( 907 | ( 908 | mdev_device.uuid, 909 | mdev_device.pci_address, 910 | pci_device.name, 911 | mdev_device.mdev_type.type, 912 | mdev_device.mdev_type.name, 913 | mdev_device.mdev_type.available_instances, 914 | mdev_device.mdev_type.description, 915 | mdev_device.nvidia.vm_name if mdev_device.nvidia else "none", 916 | ) 917 | ) 918 | ) 919 | 920 | print_table(mdev_devices_tbl) 921 | return True 922 | 923 | def print_pci_devices( 924 | self, pci_address_filter: PCIAddressFilterCB, output_format=TEXT_FORMAT, output_all_columns=False 925 | ): 926 | global PCI_DEVICES 927 | assert PCI_DEVICES is not None 928 | 929 | def column_filter(row): 930 | if output_all_columns: 931 | return row 932 | else: 933 | return row[0], row[1], row[2] 934 | 935 | pci_devices_tbl = [column_filter(("PCI_ADDRESS", "DEVICE", "DEVICE_DRIVER", "PCI_DEVICE_PATH"))] 936 | 937 | for pci_address, device_path in each_pci_device_address_and_path( 938 | vendor=NVIDIA_VENDOR, path_waiter=self.wait_for_device_path 939 | ): 940 | pci_address_obj = PCIAddress.parse(pci_address) 941 | if pci_address_filter and not pci_address_filter(pci_address_obj): 942 | continue 943 | try: 944 | driver_name = get_driver_of_pci_device(pci_address) 945 | except NoPCIAddressError: 946 | driver_name = "no device" 947 | except DeviceDriverPathNotFound: 948 | driver_name = "no driver" 949 | 950 | pci_device = PCI_DEVICES.find_device(pci_address) 951 | if pci_device is not None: 952 | pci_devices_tbl.append(column_filter((pci_address, pci_device.name, driver_name, device_path))) 953 | 954 | if output_format == TABLE_FORMAT: 955 | print_table(pci_devices_tbl) 956 | else: 957 | # text format 958 | print(" ".join([i[0] for i in pci_devices_tbl[1:]])) 959 | return True 960 | 961 | def save_config(self, output_file) -> bool: 962 | output_file.write("# NVIDIA Device Configuration\n") 963 | output_file.write("# This file is auto-generated by nvidia-dev-ctl.py save command\n") 964 | output_file.write("# pci_address\tdriver_name\tmdev_uuid\tmdev_type\n") 965 | 966 | mdev_devices_by_pci_address = defaultdict(list) 967 | 968 | try: 969 | for mdev_device in self.mdev_devices.values(): 970 | mdev_devices_by_pci_address[mdev_device.pci_address].append(mdev_device) 971 | except FileNotFoundError as e: 972 | if not e.filename.startswith(MDEV_BUS_DEVICE_PATH): 973 | raise 974 | 975 | for pci_address, device_path in each_pci_device_address_and_path( 976 | vendor=NVIDIA_VENDOR, path_waiter=self.wait_for_device_path 977 | ): 978 | try: 979 | driver_name = get_driver_of_pci_device(pci_address) 980 | except NoPCIAddressError: 981 | continue 982 | except DeviceDriverPathNotFound: 983 | continue 984 | 985 | mdev_devices = mdev_devices_by_pci_address.get(pci_address) 986 | if mdev_devices: 987 | for mdev_device in mdev_devices: 988 | output_file.write( 989 | "{}\t{}\t{}\t{}\n".format( 990 | pci_address, 991 | driver_name, 992 | mdev_device.uuid, 993 | mdev_device.mdev_type.type, 994 | ) 995 | ) 996 | del mdev_devices_by_pci_address[pci_address] 997 | else: 998 | output_file.write("{}\t{}\n".format(pci_address, driver_name)) 999 | 1000 | for mdev_devices in mdev_devices_by_pci_address.values(): 1001 | for mdev_device in mdev_devices: 1002 | LOG.warning( 1003 | "MDev device without driver: pci_address=%s mdev_uuid=%s mdev_type=%s", 1004 | mdev_device.pci_address, 1005 | mdev_device.uuid, 1006 | mdev_device.mdev_type.type, 1007 | ) 1008 | return True 1009 | 1010 | def rebind_device_driver(self, pci_address: str, driver_name: str, dry_run=False): 1011 | try: 1012 | current_driver_name = get_driver_of_pci_device(pci_address, path_waiter=self.wait_for_device_path) 1013 | if current_driver_name != driver_name: 1014 | self.unbind_driver(current_driver_name, (pci_address,), dry_run=dry_run) 1015 | except DeviceDriverPathNotFound: 1016 | LOG.info("No driver is bound to the PCI device %s", pci_address) 1017 | self.bind_driver(driver_name, (pci_address,), dry_run=dry_run) 1018 | 1019 | def restore_config(self, input_file, dry_run=False) -> bool: 1020 | success = True 1021 | for line in input_file: 1022 | line = line.strip() 1023 | comment_pos = line.find("#") 1024 | if comment_pos != -1: 1025 | line = line[:comment_pos] 1026 | if line: 1027 | device_config = line.split() 1028 | pci_address, driver_name, mdev_uuid, mdev_type_name = ( 1029 | None, 1030 | None, 1031 | None, 1032 | None, 1033 | ) 1034 | if len(device_config) == 2: 1035 | pci_address, driver_name = device_config 1036 | elif len(device_config) == 4: 1037 | pci_address, driver_name, mdev_uuid, mdev_type_name = device_config 1038 | else: 1039 | raise InvalidMdevFileFormat( 1040 | "In device configuration file should be two (PCI address, driver name) or four components (" 1041 | "PCI address, driver name, MDEV UUID, MDEV type) separated " 1042 | "by spaces " 1043 | ) 1044 | 1045 | self.rebind_device_driver(pci_address, driver_name, dry_run=dry_run) 1046 | 1047 | if mdev_uuid is not None and mdev_type_name is not None: 1048 | if not self._create_mdev_internal(pci_address, mdev_type_name, mdev_uuid, dry_run=dry_run): 1049 | success = False 1050 | return success 1051 | 1052 | def bind_driver(self, driver, devices: Optional[Sequence[str]] = None, dry_run=False): 1053 | assert driver is not None and driver, "driver should be not None and not empty" 1054 | if not devices: 1055 | return False 1056 | 1057 | return bind_driver_to_pci_devices(driver, devices, path_waiter=self.wait_for_device_path, dry_run=dry_run) 1058 | 1059 | def unbind_driver( 1060 | self, 1061 | driver=None, 1062 | devices: Optional[Sequence[str]] = None, 1063 | ignore_others=False, 1064 | dry_run=False, 1065 | ): 1066 | if not devices: 1067 | return False 1068 | 1069 | for device in devices: 1070 | if driver: 1071 | device_driver = driver 1072 | if ignore_others: 1073 | current_device_driver = get_driver_of_pci_device(device, path_waiter=self.wait_for_device_path) 1074 | if current_device_driver != device_driver: 1075 | LOG.info( 1076 | "Ignore device %s because it has driver %s and not %s", 1077 | device, 1078 | current_device_driver, 1079 | device_driver, 1080 | ) 1081 | continue 1082 | else: 1083 | device_driver = get_driver_of_pci_device(device, path_waiter=self.wait_for_device_path) 1084 | unbind_driver_from_pci_devices( 1085 | device_driver, 1086 | [device], 1087 | path_waiter=self.wait_for_device_path, 1088 | dry_run=dry_run, 1089 | ) 1090 | return True 1091 | 1092 | def fix_mdev(self): 1093 | do_restart_services = False 1094 | for svc in ("nvidia-vgpud.service", "nvidia-vgpu-mgr.service"): 1095 | if get_service_exit_code(svc) != 0: 1096 | do_restart_services = True 1097 | if do_restart_services: 1098 | restart_nvidia_services() 1099 | 1100 | def _create_mdev_internal(self, pci_address: str, mdev_type_name: str, mdev_uuid: str, dry_run=False) -> bool: 1101 | assert pci_address, "PCI address is None or empty" 1102 | assert mdev_type_name, "MDEV type name is None or empty" 1103 | assert mdev_uuid, "MDEV UUID is None or empty" 1104 | 1105 | self.fix_mdev() 1106 | 1107 | LOG.info( 1108 | "Create Mdev device with UUID %s and type %s on PCI device with address %s", 1109 | mdev_uuid, 1110 | mdev_type_name, 1111 | pci_address, 1112 | ) 1113 | 1114 | mdev_device = self.mdev_devices.get(mdev_uuid) 1115 | if mdev_device: 1116 | LOG.warning( 1117 | "Ignore Mdev device with UUID %s because it is already registered", 1118 | mdev_uuid, 1119 | ) 1120 | return True 1121 | mdev_device_class = self.mdev_device_classes.get(pci_address) 1122 | if not mdev_device_class: 1123 | LOG.error("Mdev device class with PCI address %s does not exist", pci_address) 1124 | return False 1125 | LOG.info("Found device class %s", mdev_device_class) 1126 | mdev_type = mdev_device_class.find_supported_mdev_type(mdev_type_name) 1127 | if not mdev_type: 1128 | LOG.error( 1129 | "Mdev type with name %s does not exist in device class with PCI address %s and path %s", 1130 | mdev_type_name, 1131 | pci_address, 1132 | mdev_device_class.path, 1133 | ) 1134 | return False 1135 | LOG.info("Found device type %s", mdev_type) 1136 | if mdev_type.available_instances is None or mdev_type.available_instances <= 0: 1137 | LOG.error( 1138 | "Mdev type with name %s in device class with PCI address %s and path %s has no " "available instances", 1139 | mdev_type_name, 1140 | pci_address, 1141 | mdev_device_class.path, 1142 | ) 1143 | return False 1144 | 1145 | try: 1146 | return mdev_type.create(mdev_uuid, dry_run=dry_run) 1147 | except PermissionError: 1148 | LOG.exception( 1149 | "Could not create mdev device of type %s on device with PCI address %s and path %s, " 1150 | "try to run this command as root", 1151 | mdev_type_name, 1152 | pci_address, 1153 | mdev_device_class.path, 1154 | ) 1155 | return False 1156 | except OSError: 1157 | LOG.exception( 1158 | "Could not register mdev type %s with device class with PCI address %s and path %s", 1159 | mdev_type_name, 1160 | pci_address, 1161 | mdev_device_class.path, 1162 | ) 1163 | return False 1164 | 1165 | def create_mdev( 1166 | self, 1167 | pci_address: str, 1168 | mdev_type_name: str, 1169 | driver_name: str = "nvidia", 1170 | mdev_uuid: Optional[str] = None, 1171 | dry_run=False, 1172 | ) -> Optional[str]: 1173 | if not pci_address: 1174 | LOG.error("No PCI address is specified") 1175 | return None 1176 | if not mdev_type_name: 1177 | LOG.error("No mdev type name is specified") 1178 | return None 1179 | 1180 | if not mdev_uuid: 1181 | mdev_uuid = str(uuid.uuid4()) 1182 | 1183 | self.rebind_device_driver(pci_address, driver_name, dry_run=dry_run) 1184 | if self._create_mdev_internal(pci_address, mdev_type_name, mdev_uuid, dry_run=dry_run): 1185 | return mdev_uuid 1186 | else: 1187 | return None 1188 | 1189 | def remove_mdev(self, mdev_uuid: str, dry_run=False) -> bool: 1190 | if not mdev_uuid: 1191 | LOG.error("No mdev UUID is specified") 1192 | return False 1193 | 1194 | mdev_device = self.mdev_devices.get(mdev_uuid) 1195 | if not mdev_device: 1196 | LOG.error("No mdev device with the UUID %s", mdev_uuid) 1197 | return False 1198 | 1199 | try: 1200 | return mdev_device.mdev_type.remove(mdev_uuid, dry_run=dry_run) 1201 | except PermissionError: 1202 | LOG.exception( 1203 | "Could not remove mdev device with UUID %s, type %s and PCI address %s, " 1204 | "try to run this command as root", 1205 | mdev_uuid, 1206 | mdev_device.mdev_type.type, 1207 | mdev_device.pci_address, 1208 | ) 1209 | return False 1210 | 1211 | def run_virsh(self, args: Sequence[str]): 1212 | global COMMANDS 1213 | virsh_command = [COMMANDS["virsh"]] 1214 | if self.virsh_connection: 1215 | virsh_command.append("-c") 1216 | virsh_command.append(self.virsh_connection) 1217 | virsh_command.extend(args) 1218 | LOG.debug("Run: %s", " ".join(virsh_command)) 1219 | output = subprocess.check_output(virsh_command).decode("utf-8") 1220 | return output 1221 | 1222 | def list_all_domains(self, use_cache=False): 1223 | if not self._has_virsh: 1224 | return [] 1225 | 1226 | if use_cache and self._virsh_list_all_cache: 1227 | return self._virsh_list_all_cache 1228 | output = self.run_virsh(("list", "--all", "--name")) 1229 | result = [line for line in output.splitlines() if len(line) > 0] 1230 | if use_cache: 1231 | self._virsh_list_all_cache = result 1232 | else: 1233 | self._virsh_list_all_cache = None 1234 | return result 1235 | 1236 | def dumpxml_of_domain(self, domain_name, use_cache=False): 1237 | if use_cache: 1238 | result = self._virsh_dumpxml_cache.get(domain_name, None) 1239 | if result is not None: 1240 | return result 1241 | result = self.run_virsh(("dumpxml", "--domain", domain_name)) 1242 | if use_cache: 1243 | self._virsh_dumpxml_cache[domain_name] = result 1244 | else: 1245 | self._virsh_dumpxml_cache.pop(domain_name, None) 1246 | return result 1247 | 1248 | def get_domain_state(self, domain_name: str, use_cache=False): 1249 | if use_cache: 1250 | result = self._virsh_domain_state_cache.get(domain_name, None) 1251 | if result is not None: 1252 | return result 1253 | output = self.run_virsh(["dominfo", "--domain", domain_name]) 1254 | m = RE_DOMAIN_STATE.search(output) 1255 | if not m: 1256 | raise DevCtlException("Could not get state of the virsh domain {}".format(domain_name)) 1257 | result = m.group(1) 1258 | if use_cache: 1259 | self._virsh_domain_state_cache[domain_name] = result 1260 | else: 1261 | self._virsh_domain_state_cache.pop(domain_name, None) 1262 | return result 1263 | 1264 | def restart_domain(self, domain: str, virsh_trials=60, virsh_delay=1.0, dry_run=False): 1265 | dry_run_prefix = "Dry run: " if dry_run else "" 1266 | 1267 | LOG.info(dry_run_prefix + "Shutdown domain %s", domain) 1268 | 1269 | if not dry_run: 1270 | domain_running = True 1271 | 1272 | self.run_virsh(["shutdown", domain]) 1273 | counter = virsh_trials 1274 | while counter > 0: 1275 | domain_state = self.get_domain_state(domain) 1276 | domain_running = domain_state == "running" 1277 | LOG.info("Domain %s is in state %s", domain, domain_state) 1278 | if not domain_running: 1279 | break 1280 | LOG.info("Waiting for the domain %s to be shut off", domain) 1281 | time.sleep(virsh_delay) 1282 | counter -= 1 1283 | 1284 | if domain_running: 1285 | raise DevCtlException("Could not stop domain %s", domain) 1286 | 1287 | LOG.info(dry_run_prefix + "Start domain %s", domain) 1288 | 1289 | if not dry_run: 1290 | domain_running = False 1291 | self.run_virsh(["start", domain]) 1292 | counter = virsh_trials 1293 | while counter > 0: 1294 | domain_state = self.get_domain_state(domain) 1295 | domain_running = domain_state == "running" 1296 | if domain_running: 1297 | LOG.info("Domain %s is in state %s", domain, domain_state) 1298 | break 1299 | LOG.info("Waiting for the domain %s to be running", domain) 1300 | time.sleep(virsh_delay) 1301 | counter -= 1 1302 | 1303 | if not domain_running: 1304 | raise DevCtlException("Could not start domain %s", domain) 1305 | 1306 | def get_used_pci_devices( 1307 | self, pci_address_filter: PCIAddressFilterCB, use_cache=False 1308 | ) -> "Sequence[UsedPCIDevice]": 1309 | global PCI_DEVICES 1310 | assert PCI_DEVICES is not None 1311 | 1312 | used_pci_devices: List[UsedPCIDevice] = [] 1313 | 1314 | all_domains = self.list_all_domains(use_cache=use_cache) 1315 | for domain in all_domains: 1316 | xml = self.dumpxml_of_domain(domain, use_cache=use_cache) 1317 | root = ET.fromstring(xml) 1318 | for pci_hostdev in root.findall("./devices/hostdev[@type='pci']"): 1319 | if pci_hostdev.attrib.get("mode") == "subsystem": 1320 | for address in pci_hostdev.findall("./source/address"): 1321 | pci_domain_str = address.attrib.get("domain") 1322 | pci_bus_str = address.attrib.get("bus") 1323 | pci_slot_str = address.attrib.get("slot") 1324 | pci_function_str = address.attrib.get("function") 1325 | if not (pci_domain_str and pci_bus_str and pci_slot_str and pci_function_str): 1326 | continue 1327 | pci_domain = int(pci_domain_str, 0) 1328 | pci_bus = int(pci_bus_str, 0) 1329 | pci_slot = int(pci_slot_str, 0) 1330 | pci_function = int(pci_function_str, 0) 1331 | pci_address_obj = PCIAddress(pci_domain, pci_bus, pci_slot, pci_function) 1332 | 1333 | if pci_address_filter and not pci_address_filter(pci_address_obj): 1334 | continue 1335 | 1336 | pci_device = PCI_DEVICES.find_device(pci_address_obj) 1337 | if pci_device is not None: 1338 | device = UsedPCIDevice(pci_device, domain) 1339 | used_pci_devices.append(device) 1340 | return used_pci_devices 1341 | 1342 | def print_used_pci_devices(self, pci_address_filter: PCIAddressFilterCB, output_format=TEXT_FORMAT): 1343 | used_pci_devices_tbl = [("PCI_ADDRESS", "DEVICE", "VM_NAME", "VM_STATE")] 1344 | 1345 | used_pci_devices = self.get_used_pci_devices(pci_address_filter=pci_address_filter) 1346 | for used_pci_device in used_pci_devices: 1347 | if used_pci_device.domain: 1348 | domain_state = self.get_domain_state(used_pci_device.domain, use_cache=True) 1349 | else: 1350 | domain_state = "" 1351 | used_pci_devices_tbl.append( 1352 | ( 1353 | str(used_pci_device.pci_device.pci_address), 1354 | used_pci_device.pci_device.name, 1355 | used_pci_device.domain, 1356 | domain_state, 1357 | ) 1358 | ) 1359 | if output_format == TABLE_FORMAT: 1360 | print_table(used_pci_devices_tbl) 1361 | else: 1362 | # text format 1363 | print(" ".join([i[0] for i in used_pci_devices_tbl[1:]])) 1364 | return True 1365 | 1366 | def get_used_mdev_devices( 1367 | self, pci_address_filter: PCIAddressFilterCB, mdev_type_filter: MdevTypeFilterCB, use_cache=False 1368 | ) -> "Sequence[UsedMdevDevice]": 1369 | global PCI_DEVICES 1370 | assert PCI_DEVICES is not None 1371 | 1372 | used_mdev_devices = [] 1373 | 1374 | all_domains = self.list_all_domains(use_cache=use_cache) 1375 | for domain in all_domains: 1376 | xml = self.dumpxml_of_domain(domain, use_cache=use_cache) 1377 | root = ET.fromstring(xml) 1378 | for pci_hostdev in root.findall("./devices/hostdev[@type='mdev']"): 1379 | if ( 1380 | pci_hostdev.attrib.get("mode") == "subsystem" 1381 | and pci_hostdev.attrib.get("model") == "vfio-pci" 1382 | and pci_hostdev.attrib.get("managed") == "no" 1383 | and pci_hostdev.attrib.get("display") == "off" 1384 | ): 1385 | for address in pci_hostdev.findall("./source/address[@uuid]"): 1386 | mdev_uuid = address.attrib.get("uuid") 1387 | if not mdev_uuid: 1388 | continue 1389 | mdev_device = self.mdev_devices.get(mdev_uuid) 1390 | if mdev_device: 1391 | pci_address_obj = PCIAddress.parse(mdev_device.pci_address) 1392 | if pci_address_filter and not pci_address_filter(pci_address_obj): 1393 | continue 1394 | if mdev_type_filter and not mdev_type_filter(mdev_device.mdev_type): 1395 | continue 1396 | 1397 | pci_device = PCI_DEVICES.find_device(mdev_device.pci_address) 1398 | if pci_device is not None: 1399 | device = UsedMdevDevice(mdev_device=mdev_device, pci_device=pci_device, domain=domain) 1400 | used_mdev_devices.append(device) 1401 | return used_mdev_devices 1402 | 1403 | def print_used_mdev_devices( 1404 | self, 1405 | pci_address_filter: PCIAddressFilterCB, 1406 | mdev_type_filter: MdevTypeFilterCB, 1407 | output_format=TEXT_FORMAT, 1408 | output_all_columns=False, 1409 | ): 1410 | def column_filter(row): 1411 | if output_all_columns: 1412 | return row 1413 | else: 1414 | return row[0], row[1], row[2], row[4], row[7], row[8] 1415 | 1416 | used_mdev_devices_tbl = [ 1417 | column_filter( 1418 | ( 1419 | "MDEV_DEVICE_UUID", 1420 | "PCI_ADDRESS", 1421 | "DEVICE", 1422 | "MDEV_TYPE", 1423 | "MDEV_NAME", 1424 | "AVAILABLE_INSTANCES", 1425 | "DESCRIPTION", 1426 | "VM_NAME", 1427 | "VM_STATE", 1428 | ) 1429 | ) 1430 | ] 1431 | 1432 | used_mdev_devices = self.get_used_mdev_devices( 1433 | pci_address_filter=pci_address_filter, mdev_type_filter=mdev_type_filter 1434 | ) 1435 | 1436 | for used_mdev_device in used_mdev_devices: 1437 | if used_mdev_device.domain: 1438 | domain_state = self.get_domain_state(used_mdev_device.domain, use_cache=True) 1439 | else: 1440 | domain_state = "" 1441 | column = ( 1442 | used_mdev_device.mdev_device.uuid, 1443 | used_mdev_device.mdev_device.pci_address, 1444 | used_mdev_device.pci_device.name, 1445 | used_mdev_device.mdev_device.mdev_type.type, 1446 | used_mdev_device.mdev_device.mdev_type.name, 1447 | used_mdev_device.mdev_device.mdev_type.available_instances, 1448 | used_mdev_device.mdev_device.mdev_type.description, 1449 | used_mdev_device.domain, 1450 | domain_state, 1451 | ) 1452 | used_mdev_devices_tbl.append(column_filter(column)) 1453 | 1454 | if output_format == TABLE_FORMAT: 1455 | print_table(used_mdev_devices_tbl) 1456 | else: 1457 | # text format 1458 | print(" ".join([i[0] for i in used_mdev_devices_tbl[1:]])) 1459 | return True 1460 | 1461 | def attach_mdev( 1462 | self, 1463 | mdev_uuid: str, 1464 | domain: str, 1465 | hotplug=False, 1466 | restart=False, 1467 | dry_run=False, 1468 | ): 1469 | if restart and hotplug: 1470 | LOG.error("restart and hotplug options cannot be used simultaneously") 1471 | 1472 | if not mdev_uuid: 1473 | LOG.error("No mdev UUID is specified") 1474 | return False 1475 | 1476 | if not domain: 1477 | LOG.error("No domain is specified") 1478 | return False 1479 | 1480 | dry_run_prefix = "Dry run: " if dry_run else "" 1481 | 1482 | domain_state = self.get_domain_state(domain) 1483 | domain_running = domain_state == "running" 1484 | 1485 | try: 1486 | dev_fname = None 1487 | with tempfile.NamedTemporaryFile(suffix=".xml", mode="w+t", delete=False) as tmp_dev: 1488 | dev_xml = """ 1489 | 1490 | 1491 |
1492 | 1493 | 1494 | """.format( 1495 | mdev_uuid 1496 | ) 1497 | LOG.debug("XML device file: %s", dev_xml) 1498 | tmp_dev.write(dev_xml) 1499 | dev_fname = tmp_dev.name 1500 | 1501 | LOG.info(dry_run_prefix + "Attach mdev device %s to domain %s", mdev_uuid, domain) 1502 | if not dry_run: 1503 | 1504 | if hotplug and domain_running: 1505 | cmd = ["attach-device", domain, "--file", dev_fname, "--persistent"] 1506 | else: 1507 | cmd = ["attach-device", domain, "--file", dev_fname, "--config"] 1508 | 1509 | self.run_virsh(cmd) 1510 | 1511 | finally: 1512 | if dev_fname: 1513 | os.remove(dev_fname) 1514 | 1515 | if domain_running and restart and not hotplug: 1516 | self.restart_domain(domain, dry_run=dry_run) 1517 | return True 1518 | 1519 | def detach_mdev( 1520 | self, 1521 | mdev_uuid: str, 1522 | domain: str, 1523 | hotplug=False, 1524 | restart=False, 1525 | dry_run=False, 1526 | ): 1527 | if restart and hotplug: 1528 | LOG.error("restart and hotplug options cannot be used simultaneously") 1529 | if not mdev_uuid: 1530 | LOG.error("No mdev UUID is specified") 1531 | return False 1532 | 1533 | if not domain: 1534 | LOG.error("No domain is specified") 1535 | return False 1536 | 1537 | dry_run_prefix = "Dry run: " if dry_run else "" 1538 | 1539 | domain_state = self.get_domain_state(domain) 1540 | domain_running = domain_state == "running" 1541 | 1542 | try: 1543 | dev_fname = None 1544 | with tempfile.NamedTemporaryFile(suffix=".xml", mode="w+t", delete=False) as tmp_dev: 1545 | dev_xml = """ 1546 | 1547 | 1548 |
1549 | 1550 | 1551 | """.format( 1552 | mdev_uuid 1553 | ) 1554 | LOG.debug("XML device file: %s", dev_xml) 1555 | tmp_dev.write(dev_xml) 1556 | dev_fname = tmp_dev.name 1557 | 1558 | LOG.info(dry_run_prefix + "Detach mdev device %s from domain %s", mdev_uuid, domain) 1559 | if not dry_run: 1560 | 1561 | if hotplug and domain_running: 1562 | cmd = ["detach-device", domain, "--file", dev_fname, "--persistent"] 1563 | else: 1564 | cmd = ["detach-device", domain, "--file", dev_fname, "--config"] 1565 | 1566 | self.run_virsh(cmd) 1567 | 1568 | finally: 1569 | if dev_fname: 1570 | os.remove(dev_fname) 1571 | 1572 | if domain_running and restart and not hotplug: 1573 | self.restart_domain(domain, dry_run=dry_run) 1574 | return True 1575 | 1576 | def attach_pci( 1577 | self, 1578 | pci_address: str, 1579 | domain: str, 1580 | hotplug=False, 1581 | restart=False, 1582 | dry_run=False, 1583 | ): 1584 | if restart and hotplug: 1585 | LOG.error("restart and hotplug options cannot be used simultaneously") 1586 | 1587 | if not pci_address: 1588 | LOG.error("No PCI address is specified") 1589 | return False 1590 | 1591 | if not domain: 1592 | LOG.error("No domain is specified") 1593 | return False 1594 | 1595 | dry_run_prefix = "Dry run: " if dry_run else "" 1596 | 1597 | domain_state = self.get_domain_state(domain) 1598 | domain_running = domain_state == "running" 1599 | 1600 | pci_address_obj = PCIAddress.parse(pci_address) 1601 | 1602 | if not self.bind_driver(driver="vfio-pci", devices=[pci_address], dry_run=dry_run): 1603 | return False 1604 | 1605 | try: 1606 | dev_fname = None 1607 | with tempfile.NamedTemporaryFile(suffix=".xml", mode="w+t", delete=False) as tmp_dev: 1608 | dev_xml = """ 1609 | 1610 | 1611 | 1612 |
1613 | 1614 | 1615 | """.format( 1616 | pci_address_obj.domain, pci_address_obj.bus, pci_address_obj.slot, pci_address_obj.function 1617 | ) 1618 | LOG.debug("XML device file: %s", dev_xml) 1619 | tmp_dev.write(dev_xml) 1620 | dev_fname = tmp_dev.name 1621 | 1622 | LOG.info(dry_run_prefix + "Attach PCI device %s to domain %s", pci_address, domain) 1623 | if not dry_run: 1624 | 1625 | if hotplug and domain_running: 1626 | cmd = ["attach-device", domain, "--file", dev_fname, "--persistent"] 1627 | else: 1628 | cmd = ["attach-device", domain, "--file", dev_fname, "--config"] 1629 | 1630 | self.run_virsh(cmd) 1631 | 1632 | finally: 1633 | if dev_fname: 1634 | os.remove(dev_fname) 1635 | 1636 | if domain_running and restart and not hotplug: 1637 | self.restart_domain(domain, dry_run=dry_run) 1638 | return True 1639 | 1640 | def detach_pci( 1641 | self, 1642 | pci_address: str, 1643 | domain: str, 1644 | hotplug=False, 1645 | restart=False, 1646 | dry_run=False, 1647 | ): 1648 | if restart and hotplug: 1649 | LOG.error("restart and hotplug options cannot be used simultaneously") 1650 | if not pci_address: 1651 | LOG.error("No PCI address is specified") 1652 | return False 1653 | 1654 | if not domain: 1655 | LOG.error("No domain is specified") 1656 | return False 1657 | 1658 | dry_run_prefix = "Dry run: " if dry_run else "" 1659 | 1660 | domain_state = self.get_domain_state(domain) 1661 | domain_running = domain_state == "running" 1662 | 1663 | pci_address_obj = PCIAddress.parse(pci_address) 1664 | 1665 | try: 1666 | dev_fname = None 1667 | with tempfile.NamedTemporaryFile(suffix=".xml", mode="w+t", delete=False) as tmp_dev: 1668 | dev_xml = """ 1669 | 1670 | 1671 | 1672 |
1673 | 1674 | 1675 | """.format( 1676 | pci_address_obj.domain, pci_address_obj.bus, pci_address_obj.slot, pci_address_obj.function 1677 | ) 1678 | LOG.debug("XML device file: %s", dev_xml) 1679 | tmp_dev.write(dev_xml) 1680 | dev_fname = tmp_dev.name 1681 | 1682 | LOG.info(dry_run_prefix + "Detach PCI device %s from domain %s", pci_address, domain) 1683 | if not dry_run: 1684 | 1685 | if hotplug and domain_running: 1686 | cmd = ["detach-device", domain, "--file", dev_fname, "--persistent"] 1687 | else: 1688 | cmd = ["detach-device", domain, "--file", dev_fname, "--config"] 1689 | 1690 | self.run_virsh(cmd) 1691 | 1692 | finally: 1693 | if dev_fname: 1694 | os.remove(dev_fname) 1695 | 1696 | if domain_running and restart and not hotplug: 1697 | self.restart_domain(domain, dry_run=dry_run) 1698 | return True 1699 | 1700 | def print_all_devices( 1701 | self, 1702 | pci_address_filter: PCIAddressFilterCB, 1703 | mdev_type_filter: MdevTypeFilterCB, 1704 | output_format=TEXT_FORMAT, 1705 | output_all_columns=False, 1706 | ): 1707 | global PCI_DEVICES 1708 | assert PCI_DEVICES is not None 1709 | 1710 | def column_filter(row): 1711 | if output_all_columns: 1712 | return row 1713 | else: 1714 | return row[0], row[1], row[2], row[3], row[4], row[8], row[9] 1715 | 1716 | devices_tbl_header = column_filter( 1717 | ( 1718 | "PCI_ADDRESS", 1719 | "DEVICE", 1720 | "DEVICE_DRIVER", 1721 | "MDEV_UUID", 1722 | "MDEV_NAME", 1723 | "MDEV_TYPE", 1724 | "AVAILABLE_INSTANCES", 1725 | "DESCRIPTION", 1726 | "VM_NAME", 1727 | "VM_STATE", 1728 | ) 1729 | ) 1730 | 1731 | devices_tbl = [] 1732 | 1733 | pci_address_to_domain = defaultdict(set) 1734 | for used_pci_device in self.get_used_pci_devices(pci_address_filter=pci_address_filter, use_cache=True): 1735 | pci_address_to_domain[used_pci_device.pci_device.pci_address].add(used_pci_device.domain) 1736 | 1737 | mdev_uuid_to_domain = defaultdict(set) 1738 | try: 1739 | for used_mdev_device in self.get_used_mdev_devices( 1740 | pci_address_filter=pci_address_filter, mdev_type_filter=mdev_type_filter, use_cache=True 1741 | ): 1742 | mdev_uuid_to_domain[used_mdev_device.mdev_device.uuid].add(used_mdev_device.domain) 1743 | except FileNotFoundError as e: 1744 | if not e.filename.startswith(MDEV_BUS_DEVICE_PATH): 1745 | raise 1746 | 1747 | for pci_address, device_path in each_pci_device_address_and_path( 1748 | vendor=NVIDIA_VENDOR, path_waiter=self.wait_for_device_path 1749 | ): 1750 | pci_address_obj = PCIAddress.parse(pci_address) 1751 | 1752 | if pci_address_filter and not pci_address_filter(pci_address_obj): 1753 | continue 1754 | 1755 | pci_device = PCI_DEVICES.find_device(pci_address) 1756 | if pci_device is not None: 1757 | domains = pci_address_to_domain[pci_device.pci_address] 1758 | if not domains: 1759 | domains = set([""]) 1760 | 1761 | for domain in domains: 1762 | domain_state = self.get_domain_state(domain, use_cache=True) if domain else "" 1763 | 1764 | devices_tbl.append( 1765 | column_filter( 1766 | (pci_address, pci_device.name, pci_device.driver, "", "", "", "", "", domain, domain_state) 1767 | ) 1768 | ) 1769 | 1770 | try: 1771 | for mdev_device in self.mdev_devices.values(): 1772 | pci_address_obj = PCIAddress.parse(mdev_device.pci_address) 1773 | 1774 | if pci_address_filter and not pci_address_filter(pci_address_obj): 1775 | continue 1776 | if mdev_type_filter and not mdev_type_filter(mdev_device.mdev_type): 1777 | continue 1778 | 1779 | pci_device = PCI_DEVICES.find_device(mdev_device.pci_address) 1780 | 1781 | if pci_device is not None: 1782 | domains = mdev_uuid_to_domain[mdev_device.uuid] 1783 | 1784 | if not domains: 1785 | domains = set([mdev_device.nvidia.vm_name or ""]) 1786 | 1787 | for domain in domains: 1788 | domain_state = self.get_domain_state(domain, use_cache=True) if domain else "" 1789 | 1790 | devices_tbl.append( 1791 | column_filter( 1792 | ( 1793 | mdev_device.pci_address, 1794 | pci_device.name, 1795 | pci_device.driver, 1796 | mdev_device.uuid, 1797 | mdev_device.mdev_type.name, 1798 | mdev_device.mdev_type.type, 1799 | mdev_device.mdev_type.available_instances, 1800 | mdev_device.mdev_type.description, 1801 | domain, 1802 | domain_state, 1803 | ) 1804 | ) 1805 | ) 1806 | except FileNotFoundError as e: 1807 | if not e.filename.startswith(MDEV_BUS_DEVICE_PATH): 1808 | raise 1809 | 1810 | devices_tbl.sort(key=lambda entry: entry[0]) 1811 | 1812 | devices_tbl = [devices_tbl_header] + devices_tbl 1813 | 1814 | if output_format == TABLE_FORMAT: 1815 | print_table(devices_tbl) 1816 | else: 1817 | # text format 1818 | print(" ".join([i[0] for i in devices_tbl[1:]])) 1819 | 1820 | self.validate_configuration(pci_address_filter=pci_address_filter, mdev_type_filter=mdev_type_filter) 1821 | 1822 | return True 1823 | 1824 | def validate_configuration( 1825 | self, 1826 | pci_address_filter: PCIAddressFilterCB, 1827 | mdev_type_filter: MdevTypeFilterCB, 1828 | ): 1829 | global PCI_DEVICES 1830 | assert PCI_DEVICES is not None 1831 | 1832 | result = True 1833 | 1834 | pci_address_to_domain = defaultdict(set) 1835 | for used_pci_device in self.get_used_pci_devices(pci_address_filter=pci_address_filter, use_cache=True): 1836 | pci_address_to_domain[used_pci_device.pci_device.pci_address].add(used_pci_device.domain) 1837 | 1838 | mdev_uuid_to_domain = defaultdict(set) 1839 | try: 1840 | for used_mdev_device in self.get_used_mdev_devices( 1841 | pci_address_filter=pci_address_filter, mdev_type_filter=mdev_type_filter, use_cache=True 1842 | ): 1843 | mdev_uuid_to_domain[used_mdev_device.mdev_device.uuid].add(used_mdev_device.domain) 1844 | except FileNotFoundError as e: 1845 | if not e.filename.startswith(MDEV_BUS_DEVICE_PATH): 1846 | raise 1847 | 1848 | for pci_address, device_path in each_pci_device_address_and_path( 1849 | vendor=NVIDIA_VENDOR, path_waiter=self.wait_for_device_path 1850 | ): 1851 | pci_address_obj = PCIAddress.parse(pci_address) 1852 | 1853 | if pci_address_filter and not pci_address_filter(pci_address_obj): 1854 | continue 1855 | 1856 | pci_device = PCI_DEVICES.find_device(pci_address) 1857 | if pci_device is not None: 1858 | domains = pci_address_to_domain[pci_device.pci_address] 1859 | 1860 | for domain in domains: 1861 | if domain and pci_device.driver != "vfio-pci": 1862 | LOG.warning( 1863 | "GPU %s with PCI address %s is used by VM %s, but has %s driver instead of vfio-pci", 1864 | pci_device.name, 1865 | pci_address, 1866 | domain, 1867 | pci_device.driver, 1868 | ) 1869 | result = False 1870 | 1871 | if len(domains) > 1: 1872 | LOG.warning( 1873 | "GPU %s with PCI address %s is used by more than one VMs: %s", 1874 | pci_device.name, 1875 | pci_address, 1876 | ", ".join(domains), 1877 | ) 1878 | 1879 | try: 1880 | for mdev_device in self.mdev_devices.values(): 1881 | pci_address_obj = PCIAddress.parse(mdev_device.pci_address) 1882 | if pci_address_filter and not pci_address_filter(pci_address_obj): 1883 | continue 1884 | if mdev_type_filter and not mdev_type_filter(mdev_device.mdev_type): 1885 | continue 1886 | 1887 | pci_device = PCI_DEVICES.find_device(mdev_device.pci_address) 1888 | if pci_device is not None: 1889 | domains = mdev_uuid_to_domain[mdev_device.uuid] 1890 | 1891 | if not domains and mdev_device.nvidia: 1892 | domains = set([mdev_device.nvidia.vm_name]) 1893 | 1894 | for domain in domains: 1895 | if domain and pci_device.driver != "nvidia": 1896 | LOG.warning( 1897 | "GPU %s with PCI address %s has vGPU (MDEV) with UUID %s, but has %s driver instead of " 1898 | "nvidia", 1899 | pci_device.name, 1900 | mdev_device.pci_address, 1901 | mdev_device.uuid, 1902 | pci_device.driver, 1903 | ) 1904 | result = False 1905 | 1906 | if len(domains) > 1: 1907 | LOG.warning( 1908 | "GPU %s with PCI address %s has vGPU (MDEV) with UUID %s but is used by more than one VMs " 1909 | "%s", 1910 | pci_device.name, 1911 | mdev_device.pci_address, 1912 | mdev_device.uuid, 1913 | ", ".join(domains), 1914 | ) 1915 | except FileNotFoundError as e: 1916 | if not e.filename.startswith(MDEV_BUS_DEVICE_PATH): 1917 | raise 1918 | 1919 | return result 1920 | 1921 | 1922 | DEV_CTL: Optional[DevCtl] = None 1923 | 1924 | 1925 | def list_all(args): 1926 | def pci_address_filter(pci_address: PCIAddress) -> bool: 1927 | if not args.pci_addresses: 1928 | return True 1929 | return str(pci_address) in args.pci_addresses 1930 | 1931 | def mdev_type_filter(mdev_type: MdevType) -> bool: 1932 | if not args.mdev_types: 1933 | return True 1934 | return mdev_type.type in args.mdev_types 1935 | 1936 | result = DEV_CTL.print_all_devices( 1937 | pci_address_filter=pci_address_filter, 1938 | mdev_type_filter=mdev_type_filter, 1939 | output_format=args.output_format, 1940 | output_all_columns=args.output_all, 1941 | ) 1942 | return 0 if result else 1 1943 | 1944 | 1945 | def list_pci(args): 1946 | def pci_address_filter(pci_address: PCIAddress) -> bool: 1947 | if not args.pci_addresses: 1948 | return True 1949 | return str(pci_address) in args.pci_addresses 1950 | 1951 | result = DEV_CTL.print_pci_devices( 1952 | pci_address_filter=pci_address_filter, output_format=args.output_format, output_all_columns=args.output_all 1953 | ) 1954 | return 0 if result else 1 1955 | 1956 | 1957 | def list_mdev(args): 1958 | result = False 1959 | 1960 | def pci_address_filter(pci_address: PCIAddress) -> bool: 1961 | if not args.pci_addresses: 1962 | return True 1963 | return str(pci_address) in args.pci_addresses 1964 | 1965 | def mdev_type_filter(mdev_type: MdevType) -> bool: 1966 | if not args.mdev_types: 1967 | return True 1968 | return mdev_type.type in args.mdev_types 1969 | 1970 | try: 1971 | if args.classes or args.all_classes: 1972 | result = DEV_CTL.print_mdev_device_classes( 1973 | pci_address_filter=pci_address_filter, 1974 | mdev_type_filter=mdev_type_filter, 1975 | all_classes=args.all_classes, 1976 | output_all_columns=args.output_all, 1977 | ) 1978 | else: 1979 | result = DEV_CTL.print_mdev_devices( 1980 | pci_address_filter=pci_address_filter, 1981 | mdev_type_filter=mdev_type_filter, 1982 | output_all_columns=args.output_all, 1983 | ) 1984 | except FileNotFoundError as e: 1985 | if e.filename.startswith(MDEV_BUS_DEVICE_PATH): 1986 | LOG.error("Could not access MDEV devices in sysfs: %s", e.filename) 1987 | elif e.filename.startswith(MDEV_BUS_CLASS_PATH): 1988 | LOG.error("Could not access MDEV device classes in sysfs: %s", e.filename) 1989 | else: 1990 | raise 1991 | return 0 if result else 1 1992 | 1993 | 1994 | def list_used_pci(args): 1995 | def pci_address_filter(pci_address: PCIAddress) -> bool: 1996 | if not args.pci_addresses: 1997 | return True 1998 | return str(pci_address) in args.pci_addresses 1999 | 2000 | if DEV_CTL.print_used_pci_devices(pci_address_filter=pci_address_filter, output_format=args.output_format): 2001 | return 0 2002 | else: 2003 | return 1 2004 | 2005 | 2006 | def list_used_mdev(args): 2007 | def pci_address_filter(pci_address: PCIAddress) -> bool: 2008 | if not args.pci_addresses: 2009 | return True 2010 | return str(pci_address) in args.pci_addresses 2011 | 2012 | def mdev_type_filter(mdev_type: MdevType) -> bool: 2013 | if not args.mdev_types: 2014 | return True 2015 | return mdev_type.type in args.mdev_types 2016 | 2017 | if DEV_CTL.print_used_mdev_devices( 2018 | pci_address_filter=pci_address_filter, 2019 | mdev_type_filter=mdev_type_filter, 2020 | output_format=args.output_format, 2021 | output_all_columns=args.output_all, 2022 | ): 2023 | return 0 2024 | else: 2025 | return 1 2026 | 2027 | 2028 | def save_config(args): 2029 | if DEV_CTL.save_config(output_file=args.output_file): 2030 | return 0 2031 | else: 2032 | return 1 2033 | 2034 | 2035 | def restore_config(args): 2036 | if DEV_CTL.restore_config(input_file=args.input_file, dry_run=args.dry_run): 2037 | return 0 2038 | else: 2039 | return 1 2040 | 2041 | 2042 | def bind_driver(args): 2043 | if DEV_CTL.bind_driver(driver=args.driver, devices=args.devices, dry_run=args.dry_run): 2044 | return 0 2045 | else: 2046 | return 1 2047 | 2048 | 2049 | def unbind_driver(args): 2050 | if DEV_CTL.unbind_driver( 2051 | driver=args.driver, 2052 | devices=args.devices, 2053 | ignore_others=args.ignore_others, 2054 | dry_run=args.dry_run, 2055 | ): 2056 | return 0 2057 | else: 2058 | return 1 2059 | 2060 | 2061 | def create_mdev(args): 2062 | mdev_uuid = DEV_CTL.create_mdev( 2063 | pci_address=args.pci_address, 2064 | mdev_type_name=args.mdev_type, 2065 | mdev_uuid=args.mdev_uuid, 2066 | dry_run=args.dry_run, 2067 | ) 2068 | if mdev_uuid: 2069 | print(mdev_uuid) 2070 | return 0 2071 | else: 2072 | return 1 2073 | 2074 | 2075 | def remove_mdev(args): 2076 | if DEV_CTL.remove_mdev(mdev_uuid=args.mdev_uuid, dry_run=args.dry_run): 2077 | return 0 2078 | else: 2079 | return 1 2080 | 2081 | 2082 | def attach_mdev(args): 2083 | if DEV_CTL.attach_mdev( 2084 | mdev_uuid=args.mdev_uuid, 2085 | domain=args.domain, 2086 | hotplug=args.hotplug, 2087 | restart=args.restart, 2088 | dry_run=args.dry_run, 2089 | ): 2090 | return 0 2091 | else: 2092 | return 1 2093 | 2094 | 2095 | def detach_mdev(args): 2096 | if DEV_CTL.detach_mdev( 2097 | mdev_uuid=args.mdev_uuid, 2098 | domain=args.domain, 2099 | hotplug=args.hotplug, 2100 | restart=args.restart, 2101 | dry_run=args.dry_run, 2102 | ): 2103 | return 0 2104 | else: 2105 | return 1 2106 | 2107 | 2108 | def attach_pci(args): 2109 | if DEV_CTL.attach_pci( 2110 | pci_address=args.pci_address, 2111 | domain=args.domain, 2112 | hotplug=args.hotplug, 2113 | restart=args.restart, 2114 | dry_run=args.dry_run, 2115 | ): 2116 | return 0 2117 | else: 2118 | return 1 2119 | 2120 | 2121 | def detach_pci(args): 2122 | if DEV_CTL.detach_pci( 2123 | pci_address=args.pci_address, 2124 | domain=args.domain, 2125 | hotplug=args.hotplug, 2126 | restart=args.restart, 2127 | dry_run=args.dry_run, 2128 | ): 2129 | return 0 2130 | else: 2131 | return 1 2132 | 2133 | 2134 | def restart_services(args): 2135 | if restart_nvidia_services(dry_run=args.dry_run): 2136 | return 0 2137 | else: 2138 | return 1 2139 | 2140 | 2141 | def find_commands(command_names: Sequence[str], issue_warnings=False): 2142 | commands: Dict[str, str] = {} 2143 | all_found = True 2144 | for command_name in command_names: 2145 | command_path = shutil.which(command_name) 2146 | if command_path is not None: 2147 | commands[command_name] = command_path 2148 | else: 2149 | if issue_warnings: 2150 | logfunc = LOG.warning 2151 | else: 2152 | logfunc = LOG.info 2153 | logfunc("The %s command could not be found", command_name) 2154 | all_found = False 2155 | return commands, all_found 2156 | 2157 | 2158 | def main(): 2159 | global DEV_CTL, PCI_DEVICES, COMMANDS 2160 | 2161 | # Override locale for all subprocesses 2162 | os.environ["LC_ALL"] = "C" 2163 | 2164 | default_virsh_connection = None 2165 | # Smart logic to get default libvirt connection 2166 | user_groups = [grp.getgrgid(g).gr_name for g in os.getgroups()] 2167 | if ( 2168 | not os.getenv("LIBVIRT_DEFAULT_URI", None) 2169 | and not os.getenv("VIRSH_DEFAULT_CONNECT_URI", None) 2170 | and ("libvirtd" in user_groups or "libvirt" in user_groups or "kvm" in user_groups) 2171 | ): 2172 | default_virsh_connection = "qemu:///system" 2173 | 2174 | parser = argparse.ArgumentParser( 2175 | description="NVIDIA Device Control", formatter_class=argparse.ArgumentDefaultsHelpFormatter 2176 | ) 2177 | parser.add_argument("--debug", help="debug mode", action="store_true") 2178 | parser = argparse.ArgumentParser() 2179 | parser.add_argument( 2180 | "-l", 2181 | "--log", 2182 | dest="loglevel", 2183 | default="WARNING", 2184 | help="log level (use one of CRITICAL,ERROR,WARNING,INFO,DEBUG)", 2185 | ) 2186 | parser.add_argument( 2187 | "-c", "--connection", metavar="URL", help="virsh connection URL", default=default_virsh_connection 2188 | ) 2189 | parser.add_argument("-w", "--wait", help="wait until mdev bus is available", action="store_true") 2190 | parser.add_argument( 2191 | "--trials", 2192 | type=int, 2193 | default=3, 2194 | metavar="N", 2195 | help="number of trials if waiting for device", 2196 | ) 2197 | parser.add_argument( 2198 | "--delay", 2199 | type=int, 2200 | default=1, 2201 | metavar="SECONDS", 2202 | help="delay time in seconds between trials if waiting for device", 2203 | ) 2204 | 2205 | def register_list_pci_args(argparser): 2206 | argparser.add_argument( 2207 | "-p", 2208 | "--pci-address", 2209 | help="show only devices with specified pci addresses", 2210 | action="append", 2211 | dest="pci_addresses", 2212 | ) 2213 | argparser.add_argument( 2214 | "-o", 2215 | "--output", 2216 | type=str, 2217 | help="output format", 2218 | choices=["table", "text"], 2219 | default="table", 2220 | dest="output_format", 2221 | ) 2222 | argparser.add_argument("-O", "--output-all", help="output all columns", action="store_true") 2223 | argparser.set_defaults(func=list_pci) 2224 | 2225 | def register_list_mdev_args(argparser): 2226 | argparser.add_argument("-c", "--classes", help="print mdev device classes", action="store_true") 2227 | argparser.add_argument( 2228 | "-p", 2229 | "--pci-address", 2230 | help="show only devices with specified pci addresses", 2231 | action="append", 2232 | dest="pci_addresses", 2233 | ) 2234 | argparser.add_argument( 2235 | "-m", 2236 | "--mdev-type", 2237 | help="show only devices with specified mdev types", 2238 | action="append", 2239 | dest="mdev_types", 2240 | ) 2241 | argparser.add_argument("-a", "--all-classes", help="print all mdev device classes", action="store_true") 2242 | argparser.add_argument("-O", "--output-all", help="output all columns", action="store_true") 2243 | argparser.set_defaults(func=list_mdev) 2244 | 2245 | def register_list_all_args(argparser): 2246 | argparser.add_argument( 2247 | "-p", 2248 | "--pci-address", 2249 | help="show only devices with specified pci addresses", 2250 | action="append", 2251 | dest="pci_addresses", 2252 | ) 2253 | argparser.add_argument( 2254 | "-m", 2255 | "--mdev-type", 2256 | help="show only devices with specified mdev types", 2257 | action="append", 2258 | dest="mdev_types", 2259 | ) 2260 | argparser.add_argument( 2261 | "-o", 2262 | "--output", 2263 | type=str, 2264 | help="output format", 2265 | choices=["table", "text"], 2266 | default="table", 2267 | dest="output_format", 2268 | ) 2269 | argparser.add_argument("-O", "--output-all", help="output all columns", action="store_true") 2270 | argparser.set_defaults(func=list_all) 2271 | 2272 | parser.set_defaults(subcommand="list-all") 2273 | register_list_all_args(parser) 2274 | 2275 | subparsers = parser.add_subparsers(title="subcommands", dest="subcommand", metavar="") 2276 | 2277 | list_all_p = subparsers.add_parser("list-all", help="list all NVIDIA devices") 2278 | register_list_all_args(list_all_p) 2279 | 2280 | list_pci_p = subparsers.add_parser("list-pci", help="list NVIDIA PCI devices") 2281 | register_list_pci_args(list_pci_p) 2282 | 2283 | list_mdev_p = subparsers.add_parser("list-mdev", help="list registered mdev devices") 2284 | register_list_mdev_args(list_mdev_p) 2285 | 2286 | list_used_pci_p = subparsers.add_parser("list-used-pci", help="list used NVIDIA PCI devices") 2287 | list_used_pci_p.add_argument( 2288 | "-p", 2289 | "--pci-address", 2290 | help="show only devices with specified pci addresses", 2291 | action="append", 2292 | dest="pci_addresses", 2293 | ) 2294 | list_used_pci_p.add_argument( 2295 | "-o", 2296 | "--output", 2297 | type=str, 2298 | help="output format", 2299 | choices=["table", "text"], 2300 | default="table", 2301 | dest="output_format", 2302 | ) 2303 | list_used_pci_p.set_defaults(func=list_used_pci) 2304 | 2305 | list_used_mdev_p = subparsers.add_parser("list-used-mdev", help="list used mdev devices") 2306 | list_used_mdev_p.add_argument( 2307 | "-p", 2308 | "--pci-address", 2309 | help="show only devices with specified pci addresses", 2310 | action="append", 2311 | dest="pci_addresses", 2312 | ) 2313 | list_used_mdev_p.add_argument( 2314 | "-m", 2315 | "--mdev-type", 2316 | help="show only devices with specified mdev types", 2317 | action="append", 2318 | dest="mdev_types", 2319 | ) 2320 | list_used_mdev_p.add_argument( 2321 | "-o", 2322 | "--output", 2323 | type=str, 2324 | help="output format", 2325 | choices=["table", "text"], 2326 | default="table", 2327 | dest="output_format", 2328 | ) 2329 | list_used_mdev_p.add_argument("-O", "--output-all", help="output all columns", action="store_true") 2330 | list_used_mdev_p.set_defaults(func=list_used_mdev) 2331 | 2332 | create_mdev_p = subparsers.add_parser("create-mdev", help="create new mdev device") 2333 | create_mdev_p.add_argument( 2334 | "pci_address", 2335 | metavar="PCI_ADDRESS", 2336 | help="PCI address of the NVIDIA device where to create new mdev device", 2337 | ) 2338 | create_mdev_p.add_argument("mdev_type", metavar="MDEV_TYPE_OR_NAME", help="mdev device type or type name") 2339 | create_mdev_p.add_argument( 2340 | "-u", 2341 | "--uuid", 2342 | metavar="UUID", 2343 | dest="mdev_uuid", 2344 | help="UUID of the mdev device, if not specified a new will be automatically generated", 2345 | ) 2346 | create_mdev_p.add_argument( 2347 | "-n", 2348 | "--dry-run", 2349 | help="Do everything except actually make changes", 2350 | action="store_true", 2351 | ) 2352 | create_mdev_p.set_defaults(func=create_mdev) 2353 | 2354 | remove_mdev_p = subparsers.add_parser("remove-mdev", help="remove mdev device") 2355 | remove_mdev_p.add_argument("mdev_uuid", metavar="UUID", help="UUID of the mdev device to remove") 2356 | remove_mdev_p.add_argument( 2357 | "-n", 2358 | "--dry-run", 2359 | help="Do everything except actually make changes", 2360 | action="store_true", 2361 | ) 2362 | remove_mdev_p.set_defaults(func=remove_mdev) 2363 | 2364 | save_p = subparsers.add_parser("save", help="dump registered mdev devices") 2365 | save_p.add_argument( 2366 | "-o", 2367 | "--output", 2368 | metavar="FILE", 2369 | help="output mdev devices to file", 2370 | type=argparse.FileType("w"), 2371 | default=sys.stdout, 2372 | dest="output_file", 2373 | ) 2374 | save_p.set_defaults(func=save_config) 2375 | 2376 | restore_p = subparsers.add_parser("restore", help="restore registered mdev devices") 2377 | restore_p.add_argument( 2378 | "-i", 2379 | "--input", 2380 | metavar="FILE", 2381 | help="load mdev devices from file", 2382 | type=argparse.FileType("r"), 2383 | default=sys.stdin, 2384 | dest="input_file", 2385 | ) 2386 | restore_p.add_argument( 2387 | "-n", 2388 | "--dry-run", 2389 | help="Do everything except actually make changes", 2390 | action="store_true", 2391 | ) 2392 | restore_p.set_defaults(func=restore_config) 2393 | 2394 | bind_driver_p = subparsers.add_parser("bind-driver", help="bind driver to devices") 2395 | bind_driver_p.add_argument("driver", metavar="DRIVER", help="bind driver to devices") 2396 | bind_driver_p.add_argument( 2397 | "-n", 2398 | "--dry-run", 2399 | help="Do everything except actually make changes", 2400 | action="store_true", 2401 | ) 2402 | bind_driver_p.add_argument("devices", metavar="PCI_ADDRESS", type=str, nargs="+", help="device PCI address") 2403 | bind_driver_p.set_defaults(func=bind_driver) 2404 | 2405 | unbind_driver_p = subparsers.add_parser("unbind-driver", help="unbind drivers from devices") 2406 | unbind_driver_p.add_argument( 2407 | "-d", 2408 | "--driver", 2409 | metavar="DRIVER", 2410 | help="unbind driver from devices (if not specified unbind any bound driver)", 2411 | ) 2412 | unbind_driver_p.add_argument( 2413 | "-i", 2414 | "--ignore-others", 2415 | help="unbind only specified driver and ignore others", 2416 | action="store_true", 2417 | ) 2418 | unbind_driver_p.add_argument( 2419 | "-n", 2420 | "--dry-run", 2421 | help="Do everything except actually make changes", 2422 | action="store_true", 2423 | ) 2424 | unbind_driver_p.add_argument("devices", metavar="PCI_ADDRESS", type=str, nargs="+", help="device PCI address") 2425 | unbind_driver_p.set_defaults(func=unbind_driver) 2426 | 2427 | restart_services_p = subparsers.add_parser("restart-services", help="restart NVIDIA services") 2428 | restart_services_p.add_argument( 2429 | "-n", 2430 | "--dry-run", 2431 | help="Do everything except actually make changes", 2432 | action="store_true", 2433 | ) 2434 | restart_services_p.set_defaults(func=restart_services) 2435 | 2436 | attach_mdev_p = subparsers.add_parser("attach-mdev", help="attach mdev device to virsh domain (virtual machine)") 2437 | attach_mdev_p.add_argument("mdev_uuid", metavar="UUID", help="UUID of the mdev device to remove") 2438 | attach_mdev_p.add_argument("domain", metavar="DOMAIN", help="domain name, id or uuid") 2439 | attach_mdev_p.add_argument( 2440 | "--hotplug", help="affect the running domain and keep changes after reboot", action="store_true" 2441 | ) 2442 | attach_mdev_p.add_argument( 2443 | "--restart", help="shutdown and reboot the domain after the changes are made", action="store_true" 2444 | ) 2445 | attach_mdev_p.add_argument( 2446 | "-n", 2447 | "--dry-run", 2448 | help="Do everything except actually make changes", 2449 | action="store_true", 2450 | ) 2451 | attach_mdev_p.set_defaults(func=attach_mdev) 2452 | 2453 | detach_mdev_p = subparsers.add_parser("detach-mdev", help="detach mdev device from virsh domain (virtual machine)") 2454 | detach_mdev_p.add_argument("mdev_uuid", metavar="UUID", help="UUID of the mdev device to remove") 2455 | detach_mdev_p.add_argument("domain", metavar="DOMAIN", help="domain name, id or uuid") 2456 | detach_mdev_p.add_argument( 2457 | "--hotplug", help="affect the running domain and keep changes after reboot", action="store_true" 2458 | ) 2459 | detach_mdev_p.add_argument( 2460 | "--restart", help="shutdown and reboot the domain after the changes are made", action="store_true" 2461 | ) 2462 | detach_mdev_p.add_argument( 2463 | "-n", 2464 | "--dry-run", 2465 | help="Do everything except actually make changes", 2466 | action="store_true", 2467 | ) 2468 | detach_mdev_p.set_defaults(func=detach_mdev) 2469 | 2470 | attach_pci_p = subparsers.add_parser("attach-pci", help="attach pci device to virsh domain (virtual machine)") 2471 | attach_pci_p.add_argument("pci_address", metavar="PCI_ADDRESS", help="PCI address of the NVIDIA device to attach") 2472 | attach_pci_p.add_argument("domain", metavar="DOMAIN", help="domain name, id or uuid") 2473 | attach_pci_p.add_argument( 2474 | "--hotplug", help="affect the running domain and keep changes after reboot", action="store_true" 2475 | ) 2476 | attach_pci_p.add_argument( 2477 | "--restart", help="shutdown and reboot the domain after the changes are made", action="store_true" 2478 | ) 2479 | attach_pci_p.add_argument( 2480 | "-n", 2481 | "--dry-run", 2482 | help="Do everything except actually make changes", 2483 | action="store_true", 2484 | ) 2485 | attach_pci_p.set_defaults(func=attach_pci) 2486 | 2487 | detach_pci_p = subparsers.add_parser("detach-pci", help="detach pci device from virsh domain (virtual machine)") 2488 | detach_pci_p.add_argument("pci_address", metavar="PCI_ADDRESS", help="PCI address of the NVIDIA device to attach") 2489 | detach_pci_p.add_argument("domain", metavar="DOMAIN", help="domain name, id or uuid") 2490 | detach_pci_p.add_argument( 2491 | "--hotplug", help="affect the running domain and keep changes after reboot", action="store_true" 2492 | ) 2493 | detach_pci_p.add_argument( 2494 | "--restart", help="shutdown and reboot the domain after the changes are made", action="store_true" 2495 | ) 2496 | detach_pci_p.add_argument( 2497 | "-n", 2498 | "--dry-run", 2499 | help="Do everything except actually make changes", 2500 | action="store_true", 2501 | ) 2502 | detach_pci_p.set_defaults(func=detach_pci) 2503 | 2504 | args = parser.parse_args() 2505 | 2506 | numeric_level = getattr(logging, args.loglevel.upper(), None) 2507 | if not isinstance(numeric_level, int): 2508 | print( 2509 | "Invalid log level: {}, use one of CRITICAL, ERROR, WARNING, INFO, DEBUG".format(args.loglevel), 2510 | file=sys.stderr, 2511 | ) 2512 | return 1 2513 | 2514 | debug_mode = numeric_level == logging.DEBUG 2515 | 2516 | if debug_mode: 2517 | logging.basicConfig( 2518 | format="%(asctime)s %(levelname)s %(pathname)s:%(lineno)s: %(message)s", 2519 | level=numeric_level, 2520 | ) 2521 | else: 2522 | logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s", level=numeric_level) 2523 | 2524 | if default_virsh_connection: 2525 | LOG.info("Selected default URI for the virsh connection: %s", default_virsh_connection) 2526 | if args.connection != default_virsh_connection: 2527 | LOG.info("The user set the URI of the virsh connection to: %s", args.connection) 2528 | 2529 | args = parser.parse_args() 2530 | # If args.subcommand is overwritten with None, restore the default value 2531 | if not args.subcommand: 2532 | args.subcommand = parser.get_default("subcommand") 2533 | 2534 | # Try to find all commands 2535 | found_commands, all_found = find_commands(COMMANDS.keys(), issue_warnings=(sys.platform == "win32")) 2536 | if not all_found and sys.platform != "win32": 2537 | # Try to fix paths 2538 | paths = os.environ.get("PATH", os.defpath).split(os.pathsep) 2539 | for bin_path in ("/usr/local/bin", "/usr/bin", "/usr/local/sbin", "/usr/sbin"): 2540 | if bin_path not in paths and os.path.exists(bin_path): 2541 | paths.append(bin_path) 2542 | LOG.info("Add the path %s to the environment variable PATH", bin_path) 2543 | os.environ["PATH"] = os.pathsep.join(paths) 2544 | found_commands, all_found = find_commands(COMMANDS.keys(), issue_warnings=True) 2545 | COMMANDS.update(found_commands) 2546 | LOG.debug("Found commands %s", COMMANDS) 2547 | 2548 | PCI_DEVICES = PCIDevices() 2549 | 2550 | try: 2551 | DEV_CTL = DevCtl( 2552 | wait_for_device=args.wait, 2553 | num_trials=args.trials, 2554 | wait_delay=args.delay, 2555 | virsh_connection=args.connection, 2556 | debug=debug_mode, 2557 | ) 2558 | except DevCtlException: 2559 | logging.exception("Cloud not create DevCtl") 2560 | return 1 2561 | 2562 | try: 2563 | result = args.func(args) 2564 | except DevCtlException: 2565 | LOG.exception("Could not execute %s command", args.subcommand) 2566 | return 1 2567 | except PermissionError: 2568 | LOG.exception( 2569 | "Could not execute %s command, try to run this command as root", 2570 | args.subcommand, 2571 | ) 2572 | return 1 2573 | 2574 | if result is None: 2575 | result = 0 2576 | return result 2577 | 2578 | 2579 | if __name__ == "__main__": 2580 | sys.exit(main()) 2581 | -------------------------------------------------------------------------------- /nvidia-dev-ctl.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Restore NVIDIA mdev devices 3 | After=nvidia-vgpu-mgr.service 4 | ConditionPathExists=/etc/nvidia-mdev-devices.conf 5 | 6 | [Service] 7 | Type=oneshot 8 | #ExecStartPre=/usr/bin/test ! -d /sys/class/mdev_bus/ 9 | ExecStart=/usr/bin/nvidia-dev-ctl.py --wait --delay=1 --trials=60 restore -i /etc/nvidia-mdev-devices.conf 10 | # Restart=on-failure 11 | 12 | [Install] 13 | WantedBy=multi-user.target 14 | -------------------------------------------------------------------------------- /nvidia-shlib.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright (C) 2020 Dmitri Rubinstein 4 | # NVIDIA Shell Utility Library 5 | # 6 | # Documentation 7 | # https://cubiclenate.com/2019/10/31/power-cycling-pcie-devices-from-the-command-line/ 8 | # https://nvidia.custhelp.com/app/answers/detail/a_id/3751/~/useful-nvidia-smi-queries 9 | 10 | rtrim() { 11 | echo -n "${1%"${1##*[![:space:]]}"}" 12 | } 13 | 14 | trim() { 15 | local var="$1" 16 | var="${var#"${var%%[![:space:]]*}"}" # remove leading whitespace characters 17 | var="${var%"${var##*[![:space:]]}"}" # remove trailing whitespace characters 18 | echo -n "$var" 19 | } 20 | 21 | # https://stackoverflow.com/questions/1527049/how-can-i-join-elements-of-an-array-in-bash 22 | join-by() { 23 | local d=$1; shift; local f=$1; shift; printf %s "$f" "${@/#/$d}" 24 | } 25 | 26 | get-nvidia-pci-devices() { 27 | local dev vendor 28 | for dev in /sys/bus/pci/devices/*; do 29 | if [[ -e "$dev/vendor" ]]; then 30 | vendor=$(trim "$(< "$dev/vendor")") 31 | if [[ "$vendor" = "0x10de" ]]; then 32 | printf "%s " "$(basename -- "$dev")" 33 | fi 34 | fi 35 | done 36 | printf "\n" 37 | } 38 | 39 | # $1 - driver 40 | # $2 ... - devices 41 | unbind-driver-from-devices() { 42 | local driver dev 43 | driver=$1 44 | shift 45 | if [[ ! -e "/sys/bus/pci/drivers/$driver" ]]; then 46 | echo >&2 "unbind-driver-from-devices: No driver interface /sys/bus/pci/drivers/$driver" 47 | return 1 48 | fi 49 | if [[ ! -e "/sys/bus/pci/drivers/$driver/unbind" ]]; then 50 | echo >&2 "unbind-driver-from-devices: No unbind interface: /sys/bus/pci/drivers/$driver/unbind" 51 | return 1 52 | fi 53 | for dev in "$@"; do 54 | if [[ -e "/sys/bus/pci/drivers/$driver/$dev" ]]; then 55 | echo >&2 "unbind-driver-from-devices: Unbind driver $driver from PCI device $dev" 56 | echo "$dev" > "/sys/bus/pci/drivers/$driver/unbind" 57 | else 58 | echo >&2 "unbind-driver-from-devices: Driver $driver is not loaded for device $dev" 59 | fi 60 | done 61 | } 62 | 63 | # $1 ... - devices 64 | unbind-device-drivers() { 65 | local dev driver 66 | for dev in "$@"; do 67 | if driver=$(get-driver-of-device "$dev"); then 68 | unbind-driver-from-devices "$driver" "$dev" 69 | fi 70 | done 71 | } 72 | 73 | # $1 ... - devices 74 | remove-devices() { 75 | local dev 76 | for dev in "$@"; do 77 | if [[ -e "/sys/bus/pci/devices/$dev" && -e "/sys/bus/pci/devices/$dev/remove" ]]; then 78 | unbind-device-drivers "$dev" 79 | if driver=$(get-driver-of-device "$dev"); then 80 | echo >&2 "remove-devices: Could not remove driver $driver from device $dev" 81 | continue 82 | fi 83 | echo "1" > "/sys/bus/pci/devices/$dev/remove" 84 | echo >&2 "remove-devices: Removed device $dev" 85 | else 86 | echo >&2 "remove-devices: No path /sys/bus/pci/devices/$dev or /sys/bus/pci/devices/$dev/remove" 87 | return 1 88 | fi 89 | done 90 | } 91 | 92 | # $1 ... - devices 93 | reset-devices() { 94 | local dev 95 | for dev in "$@"; do 96 | if [[ -e "/sys/bus/pci/devices/$dev" && -e "/sys/bus/pci/devices/$dev/reset" ]]; then 97 | unbind-device-drivers "$dev" 98 | if driver=$(get-driver-of-device "$dev"); then 99 | echo >&2 "remove-devices: Could not remove driver $driver from device $dev" 100 | continue 101 | fi 102 | echo "1" > "/sys/bus/pci/devices/$dev/reset" 103 | echo >&2 "remove-devices: Reset device $dev" 104 | else 105 | echo >&2 "remove-devices: No path /sys/bus/pci/devices/$dev or /sys/bus/pci/devices/$dev/reset" 106 | return 1 107 | fi 108 | done 109 | } 110 | 111 | # $1 - device 112 | get-driver-of-device() { 113 | local dev driver_path 114 | dev=$1 115 | if [[ -z "$dev" ]]; then 116 | echo >&2 "get-driver-of-device: no device specified" 117 | return 1 118 | fi 119 | if [[ ! -e "/sys/bus/pci/devices/$dev/driver" ]]; then 120 | echo >&2 "get-driver-of-device: path /sys/bus/pci/devices/$dev/driver does not exist" 121 | return 1 122 | fi 123 | driver_path=$(readlink -f "/sys/bus/pci/devices/$dev/driver") 124 | basename -- "$driver_path" 125 | } 126 | 127 | # $1 - driver 128 | # $2 ... - PCI device ID 129 | bind-driver-to-devices() { 130 | local driver dev driver_override_path 131 | driver=$1 132 | shift 133 | for dev in "$@"; do 134 | driver_override_path=/sys/bus/pci/devices/$dev/driver_override 135 | if [[ ! -e "$driver_override_path" ]]; then 136 | echo >&2 "Missing driver_override interface: $driver_override_path" 137 | continue 138 | fi 139 | echo >&2 "bind-driver-to-devices: Bind driver $driver to device $dev" 140 | echo "$driver" > "$driver_override_path" 141 | if [[ ! -e "/sys/bus/pci/drivers/$driver" ]]; then 142 | echo >&2 "Driver $driver missing, try loading it first" 143 | modprobe "$driver" 144 | if [[ "$driver" = "nvidia" ]]; then 145 | modprobe nvidia_vgpu_vfio 146 | fi 147 | fi 148 | if [[ ! -e "/sys/bus/pci/drivers/$driver" ]]; then 149 | echo >&2 "Driver $driver missing, no path /sys/bus/pci/drivers/$driver" 150 | return 1 151 | fi 152 | { echo "$dev" > "/sys/bus/pci/drivers/$driver/bind" || true; } 2>/dev/null; 153 | done 154 | # if [[ "$driver" = "nvidia" ]]; then 155 | # systemctl restart nvidia-vgpud.service 156 | # systemctl restart nvidia-vgpu-mgr.service 157 | # fi 158 | } 159 | 160 | # rmmod nvidia_vgpu_vfio 161 | # rmmod nvidia 162 | # rmmod mdev 163 | # rmmod vfio_mdev 164 | # rmmod mdev 165 | 166 | get-service-exit-code() { 167 | systemctl show -p ExecMainStatus "$1" | sed 's/ExecMainStatus=//g' 168 | } 169 | 170 | check-nvidia-mdev() { 171 | local gpus g 172 | if [[ ! -e "/sys/class/mdev_bus" ]]; then 173 | echo >&2 "check-nvidia-mdev: Missing mdev_bus path /sys/class/mdev_bus" 174 | return 1 175 | fi 176 | if [[ $# -gt 0 ]]; then 177 | gpus=$* 178 | else 179 | gpus=$(get-nvidia-pci-devices) 180 | fi 181 | for g in $gpus; do 182 | driver=$(get-driver-of-device "$g") 183 | if [[ "$driver" = "nvidia" && ! -e "/sys/class/mdev_bus/$g" ]]; then 184 | echo >&2 "check-nvidia-mdev: Missing mdev_bus for device: $g" 185 | return 1 186 | fi 187 | done 188 | return 0 189 | } 190 | 191 | restart-nvidia-services() { 192 | local svc 193 | for svc in nvidia-vgpud.service nvidia-vgpu-mgr.service; do 194 | echo >&2 "restart-nvidia-services: Restartig service $svc" 195 | systemctl restart "$svc" 196 | sleep 5 197 | if [[ "$(get-service-exit-code "$svc")" != "0" ]]; then 198 | echo >&2 "restart-nvidia-services: Service $svc failed" 199 | return 1 200 | else 201 | echo >&2 "restart-nvidia-services: Service $svc successfully restarted" 202 | fi 203 | done 204 | return 0 205 | } 206 | 207 | is-driver-loaded() { 208 | # disabling pipefail required because grep will stop after first match 209 | # https://stackoverflow.com/questions/19120263/why-exit-code-141-with-grep-q 210 | set +o pipefail 211 | if lsmod | grep -Eq "^$1 "; then 212 | set -o pipefail 213 | return 0 214 | fi 215 | return 1 216 | } 217 | 218 | # $1 pci address 219 | is-gpu-ok-adhoc() { 220 | local driver 221 | driver=$(get-driver-of-device "$1") 222 | if [[ "$driver" != "nvidia" ]]; then 223 | return 1 224 | fi 225 | # disabling pipefail required because grep will stop after first match 226 | # https://stackoverflow.com/questions/19120263/why-exit-code-141-with-grep-q 227 | set +o pipefail 228 | if sudo lspci -n -s "$1" -vv | grep -q "Latency Tolerance Reporting"; then 229 | set -o pipefail 230 | return 1 231 | fi 232 | return 0 233 | } 234 | 235 | # $1 pci address 236 | is-gpu-ok() { 237 | local driver 238 | # disabling pipefail required because grep will stop after first match 239 | # https://stackoverflow.com/questions/19120263/why-exit-code-141-with-grep-q 240 | driver=$(get-driver-of-device "$1") 241 | if [[ "$driver" != "nvidia" ]]; then 242 | return 1 243 | fi 244 | nvidia-smi --query-gpu=pci.bus_id,vbios_version -i "$1" --format=csv,noheader &>/dev/null 245 | } 246 | 247 | get-all-failed-nvidia-pci-devices() { 248 | dmesg -T | sed -E -e '/RmInitAdapter failed!/!d; s/^.*NVRM: GPU ([[:alnum:]]{4}:[[:alnum:]]{2}:[[:alnum:]]{2}.[[:alnum:]]).*$/\1/g' | sort -u 249 | } 250 | 251 | LAST_FAILED_DEVICES_FILE=/tmp/last-failed-nvidia-devices-$(id -un).txt 252 | rm -f "$LAST_FAILED_DEVICES_FILE" 253 | 254 | # shellcheck disable=SC2120 255 | get-last-failed-nvidia-pci-devices() { 256 | local failed_devices skip_num_failed_devices 257 | declare -a failed_devices_array last_failed_devices_array 258 | failed_devices=$(dmesg | sed -E -e '/RmInitAdapter failed!/!d; s/^.*NVRM: GPU ([[:alnum:]]{4}:[[:alnum:]]{2}:[[:alnum:]]{2}.[[:alnum:]]).*$/\1/g') 259 | IFS=$'\n' read -rd '' -a failed_devices_array <<<"$failed_devices" 260 | if [[ -e "$LAST_FAILED_DEVICES_FILE" ]]; then 261 | IFS=$'\n' read -rd '' -a last_failed_devices_array < "$LAST_FAILED_DEVICES_FILE" 262 | skip_num_failed_devices=${#last_failed_devices_array[@]} 263 | else 264 | skip_num_failed_devices=0 265 | fi 266 | if [[ "$1" != "--forget-last" ]]; then 267 | printf "%s" "$failed_devices" > "$LAST_FAILED_DEVICES_FILE" 268 | fi 269 | if [[ -n "$skip_num_failed_devices" && "$skip_num_failed_devices" -gt 0 ]]; then 270 | failed_devices=$(join-by $'\n' "${failed_devices_array[@]:$skip_num_failed_devices}") 271 | # failed_devices=$(sed "1,${SKIP_NUM_FAILED_DEVICES}d" <<<"$failed_devices") 272 | # IFS=$'\n' read -rd '' -a failed_array <<<"$failed" 273 | # num_failed=${#failed_array[@]} 274 | fi 275 | if [[ -n "$failed_devices" ]]; then 276 | sort -u <<<"$failed_devices" | tr '\n' ' ' 277 | fi 278 | } 279 | 280 | is-nvidia-mdev-ok() { 281 | local do_fix gpus driver 282 | if ! is-driver-loaded nvidia; then 283 | echo >&2 "is-nvidia-mdev-ok: Module nvidia is not loaded, nothing to check" 284 | return 0 285 | else 286 | echo >&2 "is-nvidia-mdev-ok: Module nvidia is loaded, check if everything is ok" 287 | fi 288 | if [[ $# -gt 0 ]]; then 289 | gpus=$* 290 | else 291 | gpus=$(get-nvidia-pci-devices) 292 | fi 293 | if [[ -z "$gpus" ]]; then 294 | echo >&2 "is-nvidia-mdev-ok: Fatal error: no NVIDIA PCI devices specified or detected" 295 | return 2 296 | fi 297 | # shellcheck disable=SC2086 298 | if check-nvidia-mdev $gpus; then 299 | echo >&2 "is-nvidia-mdev-ok: All mdev_bus devices present, nothing to fix" 300 | return 0 301 | else 302 | do_fix=true 303 | echo >&2 "is-nvidia-mdev-ok: Some mdev_bus devices missing" 304 | fi 305 | #for gpu in $gpus; do 306 | # driver=$(get-driver-of-device "$gpu") 307 | # if [[ "$driver" = "nvidia" ]] && ! is-gpu-ok "$gpu"; then 308 | # echo >&2 "is-nvidia-mdev-ok: GPU $gpu reports failure" 309 | # do_fix=true 310 | # fi 311 | #done 312 | set +o pipefail 313 | if dmesg | grep -q "RmInitAdapter failed"; then 314 | set -o pipefail 315 | do_fix=true 316 | echo >&2 "is-nvidia-mdev-ok: 'RmInitAdapter failed' error detected" 317 | fi 318 | set -o pipefail 319 | if [[ -z "$do_fix" ]]; then 320 | echo >&2 "is-nvidia-mdev-ok: No problems detected, nothing to fix" 321 | return 0 322 | fi 323 | return 1 324 | } 325 | 326 | unload-nvidia-drivers() { 327 | local d 328 | for d in nvidia_vgpu_vfio vfio_mdev mdev nvidia; do 329 | if is-driver-loaded "$d"; then 330 | echo >&2 "fix-nvidia-mdev: Unload driver $d" 331 | if ! modprobe -r "$d"; then 332 | echo >&2 "fix-nvidia-mdev: Failed unloading driver $d" 333 | return 1 334 | fi 335 | else 336 | echo >&2 "fix-nvidia-mdev: Driver $d is not loaded" 337 | fi 338 | done 339 | return 0 340 | } 341 | 342 | rescan-pci-bus() { 343 | echo "1" > /sys/bus/pci/rescan 344 | } 345 | 346 | # $1 ... - PCI device IDs 347 | fix-nvidia-mdev() { 348 | local do_fix gpus d g 349 | if [[ $# -gt 0 ]]; then 350 | gpus=$* 351 | else 352 | gpus=$(get-nvidia-pci-devices) 353 | fi 354 | if [[ -z "$gpus" ]]; then 355 | echo >&2 "fix-nvidia-mdev: Fatal error: no NVIDIA PCI devices specified or detected" 356 | return 1 357 | fi 358 | # shellcheck disable=SC2086 359 | if is-nvidia-mdev-ok $gpus; then 360 | return 0 361 | fi 362 | echo >&2 "fix-nvidia-mdev: Unbinding NVIDIA PCI devices: $gpus" 363 | # shellcheck disable=SC2086 364 | unbind-driver-from-devices nvidia $gpus 365 | echo >&2 "fix-nvidia-mdev: Unload NVIDIA drivers" 366 | if ! unload-nvidia-drivers; then 367 | return 1 368 | fi 369 | echo >&2 "fix-nvidia-mdev: nvidia drivers" 370 | lsmod | grep nv 371 | echo >&2 "fix-nvidia-mdev: pause" 372 | sleep 5 373 | echo >&2 "fix-nvidia-mdev: reload drivers" 374 | if ! modprobe nvidia_vgpu_vfio; then 375 | echo >&2 "fix-nvidia-mdev: Failed loading nvidia_vgpu_vfio" 376 | return 1 377 | fi 378 | # (set -x; modprobe -r nvidia_vgpu_vfio nvidia vfio_mdev mdev;) 379 | #for d in nvidia_vgpu_vfio nvidia vfio_mdev mdev; do echo "Unload driver $d"; rmmod "$d" || true; done 380 | 381 | #for d in nvidia nvidia_vgpu_vfio; do 382 | # echo "Loading driver: $d" 383 | # modprobe "$d" 384 | #done 385 | # (set -x; modprobe nvidia; modprobe nvidia_vgpu_vfio;) 386 | echo >&2 "fix-nvidia-mdev: restart NVIDIA mdev services" 387 | if ! restart-nvidia-services; then 388 | return 1 389 | fi 390 | sleep 10 391 | # shellcheck disable=SC2086 392 | is-nvidia-mdev-ok $gpus 393 | } 394 | 395 | fix-nvidia-mdev-2() { 396 | local gpus 397 | # shellcheck disable=SC2086 398 | if is-nvidia-mdev-ok $gpus; then 399 | return 0 400 | fi 401 | gpus=$(get-nvidia-pci-devices) 402 | # shellcheck disable=SC2086 403 | unbind-device-drivers $gpus 404 | unload-nvidia-drivers 405 | # shellcheck disable=SC2086 406 | remove-devices $gpus 407 | unload-nvidia-drivers 408 | echo >&2 "fix-nvidia-mdev-2: rescan PCI bus" 409 | echo "1" > /sys/bus/pci/rescan 410 | echo >&2 "fix-nvidia-mdev-2: pause" 411 | sleep 5 412 | echo >&2 "fix-nvidia-mdev-2: restart NVIDIA mdev services" 413 | if ! restart-nvidia-services; then 414 | return 1 415 | fi 416 | sleep 10 417 | # shellcheck disable=SC2086 418 | check-nvidia-mdev $gpus 419 | } 420 | 421 | fix-nvidia-mdev-3() { 422 | local gpus failed_devices 423 | gpus=$(get-nvidia-pci-devices) 424 | # shellcheck disable=SC2086 425 | rebind-devices-to-nvidia $gpus 426 | # shellcheck disable=SC2086 427 | if is-nvidia-mdev-ok $gpus; then 428 | return 0 429 | fi 430 | failed_devices=$(get-last-failed-nvidia-pci-devices) 431 | echo >&2 "fix-nvidia-mdev-3: failed NVIDIA devices: $failed_devices" 432 | echo >&2 "fix-nvidia-mdev-3: run nvidia-smi for driver initialization" 433 | nvidia-smi 434 | failed_devices=$(get-last-failed-nvidia-pci-devices) 435 | if [[ -n "$failed_devices" ]]; then 436 | echo >&2 "fix-nvidia-mdev-3: failed NVIDIA devices after nvidia-smi: $failed_devices" 437 | # we have an error and need to fix 438 | echo >&2 "fix-nvidia-mdev-3: reset failed NVIDIA devices: $failed_devices" 439 | # shellcheck disable=SC2086 440 | reset-devices $failed_devices 441 | echo >&2 "fix-nvidia-mdev-3: rebind failed NVIDIA devices: $failed_devices" 442 | # shellcheck disable=SC2086 443 | rebind-devices-to-nvidia $failed_devices 444 | echo >&2 "fix-nvidia-mdev-3: run nvidia-smi for driver initialization" 445 | nvidia-smi 446 | failed_devices=$(get-last-failed-nvidia-pci-devices) 447 | if [[ -n "$failed_devices" ]]; then 448 | echo >&2 "fix-nvidia-mdev-3: failed NVIDIA devices after nvidia-smi: $failed_devices" 449 | else 450 | echo >&2 "fix-nvidia-mdev-3: no failed NVIDIA devices after nvidia-smi !" 451 | fi 452 | echo >&2 "fix-nvidia-mdev-3: waiting for 15 seconds..." 453 | sleep 15 454 | failed_devices=$(get-last-failed-nvidia-pci-devices) 455 | if [[ -n "$failed_devices" ]]; then 456 | echo >&2 "fix-nvidia-mdev-3: failed NVIDIA devices after waiting: $failed_devices" 457 | else 458 | echo >&2 "fix-nvidia-mdev-3: no failed NVIDIA devices after waiting !" 459 | fi 460 | fi 461 | 462 | echo >&2 "fix-nvidia-mdev-3: restart NVIDIA services" 463 | if ! restart-nvidia-services; then 464 | return 1 465 | fi 466 | for ((i = 1 ; i <= 30; i++)); do 467 | # shellcheck disable=SC2086 468 | if is-nvidia-mdev-ok $gpus; then 469 | return 0 470 | fi 471 | sleep 2 472 | done 473 | # shellcheck disable=SC2086 474 | is-nvidia-mdev-ok $gpus 475 | } 476 | 477 | print-drivers() { 478 | local gpus dev driver 479 | if [[ $# -gt 0 ]]; then 480 | gpus=$* 481 | else 482 | gpus=$(get-nvidia-pci-devices) 483 | fi 484 | for dev in $gpus; do 485 | if ! driver=$(get-driver-of-device "$dev" 2>/dev/null); then 486 | driver="no driver" 487 | fi 488 | echo "$dev $driver" 489 | done 490 | } 491 | 492 | rebind-devices-to-nvidia() { 493 | local gpus dev driver 494 | if [[ $# -gt 0 ]]; then 495 | gpus=$* 496 | else 497 | gpus=$(get-nvidia-pci-devices) 498 | fi 499 | 500 | for dev in $gpus; do 501 | driver=$(get-driver-of-device "$dev" 2>/dev/null) 502 | if [[ "$driver" != "nvidia" && -n "$driver" ]]; then 503 | unbind-driver-from-devices "$driver" "$dev" 504 | sleep 1 505 | fi 506 | bind-driver-to-devices nvidia "$dev" 507 | done 508 | } 509 | 510 | # # Unbind PCI passtrough 511 | # GPUS=$(get-nvidia-pci-devices) 512 | # unbind-driver-from-devices vfio-pci $GPUS 513 | # bind-driver-to-devices nvidia $GPUS 514 | # 515 | # 516 | # # After reboot and 517 | # # dmesg | grep MDEV -> empty 518 | # # dmesg | grep RmInitAdapter -> non empty 519 | # unbind-driver-from-devices nvidia $GPUS 520 | # for d in nvidia_vgpu_vfio nvidia vfio_mdev mdev; do echo "Unload driver $d"; rmmod "$d" || true; done 521 | # modprobe nvidia 522 | # modprobe nvidia_vgpu_vfio 523 | # systemctl restart nvidia-vgpud.service 524 | # systemctl restart nvidia-vgpu-mgr.service 525 | 526 | # Sometimes nvidia driver is in use and you can't unload it -> nothing possible with the safe method 527 | # Twice I needed to reset the server because it was not booting 528 | # If GPU has an "RmInitAdapter failed!" error I can fix other devices but not the one with the error with the safe method 529 | # Successful tests hard method 530 | # Test x3 ok 531 | # Test #4 failed : 532 | # Jul 31 21:57:45 asr-telaviv nvidia-vgpud[4470]: error: failed to attach device: 59 533 | # Jul 31 21:57:45 asr-telaviv nvidia-vgpud[4470]: error: failed to read pGPU information: 9 534 | # Jul 31 21:57:45 asr-telaviv nvidia-vgpud[4470]: error: failed to send vGPU configuration info to RM: 9 535 | 536 | enable-pci-passtrough() { 537 | local pci_ids 538 | # Comma delimited list of PCI device IDs 539 | pci_ids=$(lspci -nn | sed -E '/[Nn][Vv][Ii][Dd][Ii][Aa]/!d;s/.*\[([[:xdigit:]]{4}:[[:xdigit:]]{4})\].*/\1,/' | sort -u | tr -d '\n' | sed 's/,$//';) 540 | echo "options vfio-pci ids=$pci_ids" > /etc/modprobe.d/vfio.conf 541 | echo 'vfio-pci' > /etc/modules-load.d/vfio-pci.conf 542 | } 543 | 544 | disable-pci-passtrough() { 545 | rm -f /etc/modprobe.d/vfio.conf /etc/modules-load.d/vfio-pci.conf 546 | } 547 | --------------------------------------------------------------------------------