pax_global_header00006660000000000000000000000064146565736070014535gustar00rootroot0000000000000052 comment=af8d735fae286e7bc94c830a86c960598a4ac014 libdfx-2024.2.0/000077500000000000000000000000001465657360700132345ustar00rootroot00000000000000libdfx-2024.2.0/CMakeLists.txt000066400000000000000000000010461465657360700157750ustar00rootroot00000000000000#*************************************************************** #* Copyright (c) 2020 Xilinx, Inc. All rights reserved. #* SPDX-License-Identifier: MIT #*************************************************************** # Specify the minimum version for CMake cmake_minimum_required(VERSION 2.8.9) project(libdfx C) OPTION(ENABLE_LIBDFX_TIME, OFF) IF(ENABLE_LIBDFX_TIME) add_compile_definitions(ENABLE_LIBDFX_TIME) endif(ENABLE_LIBDFX_TIME) #link_directories(${CMAKE_BINARY_DIR}/lib) # Project's name add_subdirectory(src) add_subdirectory(apps) libdfx-2024.2.0/LICENSE.md000066400000000000000000000447751465657360700146610ustar00rootroot00000000000000Software License Agreement ========================== MIT --- Copyright (c) Xilinx Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GPL-2.0 ------- Copyright (c) Xilinx Inc Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) < yyyy> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. Notes ========================================= Use the following tag instead of the full license text in the individual files: SPDX-License-Identifier: MIT SPDX-License-Identifier: GPL-2.0 This enables machine processing of license information based on the SPDX License Identifiers that are here available: http://spdx.org/licenses/ libdfx-2024.2.0/README.md000066400000000000000000000023501465657360700145130ustar00rootroot00000000000000 * Copyright (c) 2020 Xilinx, Inc. All rights reserved. * Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved. * SPDX-License-Identifier: MIT Introduction ============ libdfx.git - The library is a lightweight user-space library that provides APIs for application to configure the PL. The libdfx software is divided into following directories: - apps illustrating different use cases of DFX Configuration. - cmake Contains information about the toolchain. - doc Contains information about the libdfx repo. - src driver interface code implementing functionality Building libdfx from git: ============================== 1. Clone libdfx.git repo 2. mkdir build 3. cd build 4. Ensure required tool chain added to your path 5. cmake -DCMAKE_TOOLCHAIN_FILE="cmake tool chain file(complete path)" ../ Example: cmake -DCMAKE_TOOLCHAIN_FILE="/libdfx/cmake/toolchain.cmake" ../ 6. make Once the build is successfully completed the library static, shared object files and app elf file are available in the below paths. -build/src/libdfx.a -build/src/libdfx.so.1.0 -build/apps/dfx_app Note: Libdfx is currently limited to supporting Zynq UltraScale+ MPSoC and Versal platforms. For more information refer doc/README.txt. libdfx-2024.2.0/apps/000077500000000000000000000000001465657360700141775ustar00rootroot00000000000000libdfx-2024.2.0/apps/CMakeLists.txt000066400000000000000000000007461465657360700167460ustar00rootroot00000000000000#*************************************************************** #* Copyright (c) 2020 Xilinx, Inc. All rights reserved. #* Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved. #* SPDX-License-Identifier: MIT #*************************************************************** # Specify the minimum version for CMake cmake_minimum_required(VERSION 2.8.9) # Project's name project(dfx_app) add_executable(dfx_app libdfx_app.c) target_link_libraries(dfx_app dfx_static) libdfx-2024.2.0/apps/libdfx_app.c000066400000000000000000000073201465657360700164550ustar00rootroot00000000000000/*************************************************************** * Copyright (c) 2020 Xilinx, Inc. All rights reserved. * Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved. * SPDX-License-Identifier: MIT ***************************************************************/ /*This example programs the FPGA to have The base FPGA Region(static) * with One PR region (This PR region has two RM's). * * Configure Base Image * -->Also called the "static image" * An FPGA image that is designed to do full reconfiguration of the FPGA * A base image may set up a set of partial reconfiguration regions that * may later be reprogrammed. * -->DFX_EXTERNAL_CONFIG flag should be set if the FPGA has already been * configured prior to OS boot up. * * Configure the PR Images * -->An FPGA set up with a base image that created a PR region. * The contents of each PR may have multiple Reconfigurable Modules * This RM's(PR0-RM0, PR0-RM1) are reprogrammed independently while * the rest of the system continues to function. */ #include #include "libdfx.h" int main() { int package_id_full, package_id_pr0_rm0, package_id_pr0_rm1, ret; /* package FULL Initilization */ package_id_full = dfx_cfg_init("/media/full/", 0, DFX_EXTERNAL_CONFIG_EN); if (package_id_full < 0) return -1; printf("dfx_cfg_init: FULL Package completed successfully\r\n"); /* package PR0-RM0 Initilization */ package_id_pr0_rm0 = dfx_cfg_init("/media/pr0-rm0/", 0, 0); if (package_id_pr0_rm0 < 0) return -1; printf("dfx_cfg_init: PR0-RM0 Package completed successfully\r\n"); /* package PR0-RM1 Initilization */ package_id_pr0_rm1 = dfx_cfg_init("/media/pr0-rm1/", 0, 0); if (package_id_pr0_rm1 < 0) return -1; printf("dfx_cfg_init: PR0-RM1 Package completed successfully\r\n"); /* Package FULL load */ ret = dfx_cfg_load(package_id_full); if (ret) { dfx_cfg_destroy(package_id_full); return -1; } printf("dfx_cfg_load: FULL Package completed successfully\r\n"); /* Package PR0-RM0 load */ ret = dfx_cfg_load(package_id_pr0_rm0); if (ret) { dfx_cfg_destroy(package_id_pr0_rm0); return -1; } printf("dfx_cfg_load: PR0-RM0 Package completed successfully\r\n"); /* Remove PR0-RM0 package */ ret = dfx_cfg_remove(package_id_pr0_rm0); if (ret) return -1; printf("dfx_cfg_remove: PR0-RM0 Package completed successfully\r\n"); /* Package PR0-RM1 load */ ret = dfx_cfg_load(package_id_pr0_rm1); if (ret) { dfx_cfg_destroy(package_id_pr0_rm1); return -1; } printf("dfx_cfg_load: PR0-RM1 Package completed successfully\r\n"); /* Remove PR0-RM1 package */ ret = dfx_cfg_remove(package_id_pr0_rm1); if (ret) return -1; printf("dfx_cfg_remove: PR0-RM1 Package completed successfully\r\n"); /* Remove Full package */ ret = dfx_cfg_remove(package_id_full); if (ret) return -1; printf("dfx_cfg_remove: FULL Package completed successfully\r\n"); /* Destroy PR0_RM0 package */ ret = dfx_cfg_destroy(package_id_pr0_rm0); if (ret) return -1; printf("dfx_cfg_destroy: PR0-RM0 Package completed successfully\r\n"); /* Destroy PR0_RM1 package */ ret = dfx_cfg_destroy(package_id_pr0_rm1); if (ret) return -1; printf("dfx_cfg_destroy: PR0-RM1 Package completed successfully\r\n"); /* Destroy Full package */ ret = dfx_cfg_destroy(package_id_full); if (ret) return -1; printf("dfx_cfg_destroy: FULL Package completed successfully\r\n"); return 0; } libdfx-2024.2.0/cmake/000077500000000000000000000000001465657360700143145ustar00rootroot00000000000000libdfx-2024.2.0/cmake/toolchain.cmake000066400000000000000000000013231465657360700172750ustar00rootroot00000000000000#*************************************************************** #* Copyright (c) 2020 Xilinx, Inc. All rights reserved. #* SPDX-License-Identifier: MIT #*************************************************************** set (CMAKE_SYSTEM_PROCESSOR "aarch64" CACHE STRING "") set (CROSS_PREFIX "aarch64-linux-gnu-" CACHE STRING "") set (CMAKE_SYSTEM_NAME "Linux" CACHE STRING "") set (CMAKE_C_COMPILER "${CROSS_PREFIX}gcc" CACHE STRING "") set (CMAKE_CXX_COMPILER "${CROSS_PREFIX}g++" CACHE STRING "") set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER CACHE STRING "") set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER CACHE STRING "") set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER CACHE STRING "") libdfx-2024.2.0/doc/000077500000000000000000000000001465657360700140015ustar00rootroot00000000000000libdfx-2024.2.0/doc/README.txt000077500000000000000000000364611465657360700155140ustar00rootroot00000000000000libdfx - README ->Introduction ->Limitations ->Images required for Testing ->API Details ->Example Application flow ->Build procedure ============= Introduction: ============= The library is a lightweight user-space library that provides APIs for application to configure the PL. Built on top of the driver stack that supports the FPGA device, the library abstracts away hardware specific details ============ Limitations: ============ ->Libdfx is currently limited to supporting Zynq UltraScale+ MPSoC and Versal platforms ->Input package/folder should contain only one bitstream/PDI image file and its relevant overlay file ->To use the deferred probe functionality Both Image DTBO and relevant Drivers DTBO files are mandatory ->The Image dtbo file extension should be _i.dtbo  Ex: design_image_i.dtbo ->The Drivers dtbo file extension should be _d.dtbo Ex: design_drivers_d.dtbo ============================ Images required for Testing: ============================ ->PDI/BIN/BIT file ->DTBO file The Device Tree Overlay (DTO) is used to reprogram an FPGA while Linux is running. The DTO overlay will add the child node and the fragments from the .dtbo file to the base device tree, The newly added device node/drivers will be probed after PDI /BIN/BIT programming. ============= DTO contains: ============= Target FPGA Region - "target-path" or "target" - The insertion point where the contents of the overlay will go into the live tree.target-path is a full path, while target is a phandle. FPGA Image firmware file name - "firmware-name" - Specifies the name of the FPGA image file on the firmware search path. The search path is described in the firmware class documentation. Image specific information - fpga-config-from-dmabuf : boolean, set if the FPGA configured done pre-allocated dma-buffer. Child devices - child nodes corresponding to hardware that will be loaded in this region of the FPGA. ============================================================================ Devicetree Overlay file contents example: For Only PDI/BIN/BIT configuration ============================================================================ /dts-v1/; /plugin/; / { fragment@0 { target = <&fpga>; overlay0: __overlay__ { firmware-name = "partial_1.pdi"; partial-fpga-config; fpga-config-from-dmabuf; }; }; }; ======================================== PL drivers probing ( For Deferred Probe) ======================================== /dts-v1/; /plugin/; / { fragment@0 { target = <&amba>; __overlay__ { axi_gpio_0: gpio@a0000000 { #gpio-cells = <3>; clock-names = "s_axi_aclk"; clocks = <&zynqmp_clk 71>; compatible = "xlnx,axi-gpio-2.0", "xlnx,xps-gpio-1.00.a"; gpio-controller ; reg = <0x0 0xa0000000 0x0 0x1000>; xlnx,all-inputs = <0x0>; xlnx,all-inputs-2 = <0x0>; xlnx,all-outputs = <0x1>; xlnx,all-outputs-2 = <0x0>; xlnx,dout-default = <0x00000000>; xlnx,dout-default-2 = <0x00000000>; xlnx,gpio-width = <0x8>; xlnx,gpio2-width = <0x20>; xlnx,interrupt-present = <0x0>; xlnx,is-dual = <0x0>; xlnx,tri-default = <0xFFFFFFFF>; xlnx,tri-default-2 = <0xFFFFFFFF>; }; }; }; }; ==================================================================================== Devicetree Overlay file contents example: For PDI configuration + PL drivers probing ==================================================================================== /dts-v1/; /plugin/; / { fragment@0 { target = <&fpga>; overlay0: __overlay__ { firmware-name = "partial_1.pdi"; partial-fpga-config; fpga-config-from-dmabuf; }; fragment@1 { target = <&amba>; overlay1: __overlay__ { axi_gpio_0: gpio@a0000000 { #gpio-cells = <3>; clock-names = "s_axi_aclk"; clocks = <&zynqmp_clk 71>; compatible = "xlnx,axi-gpio-2.0", "xlnx,xps-gpio-1.00.a"; gpio-controller ; reg = <0x0 0xa0000000 0x0 0x1000>; xlnx,all-inputs = <0x0>; xlnx,all-inputs-2 = <0x0>; xlnx,all-outputs = <0x1>; xlnx,all-outputs-2 = <0x0>; xlnx,dout-default = <0x00000000>; xlnx,dout-default-2 = <0x00000000>; xlnx,gpio-width = <0x8>; xlnx,gpio2-width = <0x20>; xlnx,interrupt-present = <0x0>; xlnx,is-dual = <0x0>; xlnx,tri-default = <0xFFFFFFFF>; xlnx,tri-default-2 = <0xFFFFFFFF>; }; }; }; }; ====== Note:1 ====== Upstream Linux kernel changes coming in v5.0 and above versions will affect the use of Device Tree (DT) overlays.These changes introduce restriction that may require users to adjust their device tree overlays. Fortunately the adjustments required are small. However, even with adjustments users will experience new warnings.With continued upstream improvements, the new warnings are expected to subside in the future. For more info please refer this below link: https://rocketboards.org/foswiki/Documentation/UpstreamV50KernelDeviceTreeChanges We can ignore these warnings for now. Create Device Tree Overlay Blob (.dtbo) file from the partial.dts file # dtc -O dtb -o partial.dtbo -b 0 -@ partial.dtsi Ex: ./scripts/dtc/dtc -O dtb -o partial.dtbo -b 0 -@ partial.dts Copy the generated PDI and dtbo files into the target package folder  ======= Note: 2 ======= Nodes in PR region should not be the part of Base Device-tree(system.dtb) If these nodes are part of static dtb (system.dtb), these nodes cannot be removed at run-time. ============ API Details: ============ ==============================================================  -pre-fetch:  dfx_cfg_init (const char *dfx_package_path, const char *devpath, u32 flags); ============================================================== /* Provide a generic interface to the user to specify the required parameters * for PR programming. * The calling process must call this API before it performs -load/remove. * * char *dfx_package_path: The contents of the package folder should look * something as below: * -package: //-package1 * |--> Bit_file * |--> DT_Overlayfile * * char *devpath: Unused for now. The dev interface for now is always exposed * at /dev/fpga0 * * unsigned long flags: Flags to specify any special instructions for library * to perform. * * Return: returns unique package_Id or Error code on failure. */ Usage example: #include "libdfx.h" package_id1, package_id2; /* More code */ /* -store /Pre-fetch data */ package_id1 = dfx_cfg_init ("/path/package1/", "/dev/fpga0", flags); /* More code */ /* -store /Pre-fetch data */ package_id2 = dfx_cfg_init ("/path/package2/", "/dev/fpga0", flags); /* More code */ ============================================================================= -pre-fetch int dfx_cfg_init_file(const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file, const char *devpath, unsigned long flags); ============================================================================= /* Provide a generic interface to the user to specify the required parameters * for FPGA programming. To pass the required inputs user should provide the * absolute file paths. * The calling process must call this API before it performs -load/remove. * * const char *dfx_bin_file: Absolute pdi/bistream file path. *The one user wants to load. * -Ex:/lib/firmware/xilinx/example/example.pdi * * const char *dfx_dtbo_file: Absolute relevant dtbo file path * -Ex: /lib/firmware/xilinx/example/example.dtbo * * const char *dfx_driver_dtbo_file: Absolute relevant dtbo file path * - Ex: /lib/firmware/xilinx/example/drivers.dtbo (or) NULL * Note: To use the deferred probe functionality Both Image DTBO and relevant * Drivers DTBO files are mandatory for other use cases user should pass "NULL". * * char *dfx_aes_key_file: Absolute relevant aes key file path * Ex: /lib/firmware/xilinx/example/Aes_key.nky (or) NULL * Note: If the bitstream is encrypted with the user-key then the user needs to * pass relevant aes_key.key file for other use cases user should pass "NULL". * * char *devpath: The dev interface is exposed at /dev/fpga-deviceN. * Where N is the interface-device number. * * unsigned long flags: Flags to specify any special instructions for the * library to perform. * * Return: returns unique package_Id or Error code on failure. */ Usage example: #include "libdfx.h" package_id1, package_id2, package_id3 /* More code */ /* -store /Pre-fetch data - For Normal Images*/ package_id1 = dfx_cfg_init_file("/lib/firmware/xilinx/example/example.bin ", "/lib/firmware/xilinx/example/ex/ample.dtbo", NULL, NULL, /dev/fpga0", flags); /* More code */ /* -store /Pre-fetch data - For user-key encrypted bitstream use case*/ package_id2 = dfx_cfg_init_file("/lib/firmware/xilinx/example/example.bin ", "/lib/firmware/xilinx/example/ex/ample.dtbo", NULL, "/lib/firmware/xilinx/example/Aes_key.nky", /dev/fpga0", flags); /* More code */ /* -store /Pre-fetch data - For deferred drivers probe use case*/ package_id3 = dfx_cfg_init_file("/lib/firmware/xilinx/example/example.bin ", "/lib/firmware/xilinx/example/ex/pl_only_config.dtbo", "/lib/firmware/xilinx/example/drivers.dtbo", NULL, /dev/fpga0", flags); /* More code */ ================================================================ -fpga-load:  int dfx_cfg_load(struct dfx_package_Id package_Id) ================================================================ /* This API is Responsible for the following things. * -->Load into the PL * -->Probe the Drivers which are relevant to the Bitstream as per * DT overlay mentioned in dfx_package folder * * package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success or Error code on failure. */ Usage example: #include "libdfx.h" /* More code */ ret = dfx_cfg_load (package_id); if (ret) return -1 /* More code */ ==================================================================================== -Deferred-drivers-load:  int dfx_cfg_drivers_load(struct dfx_package_Id *package_Id) ==================================================================================== /* This API is Responsible for the following things. * -->Probe the Drivers which are relevant to the Bitstream as per * DT overlay mentioned in dfx_package folder(With name: *_d.dtbo) * * package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success or Error code on failure. */ Usage example: #include "libdfx.h" /* More code */ ret = dfx_cfg_drivers_load(package_id); if (ret) return -1 /* More code */ ========================================================== -Remove: dfx_cfg_remove(struct dfx_package_Id package_Id) ========================================================== /* This API is Responsible for unloading the drivers corresponding to a package * * package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success or Error code on failure. */ Usage example: #include "libdfx.h" /* More code */ ret = dfx_cfg_remove (package_id); if (ret) return -1; /* More code */ ==================================================================== -Destroy package: dfx_cfg_destroy(struct dfx_package_Id package_Id) ==================================================================== /* This API frees the resources allocated during dfx_cfg_init. * * package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success. On error, -1 is returned. */ Usage example: #include "libdfx.h" /* More code */ ret = dfx_cfg_destroy (package_id); if (ret) return -1 /* More code */ ========================= Example Application flow: ========================= #include "libdfx.h" int main() { package_id, ret; /* package initialization */ package_id = dfx_cfg_initpck1/, /dev/fpga0, 0); if (package_id < 0) return -1; /* Package load */ ret = dfx_cfg_load(package_id); if (ret) return -1; /* Remove package */ ret = dfx_cfg_remove(package_id); if (ret) return -1; /* Destroy package */ ret = dfx_cfg_destroy(package_id); return ret; } ==================================================================== -Active UID info list: dfx_get_active_uid_list(int *buffer) ==================================================================== /* This API populates buffer with {Node ID, Unique ID, Parent Unique ID, Function ID} * for each applicable NodeID in the system. * * buffer: User buffer address * * Return: Number of bytes read from the firmware in case of success. * or Negative value on failure. * * Note: The user buffer size should be 768 bytes. * */ Usage example: #include "libdfx.h" /* More code */ ret = dfx_get_active_uid_list(&buffer); if (ret < 0) return -1 /* More code */ ================================================================================= -Meta-header info: dfx_get_meta_header(char *binfile, int *buffer, int buf_size) ================================================================================= /* This API populates buffer with meta-header info related to the user * provided binary file (BIN/PDI). * * binfile: PDI Image. * buffer: User buffer address * buf_size : User buffer size. * * Return: Number of bytes read from the firmware in case of success. * or Negative value on failure. */ Usage example: #include "libdfx.h" /* More code */ ret = dfx_get_meta_header("/media/binary.bin", &buffer, buf_size); if (ret < 0) return -1 /* More code */ ================ Build procedure: ================ 1. Clone libdfx.git repo 2. mkdir build 3. cd build 4. Ensure required tool chain added to your path 5. cmake -DCMAKE_TOOLCHAIN_FILE="cmake tool chain file(complete path)" ../ Example: cmake -DCMAKE_TOOLCHAIN_FILE="/libdfx/cmake/toolchain.cmake" ../ 6. make Once the build is successfully completed the library static, shared object files and app elf file are available in the below paths. -->build/src/libdfx.a -->build/src/libdfx.so.1.0 -->build/apps/dfx_app libdfx-2024.2.0/src/000077500000000000000000000000001465657360700140235ustar00rootroot00000000000000libdfx-2024.2.0/src/CMakeLists.txt000066400000000000000000000025451465657360700165710ustar00rootroot00000000000000#*************************************************************** #* Copyright (c) 2020 Xilinx, Inc. All rights reserved. #* Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved #* SPDX-License-Identifier: MIT #*************************************************************** include(GNUInstallDirs) # Specify the minimum version for CMake cmake_minimum_required(VERSION 2.8.9) # Project's name project(dfx) enable_language(C ASM) set(libdfx_sources dmabuf_alloc.c libdfx.c ) set(LIBDFX_INCLUDE_DIRS "include/" ) SET(LIBDFX_VERSION 1.0) file(COPY include/libdfx.h DESTINATION ${CMAKE_BINARY_DIR}/include) add_library(dfx_shared SHARED ${libdfx_sources}) SET_TARGET_PROPERTIES(dfx_shared PROPERTIES SOVERSION ${LIBDFX_VERSION} OUTPUT_NAME "dfx") SET_TARGET_PROPERTIES(dfx_shared PROPERTIES CLEAN_DIRECT_OUTPUT 1) add_library(dfx_static STATIC ${libdfx_sources}) SET_TARGET_PROPERTIES(dfx_static PROPERTIES OUTPUT_NAME "dfx") SET_TARGET_PROPERTIES(dfx_static PROPERTIES CLEAN_DIRECT_OUTPUT 1) target_include_directories(dfx_shared PUBLIC ${LIBDFX_INCLUDE_DIRS}) target_include_directories(dfx_static PUBLIC ${LIBDFX_INCLUDE_DIRS}) install(FILES "include/libdfx.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(TARGETS dfx_shared; dfx_static ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) libdfx-2024.2.0/src/dmabuf_alloc.c000066400000000000000000000050601465657360700166000ustar00rootroot00000000000000/*************************************************************** * Copyright (c) 2020 Xilinx, Inc. All rights reserved. * Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved * SPDX-License-Identifier: GPL-2.0 * * This file is written by taking reference file from Linux kernel * at: tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c * ***************************************************************/ #include #include #include #include #include #include #include "dmabuf_alloc.h" #include "dma-heap.h" static int open_device (int *devfd) { *devfd = open("/dev/dma_heap/reserved", O_RDWR); if (*devfd < 0) { printf("%s: Failed to open device\n", __func__); return -1; } return 0; } static int alloc_dma_buffer(struct dma_buffer_info *dma_data) { struct dma_heap_allocation_data alloc_data_info = { .len = dma_data->dma_buflen, .fd = 0, .fd_flags = O_RDWR | O_CLOEXEC, .heap_flags = 0, }; int ret; ret = ioctl(dma_data->devfd, DMA_HEAP_IOCTL_ALLOC, &alloc_data_info); if (ret < 0) { printf("%s: DMA_HEAP_IOCTL_ALLOC: Failed\n", __func__); return -1; } if (alloc_data_info.fd < 0 || alloc_data_info.len <= 0) { printf("%s: Invalid mmap data\n", __func__); goto err; } dma_data->dma_buffd = alloc_data_info.fd; dma_data->dma_buflen = alloc_data_info.len; /* mapp buffer for the buffer fd */ dma_data->dma_buffer = (unsigned char *)mmap(NULL, dma_data->dma_buflen, PROT_READ|PROT_WRITE, MAP_SHARED, dma_data->dma_buffd, 0); if (dma_data->dma_buffer == MAP_FAILED) { printf("%s: mmap: Failed\n", __func__); goto err; } return 0; err: if (alloc_data_info.fd) close(alloc_data_info.fd); return -1; } int export_dma_buffer(struct dma_buffer_info *dma_data) { int devfd, ret; if (!dma_data) { printf("%s: Invalid input data\n", __func__); return -1; } ret = open_device(&devfd); if (ret) return ret; dma_data->devfd = devfd; ret = alloc_dma_buffer(dma_data); if (ret) goto err; return 0; err: if (devfd) close(devfd); return -1; } int close_dma_buffer(struct dma_buffer_info *dma_data) { if (!dma_data) { printf("%s: Invalid input data\n", __func__); return -1; } munmap(dma_data->dma_buffer, dma_data->dma_buflen); if (dma_data->dma_buffd > 0) close(dma_data->dma_buffd); if (dma_data->devfd > 0) close(dma_data->devfd); return 0; } libdfx-2024.2.0/src/include/000077500000000000000000000000001465657360700154465ustar00rootroot00000000000000libdfx-2024.2.0/src/include/dma-heap.h000066400000000000000000000026011465657360700172720ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * DMABUF Heaps Userspace API * * Copyright (C) 2011 Google, Inc. * Copyright (C) 2019 Linaro Ltd. */ #ifndef _UAPI_LINUX_DMABUF_POOL_H #define _UAPI_LINUX_DMABUF_POOL_H #include #include /** * DOC: DMABUF Heaps Userspace API */ /* Valid FD_FLAGS are O_CLOEXEC, O_RDONLY, O_WRONLY, O_RDWR */ #define DMA_HEAP_VALID_FD_FLAGS (O_CLOEXEC | O_ACCMODE) /* Currently no heap flags */ #define DMA_HEAP_VALID_HEAP_FLAGS (0) /** * struct dma_heap_allocation_data - metadata passed from userspace for * allocations * @len: size of the allocation * @fd: will be populated with a fd which provides the * handle to the allocated dma-buf * @fd_flags: file descriptor flags used when allocating * @heap_flags: flags passed to heap * * Provided by userspace as an argument to the ioctl */ struct dma_heap_allocation_data { __u64 len; __u32 fd; __u32 fd_flags; __u64 heap_flags; }; #define DMA_HEAP_IOC_MAGIC 'H' /** * DOC: DMA_HEAP_IOCTL_ALLOC - allocate memory from pool * * Takes a dma_heap_allocation_data struct and returns it with the fd field * populated with the dmabuf handle of the allocation. */ #define DMA_HEAP_IOCTL_ALLOC _IOWR(DMA_HEAP_IOC_MAGIC, 0x0,\ struct dma_heap_allocation_data) #endif /* _UAPI_LINUX_DMABUF_POOL_H */ libdfx-2024.2.0/src/include/dmabuf_alloc.h000066400000000000000000000016131465657360700202300ustar00rootroot00000000000000/*************************************************************** * Copyright (c) 2020 Xilinx, Inc. All rights reserved. * Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved * SPDX-License-Identifier: GPL-2.0 * * This file is written by taking reference file from Linux kernel * at: tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c * ***************************************************************/ #ifndef __DMABUF_ALLOC_H #define __DMABUF_ALLOC_H struct dma_buffer_info { int devfd; int dma_buffd; unsigned char *dma_buffer; unsigned long dma_buflen; }; /* This API is used to allocate dmaable memory in the kernel * and export to others */ int export_dma_buffer(struct dma_buffer_info *dma_data); /* This API is used to close all references related to dmaable * memory allocated by the dma_heap. */ int close_dma_buffer(struct dma_buffer_info *dma_data); #endif libdfx-2024.2.0/src/include/libdfx.h000066400000000000000000000066471465657360700171040ustar00rootroot00000000000000/*************************************************************** * Copyright (c) 2020 Xilinx, Inc. All rights reserved. * Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved * SPDX-License-Identifier: MIT ***************************************************************/ #ifndef __LIBDFX_H #define __LIBDFX_H #define DFX_NORMAL_EN (0x00000000U) #define DFX_EXTERNAL_CONFIG_EN (0x00000001U) #define DFX_ENCRYPTION_USERKEY_EN (0x00000020U) /* Error codes */ #define DFX_INVALID_PLATFORM_ERROR (0x1U) #define DFX_CREATE_PACKAGE_ERROR (0x2U) #define DFX_DUPLICATE_FIRMWARE_ERROR (0x3U) #define DFX_DUPLICATE_DTBO_ERROR (0x4U) #define DFX_READ_PACKAGE_ERROR (0x5U) #define DFX_AESKEY_READ_ERROR (0x6U) #define DFX_DMABUF_ALLOC_ERROR (0x7U) #define DFX_INVALID_PACKAGE_ID_ERROR (0x8U) #define DFX_GET_PACKAGE_ERROR (0x9U) #define DFX_FAIL_TO_OPEN_DEV_NODE (0xAU) #define DFX_IMAGE_CONFIG_ERROR (0xBU) #define DFX_DRIVER_CONFIG_ERROR (0xCU) #define DFX_NO_VALID_DRIVER_DTO_FILE (0xDU) #define DFX_DESTROY_PACKAGE_ERROR (0xEU) #define DFX_FAIL_TO_OPEN_BIN_FILE (0xFU) #define DFX_INSUFFICIENT_MEM (0x10U) #define DFX_INVALID_PARAM (0x11U) #define DFX_DUPLICATE_DRIVERS_DTBO_ERROR (0x12U) #define DFX_DUPLICATE_AES_KEY_ERROR (0x13U) /* XILFPGA/PMUFW Error Codes */ #define XFPGA_ERROR_CSUDMA_INIT_FAIL (0x2U) #define XFPGA_ERROR_PL_POWER_UP (0x3U) #define XFPGA_ERROR_PL_ISOLATION (0x4U) #define XPFGA_ERROR_PCAP_INIT (0x5U) #define XFPGA_ERROR_BITSTREAM_LOAD_FAIL (0x6U) #define XFPGA_ERROR_CRYPTO_FLAGS (0x7U) #define XFPGA_ERROR_HDR_AUTH (0X8U) #define XFPGA_ENC_ISCOMPULSORY (0x9U) #define XFPGA_PARTITION_AUTH_FAILURE (0xAU) #define XFPGA_STRING_INVALID_ERROR (0xBU) #define XFPGA_ERROR_SECURE_CRYPTO_FLAGS (0xCU) #define XFPGA_ERROR_SECURE_MODE_EN (0xDU) #define XFPGA_HDR_NOAUTH_PART_AUTH (0xEU) #define XFPGA_DEC_WRONG_KEY_SOURCE (0xFU) #define XFPGA_ERROR_DDR_AUTH_VERIFY_SPK (0x10U) #define XFPGA_ERROR_DDR_AUTH_PARTITION (0x11U) #define XFPGA_ERROR_DDR_AUTH_WRITE_PL (0x12U) #define XFPGA_ERROR_OCM_AUTH_VERIFY_SPK (0x13U) #define XFPGA_ERROR_OCM_AUTH_PARTITION (0x14U) #define XFPGA_ERROR_OCM_REAUTH_WRITE_PL (0x15U) #define XFPGA_ERROR_PCAP_PL_DONE (0x16U) #define XFPGA_ERROR_AES_DECRYPT_PL (0x17U) #define XFPGA_ERROR_CSU_PCAP_TRANSFER (0x18U) #define XFPGA_ERROR_PLSTATE_UNKNOWN (0x19U) #define XFPGA_ERROR_BITSTREAM_FORMAT (0x1AU) #define XFPGA_ERROR_UNALIGN_ADDR (0x1BU) #define XFPGA_ERROR_AES_INIT (0x1CU) #define XFPGA_ERROR_EFUSE_CHECK (0x1DU) #define XFPGA_SUCCESS (0x0U) #define XFPGA_FAILURE (0x1U) #define XFPGA_VALIDATE_ERROR (0x2U) #define XFPGA_PRE_CONFIG_ERROR (0x3U) #define XFPGA_WRITE_BITSTREAM_ERROR (0x4U) #define XFPGA_POST_CONFIG_ERROR (0x5U) #define XFPGA_OPS_NOT_IMPLEMENTED (0x6U) #define XFPGA_INVALID_PARAM (0x8U) int dfx_cfg_init(const char *dfx_package_path, const char *devpath, unsigned long flags); int dfx_cfg_load(int package_id); int dfx_cfg_drivers_load(int package_id); int dfx_cfg_remove(int package_id); int dfx_cfg_destroy(int package_id); int dfx_get_active_uid_list(int *buffer); int dfx_get_meta_header(char *binfile, int *buffer, int buf_size); int dfx_cfg_init_file(const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file, const char *devpath, unsigned long flags); #endif libdfx-2024.2.0/src/libdfx.c000066400000000000000000001210331465657360700154370ustar00rootroot00000000000000/*************************************************************** * Copyright (c) 2020 Xilinx, Inc. All rights reserved. * Copyright (C) 2023, Advanced Micro Devices, Inc. All Rights Reserved * SPDX-License-Identifier: MIT ***************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "dmabuf_alloc.h" #include "libdfx.h" #include "dma-heap.h" #define DFX_IOCTL_LOAD_DMA_BUFF _IOWR('R', 1, __u32) #define INVALID_PLATFORM 0x0U #define ZYNQMP_PLATFORM 0x2U #define VERSAL_PLATFORM 0x3U #define MAX_CMD_LEN 512U #define MAX_AES_KEY_LEN 64U #define PLATFORM_STR_LEN 128U #define FPGA_WORD_SIZE 4U #define FPGA_DUMMY_BYTE 0xFFU #define ZYNQMP_MAX_ERR 27U struct dfx_package_node { int flags; int xilplatform; unsigned long package_id; char *aes_key; char *package_name; char *package_path; char *load_image_name; char *load_image_path; char *load_aes_file_name; char *load_aes_file_path; char *load_image_dtbo_name; char *load_image_dtbo_path; char *load_drivers_dtbo_name; char *load_drivers_dtbo_path; char *load_image_overlay_pck_path; char *load_drivers_overlay_pck_path; struct dma_buffer_info *dmabuf_info; struct dfx_package_node *next; }; typedef struct dfx_package_node FPGA_NODE; FPGA_NODE *head_node, *first_node, *temp_node = NULL, *prev_node, next_node; typedef struct { int err_code; char *err_str; } dfx_err; static dfx_err zynqmp_err[] = { [0] = { .err_code = XFPGA_ERROR_CSUDMA_INIT_FAIL, .err_str = "Failed to initialize the CSUDMA module" }, [1] = { .err_code = XFPGA_ERROR_PL_POWER_UP, .err_str = " Failed to power-up the PL" }, [2] = { .err_code = XFPGA_ERROR_PL_ISOLATION, .err_str = "Failed to perform the PS-PL isolation " }, [3] = { .err_code = XPFGA_ERROR_PCAP_INIT, .err_str = "Failed to initialize the PCAP IP Initialization" }, [4] = { .err_code = XFPGA_ERROR_BITSTREAM_LOAD_FAIL, .err_str = " PL Configuration failed" }, [5] = { .err_code = XFPGA_ERROR_CRYPTO_FLAGS, .err_str = "Failed due to incorrect user crypto flags" }, [6] = { .err_code = XFPGA_ERROR_HDR_AUTH, .err_str = "Failed to authenticate the image headers" }, [7] = { .err_code = XFPGA_ENC_ISCOMPULSORY, .err_str = "Support only encrypted Image loading" }, [8] = { .err_code = XFPGA_PARTITION_AUTH_FAILURE, .err_str = "Image authentication failed" }, [9] = { .err_code = XFPGA_STRING_INVALID_ERROR, .err_str = "Firmware internal error" }, [10] = { .err_code = XFPGA_ERROR_SECURE_CRYPTO_FLAGS, .err_str = "Failed due to incorrect user crypto flags" }, [11] = { .err_code = XFPGA_ERROR_SECURE_MODE_EN, .err_str = "Supports only secure Images loading" }, [12] = { .err_code = XFPGA_HDR_NOAUTH_PART_AUTH, .err_str = "Image header authentication failed" }, [13] = { .err_code = XFPGA_DEC_WRONG_KEY_SOURCE, .err_str = "Decryption failed due to wrong key source" }, [14] = { .err_code = XFPGA_ERROR_DDR_AUTH_VERIFY_SPK, .err_str = "DDR Image authentication failed due to Invalid keys" }, [15] = { .err_code = XFPGA_ERROR_DDR_AUTH_PARTITION, .err_str = "Failed to authentication DDR image partition" }, [16] = { .err_code = XFPGA_ERROR_DDR_AUTH_WRITE_PL, .err_str = "DDR Image authentication failed" }, [17] = { .err_code = XFPGA_ERROR_OCM_AUTH_VERIFY_SPK, .err_str = "OCM Image authentication failed due to Invalid keys" }, [18] = { .err_code = XFPGA_ERROR_OCM_AUTH_PARTITION, .err_str = "Failed to authentication OCM image partition" }, [19] = { .err_code = XFPGA_ERROR_OCM_REAUTH_WRITE_PL, .err_str = "OCM Image authentication failed" }, [20] = { .err_code = XFPGA_ERROR_PCAP_PL_DONE, .err_str = "Failed to get the PCAP done status" }, [21] = { .err_code = XFPGA_ERROR_AES_DECRYPT_PL, .err_str = "Image AES decryption failed" }, [22] = { .err_code = XFPGA_ERROR_CSU_PCAP_TRANSFER, .err_str = "PCAP failed to transfer the Image" }, [23] = { .err_code = XFPGA_ERROR_PLSTATE_UNKNOWN, .err_str = "PL is in Unknow state" }, [23] = { .err_code = XFPGA_ERROR_BITSTREAM_FORMAT, .err_str = "Bitstream format error" }, [24] = { .err_code = XFPGA_ERROR_UNALIGN_ADDR, .err_str = "Error: Received Unaligned Bitstream address" }, [25] = { .err_code = XFPGA_ERROR_AES_INIT, .err_str = "AES initialization failed" }, [26] = { .err_code = XFPGA_ERROR_EFUSE_CHECK, .err_str = "Support only secure image configuration" }, }; static struct dfx_package_node *create_package(void); static struct dfx_package_node *get_package(int package_id); static int destroy_package(int package_id); static int read_package_folder(struct dfx_package_node *package_node); static int dfx_state(char *cmd, char *state); static int dfx_package_load_dmabuf(struct dfx_package_node *package_node); static int dfx_getplatform(void); static int find_key(struct dfx_package_node *package_node); static int lengthOfLastWord2(const char *input); static void strlwr(char *destination, const char *source); static int dfx_get_error(char *cmd); static void zynqmp_print_err_msg(int err); static int dfx_cfg_init_common(const char *dfx_package_path, const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file, const char *devpath, unsigned long flags); static int read_package_byname(struct dfx_package_node *package_node, const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file); static char *get_file_name_from_path(char *full_path); static void copy_file_to_firmware(const char *file); static int validate_input_files(const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file, unsigned long flags); static bool file_exists(const char *filename); #ifdef ENABLE_LIBDFX_TIME static inline double gettime(struct timeval t0, struct timeval t1); #endif /* Provide a generic interface to the user to specify the required parameters * for the library.The calling process must call this API before it performs * fpga-load/remove. * * const char *dfx_package_path: The folder path of the fpga package. * fpga package should look something as below: * fpga-package: /nava/fpga-package1 * |--> Bit_file.bin * |--> DT_Overlayfile.dtbo * const char *devpath: The dev interface is exposed at /dev/fpga-deviceN. * where N is the interface-device number. * unsigned long flags: Flags to specify any special instructions for library * to perform. * * Return: returns unique package_Id, or Error code on failure. */ int dfx_cfg_init(const char *dfx_package_path, const char *devpath, unsigned long flags) { int ret = 0; #ifdef ENABLE_LIBDFX_TIME struct timeval t1, t0; double time; gettimeofday(&t0, NULL); #endif if (dfx_package_path == NULL) { printf("%s: Invalid input args\n", __func__); return -DFX_INVALID_PARAM; } ret = dfx_cfg_init_common(dfx_package_path, NULL, NULL, NULL, NULL, devpath, flags); #ifdef ENABLE_LIBDFX_TIME gettimeofday(&t1, NULL); time = gettime(t0, t1); printf("%s API Time taken: %f Milli Seconds\n\r", __func__, time); #endif return ret; } /* Provide a generic interface to the user to specify the required parameters * for FPGA programming.It takes absolute paths of all individual files as * arguments and perform the required init functionality. * The calling process must call this API before it performs -load/remove. * * const char *dfx_bin_file: Absolute pdi/bistream file path(The one user wants to load). * -Ex:/lib/firmware/xilinx/example/example.pdi * * const char *dfx_dtbo_file: Absolute relevant dtbo file path * -Ex: /lib/firmware/xilinx/example/example.dtbo * * const char *dfx_driver_dtbo_file: Absolute relevant dtbo file path * - Ex: /lib/firmware/xilinx/example/drivers.dtbo (or) NULL * Note: To use the deferred probe functionality Both Image DTBO and relevant * Drivers DTBO files are mandatory for other use cases user should pass "NULL". * * char *dfx_aes_key_file: Absolute relevant aes key file path * Ex: /lib/firmware/xilinx/example/Aes_key.nky (or) NULL * Note: If the bitstream is encrypted with the user-key then the user needs to * pass relevant aes_key.key file for other use cases user should pass "NULL". * * char *devpath: The dev interface is exposed at /dev/fpga-deviceN. * Where N is the interface-device number. * * unsigned long flags: Flags to specify any special instructions for the * library to perform. * * Return: returns unique package_Id or Error code on failure. */ int dfx_cfg_init_file(const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file, const char *devpath, unsigned long flags) { int len, ret = 0; #ifdef ENABLE_LIBDFX_TIME struct timeval t1, t0; double time; gettimeofday(&t0, NULL); #endif /* Validate Inputs */ ret = validate_input_files(dfx_bin_file, dfx_dtbo_file, dfx_driver_dtbo_file, dfx_aes_key_file, flags); if (ret) { printf("%s: Invalid input args\n", __func__); return ret; } ret = dfx_cfg_init_common(NULL, dfx_bin_file, dfx_dtbo_file, dfx_driver_dtbo_file, dfx_aes_key_file, devpath, flags); #ifdef ENABLE_LIBDFX_TIME gettimeofday(&t1, NULL); time = gettime(t0, t1); printf("%s API Time taken: %f Milli Seconds\n\r", __func__, time); #endif return ret; } /* This API is Responsible for the following things. * -->Load bitstream into the PL * -->Probe the Drivers which are relevant to the Bitstream as per * DT overlay(mentioned in dfx_package folder) * * int package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success or Error code on failure. */ int dfx_cfg_load(int package_id) { FPGA_NODE *package_node; int len, fd, buffd, ret = 0, err = 0; char command[MAX_CMD_LEN]; char *str; DIR *FD; #ifdef ENABLE_LIBDFX_TIME struct timeval total_t1, total_t0, load_t1, load_t0; double total_time, load_time; gettimeofday(&total_t0, NULL); #endif if (package_id < 0) { printf("%s: Invalid package id\n", __func__); ret = -DFX_INVALID_PACKAGE_ID_ERROR; goto END; } package_node = get_package(package_id); if (package_node == NULL) { printf("%s: fail to get package_node\n", __func__); ret = -DFX_GET_PACKAGE_ERROR; goto END; } if (!(package_node->flags & DFX_EXTERNAL_CONFIG_EN)) { fd = open("/dev/fpga0", O_RDWR); if (fd < 0) { printf("%s: Cannot open device file...\n", __func__); ret = -DFX_FAIL_TO_OPEN_DEV_NODE; goto END; } snprintf(command, sizeof(command), "echo %x > /sys/class/fpga_manager/fpga0/flags", package_node->flags); system(command); if (package_node->flags & DFX_ENCRYPTION_USERKEY_EN) { snprintf(command, sizeof(command), "echo %s > /sys/class/fpga_manager/fpga0/key", package_node->aes_key); system(command); } buffd = package_node->dmabuf_info->dma_buffd; /* Send dmabuf-fd to the FPGA Manager */ ioctl(fd, DFX_IOCTL_LOAD_DMA_BUFF, &buffd); close(fd); } snprintf(command, sizeof(command), "/configfs/device-tree/overlays/%s_image_%d", package_node->package_name, package_node->package_id); len = strlen(command) + 1; str = (char *) calloc((len), sizeof(char)); strncpy(str, command, len); package_node->load_image_overlay_pck_path = str; snprintf(command, sizeof(command), "mkdir -p %s", package_node->load_image_overlay_pck_path); system(command); snprintf(command, sizeof(command), "echo -n %s > %s/path", package_node->load_image_dtbo_name, package_node->load_image_overlay_pck_path); #ifdef ENABLE_LIBDFX_TIME gettimeofday(&load_t0, NULL); #endif system(command); #ifdef ENABLE_LIBDFX_TIME gettimeofday(&load_t1, NULL); #endif if (!(package_node->flags & DFX_EXTERNAL_CONFIG_EN)) { snprintf(command, sizeof(command), "cat /sys/class/fpga_manager/fpga0/state >> state.txt"); ret = dfx_state(command, "operating"); if (ret) { err = dfx_get_error(command); snprintf(command, sizeof(command), "rmdir %s", package_node->load_image_overlay_pck_path); system(command); printf("%s: Image configuration failed with error: 0x%x\n", __func__, err); if (package_node->xilplatform == ZYNQMP_PLATFORM) zynqmp_print_err_msg(err); system(command); ret = -DFX_IMAGE_CONFIG_ERROR; goto END; } } snprintf(command, sizeof(command), "cat %s/path >> state.txt", package_node->load_image_overlay_pck_path); ret = dfx_state(command, package_node->load_image_dtbo_name); if (ret) { snprintf(command, sizeof(command), "rmdir %s", package_node->load_image_overlay_pck_path); system(command); printf("%s: Image configuration failed\n", __func__); ret = -DFX_IMAGE_CONFIG_ERROR; goto END; } END: #ifdef ENABLE_LIBDFX_TIME gettimeofday(&total_t1, NULL); total_time = gettime(total_t0, total_t1); load_time = gettime(load_t0, load_t1); printf("%s: Image load time from pre-allocated buffer: %f Milli Seconds\n\r", __func__, load_time); printf("%s API Total time taken: %f Milli Seconds\n\r", __func__, total_time); #endif return ret; } /* This API is Responsible for loading the drivers corresponding to a package * * package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success or Error code on failure. */ int dfx_cfg_drivers_load(int package_id) { FPGA_NODE *package_node; char command[MAX_CMD_LEN]; int len, ret = 0; char *str; #ifdef ENABLE_LIBDFX_TIME struct timeval t1, t0; double time; gettimeofday(&t0, NULL); #endif if (package_id < 0) { printf("%s: Invalid package id\n", __func__); ret = -DFX_INVALID_PACKAGE_ID_ERROR; goto END; } package_node = get_package(package_id); if (package_node == NULL) { printf("%s: fail to get package_node\n", __func__); ret = -DFX_GET_PACKAGE_ERROR; goto END; } if (package_node->load_drivers_dtbo_path == NULL) { ret = -DFX_NO_VALID_DRIVER_DTO_FILE; goto END; } snprintf(command, sizeof(command), "/configfs/device-tree/overlays/%s_driver_%d", package_node->package_name, package_node->package_id); len = strlen(command) + 1; str = (char *) calloc((len), sizeof(char)); strncpy(str, command, len); package_node->load_drivers_overlay_pck_path = str; snprintf(command, sizeof(command), "mkdir -p %s", package_node->load_drivers_overlay_pck_path); system(command); snprintf(command, sizeof(command), "echo -n %s > %s/path", package_node->load_drivers_dtbo_name, package_node->load_drivers_overlay_pck_path); system(command); snprintf(command, sizeof(command), "cat %s/path >> state.txt", package_node->load_drivers_overlay_pck_path); ret = dfx_state(command, package_node->load_drivers_dtbo_name); if (ret) { snprintf(command, sizeof(command), "rmdir %s", package_node->load_drivers_overlay_pck_path); system(command); printf("%s: Drivers DTBO config failed\n", __func__); ret = -DFX_DRIVER_CONFIG_ERROR; } END: #ifdef ENABLE_LIBDFX_TIME gettimeofday(&t1, NULL); time = gettime(t0, t1); printf("%s API Time taken: %f Milli Seconds\n\r", __func__, time); #endif return ret; } /* This API is Responsible for unloading the drivers corresponding to a package * * int package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success or Error code on failure. */ int dfx_cfg_remove(int package_id) { FPGA_NODE *package_node; char command[MAX_CMD_LEN]; int ret = 0; DIR *FD; #ifdef ENABLE_LIBDFX_TIME struct timeval t1, t0; double time; gettimeofday(&t0, NULL); #endif if (package_id < 0) { printf("%s: Invalid package id\n", __func__); ret = -DFX_INVALID_PACKAGE_ID_ERROR; goto END; } package_node = get_package(package_id); if (package_node == NULL) { printf("%s: fail to get package_node\n", __func__); ret = -DFX_GET_PACKAGE_ERROR; goto END; } if (package_node->load_drivers_overlay_pck_path != NULL) { FD = opendir(package_node->load_drivers_overlay_pck_path); if (FD) { closedir(FD); snprintf(command, sizeof(command), "rmdir %s", package_node->load_drivers_overlay_pck_path); system(command); } } if (package_node->load_image_overlay_pck_path != NULL) { FD = opendir(package_node->load_image_overlay_pck_path); if (FD) { closedir(FD); snprintf(command, sizeof(command), "rmdir %s", package_node->load_image_overlay_pck_path); system(command); } } END: #ifdef ENABLE_LIBDFX_TIME gettimeofday(&t1, NULL); time = gettime(t0, t1); printf("%s API Time taken: %f Milli Seconds\n\r", __func__, time); #endif return ret; } /* This API is Responsible for release/destroy the resouces allocated * by dfx_cfg_init(). * * int package_id: Unique package_id value which was returned by dfx_cfg_init. * * Return: returns zero on success or Error code on failure. */ int dfx_cfg_destroy(int package_id) { FPGA_NODE *package_node; char command[MAX_CMD_LEN]; int ret = 0; #ifdef ENABLE_LIBDFX_TIME struct timeval t1, t0; double time; gettimeofday(&t0, NULL); #endif if (package_id < 0) { printf("%s: Invalid package id\n", __func__); ret = -DFX_INVALID_PACKAGE_ID_ERROR; goto END; } package_node = get_package(package_id); if (package_node == NULL) { printf("%s: fail to get package_node\n", __func__); ret = -DFX_GET_PACKAGE_ERROR; goto END; } if (package_node->load_image_overlay_pck_path != NULL) { snprintf(command, sizeof(command), "rm /lib/firmware/%s", package_node->load_image_dtbo_name); system(command); } if (!(package_node->flags & DFX_EXTERNAL_CONFIG_EN)) { /* This call will do the following things * unmap the buffer properly * close the buffer fd (Free the Dmabuf memory) * Finally, close the client fd */ close_dma_buffer(package_node->dmabuf_info); } ret = destroy_package(package_node->package_id); END: #ifdef ENABLE_LIBDFX_TIME gettimeofday(&t1, NULL); time = gettime(t0, t1); printf("%s API Time taken: %f Milli Seconds\n\r", __func__, time); #endif return ret; } /* This API populates buffer with {Node ID, Unique ID, Parent Unique ID, Function ID} * for each applicable NodeID in the system. * * buffer: User buffer address * * Return: Number of bytes read from the firmware in case of success. * or Negative value on failure. */ int dfx_get_active_uid_list(int *buffer) { const char* filename = "/sys/devices/platform/firmware:versal-firmware/uid-read"; int platform, ret = 0, count = 0; FILE* fd; #ifdef ENABLE_LIBDFX_TIME struct timeval t1, t0; double time; gettimeofday(&t0, NULL); #endif platform = dfx_getplatform(); if (platform != VERSAL_PLATFORM) { ret = -DFX_INVALID_PLATFORM_ERROR; goto END; } fd = fopen(filename, "rb"); if (!fd) { printf("Unable to open file!"); ret = -DFX_FAIL_TO_OPEN_BIN_FILE; goto END; } while(!feof(fd)) { fread(&buffer[count], sizeof(int), 1,fd); count++; } fclose(fd); ret = (count - 1) * sizeof(int); END: #ifdef ENABLE_LIBDFX_TIME gettimeofday(&t1, NULL); time = gettime(t0, t1); printf("%s API Time taken: %f Milli Seconds\n\r", __func__, time); #endif return ret; } /* This API populates buffer with meta-header info related to the user * provided PDI. * * binfile: PDI Image. * buffer: User buffer address * buf_size : User buffer size. * * Return: Number of bytes read from the firmware in case of success. * or Negative value on failure. */ int dfx_get_meta_header(char *binfile, int *buffer, int buf_size) { const char* filename = "/sys/devices/platform/firmware:versal-firmware/meta-header-read"; char command[2048], *token, *tmp, *tmp1; int platform, ret = 0, count = 0; FILE* fd; DIR *FD; #ifdef ENABLE_LIBDFX_TIME struct timeval t1, t0; double time; gettimeofday(&t0, NULL); #endif platform = dfx_getplatform(); if (platform != VERSAL_PLATFORM) { ret = -DFX_INVALID_PLATFORM_ERROR; goto END; } fd = fopen(binfile, "rb"); if (!fd) { printf("Unable to open binary file!"); ret = -DFX_FAIL_TO_OPEN_BIN_FILE; goto END; } fclose(fd); FD = opendir("/lib/firmware"); if (FD) closedir(FD); else system("mkdir -p /lib/firmware"); snprintf(command, sizeof(command), "cp %s /lib/firmware", binfile); system(command); tmp = strdup(binfile); while((token = strsep(&tmp, "/"))) tmp1 = token; snprintf(command, sizeof(command), "echo %s > /sys/devices/platform/firmware:versal-firmware/firmware", tmp1); system(command); free(tmp); fd = fopen(filename, "rb"); if (!fd) { printf("Unable to open sysfs binary file!"); ret = -DFX_FAIL_TO_OPEN_BIN_FILE; goto END; } while(!feof(fd)) { if(buf_size < count) { count = -DFX_INSUFFICIENT_MEM; break; } fread(&buffer[count], sizeof(int), 1,fd); count++; } fclose(fd); closedir(FD); ret = count * sizeof(int); END: #ifdef ENABLE_LIBDFX_TIME gettimeofday(&t1, NULL); time = gettime(t0, t1); printf("%s API Time taken: %f Milli Seconds\n\r", __func__, time); #endif return ret; } static int read_package_folder(struct dfx_package_node *package_node) { int bin_count = 0, dtbo_count = 0, driver_dtbo_count = 0, nky_count = 0; char command[MAX_CMD_LEN]; struct dirent *dir; int len, pcklen; char *bin = ".bin"; char *pdi = ".pdi"; char *extension; char *file_name; char *str; DIR *FD; if (package_node->xilplatform == VERSAL_PLATFORM) extension = pdi; else extension = bin; pcklen = strlen(package_node->package_path); FD = opendir(package_node->package_path); if (FD) { while ((dir = readdir(FD)) != NULL) { len = strlen(dir->d_name); file_name = (char *) calloc((len + 1), sizeof(char)); strlwr(file_name, dir->d_name); if (len > 4) { if (!strcmp(file_name + (len - 4), extension)) { str = (char *) calloc( (len + pcklen + 1), sizeof(char)); strcpy(str, package_node->package_path); strcat(str, dir->d_name); package_node->load_image_path = str; str = (char *) calloc((len + 1), sizeof(char)); strcpy(str, dir->d_name); package_node->load_image_name = str; bin_count++; } else if ((!strcmp(file_name + (len - 4), ".bit")) && package_node->xilplatform == ZYNQMP_PLATFORM) { str = (char *) calloc( (len + pcklen + 1), sizeof(char)); strcpy(str, package_node->package_path); strcat(str, dir->d_name); package_node->load_image_path = str; str = (char *) calloc((len + 1), sizeof(char)); strcpy(str, dir->d_name); package_node->load_image_name = str; bin_count++; } else if (!strcmp(file_name + (len - 7), "_i.dtbo")) { str = (char *) calloc( (len + pcklen + 1), sizeof(char)); strcpy(str, package_node->package_path); strcat(str, dir->d_name); package_node->load_image_dtbo_path = str; str = (char *) calloc((len + 1), sizeof(char)); strcpy(str, dir->d_name); package_node->load_image_dtbo_name = str; dtbo_count++; } else if (!strcmp(file_name + (len - 7), "_d.dtbo")) { str = (char *) calloc( (len + pcklen + 1), sizeof(char)); strcpy(str, package_node->package_path); strcat(str, dir->d_name); package_node->load_drivers_dtbo_path = str; str = (char *) calloc((len + 1), sizeof(char)); strcpy(str, dir->d_name); package_node->load_drivers_dtbo_name = str; driver_dtbo_count++; } else if (!strcmp(file_name + (len - 5), ".dtbo")) { str = (char *) calloc( (len + pcklen + 1), sizeof(char)); strcpy(str, package_node->package_path); strcat(str, dir->d_name); package_node->load_image_dtbo_path = str; str = (char *) calloc((len + 1), sizeof(char)); strcpy(str, dir->d_name); package_node->load_image_dtbo_name = str; dtbo_count++; } else if (!strcmp(file_name + (len - 4), ".nky")) { str = (char *) calloc( (len + pcklen + 1), sizeof(char)); strcpy(str, package_node->package_path); strcat(str, dir->d_name); package_node->load_aes_file_path = str; str = (char *) calloc((len + 1), sizeof(char)); strcpy(str, dir->d_name); package_node->load_aes_file_name = str; nky_count++; } } free(file_name); } closedir(FD); } if (bin_count > 1) { printf("libdfx: Error: %s* has multiple Bitstream files!\n", package_node->package_path); return -DFX_DUPLICATE_FIRMWARE_ERROR; } if (dtbo_count > 1) { printf("libdfx: Error: %s* has multiple overlay files!\n", package_node->package_path); return -DFX_DUPLICATE_DTBO_ERROR; } if (driver_dtbo_count > 1) { printf("libdfx: warning: %s* has multiple Drivers overlay files(Deferred probe)!\n", package_node->package_path); return -DFX_DUPLICATE_DRIVERS_DTBO_ERROR; } if (nky_count > 1) { printf("libdfx: warning: %s* has multiple AES key files!\n", package_node->package_path); return -DFX_DUPLICATE_AES_KEY_ERROR; } if (package_node->load_image_dtbo_path != NULL) { len = strlen(package_node->load_image_dtbo_path); str = (char *) calloc((len + 1), sizeof(char)); strcpy(str, package_node->load_image_dtbo_path); dirname(str); snprintf(command, sizeof(command), "%s", basename(str)); free(str); len = strlen(command) + 1; str = (char *) calloc((len), sizeof(char)); strncpy(str, command, len); package_node->package_name = str; snprintf(command, sizeof(command), "cp %s /lib/firmware/", package_node->load_image_dtbo_path); system(command); if (package_node->load_drivers_dtbo_path != NULL) { snprintf(command, sizeof(command), "cp %s /lib/firmware/", package_node->load_drivers_dtbo_path); system(command); } } else { printf("%s: Invalid package\n", __func__); return -DFX_READ_PACKAGE_ERROR; } return 0; } static struct dfx_package_node *create_package() { FPGA_NODE *package_node; DIR *FD; FD = opendir("/lib/firmware"); if (FD) closedir(FD); else system("mkdir -p /lib/firmware"); FD = opendir("/configfs/device-tree/overlays/"); if (FD) closedir(FD); else { system("mkdir -p /configfs"); system("mount -t configfs configfs /configfs"); } temp_node = first_node; package_node = (FPGA_NODE *) calloc(1, sizeof(FPGA_NODE)); package_node->next = NULL; if (first_node == NULL) { package_node->package_id = 1; first_node = package_node; } else { while (temp_node != NULL) { if (temp_node->next == NULL) { package_node->package_id = temp_node->package_id + 1; temp_node->next = package_node; break; } temp_node = temp_node->next; } } return package_node; } static struct dfx_package_node *get_package(int package_id) { temp_node = first_node; while (temp_node != NULL) { if (temp_node->package_id == package_id) break; temp_node = temp_node->next; } return temp_node; } static int destroy_package(int package_id) { FPGA_NODE *package_node = NULL; temp_node = first_node; if (first_node == NULL) return -DFX_DESTROY_PACKAGE_ERROR; if (first_node->package_id == package_id) { if (first_node->next != NULL) first_node = first_node->next; else first_node = NULL; package_node = temp_node; } else { while (temp_node->next != NULL) { if (temp_node->next->package_id == package_id) { package_node = temp_node->next; temp_node->next = package_node->next; break; } temp_node = temp_node->next; } } if (package_node != NULL) { if (package_node->package_name != NULL) free(package_node->package_name); if (package_node->package_path != NULL) free(package_node->package_path); if (package_node->load_image_name != NULL) free(package_node->load_image_name); if (package_node->load_image_path != NULL) free(package_node->load_image_path); if (package_node->load_image_dtbo_name != NULL) free(package_node->load_image_dtbo_name); if (package_node->load_image_dtbo_path != NULL) free(package_node->load_image_dtbo_path); if (package_node->load_drivers_dtbo_name != NULL) free(package_node->load_drivers_dtbo_name); if (package_node->load_drivers_dtbo_path != NULL) free(package_node->load_drivers_dtbo_path); if (package_node->load_image_overlay_pck_path != NULL) free(package_node->load_image_overlay_pck_path); if (package_node->load_drivers_overlay_pck_path != NULL) free(package_node->load_drivers_overlay_pck_path); if (package_node->dmabuf_info != NULL) free(package_node->dmabuf_info); if (package_node->aes_key != NULL) free(package_node->aes_key); free(package_node); } else return -DFX_DESTROY_PACKAGE_ERROR; return 0; } static int dfx_state(char *cmd, char *state) { char buf[PLATFORM_STR_LEN]; FILE *fptr; int len; system(cmd); len = strlen(state) + 1; fptr = fopen("state.txt", "r"); if (fptr) { fgets(buf, len, fptr); fclose(fptr); system("rm state.txt"); if (!strcmp(buf, state)) return 0; else return 1; } return 1; } static int dfx_get_error(char *cmd) { char string[PLATFORM_STR_LEN]; FILE *fp; int c; system(cmd); fp = fopen("state.txt", "r"); c = getc(fp); while(c!=EOF) { fscanf(fp, "%s", string); c = getc(fp); } fclose(fp); system("rm state.txt"); return (int)strtol(string, NULL, 0); } static int dfx_package_load_dmabuf(struct dfx_package_node *package_node) { int word_align = 0, index, fd, ret; struct dma_buf_sync sync = { 0 }; struct dma_buffer_info info; long fileLen, count; char *dma_buf; FILE *fp; fp = fopen(package_node->load_image_path, "rb"); if (fp == NULL) { printf("%s: File open failed\n", __func__); return -1; } //Get Bitstream/PDI Image Size fseek(fp, 0, SEEK_END); fileLen = ftell(fp); fseek(fp, 0, SEEK_SET); if (package_node->xilplatform == ZYNQMP_PLATFORM) { word_align = fileLen % FPGA_WORD_SIZE; if(word_align) word_align = FPGA_WORD_SIZE - word_align; fileLen = fileLen + word_align; } package_node->dmabuf_info = (struct dma_buffer_info *) calloc(1, sizeof(struct dma_buffer_info)); package_node->dmabuf_info->dma_buflen = fileLen; /* This call will do the following things * 1. Allocate memory from the DMA pool and return a valid buffer fd * 2. Create memory mapped buffer for the buffer fd */ ret = export_dma_buffer(package_node->dmabuf_info); if (ret < 0) { printf("%s: DMA buffer alloc failed\n", __func__); goto err_update; } /* DO Memory access synchronization */ sync.flags = DMA_BUF_SYNC_START | DMA_BUF_SYNC_RW; ret = ioctl(package_node->dmabuf_info->dma_buffd, DMA_BUF_IOCTL_SYNC, &sync); if (ret) { printf("%s: sync start failed\n", __func__); goto unmap_buf; } /* Copy Bitfile/PDI image into the Dmabuf */ if (word_align) { dma_buf = (char *) package_node->dmabuf_info->dma_buffer; for (index = 0; index < word_align; index++) dma_buf[index] = FPGA_DUMMY_BYTE; fileLen = fileLen - word_align; count = fread(&dma_buf[index], 1, fileLen, fp); } else count = fread((char *) package_node->dmabuf_info->dma_buffer, 1, fileLen, fp); if (count != fileLen) { printf("%s: Image copy failed\n", __func__); goto unmap_buf; } sync.flags = DMA_BUF_SYNC_END | DMA_BUF_SYNC_RW; ret = ioctl(package_node->dmabuf_info->dma_buffd, DMA_BUF_IOCTL_SYNC, &sync); if (ret) { printf("%s: sync end failed\n", __func__); goto unmap_buf; } fclose(fp); return 0; unmap_buf: close_dma_buffer(package_node->dmabuf_info); err_update: fclose(fp); return -DFX_DMABUF_ALLOC_ERROR; } static int dfx_getplatform(void) { char *zynqmpstr = "Xilinx ZynqMP FPGA Manager"; char *Versalstr = "Xilinx Versal FPGA Manager"; char fpstr[PLATFORM_STR_LEN]; FILE *fptr; fptr = fopen("/sys/class/fpga_manager/fpga0/name", "r"); if (fptr == NULL) { printf("Error! opening the platform file"); return INVALID_PLATFORM; } // reads text until newline fscanf(fptr, "%[^\n]", fpstr); fclose(fptr); if (!strcmp(zynqmpstr, fpstr)) return ZYNQMP_PLATFORM; else if (!strcmp(Versalstr, fpstr)) return VERSAL_PLATFORM; else return INVALID_PLATFORM; } static int lengthOfLastWord2(const char *input) { int result = 0; while (*input != '\0') { if (*input != ' ') result++; else result = 0; input++; } return result; } static int find_key(struct dfx_package_node *package_node) { int len; char line[MAX_CMD_LEN]; int find_result = 0; FILE *fp = fopen(package_node->load_aes_file_path, "r"); package_node->aes_key = (char *) calloc(MAX_AES_KEY_LEN, sizeof(char)); while (fgets(line, sizeof(line), fp) != NULL) { if (strstr(line, "Key") != NULL) { len = strlen(line) - lengthOfLastWord2(line); strncpy(package_node->aes_key, line + len, MAX_AES_KEY_LEN); package_node->aes_key[MAX_AES_KEY_LEN] = '\0'; find_result++; break; } } //Close the file if still open. if (fp) fclose(fp); if (find_result == 0) { free(package_node->aes_key); return -DFX_AESKEY_READ_ERROR; } return 0; } static inline void strlwr(char *destination, const char *source) { while (*source) { *destination = tolower((unsigned char)*source); source++; destination++; } } static void zynqmp_print_err_msg(int err) { int i, err_found = 0; if ((err & 0xFF) == XFPGA_VALIDATE_ERROR) printf("Error: Image validation"); if ((err & 0xFF) == XFPGA_PRE_CONFIG_ERROR) printf("Error: Image Pre-configuration"); if ((err & 0xFF) == XFPGA_WRITE_BITSTREAM_ERROR) printf("Error: Image write:"); if ((err & 0xFF) == XFPGA_POST_CONFIG_ERROR) printf("Error: Image Post-configuration"); if ((err & 0xFF) == XFPGA_OPS_NOT_IMPLEMENTED) printf("Error: Operation not supported"); if ((err & 0xFF) == XFPGA_INVALID_PARAM) printf("Error: Invalid input parameters"); for (i = 0; i < ZYNQMP_MAX_ERR; i++) { if (zynqmp_err[i].err_code == (err >> 8) & 0xFF) { printf(": %s\r\n", zynqmp_err[i].err_str); err_found++; break; } } if ((!err_found) && (err & 0xFF)) printf("\r\n"); } static int dfx_cfg_init_common(const char *dfx_package_path, const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file, const char *devpath, unsigned long flags) { FPGA_NODE *package_node; int err, ret = 0; int platform; size_t len; platform = dfx_getplatform(); if (platform == INVALID_PLATFORM) { printf("%s: fpga manager not enabled in the kernel Image\r\n", __func__); ret = -DFX_INVALID_PLATFORM_ERROR; goto END; } package_node = create_package(); if (package_node == NULL) { printf("%s: create_package failed\r\n", __func__); ret = -DFX_CREATE_PACKAGE_ERROR; goto END; } package_node->xilplatform = platform; package_node->flags = flags; if (dfx_package_path == NULL) { ret = read_package_byname(package_node, dfx_bin_file, dfx_dtbo_file, dfx_driver_dtbo_file, dfx_aes_key_file); if (ret) { printf("%s: package read failed\r\n", __func__); goto destroy_package; } } else { /*Update package path */ len = strlen(dfx_package_path); if (dfx_package_path[len-1] != '/') { /* one for extra char, one for trailing zero */ package_node->package_path = (char *)malloc(len + 1 + 1); strcpy(package_node->package_path, dfx_package_path); package_node->package_path[len] = '/'; package_node->package_path[len + 1] = '\0'; } else { package_node->package_path = (char *)malloc(len + 1); strcpy(package_node->package_path, dfx_package_path); } ret = read_package_folder(package_node); if (ret) { printf("%s: package read failed\r\n", __func__); goto destroy_package; } } if (flags & DFX_ENCRYPTION_USERKEY_EN) { ret = find_key(package_node); if (ret) { printf("%s: fail to get key info\r\n", __func__); goto destroy_package; } } if (!(flags & DFX_EXTERNAL_CONFIG_EN)) { ret = dfx_package_load_dmabuf(package_node); if (ret) { printf("%s: load dmabuf failed\r\n", __func__); goto destroy_package; } } return package_node->package_id; destroy_package: err = destroy_package(package_node->package_id); if (err) printf("%s:Destroy package failed \r\n", __func__); END: return ret; } static int read_package_byname(struct dfx_package_node *package_node, const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file) { int ret; char *str; char slen; if(dfx_bin_file != NULL) { package_node->load_image_path = strdup(dfx_bin_file); str = strdup(get_file_name_from_path(package_node->load_image_path)); package_node->load_image_name = str; copy_file_to_firmware(dfx_bin_file); } else { return -DFX_READ_PACKAGE_ERROR; } if (dfx_dtbo_file != NULL) { package_node->load_image_dtbo_path = strdup(dfx_dtbo_file); str = strdup(get_file_name_from_path(package_node->load_image_dtbo_path)); package_node->load_image_dtbo_name = str; slen = strlen(str) - 4; str = strndup(package_node->load_image_dtbo_name, slen); str[slen - 1] = '\0'; package_node->package_name = str; copy_file_to_firmware(dfx_dtbo_file); } else { return -DFX_READ_PACKAGE_ERROR; } if(dfx_driver_dtbo_file != NULL) { package_node->load_drivers_dtbo_path = strdup(dfx_driver_dtbo_file); str = strdup(get_file_name_from_path(package_node->load_drivers_dtbo_path)); package_node->load_drivers_dtbo_name = str; copy_file_to_firmware(dfx_driver_dtbo_file); } else { package_node->load_drivers_dtbo_path = NULL; package_node->load_drivers_dtbo_name = NULL; } if (dfx_aes_key_file != NULL) { package_node->load_aes_file_path = strdup(dfx_aes_key_file); str = strdup(get_file_name_from_path(package_node->load_aes_file_path)); package_node->load_aes_file_name = str; } else { package_node->load_aes_file_path = NULL; package_node->load_aes_file_name = NULL; } return 0; } static char *get_file_name_from_path(char *full_path) { char *ssc; int l = 0; char *path = full_path; ssc = strstr(path, "/"); do{ l = strlen(ssc) + 1; path = &path[strlen(path)-l+2]; ssc = strstr(path, "/"); }while(ssc); return path; } static void copy_file_to_firmware(const char *file) { char command[MAX_CMD_LEN]; snprintf(command, sizeof(command), "cp %s /lib/firmware/", file); system(command); } static bool file_exists(const char *filename) { FILE *fp = fopen(filename, "r"); bool is_exist = false; if (fp != NULL) { is_exist = true; fclose(fp); // close the file } return is_exist; } static int validate_input_files(const char *dfx_bin_file, const char *dfx_dtbo_file, const char *dfx_driver_dtbo_file, const char *dfx_aes_key_file, unsigned long flags) { int len, ret = 0; /* Validate Inputs */ len = strlen(dfx_bin_file); if ((strcmp(dfx_bin_file + (len - 4), ".bit")) && (strcmp(dfx_bin_file + (len - 4), ".bin")) && (strcmp(dfx_bin_file + (len - 4), ".pdi"))) { printf("%s: Invalid bitstream file extension\r\n", __func__); printf("%s: File extension should be .bit (or) .bin (or) .pdi\n", __func__); return -DFX_INVALID_PARAM; } if (!file_exists(dfx_bin_file)) { printf("%s: User provided bitstream file doesn't exist\r\n", __func__); return -DFX_INVALID_PARAM; } len = strlen(dfx_dtbo_file); if (strcmp(dfx_dtbo_file + (len - 5), ".dtbo")) { printf("%s: Invalid Overlay file extension\r\n", __func__); printf("%s: File extension should be .dtbo\n", __func__); return -DFX_INVALID_PARAM; } if (!file_exists(dfx_dtbo_file)) { printf("%s: User provided Overlay file doesn't exist\r\n", __func__); return -DFX_INVALID_PARAM; } if (dfx_driver_dtbo_file != NULL) { len = strlen(dfx_driver_dtbo_file); if (strcmp(dfx_driver_dtbo_file + (len - 5), ".dtbo")) { printf("%s: Invalid PL IP's Overlay file extension\r\n", __func__); printf("%s: File extension should be .dtbo\n", __func__); return -DFX_INVALID_PARAM; } if (!file_exists(dfx_driver_dtbo_file)) { printf("%s: User provided PL IP's Overlay file doesn't exist\r\n", __func__); return -DFX_INVALID_PARAM; } } if (flags & DFX_ENCRYPTION_USERKEY_EN) { len = strlen(dfx_aes_key_file); if (strcmp(dfx_aes_key_file + (len - 4), ".nky")) { printf("%s: Invalid AES key file extension\r\n", __func__); printf("%s: File extension should be .nky\n", __func__); return -DFX_INVALID_PARAM; } if (!file_exists(dfx_aes_key_file)) { printf("%s: User provided AES key file doesn't exist\r\n", __func__); return -DFX_INVALID_PARAM; } } } #ifdef ENABLE_LIBDFX_TIME static inline double gettime(struct timeval t0, struct timeval t1) { return ((t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec -t0.tv_usec) / 1000.0f); } #endif