pax_global_header00006660000000000000000000000064143661263150014521gustar00rootroot0000000000000052 comment=1e624fa5fd4ef3cc32a3d912b6789eb61f33a24a libzbd-2.0.4/000077500000000000000000000000001436612631500127725ustar00rootroot00000000000000libzbd-2.0.4/.gitignore000066400000000000000000000012631436612631500147640ustar00rootroot00000000000000# SPDX-License-Identifier: CC0-1.0 # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. # Object files *.o *.lo *.obj *.elf *.la *.so *.so.* *.out *.dump tools/zbd tools/gzbd tools/gzbd-viewer # Generated files *.desktop *.policy # Dependency files .depfile .depend # RPM packages build files and directories rpmbuild *.tar.gz *.rpm # Debian packages build files and directories debbuild *.deb # Other Thumbs.db desktop.ini .DS_Store *~ # Autotools stuff m4/*.m4 Makefile.in aclocal.m4 autom4te.cache/ build-aux/ configure include/config.h.in Makefile config.log config.status include/config.h include/stamp-h1 .deps libtool lib/libzbd.pc .libs .dirstamp libzbd-2.0.4/CODE_OF_CONDUCT.md000066400000000000000000000127011436612631500155720ustar00rootroot00000000000000 # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [Open Source Inquiries][contact]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations [contact]: https://www.westerndigital.com/contact/contact-open-source libzbd-2.0.4/LICENSES/000077500000000000000000000000001436612631500141775ustar00rootroot00000000000000libzbd-2.0.4/LICENSES/CC0-1.0.txt000066400000000000000000000156101436612631500156040ustar00rootroot00000000000000Creative Commons Legal Code CC0 1.0 Universal CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; ii. moral rights retained by the original author(s) and/or performer(s); iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; v. rights protecting the extraction, dissemination, use and reuse of data in a Work; vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. libzbd-2.0.4/LICENSES/GPL-3.0-or-later.txt000066400000000000000000001045151436612631500174110ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state 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) 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 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . libzbd-2.0.4/LICENSES/LGPL-3.0-or-later.txt000066400000000000000000000167431436612631500175320ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. libzbd-2.0.4/Makefile.am000066400000000000000000000015711436612631500150320ustar00rootroot00000000000000# SPDX-License-Identifier: LGPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. ACLOCAL_AMFLAGS = -I m4 SUBDIRS = lib tools EXTRA_DIST = autogen.sh \ README.md \ LICENSES/GPL-3.0-or-later.txt \ LICENSES/LGPL-3.0-or-later.txt if BUILDING_RPM rpmdir = $(abs_top_builddir)/rpmbuild EXTRA_DIST += libzbd.spec RPMARCH=`$(RPM) --eval %_target_cpu` rpm: dist @echo "Building RPM packages..." @mkdir -p $(rpmdir) $(RPMBUILD) -ta --clean -D "_topdir $(rpmdir)" libzbd-$(PACKAGE_VERSION).tar.gz @mv -f $(rpmdir)/RPMS/$(RPMARCH)/*.rpm $(abs_top_builddir) @mv -f $(rpmdir)/SRPMS/*.rpm $(abs_top_builddir) @rm -rf $(rpmdir) @rm -f libzbd-$(PACKAGE_VERSION).tar.gz else rpm: @echo "Building RPM packages requires rpmbuild and rpm utilities" exit 1 endif CLEANFILES = *.rpm *.tar.gz DISTCLEANFILES = *.rpm *.tar.gz configure libzbd-2.0.4/README.md000066400000000000000000000243431436612631500142570ustar00rootroot00000000000000Copyright (C) 2020 Western Digital Corporation or its affiliates. # libzbd *libzbd* is a library providing functions simplifying access to zoned block device information and the execution of zone management operations. An example command line application using *libzbd* is available under the tools directory. Additionally, graphical user interface applications are also implemented to visually represent the state and usage of zones of a zoned block device. ## License *libzbd* is distributed under the terms of the of the GNU Lesser General Public License Version 3 or any later verison ((SPDX: *LGPL-3.0-or-later*). A copy of this license with *libzbd* copyright can be found in the file [LICENSES/LGPL-3.0-or-later.txt](LICENSES/LGPL-3.0-or-later.txt). All example applications under the tools directory are distributed under the terms of the GNU General Public License version 3, or any later version. A copy of this license can be found in the file [LICENSES/GPL-3.0-or-later.txt](LICENSES/GPL-3.0-or-later.txt). If *libzbd* license files are missing, please see the LGPL version 3 text [here](https://www.gnu.org/licenses/lgpl-3.0.html) and the GPL version 3 text [here](https://www.gnu.org/licenses/gpl-3.0.html). All source files in *libzbd* contain the LGPL v3 or GPL v3 license SPDX short identifiers in place of the full license text. ``` SPDX-License-Identifier: LGPL-3.0-or-later SPDX-License-Identifier: GPL-3.0-or-later ``` Some files such as the `.gitignore` file are public domain specified by the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication. These files are identified with the following SPDX header. ``` SPDX-License-Identifier: CC0-1.0 ``` See the file [LICENSES/CC0-1.0.txt] for the full text of this license. *libzbd* and all its example applications are distributed "as is," without technical support, and WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ## Contributions and Bug Reports Contributions are accepted as github pull requests or via email (`git send-email` patches). Any problem may also be reported through github issues page or by contacting: * Damien Le Moal (damien.lemoal@wdc.com) * Niklas Cassel (niklas.cassel@wdc.com) PLEASE DO NOT SUBMIT CONFIDENTIAL INFORMATION OR INFORMATION SPECIFIC TO DRIVES THAT ARE VENDOR SAMPLES OR NOT PUBLICLY AVAILABLE. ## Compilation and installation ### Requirements *libzbd* requires the following packages for compilation: * m4 * autoconf * automake * libtool * m4 * GTK3 and GTK3 development headers (when building the *gzbd* and *gzbd-viewer* graphical applications) Since *libzbd* uses Linux(tm) kernel zoned block device interface, compilation must be done on a system where the kernel header file *blkzoned.h* for zoned block devices interface is installed under /usr/include/linux/. This implies that the kernel version must be higher than version 4.10.0. If the GTK3 and GTK3 development packages are not installed, compilation of the *gzbd* and *gzbd-viewer* graphical applications is automatically disabled. ### Compilation To compile the library and all example applications under the tools directory, execute the following commands. ``` $ sh ./autogen.sh $ ./configure $ make ``` ### Installation To install the library and all example applications compiled under the tools directory, execute the following command. ``` $ sudo make install ``` The library files are by default installed under `/usr/lib` (or `/usr/lib64`). The library header file is installed under `/usr/include/libzbd`. The executable files for the example applications are installed under `/usr/bin`. These default installation paths can be changed. Executing the following command displays the options used to control the installation paths. ``` $ ./configure --help ``` ### Building RPM Packages The *rpm* and *rpmbuild* utilities are necessary to build *libzbd* RPM packages. Once these utilities are installed, the RPM packages can be built using the following command. ``` $ sh ./autogen.sh $ ./configure $ make rpm ``` Five RPM packages are built: * A binary package providing *libzbd* library file, the tools executables, the tools man pages, documentation and license files. * A source RPM package * A *debuginfo* RPM package and a *debugsource* RPM package * A development package providing the *libzbd* header files The source RPM package can be used to build the binary and debug RPM packages outside of *libzbd* source tree using the following command. ``` $ rpmbuild --rebuild libzbd-.src.rpm ``` ## Library *libzbd* defines a set of functions and data structures simplifying the management and use of zoned block devices. ### Overview *libzbd* functions and data structures are defined in the header file [include/libzbd/zbd.h]. Applications using *libzbd* must include this header file and compile against *libzbd* using dynamic linking (`libzbd.so` library file) or statically linking using the `libzbd.a` archive file. *libzbd* internal implementation is simple. No internal library state is maintained at run-time, with the exception of a list of open zoned block device. Data types and units used by regular file access system calls are reused. * Open zoned block device files are identified using a file descriptor similar to one that the *open()* system call returns. * Zone information such as zone start position, zone size and zone write pointer position use Byte unit, the same unit as used by system calls such as *fseek()*, *read()* or *write()* for file offset position and I/O buffer sizes. *libzbd* provides data structures for describing zones of a zoned block device (*struct zbd_zone*) and providing information about the device itself (*struct zbd_info*). ### Library Functions *libzbd* implements the following functions. Function | Description ----------------------- | ----------------------------------------------- *zbd_device_is_zoned()* | Test if a block device is a zoned block device *zbd_open()* | Open a zoned block device *zbd_close()* | Close a zoned block device *zbd_get_info()* | Get an open zoned block device information *zbd_report_zones()*
*zbd_list_zones()* | Get zone information of an open device *zbd_report_nr_zones()* | Get the number of zones of an open device *zbd_zone_operation()* | Execute a zone management operation *zbd_reset_zones()* | Reset the write pointer position of a range of zones *zbd_open_zones()* | Explicitly open a range of zones *zbd_close_zones()* | Explicitly close a range of open zones *zbd_finish_zones()* | Finish a range of zones The following macro definitions are defined to facilitate manipulation of a zone descriptor information (*struct zbd_zone*). Function | Description ----------------------- | -------------------------------------------------- *zbd_zone_type()* | Get a zone type (*enum zbd_zone_type*) *zbd_zone_cnv()* | Test if a zone type is conventional *zbd_zone_swr()* | Test if a zone type is sequential write required *zbd_zone_swp()* | Test if a zone type is sequential write preferred *zbd_zone_seq()* | Test if zone type is sequential (not conventional) *zbd_zone_cond()* | Get a zone condition (*enum zbd_zone_cond*) *zbd_zone_not_wp()* | Test if a zone is "not write pointer" (conventional zones) *zbd_zone_empty()* | Test if a zone is empty *zbd_zone_imp_open()* | Test if a zone is implicitly open *zbd_zone_exp_open()* | Test if a zone is explicitly open *zbd_zone_is_open()* | Test if a zone is open (implicitly or explicitly) *zbd_zone_closed()* | Test if a zone is closed *zbd_zone_full()* | Test if a zone is full *zbd_zone_rdonly()* | Test if a zone is read-only *zbd_zone_offline()* | Test if a zone is offline *zbd_zone_start()* | Get a zone start position (bytes) *zbd_zone_len()* | Get a zone size (bytes) *zbd_zone_capacity()* | Get a zone capacity (bytes) *zbd_zone_wp()* | Get a zone write pointer position (bytes) *zbd_zone_flags()* | Get a zone state flags *zbd_zone_rwp_recommended()* | Test if a zone indicates reset write pointer recommended *zbd_zone_non_seq_resources()* | Test if a zone indicates using non-sequential write resources The followimg utility functions are also defined. Function | Description ------------------------ | -------------------------------------------------- *zbd_set_log_level()* | Set the logging level of the library functions *zbd_device_model_str()* | Get a string describing a device zoned model *zbd_zone_type_str()* | Get a string describing a zone type *zbd_zone_cond_str()* | Get a string describing a zone condition ### Thread Safety Since *libzbd* does not maintain any internal state for open zoned block devices, that is, it does not dynamically maintain the zone state of open zoned block devices, no synchronization mechanism for multiple threads applications is implemented. It is the responsibility of the application to ensure that zones of a device are manipulated correctly with mutual exclusion when needed. This is in particular necessary for operations like concurrent write to the same zone by multiple threads or the execution of zone management operations while reading or writing the target zones. ### Functions Documentation *libzbd* functions and data types are documented in more details using code comments in the file [include/libzbd/zbd.h]. ## Tools Under the tools directory, several simple applications are available as examples. These appliations are as follows. * **zbd** This application execute zone commands on a device. * **gzbd** provides a graphical user interface showing zone information of a zoned block device. It also displays the write status (write pointer position) of zones graphically using color coding (red for written space and green for unwritten space). Operations on zones can also be executed directly from the interface (reset zone write pointer, open zone, close zone, etc). * **gzbd-viewer** provides a simple graphical user interface showing the write pointer position and zone state of zones of a zoned block device. Similar color coding as *gzbd* is used. This application automatically refresh the device zone information after a configurable timeout elapses. The default refresh cycle is 2 times per seconds (500 ms). libzbd-2.0.4/autogen.sh000077500000000000000000000002401436612631500147670ustar00rootroot00000000000000#!/bin/sh # # SPDX-License-Identifier: LGPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. exec autoreconf -f -i libzbd-2.0.4/configure.ac000066400000000000000000000047531436612631500152710ustar00rootroot00000000000000# SPDX-License-Identifier: LGPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. AC_INIT([libzbd], [2.0.4], [damien.lemoal@wdc.com, niklas.cassel@wdc.com], [libzbd], [https://github.com/westerndigitalcorporation/libzbd]) AC_CONFIG_AUX_DIR([build-aux]) AC_CANONICAL_TARGET AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADERS([include/config.h]) AC_PREFIX_DEFAULT(/usr) AM_INIT_AUTOMAKE([-Wall foreign subdir-objects]) AM_SILENT_RULES([yes]) # Change default CFLAGS from "-g -O2" to "-O2" for regular builds. AC_ARG_ENABLE(debug, [ --enable-debug Compile with "-g" option], [DBGCFLAGS="-g"], [DBGCFLAGS="-O2"]) CFLAGS="$CFLAGS $DBGCFLAGS" AC_PROG_CC AM_PROG_CC_C_O AC_PROG_INSTALL AC_USE_SYSTEM_EXTENSIONS AC_SYS_LARGEFILE m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) m4_pattern_allow([AM_PROG_AR]) LT_INIT # Package version details: .. PACKAGE_VERSION_MAJOR=$(echo $PACKAGE_VERSION | awk -F. '{print $1}') PACKAGE_VERSION_MINOR=$(echo $PACKAGE_VERSION | awk -F. '{print $2}') PACKAGE_VERSION_RELEASE=$(echo $PACKAGE_VERSION | awk -F. '{print $3}') # libtool friendly library version format LIBZBD_VERSION_LT=$PACKAGE_VERSION_MAJOR:$PACKAGE_VERSION_MINOR:$PACKAGE_VERSION_RELEASE AC_SUBST([LIBZBD_VERSION_LT]) # Checks for rpm package builds AC_PATH_PROG([RPMBUILD], [rpmbuild], [notfound]) AC_PATH_PROG([RPM], [rpm], [notfound]) AM_CONDITIONAL([BUILDING_RPM], [test "x$RPMBUILD" != xnotfound && test "x$RPM" != xnotfound]) # Checks for header files AC_CHECK_HEADER(libgen.h, [], [AC_MSG_ERROR([Couldn't find libgen.h])], [[#include ]]) AC_CHECK_HEADER(linux/blkzoned.h, [], [AC_MSG_ERROR([Couldn't find linux/blkzoned.h. Kernel too old ?])], [[#include ]]) AC_CHECK_MEMBER([struct blk_zone.capacity], [AC_DEFINE(HAVE_BLK_ZONE_REP_V2, [1], [report zones includes zone capacity])], [], [[#include ]]) # Conditionals # Build GUI tools only if GTK3 is installed and can be detected with pkg-config. AC_ARG_ENABLE([gui], AS_HELP_STRING([--disable-gui], [Disable build of GUI tools (gzbd and gzbd-viewer) [default=no]])) AS_IF([test "x$enable_gui" != "xno"], [m4_ifdef([PKG_CHECK_MODULES], [PKG_CHECK_MODULES([GTK], [gtk+-3.0], [HAVE_GTK3=1], [HAVE_GTK3=0])], [HAVE_GTK3=0]) AM_CONDITIONAL([BUILD_GUI], [test "$HAVE_GTK3" -eq 1])], [AM_CONDITIONAL([BUILD_GUI], false)]) AC_CONFIG_FILES([ lib/libzbd.pc lib/Makefile tools/Makefile Makefile ]) AC_OUTPUT libzbd-2.0.4/debian/000077500000000000000000000000001436612631500142145ustar00rootroot00000000000000libzbd-2.0.4/debian/changelog000066400000000000000000000034101436612631500160640ustar00rootroot00000000000000libzbd (2.0.2-2) unstable; urgency=medium * Source only upload. -- Sudip Mukherjee Tue, 15 Feb 2022 22:02:14 +0000 libzbd (2.0.2-1) unstable; urgency=medium [ Debian Janitor ] * Set upstream metadata fields: Bug-Database, Bug-Submit, Repository, Repository-Browse. * Update standards version to 4.6.0, no changes needed. [ Sudip Mukherjee ] * New upstream version 2.0.2 - Update version for SONAME change. - Update symbols. * Update Standards-Version to 4.6.0.1 -- Sudip Mukherjee Mon, 14 Feb 2022 14:23:27 +0000 libzbd (1.5.0-1) unstable; urgency=medium * Upload to unstable. * New upstream version 1.5.0 - Update installed library name. - Update library name in symbols. -- Sudip Mukherjee Wed, 18 Aug 2021 23:00:07 +0100 libzbd (1.4.0-1) experimental; urgency=medium * New upstream version 1.4.0 - Update symbols. - Update copyright. -- Sudip Mukherjee Fri, 11 Jun 2021 23:41:24 +0100 libzbd (1.3.0-1) experimental; urgency=medium * New upstream version 1.3.0 - Update copyright. - Update symbols. -- Sudip Mukherjee Fri, 16 Apr 2021 19:50:56 +0100 libzbd (1.2.0-1) unstable; urgency=medium * New upstream version 1.2.0 - Update symbols. - Update copyright. -- Sudip Mukherjee Sat, 16 Jan 2021 22:53:00 +0000 libzbd (1.1.0-2) unstable; urgency=medium * Source only upload. -- Sudip Mukherjee Sun, 10 Jan 2021 18:23:39 +0000 libzbd (1.1.0-1) unstable; urgency=medium * Initial release (Closes: #977914) -- Sudip Mukherjee Wed, 23 Dec 2020 23:39:53 +0000 libzbd-2.0.4/debian/control000066400000000000000000000034751436612631500156300ustar00rootroot00000000000000Source: libzbd Priority: optional Maintainer: Sudip Mukherjee Build-Depends: debhelper-compat (= 13), autoconf-archive, libgtk-3-dev Standards-Version: 4.6.0.1 Section: libs Homepage: https://zonedstorage.io/projects/libzbd/ Vcs-Browser: https://salsa.debian.org/sudip/libzbd Vcs-Git: https://salsa.debian.org/sudip/libzbd.git Package: libzbd-dev Section: libdevel Architecture: linux-any Multi-Arch: same Depends: libzbd2 (= ${binary:Version}), ${misc:Depends} Description: Library to manipulate zoned block devices (development files) libzbd uses the kernel provided zoned block device interface based on the ioctl() system call. It provides functions for discovering and managing the state of zones of zoned block devices. Read and write accesses to the devices can be done using standard standard I/O system calls. . This package is needed to compile programs against libzbd. Package: libzbd2 Architecture: linux-any Multi-Arch: same Depends: ${shlibs:Depends}, ${misc:Depends} Description: Library to manipulate zoned block devices (shared library) libzbd uses the kernel provided zoned block device interface based on the ioctl() system call. It provides functions for discovering and managing the state of zones of zoned block devices. Read and write accesses to the devices can be done using standard standard I/O system calls. . This package contains the shared library. Package: zbd-utils Section: utils Architecture: linux-any Depends: ${shlibs:Depends}, ${misc:Depends} Description: Utilities to manipulate zoned block devices zbd is a command line utility to report, open, close, reset and finish zones of a device. . gzbd is similar to zbd but using a graphical user interface. . gzbd-viewer is a graphical user interface showing the condition and state of zones of a zoned block device. libzbd-2.0.4/debian/copyright000066400000000000000000000052461436612631500161560ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: libzbd Upstream-Contact: Damien Le Moal Source: https://github.com/westerndigitalcorporation/libzbd Files: * Copyright: 2020, 2021, Western Digital Corporation or its affiliates License: GPL-3.0-or-later Files: Makefile.am autogen.sh configure.ac lib/exports include/libzbd/zbd.h lib/Makefile.am lib/zbd.c lib/zbd.h lib/zbd_utils.c lib/libzbd.pc.in libzbd.spec Copyright: 2020, Western Digital Corporation or its affiliates License: LGPL-3.0-or-later Files: m4/dontremove .gitignore Copyright: 2020, Western Digital Corporation or its affiliates License: CC0-1.0 Files: debian/* Copyright: 2020, Sudip Mukherjee License: GPL-3.0-or-later License: GPL-3.0-or-later This package 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 3 of the License, or (at your option) any later version. . This package 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, see . On Debian systems, the complete text of the GNU General Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". License: LGPL-3.0-or-later This package is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. . This package 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 Lesser General Public License for more details. . You should have received a copy of the GNU General Public License along with this program. If not, see . . On Debian systems, the complete text of the GNU Lesser General Public License can be found in "/usr/share/common-licenses/LGPL-3" License: CC0-1.0 On Debian systems, the full text of the CC0 1.0 Universal License can be found in the file "/usr/share/common-licenses/CC0-1.0" libzbd-2.0.4/debian/libzbd-dev.install000066400000000000000000000001161436612631500176240ustar00rootroot00000000000000usr/include/libzbd usr/lib/*/libzbd.a usr/lib/*/libzbd.so usr/lib/*/pkgconfig libzbd-2.0.4/debian/libzbd2.install000066400000000000000000000000261436612631500171320ustar00rootroot00000000000000usr/lib/*/libzbd.so.* libzbd-2.0.4/debian/libzbd2.symbols000066400000000000000000000006631436612631500171630ustar00rootroot00000000000000libzbd.so.2 libzbd2 #MINVER# ZBD_GLOBAL@ZBD_GLOBAL 1.1.0 zbd_close@ZBD_GLOBAL 1.1.0 zbd_device_is_zoned@ZBD_GLOBAL 1.1.0 zbd_device_model_str@ZBD_GLOBAL 1.1.0 zbd_get_info@ZBD_GLOBAL 2.0.2 zbd_list_zones@ZBD_GLOBAL 1.1.0 zbd_open@ZBD_GLOBAL 1.1.0 zbd_report_zones@ZBD_GLOBAL 1.1.0 zbd_set_log_level@ZBD_GLOBAL 1.1.0 zbd_zone_cond_str@ZBD_GLOBAL 1.1.0 zbd_zone_type_str@ZBD_GLOBAL 1.1.0 zbd_zones_operation@ZBD_GLOBAL 1.1.0 libzbd-2.0.4/debian/not-installed000066400000000000000000000000241436612631500167100ustar00rootroot00000000000000usr/lib/*/libzbd.la libzbd-2.0.4/debian/rules000077500000000000000000000000361436612631500152730ustar00rootroot00000000000000#!/usr/bin/make -f %: dh $@ libzbd-2.0.4/debian/salsa-ci.yml000066400000000000000000000010271436612631500164330ustar00rootroot00000000000000# For more information on what jobs are run see: # https://salsa.debian.org/salsa-ci-team/pipeline # # To enable the jobs, go to your repository (at salsa.debian.org) # and click over Settings > CI/CD > Expand (in General pipelines). # In "Custom CI config path" write debian/salsa-ci.yml and click # in "Save Changes". The CI tests will run after the next commit. --- include: - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/salsa-ci.yml - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/pipeline-jobs.yml libzbd-2.0.4/debian/source/000077500000000000000000000000001436612631500155145ustar00rootroot00000000000000libzbd-2.0.4/debian/source/format000066400000000000000000000000141436612631500167220ustar00rootroot000000000000003.0 (quilt) libzbd-2.0.4/debian/tests/000077500000000000000000000000001436612631500153565ustar00rootroot00000000000000libzbd-2.0.4/debian/tests/control000066400000000000000000000001231436612631500167550ustar00rootroot00000000000000Test-Command: gzbd --help; gzbd-viewer --help Depends: @ Restrictions: superficial libzbd-2.0.4/debian/upstream/000077500000000000000000000000001436612631500160545ustar00rootroot00000000000000libzbd-2.0.4/debian/upstream/metadata000066400000000000000000000004431436612631500175600ustar00rootroot00000000000000--- Bug-Database: https://github.com/westerndigitalcorporation/libzbd/issues Bug-Submit: https://github.com/westerndigitalcorporation/libzbd/issues/new Repository: https://github.com/westerndigitalcorporation/libzbd.git Repository-Browse: https://github.com/westerndigitalcorporation/libzbd libzbd-2.0.4/debian/watch000066400000000000000000000003041436612631500152420ustar00rootroot00000000000000version=4 opts="filenamemangle=s%(?:.*?)?v?(\d[\d.]*)\.tar\.gz%libzbd-$1.tar.gz%" \ https://github.com/westerndigitalcorporation/libzbd/tags \ (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate libzbd-2.0.4/debian/zbd-utils.install000066400000000000000000000000261436612631500175170ustar00rootroot00000000000000usr/bin/* usr/share/* libzbd-2.0.4/include/000077500000000000000000000000001436612631500144155ustar00rootroot00000000000000libzbd-2.0.4/include/libzbd/000077500000000000000000000000001436612631500156635ustar00rootroot00000000000000libzbd-2.0.4/include/libzbd/zbd.h000066400000000000000000000426351436612631500166250ustar00rootroot00000000000000/* * SPDX-License-Identifier: LGPL-3.0-or-later * * Copyright (c) 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) * Ting Yao */ #ifndef _LIBZBD_H_ #define _LIBZBD_H_ #ifdef __cplusplus extern "C" { #endif #include #include #include #include #include #include /** * @brief Zone types * * @ZBD_ZONE_TYPE_CNV: The zone has no write pointer and can be writen * randomly. Zone reset has no effect on the zone. * @ZBD_ZONE_TYPE_SWR: The zone must be written sequentially * @ZBD_ZONE_TYPE_SWP: The zone can be written randomly */ enum zbd_zone_type { ZBD_ZONE_TYPE_CNV = BLK_ZONE_TYPE_CONVENTIONAL, ZBD_ZONE_TYPE_SWR = BLK_ZONE_TYPE_SEQWRITE_REQ, ZBD_ZONE_TYPE_SWP = BLK_ZONE_TYPE_SEQWRITE_PREF, }; /** * @brief Zone conditions (state) * * @ZBD_ZONE_COND_NOT_WP: The zone has no write pointer, it is conventional. * @ZBD_ZONE_COND_EMPTY: The zone is empty. * @ZBD_ZONE_COND_IMP_OPEN: The zone is open, but not explicitly opened. * @ZBD_ZONE_COND_EXP_OPEN: The zones was explicitly opened by an * OPEN ZONE command. * @ZBD_ZONE_COND_CLOSED: The zone was [explicitly] closed after writing. * @ZBD_ZONE_COND_FULL: The zone is marked as full, possibly by a zone * FINISH ZONE command. * @ZBD_ZONE_COND_READONLY: The zone is read-only. * @ZBD_ZONE_COND_OFFLINE: The zone is offline (dead). */ enum zbd_zone_cond { ZBD_ZONE_COND_NOT_WP = BLK_ZONE_COND_NOT_WP, ZBD_ZONE_COND_EMPTY = BLK_ZONE_COND_EMPTY, ZBD_ZONE_COND_IMP_OPEN = BLK_ZONE_COND_IMP_OPEN, ZBD_ZONE_COND_EXP_OPEN = BLK_ZONE_COND_EXP_OPEN, ZBD_ZONE_COND_CLOSED = BLK_ZONE_COND_CLOSED, ZBD_ZONE_COND_FULL = BLK_ZONE_COND_FULL, ZBD_ZONE_COND_READONLY = BLK_ZONE_COND_READONLY, ZBD_ZONE_COND_OFFLINE = BLK_ZONE_COND_OFFLINE, }; /** * @brief Zone flags * * @ZBD_ZONE_RWP_RECOMMENDED: The zone should be reset. * @ZBD_ZONE_NON_SEQ: The zone is using non-sequential write resources. */ enum zbd_zone_flags { ZBD_ZONE_RWP_RECOMMENDED = (1U << 0), ZBD_ZONE_NON_SEQ_RESOURCES = (1U << 1), }; /** * @brief Zone descriptor data structure * * Provide information on a zone with all position and size values in bytes. */ struct zbd_zone { unsigned long long start; /* Zone start */ unsigned long long len; /* Zone length */ unsigned long long capacity; /* Zone capacity */ unsigned long long wp; /* Zone write pointer */ unsigned int flags; /* Zone state flags */ unsigned int type; /* Zone type */ unsigned int cond; /* Zone condition */ uint8_t reserved[20]; /* Padding to 64B */ } __attribute__((packed)); /** * @brief Library log levels */ enum zbd_log_level { ZBD_LOG_NONE = 0, /* Disable all messages */ ZBD_LOG_ERROR, /* Output details about errors */ ZBD_LOG_DEBUG, /* Debug-level messages */ }; /** * @brief Set the library log level * @param[in] log_level Library log level * * Set the library log level using the level name specified by \a log_level. * Log level are incremental: each level includes the levels preceding it. * Valid log level names are: * "none" : Silent operation (no messages) * "warning" : Print device level standard compliance problems * "error" : Print messages related to unexpected errors * "info" : Print normal information messages * "debug" : Verbose output decribing internally executed commands * The default level is "warning". */ extern void zbd_set_log_level(enum zbd_log_level); /** * @brief Block device zone models. */ enum zbd_dev_model { ZBD_DM_HOST_MANAGED = 1, ZBD_DM_HOST_AWARE, ZBD_DM_NOT_ZONED, }; /** * @brief Device information vendor id string maximum length. */ #define ZBD_VENDOR_ID_LENGTH 32 /** * @brief Device information data structure * * Provide information on a device open using the \a zbd_open function. */ struct zbd_info { /** * Device vendor, model and firmware revision string. */ char vendor_id[ZBD_VENDOR_ID_LENGTH]; /** * Total number of 512B sectors of the device. */ unsigned long long nr_sectors; /** * Total number of logical blocks of the device. */ unsigned long long nr_lblocks; /** * Total number of physical blocks of the device. */ unsigned long long nr_pblocks; /** * Size in bytes of a zone. */ unsigned long long zone_size; /** * Size in 512B sectors of a zone. */ unsigned int zone_sectors; /** * Size in bytes of the device logical blocks. */ unsigned int lblock_size; /** * Size in bytes of the device physical blocks. */ unsigned int pblock_size; /** * Number of zones. */ unsigned int nr_zones; /** * Maximum number of explicitely open zones. A value of 0 means that * the device has no limit. A value of -1 means that the value is * unknown. */ unsigned int max_nr_open_zones; /** * Maximum number of active zones. A value of 0 means that the device * has no limit. A value of -1 means that the value is unknown. */ unsigned int max_nr_active_zones; /** * Device zone model. */ unsigned int model; /** * Padding to 128B. */ uint8_t reserved[36]; } __attribute__((packed)); /** * @brief Test if a device is a zoned block device * @param[in] filename Path to the device file * @param[in] info Address where to store the device information * * Test if a device supports the ZBD/ZAC command set. If \a fake is false, * only test physical devices. Otherwise, also test regular files and * regular block devices that may be in use with the fake backend driver * to create an emulated host-managed zoned block device. * If \a info is not NULL and the device is identified as a zoned * block device, the device information is returned at the address * specified by \a info. * * @return Returns a negative error code if the device test failed. * 1 is returned if the device is identified as a zoned zoned block device. * Otherwise, 0 is returned. */ extern int zbd_device_is_zoned(const char *filename); /** * @brief Open a ZBD device * @param[in] filename Path to a device file * @param[in] flags Device file open flags * @param[out] info Device information * * Opens the device specified by \a filename, and returns a file descriptor * number similarly to the regular open() system call. If @info is non-null, * information on the device is returned at the specified address. * * @return If the device is not a zoned block device, -ENXIO is returned. * Any other error code returned by open(2) can be returned as well. */ extern int zbd_open(const char *filename, int flags, struct zbd_info *info); /** * @brief Close a ZBD device * @param[in] fd File descriptor obtained with \a zbd_open * * Performs the equivalent to close(2) for a zoned block device open * using \a zbd_open. */ extern void zbd_close(int fd); /** * @brief Get a device information * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] info Address of the information structure to fill * * Get information about an open device. The \a info parameter is used to * return a device information. \a info must be allocated by the caller. */ extern int zbd_get_info(int fd, struct zbd_info *info); /** * @brief Reporting options definitions * * Used to filter the zone information returned by the execution of a * REPORT ZONES command. Filtering is based on the value of the reporting * option and on the condition of the zones at the time of the execution of * the REPORT ZONES command. * * ZBD_RO_PARTIAL is not a filter: this reporting option can be combined * (or'ed) with any other filter option to limit the number of reported * zone information to the size of the REPORT ZONES command buffer. */ enum zbd_report_option { /* Report all zones */ ZBD_RO_ALL = 0x00, /* Report only empty zones */ ZBD_RO_EMPTY = 0x01, /* Report only implicitly open zones */ ZBD_RO_IMP_OPEN = 0x02, /* Report only explicitly open zones */ ZBD_RO_EXP_OPEN = 0x03, /* Report only closed zones */ ZBD_RO_CLOSED = 0x04, /* Report only full zones */ ZBD_RO_FULL = 0x05, /* Report only read-only zones */ ZBD_RO_RDONLY = 0x06, /* Report only offline zones */ ZBD_RO_OFFLINE = 0x07, /* Report only zones with reset recommended flag set */ ZBD_RO_RWP_RECOMMENDED = 0x10, /* Report only zones with the non-sequential resource used flag set */ ZBD_RO_NON_SEQ = 0x11, /* Report only conventional zones (non-write-pointer zones) */ ZBD_RO_NOT_WP = 0x3f, }; /** * @brief Get zone information * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset from which to report zones * @param[in] len Maximum length in bytes from \a ofst of the device * capacity range to inspect for the report * @param[in] ro Reporting options * @param[in] zones Pointer to the array of zone information to fill * @param[out] nr_zones Number of zones in the array \a zones * * Get zone information of at most \a nr_zones zones in the range * [ofst..ofst+len] and matching the \a ro option. If \a len is 0, * at most \a nr_zones zones starting from \a ofst up to the end on the device * capacity will be reported. * Return the zone information obtained in the array \a zones and the number * of zones reported at the address specified by \a nr_zones. * The array \a zones must be allocated by the caller and \a nr_zones * must point to the size of the allocated array (number of zone information * structures in the array). The first zone reported will be the zone * containing or after \a ofst. The last zone reported will be the zone * containing or before \a ofst + \a len. * * @return Returns 0 on success and -1 otherwise. */ extern int zbd_report_zones(int fd, off_t ofst, off_t len, enum zbd_report_option ro, struct zbd_zone *zones, unsigned int *nr_zones); /** * @brief Get number of zones * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset from which to report zones * @param[in] len Maximum length in bytes from \a ofst of the device * capacity range to inspect for the report * @param[in] ro Reporting options * @param[out] nr_zones The number of matching zones * * Similar to \a zbd_report_zones, but returns only the number of zones that * \a zbd_report_zones would have returned. This is useful to determine the * number of zones of a device to allocate an array of zone information * structures for use with \a zbd_report_zones. * * @return Returns 0 on success and -1 otherwise. */ static inline int zbd_report_nr_zones(int fd, off_t ofst, off_t len, enum zbd_report_option ro, unsigned int *nr_zones) { return zbd_report_zones(fd, ofst, len, ro, NULL, nr_zones); } /** * @brief Get zone information * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset from which to report zones * @param[in] len Maximum length in bytes from \a ofst of the device * capacity range to inspect for the report * @param[in] ro Reporting options * @param[out] zones The array of zone information filled * @param[out] nr_zones Number of zones in the array \a zones * * Similar to \a zbd_report_zones, but also allocates an appropriatly sized * array of zone information structures and return the address of the array * at the address specified by \a zones. The size of the array allocated and * filled is returned at the address specified by \a nr_zones. Freeing of the * memory used by the array of zone information structures allocated by this * function is the responsability of the user. * * @return Returns 0 on success and -1 otherwise. * Returns -ENOMEM if memory could not be allocated for \a zones. */ extern int zbd_list_zones(int fd, off_t ofst, off_t len, enum zbd_report_option ro, struct zbd_zone **zones, unsigned int *nr_zones); /** * @brief Zone management operations. */ enum zbd_zone_op { /** * Reset zones write pointer. */ ZBD_OP_RESET = 0x01, /** * Explicitly open zones. */ ZBD_OP_OPEN = 0x02, /** * Close opened zones. */ ZBD_OP_CLOSE = 0x03, /** * Transition zones to full state. */ ZBD_OP_FINISH = 0x04, }; /** * @brief Execute an operation on a range of zones * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset identifying the first zone to operate on * @param[in] len Maximum length in bytes from \a ofst of the set of zones * to operate on * @param[in] op The operation to perform * * Exexcute an operation on the range of zones defined by [ofst..ofst+len] * If \a len is 0, all zones from \a ofst will be processed. * The validity of the operation (reset, open, close or finish) depends on the * type and condition of the target zones. * * @return Returns 0 on success and -1 otherwise. */ extern int zbd_zones_operation(int fd, enum zbd_zone_op op, off_t ofst, off_t len); /** * @brief Reset the write pointer of a range of zones * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset identifying the first zone to reset * @param[in] len Maximum length in bytes from \a ofst of the set of zones * to reset * * Resets the write pointer of the zones in the range [ofst..ofst+len]. * If \a len is 0, all zones from \a ofst will be processed. * * @return Returns 0 on success and -1 otherwise. */ static inline int zbd_reset_zones(int fd, off_t ofst, off_t len) { return zbd_zones_operation(fd, ZBD_OP_RESET, ofst, len); } /** * @brief Explicitly open a range of zones * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset identifying the first zone to open * @param[in] len Maximum length in bytes from \a ofst of the set of zones * to open * * Explicitly open the zones in the range [ofst..ofst+len]. If \a len is 0, * all zones from \a ofst will be processed. * * @return Returns 0 on success and -1 otherwise. */ static inline int zbd_open_zones(int fd, off_t ofst, off_t len) { return zbd_zones_operation(fd, ZBD_OP_OPEN, ofst, len); } /** * @brief Close a range of zones * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset identifying the first zone to close * @param[in] len Maximum length in bytes from \a ofst of the set of zones * to close * * Close the zones in the range [ofst..ofst+len]. * If \a len is 0, all zones from \a ofst will be processed. * * @return Returns 0 on success and -1 otherwise. */ static inline int zbd_close_zones(int fd, off_t ofst, off_t len) { return zbd_zones_operation(fd, ZBD_OP_CLOSE, ofst, len); } /** * @brief Finish a range of zones * @param[in] fd File descriptor obtained with \a zbd_open * @param[in] ofst Byte offset identifying the first zone to finish * @param[in] len Maximum length in bytes from \a ofst of the set of zones * to finish * * Finish the zones in the range [ofst..ofst+len]. * If \a len is 0, all zones from \a ofst will be processed. * * @return Returns 0 on success and -1 otherwise. */ static inline int zbd_finish_zones(int fd, off_t ofst, off_t len) { return zbd_zones_operation(fd, ZBD_OP_FINISH, ofst, len); } /** * Accessors */ #define zbd_zone_type(z) ((z)->type) #define zbd_zone_cnv(z) ((z)->type == ZBD_ZONE_TYPE_CNV) #define zbd_zone_swr(z) ((z)->type == ZBD_ZONE_TYPE_SWR) #define zbd_zone_swp(z) ((z)->type == ZBD_ZONE_TYPE_SWP) #define zbd_zone_seq(z) (zbd_zone_swr(z) || zbd_zone_swp(z)) #define zbd_zone_cond(z) ((z)->cond) #define zbd_zone_not_wp(z) ((z)->cond == ZBD_ZONE_COND_NOT_WP) #define zbd_zone_empty(z) ((z)->cond == ZBD_ZONE_COND_EMPTY) #define zbd_zone_imp_open(z) ((z)->cond == ZBD_ZONE_COND_IMP_OPEN) #define zbd_zone_exp_open(z) ((z)->cond == ZBD_ZONE_COND_EXP_OPEN) #define zbd_zone_is_open(z) (zbd_zone_imp_open(z) || zbd_zone_exp_open(z)) #define zbd_zone_closed(z) ((z)->cond == ZBD_ZONE_COND_CLOSED) #define zbd_zone_is_active(z) (zbd_zone_is_open(z) || zbd_zone_closed(z)) #define zbd_zone_full(z) ((z)->cond == ZBD_ZONE_COND_FULL) #define zbd_zone_rdonly(z) ((z)->cond == ZBD_ZONE_COND_READONLY) #define zbd_zone_offline(z) ((z)->cond == ZBD_ZONE_COND_OFFLINE) #define zbd_zone_start(z) ((z)->start) #define zbd_zone_len(z) ((z)->len) #define zbd_zone_capacity(z) ((z)->capacity) #define zbd_zone_wp(z) ((z)->wp) #define zbd_zone_flags(z) ((z)->flags) #define zbd_zone_rwp_recommended(z) ((z)->flags & ZBD_ZONE_RWP_RECOMMENDED) #define zbd_zone_non_seq_resources(z) ((z)->flags & ZBD_ZONE_NON_SEQ_RESOURCES) /** * @brief Returns a string describing a device zone model * @param[in] model Device model * @param[in] s Get abbreviated name * * Return a string (long or abbreviated) describing a device zone model. * * @return Device model string or NULL for an invalid model. */ extern const char *zbd_device_model_str(enum zbd_dev_model model, bool s); /** * @brief Returns a string describing a zone type * @param[in] z Zone descriptor * @param[in] s Get abbreviated zone type name * * Return a string (long or abbreviated) describing a zone type. * * @return Zone type string or NULL for an invalid zone type. */ extern const char *zbd_zone_type_str(struct zbd_zone *z, bool s); /** * @brief Returns a string describing a zone condition * @param[in] z Zone descriptor * @param[in] s Get abbreviated zone condition name * * Return a string (long or abbreviated) describing a zone condition. * * @return Zone type string or NULL for an invalid zone condition. */ extern const char *zbd_zone_cond_str(struct zbd_zone *z, bool s); #ifdef __cplusplus } #endif #endif /* _LIBZBD_H_ */ libzbd-2.0.4/lib/000077500000000000000000000000001436612631500135405ustar00rootroot00000000000000libzbd-2.0.4/lib/Makefile.am000066400000000000000000000012371436612631500155770ustar00rootroot00000000000000# SPDX-License-Identifier: LGPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. AM_CFLAGS = \ $(CFLAGS) \ -Wall -Wextra -Wno-unused-parameter \ -I$(top_srcdir)/include pkgconfdir = $(libdir)/pkgconfig pkgconf_DATA = libzbd.pc pkginclude_HEADERS = ../include/libzbd/zbd.h lib_LTLIBRARIES = libzbd.la EXTRA_DIST = exports CFILES = \ zbd.c \ zbd_utils.c HFILES = \ zbd.h libzbd_la_DEPENDENCIES = exports libzbd_la_SOURCES = $(CFILES) $(HFILES) libzbd_la_CFLAGS = $(AM_CFLAGS) -fPIC libzbd_la_LDFLAGS = \ -lpthread \ -Wl,--version-script,exports \ -version-number @LIBZBD_VERSION_LT@ libzbd-2.0.4/lib/exports000066400000000000000000000005521436612631500151710ustar00rootroot00000000000000# SPDX-License-Identifier: LGPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. ZBD_GLOBAL { global: zbd_set_log_level; zbd_device_is_zoned; zbd_open; zbd_close; zbd_get_info; zbd_report_zones; zbd_list_zones; zbd_zones_operation; zbd_device_model_str; zbd_zone_type_str; zbd_zone_cond_str; local: *; }; libzbd-2.0.4/lib/libzbd.pc.in000066400000000000000000000006251436612631500157420ustar00rootroot00000000000000# SPDX-License-Identifier: LGPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: libzbd Description: A library simplifying management of zoned block devices Version: @PACKAGE_VERSION@ Cflags: -I${includedir} Libs: -L${libdir} -lzbd libzbd-2.0.4/lib/zbd.c000066400000000000000000000373431436612631500144750ustar00rootroot00000000000000// SPDX-License-Identifier: LGPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) * Ting Yao */ #include "zbd.h" #include #include #include #include #include #include #include #include #include /* * Per fd device information. */ #define ZBD_FD_MAX 1024 static struct zbd_info *zbd_fdi[ZBD_FD_MAX]; static inline struct zbd_info *zbd_get_fd(int fd) { if (fd < 0 || fd >= ZBD_FD_MAX) return NULL; return zbd_fdi[fd]; } static inline void zbd_put_fd(int fd) { free(zbd_fdi[fd]); zbd_fdi[fd] = NULL; } static int zbd_dev_path(const char *filename, char **path, char **devname) { char *p; /* Follow symlinks (required for device mapped devices) */ p = realpath(filename, NULL); if (!p) { zbd_error("%s: Failed to get real path %d (%s)\n", filename, errno, strerror(errno)); return -1; } *path = p; *devname = basename(p); return 0; } /* * Get a block device zone model. */ static enum zbd_dev_model zbd_get_dev_model(char *devname) { char str[128]; int ret; /* Check that this is a zoned block device */ ret = zbd_get_sysfs_attr_str(devname, "queue/zoned", str, sizeof(str)); if (ret) { long long val; /* * Assume old kernel or kernel without ZBD support enabled: try * a sysfs file that must exist for all block devices. If it is * found, then this is a regular non-zoned device. */ ret = zbd_get_sysfs_attr_int64(devname, "queue/logical_block_size", &val); if (ret == 0) return ZBD_DM_NOT_ZONED; return -1; } if (strcmp(str, "host-aware") == 0) return ZBD_DM_HOST_AWARE; if (strcmp(str, "host-managed") == 0) return ZBD_DM_HOST_MANAGED; if (strcmp(str, "none") == 0) return ZBD_DM_NOT_ZONED; return -1; } /* * Get max number of open/active zones. */ static void zbd_get_max_resources(char *devname, struct zbd_info *zbdi) { long long val; int ret; /* * According to max_open_zones/max_active_zones sysfs documentation, * a sysfs value of 0 means no limit. * * While the ZAC/ZBC standard has special treatment for unknown, * unknown is exported to sysfs as 0. * * Default both to unlimited, and set a limit if we managed to read * a limit from sysfs successfully. */ ret = zbd_get_sysfs_attr_int64(devname, "queue/max_open_zones", &val); if (ret) val = 0; zbdi->max_nr_open_zones = val; ret = zbd_get_sysfs_attr_int64(devname, "queue/max_active_zones", &val); if (ret) val = 0; zbdi->max_nr_active_zones = val; } /* * Get vendor ID. */ static int zbd_get_vendor_id(char *devname, struct zbd_info *zbdi) { char str[128]; int ret, n = 0; ret = zbd_get_sysfs_attr_str(devname, "device/vendor", str, sizeof(str)); if (!ret) n = snprintf(zbdi->vendor_id, ZBD_VENDOR_ID_LENGTH, "%s ", str); ret = zbd_get_sysfs_attr_str(devname, "device/model", str, sizeof(str)); if (!ret) n += snprintf(&zbdi->vendor_id[n], ZBD_VENDOR_ID_LENGTH - n, "%s ", str); ret = zbd_get_sysfs_attr_str(devname, "device/rev", str, sizeof(str)); if (!ret) n += snprintf(&zbdi->vendor_id[n], ZBD_VENDOR_ID_LENGTH - n, "%s", str); return n > 0; } /* * Get zone size in 512B sector unit. */ #ifdef BLKGETZONESZ static int zbd_get_zone_sectors(int fd, char *devname, __u32 *zone_sectors) { int ret; ret = ioctl(fd, BLKGETZONESZ, zone_sectors); if (ret) { zbd_error("ioctl BLKGETZONESZ failed %d (%s)\n", errno, strerror(errno)); return -1; } return 0; } #else static int zbd_get_zone_sectors(int fd, char *devname, __u32 *zone_sectors) { long long zs; int ret; ret = zbd_get_sysfs_attr_int64(devname, "queue/chunk_sectors", &zs); if (ret) { zbd_error("Get zone size from sysfs failed\n"); return -1; } if (zs >= UINT_MAX) { zbd_error("Invalid zone sectors %lld\n", zs); return -1; } *zone_sectors = zs; return 0; } #endif static int zbd_get_zone_size(int fd, char *devname, struct zbd_info *zbdi) { __u32 zone_sectors; int ret; ret = zbd_get_zone_sectors(fd, devname, &zone_sectors); if (ret) return ret; if (!zone_sectors) { zbd_error("Invalid 0 zone size\n"); return -1; } zbdi->zone_sectors = zone_sectors; zbdi->zone_size = (unsigned long long)zone_sectors << SECTOR_SHIFT; return 0; } /* * Get total number of zones. */ static int zbd_get_nr_zones(int fd, char *devname, struct zbd_info *zbdi) { __u32 nr_zones; #ifdef BLKGETNRZONES int ret = ioctl(fd, BLKGETNRZONES, &nr_zones); if (ret != 0) { zbd_error("ioctl BLKGETNRZONES failed %d (%s)\n", errno, strerror(errno)); return -1; } #else nr_zones = (zbdi->nr_sectors + zbdi->zone_sectors - 1) / zbdi->zone_sectors; #endif if (!nr_zones) { zbd_error("Invalid 0 number of zones\n"); return -1; } zbdi->nr_zones = nr_zones; return 0; } static struct zbd_info *zbd_do_get_info(int fd, char *devname) { unsigned long long size64; struct zbd_info *zbdi; int ret, size32; zbdi = malloc(sizeof(struct zbd_info)); if (!zbdi) return NULL; /* Get zone model */ zbdi->model = zbd_get_dev_model(devname); if (zbdi->model != ZBD_DM_HOST_AWARE && zbdi->model != ZBD_DM_HOST_MANAGED) { zbd_error("Invalid device zone model\n"); goto err; } /* Get logical block size */ ret = ioctl(fd, BLKSSZGET, &size32); if (ret != 0) { zbd_error("ioctl BLKSSZGET failed %d (%s)\n", errno, strerror(errno)); goto err; } zbdi->lblock_size = size32; if (zbdi->lblock_size <= 0) { zbd_error("invalid logical sector size %d\n", size32); goto err; } /* Get physical block size */ ret = ioctl(fd, BLKPBSZGET, &size32); if (ret != 0) { zbd_error("ioctl BLKPBSZGET failed %d (%s)\n", errno, strerror(errno)); goto err; } zbdi->pblock_size = size32; if (zbdi->pblock_size <= 0) { zbd_error("Invalid physical sector size %d\n", size32); goto err; } /* Get capacity (Bytes) */ ret = ioctl(fd, BLKGETSIZE64, &size64); if (ret != 0) { zbd_error("ioctl BLKGETSIZE64 failed %d (%s)\n", errno, strerror(errno)); goto err; } zbdi->nr_sectors = size64 >> SECTOR_SHIFT; zbdi->nr_lblocks = size64 / zbdi->lblock_size; if (!zbdi->nr_lblocks) { zbd_error("Invalid capacity (logical blocks)\n"); goto err; } zbdi->nr_pblocks = size64 / zbdi->pblock_size; if (!zbdi->nr_pblocks) { zbd_error("Invalid capacity (physical blocks)\n"); goto err; } /* Get zone size */ ret = zbd_get_zone_size(fd, devname, zbdi); if (ret) goto err; /* Get number of zones */ ret = zbd_get_nr_zones(fd, devname, zbdi); if (ret) goto err; /* Get max number of open/active zones */ zbd_get_max_resources(devname, zbdi); /* Finish setting */ if (!zbd_get_vendor_id(devname, zbdi)) strncpy(zbdi->vendor_id, "Unknown", ZBD_VENDOR_ID_LENGTH - 1); return zbdi; err: free(zbdi); return NULL; } /** * zbd_device_is_zoned - Test if a physical device is zoned. */ int zbd_device_is_zoned(const char *filename) { char *path = NULL, *devname = NULL; enum zbd_dev_model model; struct stat st; int ret; ret = zbd_dev_path(filename, &path, &devname); if (ret) return ret; /* Check device */ if (stat(path, &st) != 0) { zbd_error("Stat device file failed %d (%s)\n", errno, strerror(errno)); free(path); return 0; } if (!S_ISBLK(st.st_mode)) { free(path); return 0; } model = zbd_get_dev_model(devname); free(path); return model == ZBD_DM_HOST_AWARE || model == ZBD_DM_HOST_MANAGED; } /** * zbd_open - open a ZBD device */ int zbd_open(const char *filename, int flags, struct zbd_info *info) { char *path = NULL, *devname = NULL; struct zbd_info *zbdi; int ret, fd; if (!zbd_device_is_zoned(filename)) { zbd_error("Device %s is not a zoned block device\n", filename); return -1; } ret = zbd_dev_path(filename, &path, &devname); if (ret) return ret; /* Open block device */ fd = open(path, flags | O_LARGEFILE); //direct if (fd < 0) { zbd_error("open %s failed %d (%s)\n", filename, errno, strerror(errno)); goto err; } /* Get device information */ zbdi = zbd_do_get_info(fd, devname); if (!zbdi) goto err; zbd_fdi[fd] = zbdi; if (info) memcpy(info, zbdi, sizeof(struct zbd_info)); free(path); return fd; err: if (fd >= 0) { close(fd); fd = -1; } free(path); return fd; } /** * zbd_close - close a ZBD Device */ void zbd_close(int fd) { struct zbd_info *zbdi = zbd_get_fd(fd); if (!zbdi) { zbd_error("Invalid file descriptor %d\n\n", fd); return; } close(fd); zbd_put_fd(fd); } /** * zbd_get_info - Get a ZBD device information */ int zbd_get_info(int fd, struct zbd_info *info) { struct zbd_info *zbdi = zbd_get_fd(fd); if (!zbdi) { zbd_error("Invalid file descriptor %d\n\n", fd); return -1; } if (!info) return -1; memcpy(info, zbdi, sizeof(struct zbd_info)); return 0; } /* * zbd_should_report_zone - Test if a zone must be reported. */ static bool zbd_should_report_zone(struct zbd_zone *zone, enum zbd_report_option ro) { switch (ro) { case ZBD_RO_ALL: return true; case ZBD_RO_NOT_WP: return zbd_zone_not_wp(zone); case ZBD_RO_EMPTY: return zbd_zone_empty(zone); case ZBD_RO_IMP_OPEN: return zbd_zone_imp_open(zone); case ZBD_RO_EXP_OPEN: return zbd_zone_exp_open(zone); case ZBD_RO_CLOSED: return zbd_zone_closed(zone); case ZBD_RO_FULL: return zbd_zone_full(zone); case ZBD_RO_RDONLY: return zbd_zone_rdonly(zone); case ZBD_RO_OFFLINE: return zbd_zone_offline(zone); case ZBD_RO_RWP_RECOMMENDED: return zbd_zone_rwp_recommended(zone); case ZBD_RO_NON_SEQ: return zbd_zone_non_seq_resources(zone); default: return false; } } /* * zbd_parse_zone - Fill a zone descriptor */ static inline void zbd_parse_zone(struct zbd_zone *zone, struct blk_zone *blkz, struct blk_zone_report *rep) { zone->start = blkz->start << SECTOR_SHIFT; zone->len = blkz->len << SECTOR_SHIFT; if (rep->flags & BLK_ZONE_REP_CAPACITY) zone->capacity = blkz->capacity << SECTOR_SHIFT; else zone->capacity = zone->len; zone->wp = blkz->wp << SECTOR_SHIFT; zone->type = blkz->type; zone->cond = blkz->cond; zone->flags = 0; if (blkz->reset) zone->flags |= ZBD_ZONE_RWP_RECOMMENDED; if (blkz->non_seq) zone->flags |= ZBD_ZONE_NON_SEQ_RESOURCES; } #define ZBD_REPORT_MAX_NR_ZONE 8192 /** * zbd_report_zones - Get zone information */ int zbd_report_zones(int fd, off_t ofst, off_t len, enum zbd_report_option ro, struct zbd_zone *zones, unsigned int *nr_zones) { struct zbd_info *zbdi = zbd_get_fd(fd); unsigned long long zone_size_mask, end; struct blk_zone_report *rep; size_t rep_size; unsigned int rep_nr_zones; unsigned int nrz, n = 0, i = 0; struct blk_zone *blkz; struct zbd_zone z; int ret = 0; if (!zbdi) { zbd_error("Invalid file descriptor %d\n\n", fd); return -1; } /* * To get zone reports, we need zones and nr_zones. * To get only the number of zones, we need only nr_zones. */ if ((!zones && !nr_zones) || (zones && !nr_zones)) return -1; /* * When reporting only the number of zones (zones == NULL case), * ignore the value pointed by nr_zones. */ if (zones) { nrz = *nr_zones; if (!nrz) return 0; } else { nrz = 0; } zone_size_mask = zbdi->zone_size - 1; if (len == 0) len = zbdi->nr_sectors << SECTOR_SHIFT; end = ((ofst + len + zone_size_mask) & (~zone_size_mask)) >> SECTOR_SHIFT; if (end > zbdi->nr_sectors) end = zbdi->nr_sectors; ofst = (ofst & (~zone_size_mask)) >> SECTOR_SHIFT; if ((unsigned long long)ofst >= zbdi->nr_sectors) { *nr_zones = 0; return 0; } /* Get all zones information */ rep_nr_zones = ZBD_REPORT_MAX_NR_ZONE; if (nrz && nrz < rep_nr_zones) rep_nr_zones = nrz; rep_size = sizeof(struct blk_zone_report) + sizeof(struct blk_zone) * rep_nr_zones; rep = (struct blk_zone_report *)malloc(rep_size); if (!rep) { zbd_error("%d: No memory for array of zones\n\n", fd); return -ENOMEM; } blkz = (struct blk_zone *)(rep + 1); while ((!nrz || n < nrz) && (unsigned long long)ofst < end) { memset(rep, 0, rep_size); rep->sector = ofst; rep->nr_zones = rep_nr_zones; ret = ioctl(fd, BLKREPORTZONE, rep); if (ret != 0) { ret = -errno; zbd_error("%d: ioctl BLKREPORTZONE at %llu failed %d (%s)\n", fd, (unsigned long long)ofst, errno, strerror(errno)); goto out; } if (!rep->nr_zones) break; for (i = 0; i < rep->nr_zones; i++) { if ((nrz && (n >= nrz)) || ((unsigned long long)ofst >= end)) break; zbd_parse_zone(&z, &blkz[i], rep); if (zbd_should_report_zone(&z, ro)) { if (zones) memcpy(&zones[n], &z, sizeof(z)); n++; } ofst = blkz[i].start + blkz[i].len; } } /* Return number of zones */ *nr_zones = n; out: free(rep); return ret; } /** * zbd_list_zones - Get zone information */ int zbd_list_zones(int fd, off_t ofst, off_t len, enum zbd_report_option ro, struct zbd_zone **pzones, unsigned int *pnr_zones) { struct zbd_info *zbdi = zbd_get_fd(fd); struct zbd_zone *zones = NULL; unsigned int nr_zones = 0; int ret; if (!zbdi) { zbd_error("Invalid file descriptor %d\n\n", fd); return -1; } /* Get number of zones */ ret = zbd_report_nr_zones(fd, ofst, len, ro, &nr_zones); if (ret < 0) return ret; if (!nr_zones) goto out; /* Allocate zone array */ zones = (struct zbd_zone *) calloc(nr_zones, sizeof(struct zbd_zone)); if (!zones) return -ENOMEM; /* Get zones information */ ret = zbd_report_zones(fd, ofst, len, ro, zones, &nr_zones); if (ret != 0) { zbd_error("%d: zbd_report_zones failed %d\n", fd, ret); free(zones); return ret; } out: *pzones = zones; *pnr_zones = nr_zones; return 0; } /* * BLKOPENZONE, BLKCLOSEZONE and BLKFINISHZONE ioctl commands * were introduced with kernel 5.5. If they are not defined on the * current system, manually define these operations here to generate * code portable to newer kernels. */ #ifndef BLKOPENZONE #define BLKOPENZONE _IOW(0x12, 134, struct blk_zone_range) #endif #ifndef BLKCLOSEZONE #define BLKCLOSEZONE _IOW(0x12, 135, struct blk_zone_range) #endif #ifndef BLKFINISHZONE #define BLKFINISHZONE _IOW(0x12, 136, struct blk_zone_range) #endif #ifndef ENOIOCTLCMD #define ENOIOCTLCMD 515 #endif /** * zbd_zone_operation - Execute an operation on a zone */ int zbd_zones_operation(int fd, enum zbd_zone_op op, off_t ofst, off_t len) { struct zbd_info *zbdi = zbd_get_fd(fd); unsigned long long zone_size_mask, end; struct blk_zone_range range; const char *ioctl_name; unsigned long ioctl_op; int ret; if (!zbdi) { zbd_error("Invalid file descriptor %d\n\n", fd); return -1; } zone_size_mask = zbdi->zone_size - 1; if (len == 0) len = zbdi->nr_sectors << SECTOR_SHIFT; end = ((ofst + len + zone_size_mask) & (~zone_size_mask)) >> SECTOR_SHIFT; if (end > zbdi->nr_sectors) end = zbdi->nr_sectors; /* Check the operation */ switch (op) { case ZBD_OP_RESET: ioctl_name = "BLKRESETZONE"; ioctl_op = BLKRESETZONE; break; case ZBD_OP_OPEN: ioctl_name = "BLKOPENZONE"; ioctl_op = BLKOPENZONE; break; case ZBD_OP_CLOSE: ioctl_name = "BLKCLOSEZONE"; ioctl_op = BLKCLOSEZONE; break; case ZBD_OP_FINISH: ioctl_name = "BLKFINISHZONE"; ioctl_op = BLKFINISHZONE; break; default: zbd_error("Invalid zone operation 0x%x\n", op); errno = EINVAL; return -1; } ofst = (ofst & (~zone_size_mask)) >> SECTOR_SHIFT; if ((unsigned long long)ofst >= zbdi->nr_sectors || end == (unsigned long long)ofst) return 0; /* Execute the operation */ range.sector = ofst; range.nr_sectors = end - ofst; ret = ioctl(fd, ioctl_op, &range); if (ret != 0) { if (errno == ENOIOCTLCMD || errno == ENOTTY) { zbd_error("ioctl %s is not supported\n", ioctl_name); errno = ENOTSUP; } else { zbd_error("ioctl %s failed %d (%s)\n", ioctl_name, errno, strerror(errno)); } return -1; } return 0; } libzbd-2.0.4/lib/zbd.h000066400000000000000000000045421436612631500144750ustar00rootroot00000000000000/* SPDX-License-Identifier: LGPL-3.0-or-later */ /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) * Ting Yao */ #ifndef __LIBZBD_INTERNAL_H__ #define __LIBZBD_INTERNAL_H__ #define _GNU_SOURCE #include "config.h" #include "libzbd/zbd.h" #include #include /* * 512B sector size shift. */ #define SECTOR_SHIFT 9 /* * Handle kernel zone capacity support */ #ifndef HAVE_BLK_ZONE_REP_V2 #define BLK_ZONE_REP_CAPACITY (1 << 0) struct blk_zone_v2 { __u64 start; /* Zone start sector */ __u64 len; /* Zone length in number of sectors */ __u64 wp; /* Zone write pointer position */ __u8 type; /* Zone type */ __u8 cond; /* Zone condition */ __u8 non_seq; /* Non-sequential write resources active */ __u8 reset; /* Reset write pointer recommended */ __u8 resv[4]; __u64 capacity; /* Zone capacity in number of sectors */ __u8 reserved[24]; }; #define blk_zone blk_zone_v2 struct blk_zone_report_v2 { __u64 sector; __u32 nr_zones; __u32 flags; struct blk_zone zones[0]; }; #define blk_zone_report blk_zone_report_v2 #endif /* HAVE_BLK_ZONE_REP_V2 */ extern int zbd_get_sysfs_attr_int64(char *devname, const char *attr, long long *val); extern int zbd_get_sysfs_attr_str(char *devname, const char *attr, char *val, int val_len); /* * Library log level (per thread). */ extern __thread int zbd_log_level; #define zbd_print(stream,format,args...) \ do { \ fprintf((stream), format, ## args); \ fflush(stream); \ } while (0) #define zbd_print_level(l,stream,format,args...) \ do { \ if ((l) <= zbd_log_level) \ zbd_print((stream), "(libzbd) " format, \ ## args); \ } while (0) #define zbd_error(format,args...) \ zbd_print_level(ZBD_LOG_ERROR, stderr, "[ERROR] " format, ##args) #define zbd_debug(format,args...) \ zbd_print_level(ZBD_LOG_DEBUG, stdout, format, ##args) #define zbd_panic(format,args...) \ do { \ zbd_print_level(ZBD_LOG_ERROR, \ stderr, \ "[PANIC] " format, \ ##args); \ assert(0); \ } while (0) #define zbd_assert(cond) \ do { \ if (!(cond)) \ zbd_panic("Condition %s failed\n", \ # cond); \ } while (0) #endif /* __LIBZBD_INTERNAL_H__ */ libzbd-2.0.4/lib/zbd_utils.c000066400000000000000000000070321436612631500157050ustar00rootroot00000000000000// SPDX-License-Identifier: LGPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) * Ting Yao */ #include "zbd.h" #include #include #include #include #include /* * Log level. */ __thread int zbd_log_level = ZBD_LOG_NONE; void zbd_set_log_level(enum zbd_log_level level) { switch (level) { case ZBD_LOG_NONE: case ZBD_LOG_ERROR: case ZBD_LOG_DEBUG: zbd_log_level = level; break; default: fprintf(stderr, "libzbd: Invalid log level %d\n", level); break; } } /* * To handle string conversions. */ struct zbd_str { unsigned int val; const char *str; const char *str_short; }; static const char *zbd_get_str(struct zbd_str *str, unsigned int val, bool s) { unsigned int i = 0; while (str[i].val != UINT_MAX) { if (str[i].val == val) break; i++; } if (s) return str[i].str_short; return str[i].str; } static struct zbd_str zbd_dm_str[] = { { ZBD_DM_HOST_MANAGED, "host-managed", "HM" }, { ZBD_DM_HOST_AWARE, "host-aware", "HA" }, { ZBD_DM_NOT_ZONED, "not-zoned", "NZ" }, { UINT_MAX, "unknown", "??" }, }; /** * zbd_device_model_str - Returns a device zone model name */ const char *zbd_device_model_str(enum zbd_dev_model model, bool s) { return zbd_get_str(zbd_dm_str, model, s); } static struct zbd_str zbd_ztype_str[] = { { ZBD_ZONE_TYPE_CNV, "conventional", "cnv" }, { ZBD_ZONE_TYPE_SWR, "seq-write-required", "swr" }, { ZBD_ZONE_TYPE_SWP, "seq-write-preferred", "swp" }, { UINT_MAX, "unknown", "???" } }; /** * zbd_zone_type_str - returns a string describing a zone type */ const char *zbd_zone_type_str(struct zbd_zone *z, bool s) { return zbd_get_str(zbd_ztype_str, z->type, s); } static struct zbd_str zbd_zcond_str[] = { { ZBD_ZONE_COND_NOT_WP, "not-write-pointer", "nw" }, { ZBD_ZONE_COND_EMPTY, "empty", "em" }, { ZBD_ZONE_COND_FULL, "full", "fu" }, { ZBD_ZONE_COND_IMP_OPEN, "open-implicit", "oi" }, { ZBD_ZONE_COND_EXP_OPEN, "open-explicit", "oe" }, { ZBD_ZONE_COND_CLOSED, "closed", "cl" }, { ZBD_ZONE_COND_READONLY, "read-only", "ro" }, { ZBD_ZONE_COND_OFFLINE, "offline", "ol" }, { UINT_MAX, "unknown", "??" } }; /** * zbd_zone_cond_str - Returns a string describing a zone condition */ const char *zbd_zone_cond_str(struct zbd_zone *z, bool s) { return zbd_get_str(zbd_zcond_str, z->cond, s); } /* * Strip a string of trailing spaces and carriage return. */ static int zbd_str_strip(char *str) { int i = strlen(str) - 1; while (i >= 0) { if (str[i] == ' ' || str[i] == '\t' || str[i] == '\r' || str[i] == '\n') { str[i] = '\0'; i--; } else { break; } } return i + 1; } static int zbd_get_sysfs_attr(char *devname, const char *attr, char *str, int str_len) { char attr_path[128]; FILE *file; int ret = 0; snprintf(attr_path, sizeof(attr_path), "/sys/block/%s/%s", devname, attr); file = fopen(attr_path, "r"); if (!file) return -ENOENT; if (!fgets(str, str_len, file)) { ret = -EINVAL; goto close; } if (!zbd_str_strip(str)) ret = -EINVAL; close: fclose(file); return ret; } int zbd_get_sysfs_attr_int64(char *devname, const char *attr, long long *val) { char str[128]; int ret; ret = zbd_get_sysfs_attr(devname, attr, str, 128); if (ret) return ret; *val = atoll(str); return 0; } int zbd_get_sysfs_attr_str(char *devname, const char *attr, char *val, int val_len) { return zbd_get_sysfs_attr(devname, attr, val, val_len); } libzbd-2.0.4/libzbd.spec000066400000000000000000000047141436612631500151220ustar00rootroot00000000000000Name: libzbd Version: 2.0.4 Release: 1%{?dist} Summary: A library to control zoned block devices License: LGPLv3+ and GPLv3+ URL: https://github.com/westerndigitalcorporation/%{name} Source0: %{url}/releases/download/v%{version}/%{name}-%{version}.tar.gz BuildRequires: desktop-file-utils BuildRequires: gtk3-devel BuildRequires: autoconf BuildRequires: automake BuildRequires: libtool BuildRequires: make BuildRequires: gcc %description libzbd is a library providing functions simplifying the management and use of zoned block devices using the kernel ioctl interface. # Development headers package %package devel Summary: Development header files for libzbd Requires: %{name}%{?_isa} = %{version}-%{release} %description devel This package provides development header files for libzbd. # Command line tools package %package cli-tools Summary: Command line tools using libzbd Requires: %{name}%{?_isa} = %{version}-%{release} %description cli-tools This package provides command line tools using libzbd. # Graphic tools package %package gtk-tools Summary: GTK tools using libzbd Requires: %{name}%{?_isa} = %{version}-%{release} %description gtk-tools This package provides GTK-based graphical tools using libzbd. %prep %autosetup %build sh autogen.sh %configure --libdir="%{_libdir}" --includedir="%{_includedir}" %make_build %install %make_install PREFIX=%{_prefix} chmod -x ${RPM_BUILD_ROOT}%{_mandir}/man8/*.8* find ${RPM_BUILD_ROOT} -name '*.la' -delete desktop-file-validate %{buildroot}/%{_datadir}/applications/gzbd.desktop desktop-file-validate %{buildroot}/%{_datadir}/applications/gzbd-viewer.desktop %ldconfig_scriptlets %files %{_libdir}/*.so.* %exclude %{_libdir}/*.a %exclude %{_libdir}/pkgconfig/*.pc %license LICENSES/LGPL-3.0-or-later.txt %doc README.md %files devel %{_includedir}/* %{_libdir}/*.so %{_libdir}/pkgconfig/*.pc %license LICENSES/LGPL-3.0-or-later.txt %files cli-tools %{_bindir}/zbd %{_mandir}/man8/zbd.8* %license LICENSES/GPL-3.0-or-later.txt %files gtk-tools %{_bindir}/gzbd %{_datadir}/polkit-1/actions/org.gnome.gzbd.policy %{_datadir}/applications/gzbd.desktop %{_datadir}/pixmaps/gzbd.png %{_bindir}/gzbd-viewer %{_datadir}/polkit-1/actions/org.gnome.gzbd-viewer.policy %{_datadir}/applications/gzbd-viewer.desktop %{_datadir}/pixmaps/gzbd-viewer.png %{_mandir}/man8/gzbd.8* %{_mandir}/man8/gzbd-viewer.8* %license LICENSES/GPL-3.0-or-later.txt %changelog * Tue Jan 31 2023 Damien Le Moal 2.0.4 - Update to version 2.0.4 libzbd-2.0.4/m4/000077500000000000000000000000001436612631500133125ustar00rootroot00000000000000libzbd-2.0.4/m4/dontremove000066400000000000000000000002661436612631500154230ustar00rootroot00000000000000# SPDX-License-Identifier: CC0-1.0 # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. the only purpose of this file is to keep the m4 directory in git libzbd-2.0.4/tools/000077500000000000000000000000001436612631500141325ustar00rootroot00000000000000libzbd-2.0.4/tools/Makefile.am000066400000000000000000000017771436612631500162020ustar00rootroot00000000000000# SPDX-License-Identifier: LGPL-3.0-or-later # # SPDX-FileCopyrightText: 2021 Western Digital Corporation or its affiliates. SUBDIRS = . $(subdirs) AM_CFLAGS = \ $(CFLAGS) \ -Wall -Wextra -Wno-unused-parameter \ -I$(top_srcdir)/include libzbd_ldadd = $(top_builddir)/lib/libzbd.la bin_PROGRAMS = dist_man8_MANS = include cli/Makefile.am if BUILD_GUI polkitdir = $(datadir)/polkit-1/actions polkit_action_in_FILES = desktopdir = $(datadir)/applications desktop_in_FILES = pixmapdir = $(datadir)/pixmaps pixmap_FILES = bin_subst = sed -e 's,[@]bindir[@],$(bindir),g' include gui/Makefile.am include viewer/Makefile.am polkit_action_FILES = $(polkit_action_in_FILES:.policy.in=.policy) polkit_DATA = $(polkit_action_FILES) desktop_FILES = $(desktop_in_FILES:.desktop.in=.desktop) desktop_DATA = $(desktop_FILES) pixmap_DATA = $(pixmap_FILES) CLEANFILES = $(desktop_FILES) $(polkit_action_FILES) EXTRA_DIST = \ $(polkit_action_in_FILES) \ $(desktop_in_FILES) \ $(pixmap_FILES) endif libzbd-2.0.4/tools/cli/000077500000000000000000000000001436612631500147015ustar00rootroot00000000000000libzbd-2.0.4/tools/cli/Makefile.am000066400000000000000000000004041436612631500167330ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. bin_PROGRAMS += zbd zbd_SOURCES = \ cli/zbd.c \ cli/zbd_dump.c \ cli/zbd.h zbd_LDADD = $(libzbd_ldadd) dist_man8_MANS += cli/zbd.8 libzbd-2.0.4/tools/cli/zbd.8000066400000000000000000000123671436612631500155620ustar00rootroot00000000000000.\" SPDX-License-Identifier: GPL-3.0-or-later .\" SPDX-FileCopyrightText: 2020, Western Digital Corporation or its affiliates. .\" Written by Damien Le Moal .\" .TH ZBD 8 .SH NAME zbd \- manage zoned block devices .SH SYNOPSIS .B zbd .I command [options] .I device .SH DESCRIPTION .B zbd is used to manipulate zones of a zoned block device. Zoned block devies are block devices that support the SCSI Zoned Block Commands (ZBC), ATA Zoned-device ATA Commands (ZAC) or NVMe Zoned NameSpace commands (ZNS). The zones to operate on can be specified using the offset and length options. .PP The .I device argument must be the pathname of the target zoned block device. .SH COMMANDS By default, all commands will operate from the zone at device offset 0 and operate on all zones. The common options \fB-ofst\fP and \fB-len\fP can be used to modify the operation range of commands. .SS report The command \fBzbd report\fP is used to obtain and display the device zone information. .PP By default, the command will report all zones from the start of the device up to the last zone of the device. Options may be used to modify this behavior, changing the starting zone or the size of the report. .B Report output .TS tab(:); l l. Zone:Zone number type:Type of the zone ofst:Zone start offset in Bytes len:Zone length in Bytes cap:Zone usable capacity in Bytes wp:Zone write pointer position in Bytes cond:Zone condition non_seq:Non-sequential write resources active reset:Reset write pointer recommended .TE .B Zone types .TS tab(:); l l. cnv:Conventional swr:Sequential write required swp:Sequential write preferred ???:Unknown (should not be reported) .TE .B Zone conditions .TS tab(:); l l. nw:Not write pointer em:Empty fu:Full oe:Explicitly opened oi:Implicitly opened cl:Closed ol:Offline ro:Read only ??:Reserved conditions (should not be reported) .TE .SS reset The command \fBzbd reset\fP is used to reset the write pointer of one or more zones. .SS open The command \fBzbd open\fP is used to explicitly open one or more zones. .SS close The command \fBzbd close\fP is used to close one or more zones. .SS finish The command \fBzbd finish\fP is used to finish (transition to full) one or more zones. .SS dump Save the zone information and zone data of a zoned device to files. The files are by default saved in the current working directory. A different output path can be specified using the option \fB-d\fP. The file names are prefixed by default using the device base name. The device zone information is saved in the file \fI_zone_info.dump\fP and the device zone data is saved in the file \fI_zone_data.dump\fP. The file name prefix can be changed using the option \fB-f\fP. .PP The \fBdump\fP command will save the data of all conventional zones and the written data of all sequential zones in the operation range. The options \fB-ofst\fP and \fB-len\fP can be used to limit in size the operation range. .PP The zone information file always saves zone information for all zones of the device, regardless of the specified operation range. This file can be specified in place of a device name with the \fBreport\fP command to inspect its content. .SS restore Set a zoned block device zone status and zone data according to the zone information and zoned data saved in files generated using the \fBdump\fP command. The resulting state of the target device will be identical to that of the device used to generate the dump files. The \fBrestore\fP command will only operate on the zone range that was used with the \fBdump\fP command. The target zoned block device must be compatible with the zoned block device used as the source for the dump operation. That is, the target device must have the same capacity and zone configuration (zone type, zone size and zone capacity) as the source device. .PP The path and name prefix of the dump files to use for restoring a device can be changed using the options \fB-d\fP and \fB-f\fP. .SH OPTIONS Options applicable to all commands are as follows. .TP .BR \-v Verbose mode (for debug). .TP .BR \-i Display device information before executing the command. .TP .BR "\-ofst " \fIoffset\fP Start offset in Bytes of the first zone to operate on. .TP .BR "\-len " \fIlength\fP Length in Bytes of the range of zones to operate on. .TP .BR \-h , " \-\-help" Display help text and exit. .TP Options applicable only to the \fBzbd report\fP command are as follows. .TP .BR \-csv Output zone information using the comma-separated (csv) format. .TP .BR \-n Display the number of zones that are to be reported. .TP .BR \-c Display the total capacity of all reported zones. When used with the \fB-n\fP and \fB-csv\fP options, the number of zones is output first. .TP .BR "\-ro " \fIfilter\fP Sepcify reporting option to filter the zone report. \fIfilter\fP can be one of the following. .TS tab(:); l l. em:Empty zones oi:Implicitly opened zones oe:Explicitly opened zones cl:Closed zones fu:Full zones ro:Read only zones ol:Offline zones nw:Conventional zones ns:Non_seq write resource zones rw:Reset write pointer recommended zones .TE .SH AUTHOR .nf Damien Le Moal .fi .SH SEE ALSO .BR blkzone (8) .SH AVAILABILITY The zbd command is part of the libzbd library available from .UR https://\:github.com\:/westerndigitalcorporation\:/libzbd .UE . libzbd-2.0.4/tools/cli/zbd.c000066400000000000000000000314471436612631500156350ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) * Ting Yao */ #include "zbd.h" static int zbd_mgmt(int fd, struct zbd_opts *opts) { int ret; /* Check zone range */ if (opts->ofst % opts->dev_info.zone_size || opts->len % opts->dev_info.zone_size) { fprintf(stderr, "Invalid unaligned offset/length\n"); return 1; } switch (opts->cmd) { case ZBD_RESET: ret = zbd_reset_zones(fd, opts->ofst, opts->len); break; case ZBD_OPEN: ret = zbd_open_zones(fd, opts->ofst, opts->len); break; case ZBD_CLOSE: ret = zbd_close_zones(fd, opts->ofst, opts->len); break; case ZBD_FINISH: ret = zbd_finish_zones(fd, opts->ofst, opts->len); break; default: fprintf(stderr, "Invalid operation\n"); return 1; } if (ret) fprintf(stderr, "Zone operation failed %d (%s)\n", errno, strerror(errno)); return ret; } static void zbd_print_zone(struct zbd_opts *opts, struct zbd_zone *z) { unsigned int zno = zbd_zone_start(z) / opts->dev_info.zone_size; if (opts->rep_csv) { printf("%05u, %u, %014llu, %014llu, %014llu, %014llu, 0x%01x, %01d, %01d\n", zno, (unsigned int)zbd_zone_type(z), zbd_zone_start(z) / opts->unit, zbd_zone_len(z) / opts->unit, zbd_zone_capacity(z) / opts->unit, zbd_zone_wp(z) / opts->unit, zbd_zone_cond(z), zbd_zone_non_seq_resources(z) ? 1 : 0, zbd_zone_rwp_recommended(z) ? 1 : 0); return; } if (zbd_zone_cnv(z)) { printf("Zone %05u: %s, ofst %014llu, len %014llu, cap %014llu\n", zno, zbd_zone_type_str(z, true), zbd_zone_start(z) / opts->unit, zbd_zone_len(z) / opts->unit, zbd_zone_capacity(z) / opts->unit); return; } if (zbd_zone_seq(z)) { printf("Zone %05u: %s, ofst %014llu, len %014llu, cap %014llu, " "wp %014llu, %s, non_seq %01d, reset %01d\n", zno, zbd_zone_type_str(z, true), zbd_zone_start(z) / opts->unit, zbd_zone_len(z) / opts->unit, zbd_zone_capacity(z) / opts->unit, zbd_zone_wp(z) / opts->unit, zbd_zone_cond_str(z, true), zbd_zone_non_seq_resources(z) ? 1 : 0, zbd_zone_rwp_recommended(z) ? 1 : 0); return; } printf("Zone %05u: unknown type 0x%01x, ofst %014llu, len %014llu\n", zno, zbd_zone_type(z), zbd_zone_start(z) / opts->unit, zbd_zone_len(z) / opts->unit); } static int zbd_report(int fd, struct zbd_opts *opts) { struct zbd_zone *zones = NULL; unsigned int i, nz; int ret; /* Allocate zone array */ nz = (opts->len + opts->dev_info.zone_size - 1) / opts->dev_info.zone_size; if (!nz) return 0; zones = (struct zbd_zone *) calloc(nz, sizeof(struct zbd_zone)); if (!zones) { fprintf(stderr, "No memory\n"); return 1; } if (!opts->rep_dump) { /* Get zone information from the device */ ret = zbd_report_zones(fd, opts->ofst, opts->len, opts->rep_opt, zones, &nz); if (ret != 0) { fprintf(stderr, "zbd_report_zones() failed %d\n", ret); ret = 1; goto out; } } else { /* Get zone information from the dump file */ ret = zbd_dump_report_zones(fd, opts, zones, &nz); if (ret != 0) { ret = 1; goto out; } } if (opts->rep_num_zones) { if (opts->rep_csv) { if (!opts->rep_capacity) printf("%u\n", nz); else printf("%u, ", nz); } else { printf("%u zones\n", nz); } if (!opts->rep_capacity) goto out; } if (opts->rep_capacity) { unsigned long long capacity = 0; for (i = 0; i < nz; i++) capacity += zbd_zone_capacity(&zones[i]) / opts->unit; if (opts->rep_csv) { printf("%llu\n", capacity); } else { if (opts->unit != 1) printf("%llu x %zu B total zone capacity\n", capacity, opts->unit); else printf("%llu B total zone capacity\n", capacity); } goto out; } if (opts->rep_csv) printf("zone num, type, ofst, len, cap, wp, cond, non_seq, reset\n"); for (i = 0; i < nz; i++) zbd_print_zone(opts, &zones[i]); out: free(zones); return ret; } struct zbd_action { int (*action)(int, struct zbd_opts *); int flags; }; static struct zbd_action zact[] = { { zbd_report, O_RDONLY }, /* ZBD_REPORT */ { zbd_mgmt, O_WRONLY }, /* ZBD_RESET */ { zbd_mgmt, O_WRONLY }, /* ZBD_OPEN */ { zbd_mgmt, O_WRONLY }, /* ZBD_CLOSE */ { zbd_mgmt, O_WRONLY }, /* ZBD_FINISH */ { zbd_dump, O_RDONLY }, /* ZBD_DUMP */ { zbd_restore, O_RDWR | O_DIRECT }, /* ZBD_RESTORE */ }; static void zbd_print_dev_info(struct zbd_opts *opts) { if (opts->cmd == ZBD_REPORT && opts->rep_csv) return; printf("Device %s:\n", opts->dev_path); printf(" Vendor ID: %s\n", opts->dev_info.vendor_id); printf(" Zone model: %s\n", zbd_device_model_str(opts->dev_info.model, false)); printf(" Capacity: %.03F GB (%llu 512-bytes sectors)\n", (double)(opts->dev_info.nr_sectors << 9) / 1000000000, opts->dev_info.nr_sectors); printf(" Logical blocks: %llu blocks of %u B\n", opts->dev_info.nr_lblocks, opts->dev_info.lblock_size); printf(" Physical blocks: %llu blocks of %u B\n", opts->dev_info.nr_pblocks, opts->dev_info.pblock_size); printf(" Zones: %u zones of %.1F MB\n", opts->dev_info.nr_zones, (double)opts->dev_info.zone_size / 1048576.0); printf(" Maximum number of open zones: "); if (opts->dev_info.max_nr_open_zones == 0) printf("no limit\n"); else printf("%u\n", opts->dev_info.max_nr_open_zones); printf(" Maximum number of active zones: "); if (opts->dev_info.max_nr_active_zones == 0) printf("no limit\n"); else printf("%u\n", opts->dev_info.max_nr_active_zones); } static int zbd_usage(char *cmd) { printf("Usage: %s [options] \n" "Commands:\n" " report : Get zone information from a device or from\n" " a zone information dump file\n" " reset : Reset zone(s) of a device\n" " open : Explicitly open zone(s) of a device\n" " close : Close zone(s) of a device\n" " finish : Finish zone(s) of a device\n" " dump : Dump a device zone information and zone data to\n" " files (see -d and -f options).\n" " restore : Restore a device zones status and data from dump\n" " files (see -d and -f options).\n" "Common options:\n" " -v : Verbose mode (for debug)\n" " -i : Display device information\n" " -ofst : Start offset of the first zone of the\n" " target range (default: 0)\n" " -len : Size of the zone range to operate on\n" " (default: device capacity)\n" " -u : Size unit to use for ofst and len options,\n" " and for displaying zone report results.\n" " (default: 1)\n" "Report command options:\n" " -csv : Use csv output format\n" " -n : Only output the number of zones reported\n" " -c : Only output the total capacity of zones reported\n" " -ro : Specify a zone report option. Possible values are:\n" " * \"em\": empty zones\n" " * \"oi\": implicitly open zones\n" " * \"oe\": explicitly open zones\n" " * \"cl\": closed zones\n" " * \"fu\": full zones\n" " * \"ro\": read-only zones\n" " * \"ol\": offline zones\n" " * \"nw\": conventional zones\n" " * \"ns\": non-seq write resource zones\n" " * \"rw\": reset-wp recommended zones\n" "dump and restore commands options:\n" " -d : Path where to save dump files.\n" " -f : Name prefix for the dump files. If not\n" " specified, the device base name is used\n" " as a dump file name prefix\n", cmd); return 1; } int main(int argc, char **argv) { struct zbd_opts opts; bool dev_info = false; int dev_fd = 0, i, ret = 1; long long capacity; char dev_path[PATH_MAX]; memset(&opts, 0, sizeof(struct zbd_opts)); opts.rep_opt = ZBD_RO_ALL; opts.rep_dump = false; opts.unit = 1; /* Parse options */ if (argc < 3) return zbd_usage(argv[0]); if (strcmp(argv[1], "report") == 0) { opts.cmd = ZBD_REPORT; } else if (strcmp(argv[1], "reset") == 0) { opts.cmd = ZBD_RESET; } else if (strcmp(argv[1], "open") == 0) { opts.cmd = ZBD_OPEN; } else if (strcmp(argv[1], "close") == 0) { opts.cmd = ZBD_CLOSE; } else if (strcmp(argv[1], "finish") == 0) { opts.cmd = ZBD_FINISH; } else if (strcmp(argv[1], "dump") == 0) { opts.cmd = ZBD_DUMP; } else if (strcmp(argv[1], "restore") == 0) { opts.cmd = ZBD_RESTORE; } else { fprintf(stderr, "Invalid command \"%s\"\n", argv[1]); return 1; } for (i = 2; i < (argc - 1); i++) { /* * Common options. */ if (strcmp(argv[i], "-v") == 0) { zbd_set_log_level(ZBD_LOG_DEBUG); } else if (strcmp(argv[i], "-i") == 0) { dev_info = true; } else if (strcmp(argv[i], "-ofst") == 0) { if (i >= (argc - 1)) { fprintf(stderr, "Invalid command line\n"); return 1; } i++; opts.ofst = strtoll(argv[i], NULL, 10); } else if (strcmp(argv[i], "-len") == 0) { if (i >= (argc - 1)) { fprintf(stderr, "Invalid command line\n"); return 1; } i++; opts.len = strtoll(argv[i], NULL, 10); } else if (strcmp(argv[i], "-u") == 0) { if (i >= (argc - 1)) { fprintf(stderr, "Invalid command line\n"); return 1; } i++; opts.unit = strtoll(argv[i], NULL, 10); /* * Report zones options. */ } else if (strcmp(argv[i], "-csv") == 0) { opts.rep_csv = true; } else if (strcmp(argv[i], "-n") == 0) { opts.rep_num_zones = true; } else if (strcmp(argv[i], "-c") == 0) { opts.rep_capacity = true; } else if (strcmp(argv[i], "-ro") == 0) { if (i >= (argc - 1)) { fprintf(stderr, "Invalid command line\n"); return 1; } i++; if (strcmp(argv[i], "em") == 0) { opts.rep_opt = ZBD_RO_EMPTY; } else if (strcmp(argv[i], "oi") == 0) { opts.rep_opt = ZBD_RO_IMP_OPEN; } else if (strcmp(argv[i], "oe") == 0) { opts.rep_opt = ZBD_RO_EXP_OPEN; } else if (strcmp(argv[i], "cl") == 0) { opts.rep_opt = ZBD_RO_CLOSED; } else if (strcmp(argv[i], "fu") == 0) { opts.rep_opt = ZBD_RO_FULL; } else if (strcmp(argv[i], "ro") == 0) { opts.rep_opt = ZBD_RO_RDONLY; } else if (strcmp(argv[i], "ol") == 0) { opts.rep_opt = ZBD_RO_OFFLINE; } else if (strcmp(argv[i], "rw") == 0) { opts.rep_opt = ZBD_RO_RWP_RECOMMENDED; } else if (strcmp(argv[i], "ns") == 0) { opts.rep_opt = ZBD_RO_NON_SEQ; } else if (strcmp(argv[i], "nw") == 0) { opts.rep_opt = ZBD_RO_NOT_WP; } else { fprintf(stderr, "Unknown report option \"%s\"\n", argv[i]); return 1; } /* * Dump and restore command options. */ } else if (strcmp(argv[i], "-d") == 0) { if (i >= (argc - 1)) { fprintf(stderr, "Invalid command line\n"); return 1; } i++; opts.dump_path = argv[i]; } else if (strcmp(argv[i], "-f") == 0) { if (i >= (argc - 1)) { fprintf(stderr, "Invalid command line\n"); return 1; } i++; opts.dump_prefix = argv[i]; } else if (argv[i][0] == '-') { fprintf(stderr, "Unknown option \"%s\"\n", argv[i]); return 1; } else { break; } } if (i != (argc - 1)) { fprintf(stderr, "No device specified\n"); return 1; } if (!realpath(argv[i], dev_path)) { fprintf(stderr, "Invalid device path %s\n", argv[i]); return 1; } opts.dev_path = dev_path; /* * Special case for zone report using zone info dump file. */ if (opts.cmd == ZBD_REPORT) { dev_fd = zbd_open_dump(&opts); if (dev_fd < 0) return 1; } if (!dev_fd) { /* Open device */ dev_fd = zbd_open(opts.dev_path, zact[opts.cmd].flags | O_LARGEFILE, &opts.dev_info); if (dev_fd < 0) { fprintf(stderr, "Open %s failed (%s)\n", opts.dev_path, strerror(errno)); return 1; } } /* Check unit, offset and length */ capacity = (long long)opts.dev_info.nr_sectors << 9; if (opts.unit > 1 && (opts.unit > opts.dev_info.zone_size || opts.unit % 512)) { fprintf(stderr, "Invalid unit\n"); ret = 1; goto out; } if (opts.ofst % 512 || opts.len % 512) { fprintf(stderr, "Invalid unaligned offset/length\n"); ret = 1; goto out; } if (opts.ofst >= capacity) { ret = 0; goto out; } if (!opts.len) opts.len = capacity; if (opts.ofst + opts.len > capacity) opts.len = capacity - opts.ofst; if (dev_info) zbd_print_dev_info(&opts); ret = zact[opts.cmd].action(dev_fd, &opts); if (ret) ret = 1; out: if (!opts.rep_dump) zbd_close(dev_fd); else close(dev_fd); return ret; } libzbd-2.0.4/tools/cli/zbd.h000066400000000000000000000030001436612631500156220ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2021 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #ifndef _ZBD_TOOL_H_ #define _ZBD_TOOL_H_ #define _LARGEFILE64_SOURCE #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include "libzbd/zbd.h" enum zbd_cmd { ZBD_REPORT, ZBD_RESET, ZBD_OPEN, ZBD_CLOSE, ZBD_FINISH, ZBD_DUMP, ZBD_RESTORE, }; /* * Command line options and device information. */ struct zbd_opts { /* Common options */ char *dev_path; char *dump_path; char *dump_prefix; struct zbd_info dev_info; enum zbd_cmd cmd; long long ofst; long long len; size_t unit; /* Report zones options */ bool rep_csv; bool rep_num_zones; bool rep_capacity; bool rep_dump; enum zbd_report_option rep_opt; }; /* * Zone information dump file header. */ struct zbd_dump { struct zbd_info dev_info; /* 128 */ unsigned int zstart; /* 132 */ unsigned int zend; /* 136 */ uint8_t reserved[56]; /* 192 */ } __attribute__((packed)); int zbd_open_dump(struct zbd_opts *opts); int zbd_dump_report_zones(int fd, struct zbd_opts *opts, struct zbd_zone *zones, unsigned int *nr_zones); int zbd_dump(int fd, struct zbd_opts *opts); int zbd_restore(int fd, struct zbd_opts *opts); #endif /* _ZBD_TOOL_H_ */ libzbd-2.0.4/tools/cli/zbd_dump.c000066400000000000000000000445751436612631500166700ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #include "./zbd.h" static ssize_t zbd_rw(int fd, bool read, void *buf, size_t count, off_t offset) { size_t remaining = count; off_t ofst = offset; ssize_t ret; while (remaining) { if (read) ret = pread(fd, buf, remaining, ofst); else ret = pwrite(fd, buf, remaining, ofst); if (ret < 0) { fprintf(stderr, "%s failed %d (%s)\n", read ? "read" : "write", errno, strerror(errno)); return -1; } if (!ret) break; remaining -= ret; ofst += ret; } return count - remaining; } static inline ssize_t zbd_read(int fd, void *buf, size_t count, off_t offset) { return zbd_rw(fd, true, buf, count, offset); } static inline ssize_t zbd_write(int fd, void *buf, size_t count, off_t offset) { return zbd_rw(fd, false, buf, count, offset); } int zbd_open_dump(struct zbd_opts *opts) { struct zbd_dump dump; struct stat st; int dev_fd = 0; ssize_t ret; ret = stat(opts->dev_path, &st); if (ret) { fprintf(stderr, "stat %s failed\n", opts->dev_path); return -1; } if (!S_ISREG(st.st_mode)) return 0; printf("Regular file specified: assuming dump file\n"); dev_fd = open(opts->dev_path, O_RDONLY | O_LARGEFILE); if (dev_fd < 0) { fprintf(stderr, "Open %s failed (%s)\n", opts->dev_path, strerror(errno)); return -1; } ret = zbd_read(dev_fd, &dump, sizeof(struct zbd_dump), 0); if (ret != sizeof(struct zbd_dump)) { fprintf(stderr, "Read dump header failed\n"); close(dev_fd); return -1; } memcpy(&opts->dev_info, &dump.dev_info, sizeof(struct zbd_info)); opts->rep_dump = true; return dev_fd; } static bool zbd_dump_should_report_zone(struct zbd_zone *zone, enum zbd_report_option ro) { switch (ro) { case ZBD_RO_ALL: return true; case ZBD_RO_NOT_WP: return zbd_zone_not_wp(zone); case ZBD_RO_EMPTY: return zbd_zone_empty(zone); case ZBD_RO_IMP_OPEN: return zbd_zone_imp_open(zone); case ZBD_RO_EXP_OPEN: return zbd_zone_exp_open(zone); case ZBD_RO_CLOSED: return zbd_zone_closed(zone); case ZBD_RO_FULL: return zbd_zone_full(zone); case ZBD_RO_RDONLY: return zbd_zone_rdonly(zone); case ZBD_RO_OFFLINE: return zbd_zone_offline(zone); case ZBD_RO_RWP_RECOMMENDED: return zbd_zone_rwp_recommended(zone); case ZBD_RO_NON_SEQ: return zbd_zone_non_seq_resources(zone); default: return false; } } int zbd_dump_report_zones(int fd, struct zbd_opts *opts, struct zbd_zone *zones, unsigned int *nr_zones) { unsigned int i, nz = 0, zstart, zend; struct zbd_zone zone; loff_t ofst; ssize_t ret; zstart = opts->ofst / opts->dev_info.zone_size; zend = (opts->ofst + opts->len + opts->dev_info.zone_size - 1) / opts->dev_info.zone_size; ofst = sizeof(struct zbd_dump) + zstart * sizeof(struct zbd_zone); for (i = zstart; i < zend; i++) { ret = zbd_read(fd, &zone, sizeof(struct zbd_zone), ofst); if (ret != sizeof(struct zbd_zone)) { fprintf(stderr, "Read zone information failed\n"); return -1; } if (zbd_dump_should_report_zone(&zone, opts->rep_opt)) { memcpy(&zones[nz], &zone, sizeof(struct zbd_zone)); nz++; } ofst += sizeof(struct zbd_zone); } *nr_zones = nz; return 0; } #define ZBD_DUMP_IO_SIZE (1024 * 1024) static ssize_t zbd_dump_one_zone(int fd, struct zbd_opts *opts, struct zbd_zone *zone, int dump_fd, void *buf) { long long ofst, end; ssize_t ret, iosize; /* Ignore offline zones */ if (zbd_zone_offline(zone)) return 0; /* Copy zone data */ ofst = zbd_zone_start(zone); if (zbd_zone_seq(zone) && !zbd_zone_full(zone)) end = zbd_zone_wp(zone); else end = ofst + zbd_zone_capacity(zone); while (ofst < end) { if (ofst + ZBD_DUMP_IO_SIZE > end) iosize = end - ofst; else iosize = ZBD_DUMP_IO_SIZE; ret = zbd_read(fd, buf, iosize, ofst); if (ret != iosize) { fprintf(stderr, "Read zone data failed\n"); return -1; } ret = zbd_write(dump_fd, buf, iosize, ofst); if (ret != iosize) { fprintf(stderr, "Write zone data failed\n"); return -1; } ofst += iosize; } return end - zbd_zone_start(zone); } static int zbd_dump_zone_data(int fd, struct zbd_opts *opts, struct zbd_zone *zones, struct zbd_dump *dump) { long long dumped_bytes = 0; unsigned int dumped_zones = 0; char *data_path = NULL; int data_fd = 0; unsigned int i; ssize_t ret; void *buf; /* Get an IO buffer */ ret = posix_memalign(&buf, sysconf(_SC_PAGESIZE), ZBD_DUMP_IO_SIZE); if (ret) { fprintf(stderr, "No memory\n"); return -1; } /* Dump zone data */ ret = asprintf(&data_path, "%s/%s_zone_data.dump", opts->dump_path, opts->dump_prefix); if (ret < 0) { fprintf(stderr, "No memory\n"); goto out; } printf(" Dumping zones [%u..%u] data to %s (this may take a while)...\n", dump->zstart, dump->zend - 1, data_path); data_fd = open(data_path, O_WRONLY | O_LARGEFILE | O_TRUNC | O_CREAT, 0644); if (data_fd < 0) { fprintf(stderr, "Create data file %s failed %d (%s)\n", data_path, errno, strerror(errno)); ret = -1; goto out; } /* * Make sure that the zone data dump file size is always equal * to the device capacity, even for partial dumps. */ ret = ftruncate(data_fd, opts->dev_info.nr_sectors << 9); if (ret) { fprintf(stderr, "Truncate data file %s failed %d (%s)\n", data_path, errno, strerror(errno)); goto out; } for (i = dump->zstart; i < dump->zend; i++) { ret = zbd_dump_one_zone(fd, opts, &zones[i], data_fd, buf); if (ret < 0) goto out; if (ret) { dumped_bytes += ret; dumped_zones++; } } printf(" Dumped %lld B from %u zones\n", dumped_bytes, dumped_zones); ret = fsync(data_fd); if (ret) fprintf(stderr, "fsync data file %s failed %d (%s)\n", data_path, errno, strerror(errno)); out: if (data_fd > 0) close(data_fd); free(data_path); free(buf); return ret; } static int zbd_dump_zone_info(int fd, struct zbd_opts *opts, struct zbd_zone *zones, struct zbd_dump *dump) { char *info_path = NULL; int info_fd = 0; ssize_t ret, sz; /* Dump zone information */ ret = asprintf(&info_path, "%s/%s_zone_info.dump", opts->dump_path, opts->dump_prefix); if (ret < 0) { fprintf(stderr, "No memory\n"); return -1; } printf(" Dumping zone information to %s\n", info_path); info_fd = open(info_path, O_WRONLY | O_LARGEFILE | O_TRUNC | O_CREAT, 0644); if (info_fd < 0) { fprintf(stderr, "Create file %s failed %d (%s)\n", info_path, errno, strerror(errno)); ret = -1; goto out; } ret = zbd_write(info_fd, dump, sizeof(struct zbd_dump), 0); if (ret != (ssize_t)sizeof(struct zbd_dump)) { fprintf(stderr, "Write dump header failed\n"); ret = -1; goto out; } sz = sizeof(struct zbd_zone) * opts->dev_info.nr_zones; ret = zbd_write(info_fd, zones, sz, sizeof(struct zbd_dump)); if (ret != sz) { fprintf(stderr, "Write zone information failed\n"); ret = -1; goto out; } ret = fsync(info_fd); if (ret) fprintf(stderr, "fsync zone information file %s failed %d (%s)\n", info_path, errno, strerror(errno)); out: if (info_fd > 0) close(info_fd); free(info_path); return ret; } static void zbd_dump_prep_path(struct zbd_opts *opts) { if (!opts->dump_path) { opts->dump_path = get_current_dir_name(); if (!opts->dump_path) opts->dump_path = "."; } if (!opts->dump_prefix) opts->dump_prefix = basename(opts->dev_path); } int zbd_dump(int fd, struct zbd_opts *opts) { struct zbd_zone *zones = NULL; struct zbd_dump dump; unsigned int nz; int ret; zbd_dump_prep_path(opts); /* Setup dump header */ memset(&dump, 0, sizeof(struct zbd_dump)); memcpy(&dump.dev_info, &opts->dev_info, sizeof(struct zbd_info)); dump.zstart = opts->ofst / opts->dev_info.zone_size; dump.zend = (opts->ofst + opts->len + opts->dev_info.zone_size - 1) / opts->dev_info.zone_size; /* Get zone information */ ret = zbd_list_zones(fd, 0, 0, ZBD_RO_ALL, &zones, &nz); if (ret != 0) { fprintf(stderr, "zbd_list_zones() failed %d\n", ret); return 1; } if (nz != opts->dev_info.nr_zones) { fprintf(stderr, "Invalid number of zones: expected %u, got %u\n", opts->dev_info.nr_zones, nz); ret = 1; goto out; } printf("%s: %u zones\n", opts->dev_path, opts->dev_info.nr_zones); /* Dump zone information and zone data */ ret = zbd_dump_zone_data(fd, opts, zones, &dump); if (ret) goto out; ret = zbd_dump_zone_info(fd, opts, zones, &dump); out: free(zones); return ret; } struct zbd_restore { int data_fd; struct zbd_info dev_info; struct zbd_zone *dump_zones; struct zbd_zone *dev_zones; unsigned int zstart; unsigned int zend; void *buf; long long restored_bytes; unsigned int restored_zones; }; static int zbd_load_zone_info(struct zbd_restore *ropts, struct zbd_opts *opts) { struct zbd_dump dump; struct zbd_zone *devz, *dumpz; unsigned int nr_open_zones = 0; unsigned int nr_active_zones = 0; char *info_path = NULL; ssize_t ret, sz; unsigned int i; int info_fd; /* Dump zone information */ ret = asprintf(&info_path, "%s/%s_zone_info.dump", opts->dump_path, opts->dump_prefix); if (ret < 0) { fprintf(stderr, "No memory\n"); return -1; } printf(" Getting zone information from %s\n", info_path); info_fd = open(info_path, O_RDONLY | O_LARGEFILE); if (info_fd < 0) { fprintf(stderr, "Open zone information dump file %s failed %d (%s)\n", info_path, errno, strerror(errno)); ret = -1; goto out; } /* Read dump header */ ret = zbd_read(info_fd, &dump, sizeof(struct zbd_dump), 0); if (ret != (ssize_t)sizeof(struct zbd_dump)) { fprintf(stderr, "Read dump header failed\n"); ret = -1; goto out; } memcpy(&ropts->dev_info, &dump.dev_info, sizeof(struct zbd_info)); ropts->zstart = dump.zstart; ropts->zend = dump.zend; /* Check device information against target device */ ret = -1; if (ropts->dev_info.nr_sectors != opts->dev_info.nr_sectors) { fprintf(stderr, "Incompatible capacity\n"); goto out; } if (ropts->dev_info.lblock_size != opts->dev_info.lblock_size) { fprintf(stderr, "Incompatible logical block size\n"); goto out; } if (ropts->dev_info.pblock_size != opts->dev_info.pblock_size) { fprintf(stderr, "Incompatible physical block size\n"); goto out; } if (ropts->dev_info.nr_zones != opts->dev_info.nr_zones) { fprintf(stderr, "Incompatible number of zones\n"); goto out; } if (ropts->dev_info.zone_size != opts->dev_info.zone_size) { fprintf(stderr, "Incompatible zone size\n"); goto out; } /* Read dumped zone information */ ropts->dump_zones = calloc(ropts->dev_info.nr_zones, sizeof(struct zbd_zone)); if (!ropts->dump_zones) { fprintf(stderr, "No memory\n"); goto out; } sz = sizeof(struct zbd_zone) * ropts->dev_info.nr_zones; ret = zbd_read(info_fd, ropts->dump_zones, sz, sizeof(struct zbd_dump)); if (ret != sz) { fprintf(stderr, "Read zone information failed %zd %zd\n", ret, sz); ret = -1; goto out; } /* Check zones against target device zones */ for (i = 0; i < ropts->dev_info.nr_zones; i++) { dumpz = &ropts->dump_zones[i]; devz = &ropts->dev_zones[i]; ret = -1; if (zbd_zone_type(dumpz) != zbd_zone_type(devz)) { fprintf(stderr, "Incompatible zone %u type\n", i); goto out; } if (zbd_zone_start(dumpz) != zbd_zone_start(devz)) { fprintf(stderr, "Incompatible zone %u start\n", i); goto out; } if (zbd_zone_len(dumpz) != zbd_zone_len(devz)) { fprintf(stderr, "Incompatible zone %u start\n", i); goto out; } if (zbd_zone_capacity(dumpz) != zbd_zone_capacity(devz)) { fprintf(stderr, "Incompatible zone %u start\n", i); goto out; } if (zbd_zone_offline(devz) && !zbd_zone_offline(dumpz)) { fprintf(stderr, "Incompatible offline zone %u\n", i); goto out; } if (zbd_zone_rdonly(devz)) { fprintf(stderr, "Incompatible read-only zone %u\n", i); goto out; } /* Count open and active zones */ if (zbd_zone_is_open(dumpz)) nr_open_zones++; if (zbd_zone_is_active(dumpz)) nr_active_zones++; } /* * Check that the target drive has enough open and * active zones resource. */ if (opts->dev_info.max_nr_open_zones && nr_open_zones > opts->dev_info.max_nr_open_zones) { fprintf(stderr, "Incompatible maximum number of open zones\n"); goto out; } if (opts->dev_info.max_nr_active_zones && nr_active_zones > opts->dev_info.max_nr_active_zones) { fprintf(stderr, "Incompatible maximum number of active zones\n"); goto out; } ret = 0; out: free(info_path); close(info_fd); return ret; } static int zbd_open_zone_data(struct zbd_restore *ropts, struct zbd_opts *opts) { char *data_path = NULL; struct stat st; int ret; /* Dump zone information */ ret = asprintf(&data_path, "%s/%s_zone_data.dump", opts->dump_path, opts->dump_prefix); if (ret < 0) { fprintf(stderr, "No memory\n"); return -1; } printf(" Restoring zones [%u..%u] data from %s (this may take a while)...\n", ropts->zstart, ropts->zend - 1, data_path); ropts->data_fd = open(data_path, O_RDONLY | O_LARGEFILE); if (ropts->data_fd < 0) { fprintf(stderr, "Open zone data dump file %s failed %d (%s)\n", data_path, errno, strerror(errno)); ret = -1; goto out; } /* Check zone data file size */ ret = fstat(ropts->data_fd, &st); if (ret) { fprintf(stderr, "stat zone data dump file %s failed %d (%s)\n", data_path, errno, strerror(errno)); goto out; } if ((unsigned long long)st.st_size != opts->dev_info.nr_sectors << 9) { fprintf(stderr, "Invalid zone data dump file size\n"); ret = -1; } out: free(data_path); return ret; } static long long zbd_restore_zone_data(int fd, struct zbd_restore *ropts, struct zbd_zone *dumpz) { long long ofst, end; ssize_t ret, iosize; /* Copy zone dump data */ ofst = zbd_zone_start(dumpz); if (zbd_zone_seq(dumpz) && !zbd_zone_full(dumpz)) end = zbd_zone_wp(dumpz); else end = ofst + zbd_zone_capacity(dumpz); while (ofst < end) { if (ofst + ZBD_DUMP_IO_SIZE > end) iosize = end - ofst; else iosize = ZBD_DUMP_IO_SIZE; ret = zbd_read(ropts->data_fd, ropts->buf, iosize, ofst); if (ret != iosize) { fprintf(stderr, "Read zone dump data failed\n"); return -1; } ret = zbd_write(fd, ropts->buf, iosize, ofst); if (ret != iosize) { fprintf(stderr, "Write zone data failed\n"); return -1; } ofst += iosize; } return end - zbd_zone_start(dumpz); } static int zbd_restore_one_zone(int fd, struct zbd_restore *ropts, struct zbd_zone *dumpz, struct zbd_zone *devz) { long long restored_bytes; int ret; /* Copy zone data */ restored_bytes = zbd_restore_zone_data(fd, ropts, dumpz); if (restored_bytes < 0) return restored_bytes; if (restored_bytes) { ropts->restored_bytes += restored_bytes; ropts->restored_zones++; } /* Restore zone condition */ if (zbd_zone_closed(dumpz)) { ret = zbd_close_zones(fd, zbd_zone_start(devz), zbd_zone_len(devz)); if (ret) { fprintf(stderr, "Close target zone at %llu failed %d (%s)\n", zbd_zone_start(devz), errno, strerror(errno)); return ret; } } else if (zbd_zone_exp_open(dumpz)) { ret = zbd_open_zones(fd, zbd_zone_start(devz), zbd_zone_len(devz)); if (ret) { fprintf(stderr, "Open target zone at %llu failed %d (%s)\n", zbd_zone_start(devz), errno, strerror(errno)); return ret; } } return 0; } int zbd_restore(int fd, struct zbd_opts *opts) { struct zbd_restore ropts; struct zbd_zone *dumpz, *devz; unsigned int i, nz = 0; int ret; memset(&ropts, 0, sizeof(struct zbd_restore)); zbd_dump_prep_path(opts); /* Get zone information from the target device */ ret = zbd_list_zones(fd, 0, 0, ZBD_RO_ALL, &ropts.dev_zones, &nz); if (ret != 0) { fprintf(stderr, "zbd_list_zones() failed %d\n", ret); return ret; } if (nz != opts->dev_info.nr_zones) { fprintf(stderr, "Invalid number of zones: expected %u, got %u\n", opts->dev_info.nr_zones, nz); ret = -1; goto out; } /* Get and check zone information from the dump file */ ret = zbd_load_zone_info(&ropts, opts); if (ret) goto out; /* Open and check the zone data dump file */ ret = zbd_open_zone_data(&ropts, opts); if (ret) goto out; /* Get an IO buffer */ ret = posix_memalign(&ropts.buf, sysconf(_SC_PAGESIZE), ZBD_DUMP_IO_SIZE); if (ret) { fprintf(stderr, "No memory\n"); goto out; } /* * Restore the target device. To avoid hitting the max active or max * open zone limits of the target drive, process all zones in several * passes with each pass handling one condition. */ /* Pass 1: Reset all zones in the dump range */ for (i = ropts.zstart; i < ropts.zend; i++) { dumpz = &ropts.dump_zones[i]; devz = &ropts.dev_zones[i]; if (zbd_zone_offline(dumpz)) continue; if (!zbd_zone_seq(dumpz) || zbd_zone_empty(dumpz)) continue; ret = zbd_reset_zones(fd, zbd_zone_start(devz), zbd_zone_len(devz)); if (ret) { fprintf(stderr, "Reset target zone %u failed %d (%s)\n", i, errno, strerror(errno)); goto out; } } /* Pass 2: copy data of conventional and full sequential zones */ for (i = ropts.zstart; i < ropts.zend; i++) { dumpz = &ropts.dump_zones[i]; devz = &ropts.dev_zones[i]; if (!zbd_zone_cnv(dumpz) && !zbd_zone_full(dumpz)) continue; ret = zbd_restore_one_zone(fd, &ropts, dumpz, devz); if (ret < 0) goto out; } /* Pass 3: handle closed zones */ for (i = ropts.zstart; i < ropts.zend; i++) { dumpz = &ropts.dump_zones[i]; devz = &ropts.dev_zones[i]; if (!zbd_zone_closed(dumpz)) continue; ret = zbd_restore_one_zone(fd, &ropts, dumpz, devz); if (ret < 0) goto out; } /* Pass 4: handle explicitly open zones */ for (i = ropts.zstart; i < ropts.zend; i++) { dumpz = &ropts.dump_zones[i]; devz = &ropts.dev_zones[i]; if (!zbd_zone_exp_open(dumpz)) continue; ret = zbd_restore_one_zone(fd, &ropts, dumpz, devz); if (ret < 0) goto out; } /* Pass 5: handle implicitly open zones */ for (i = ropts.zstart; i < ropts.zend; i++) { dumpz = &ropts.dump_zones[i]; devz = &ropts.dev_zones[i]; if (!zbd_zone_imp_open(dumpz)) continue; ret = zbd_restore_one_zone(fd, &ropts, dumpz, devz); if (ret < 0) goto out; } printf(" Restored %lld B in %u zones\n", ropts.restored_bytes, ropts.restored_zones); ret = fsync(fd); if (ret) fprintf(stderr, "fsync target device failed %d (%s)\n", errno, strerror(errno)); fsync(fd); out: if (ropts.data_fd > 0) close(ropts.data_fd); free(ropts.dev_zones); free(ropts.dump_zones); free(ropts.buf); return ret; } libzbd-2.0.4/tools/gui/000077500000000000000000000000001436612631500147165ustar00rootroot00000000000000libzbd-2.0.4/tools/gui/Makefile.am000066400000000000000000000013121436612631500167470ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. polkit_action_in_FILES += gui/org.gnome.gzbd.policy.in desktop_in_FILES += gui/gzbd.desktop.in pixmap_FILES += gui/gzbd.png bin_PROGRAMS += gzbd gzbd_SOURCES = \ gui/gzbd.c \ gui/gzbd_if.c \ gui/gzbd_if_dev.c \ gui/gzbd.h gzbd_CFLAGS = $(CFLAGS) $(GTK_CFLAGS) gzbd_LDADD = $(libzbd_ldadd) $(GTK_LIBS) -lpthread dist_man8_MANS += gui/gzbd.8 gui/org.gnome.gzbd.policy: gui/org.gnome.gzbd.policy.in Makefile $(bin_subst) < gui/org.gnome.gzbd.policy.in > gui/org.gnome.gzbd.policy gui/gzbd.desktop: gui/gzbd.desktop.in Makefile $(bin_subst) < gui/gzbd.desktop.in > gui/gzbd.desktop libzbd-2.0.4/tools/gui/gzbd.8000066400000000000000000000027751436612631500157500ustar00rootroot00000000000000.\" SPDX-License-Identifier: GPL-3.0-or-later .\" SPDX-FileCopyrightText: 2020, Western Digital Corporation or its affiliates. .\" Written by Damien Le Moal .\" .TH GZBD 8 .SH NAME gzbd \- zoned block device management graphical interface .SH SYNOPSIS .B gzbd [options] .I device .SH DESCRIPTION .B gzbd is a graphical user interface allowing to view a zoned block device zones and to execute zone commands. The zone reset, open, close and finish commands can be applied to zones selected from the list of zones displayed. The list of zones displayed can be filtered based on zone type and condition. Zones are also represented graphically using colored boxes using a similar color coding as gzbd-viewer. .PP The .I device argument must be the pathname of the target zoned block device. .SH OPTIONS .TP .BR \-? , " \-\-help" Show help options and exit. .TP .BR \-\-help\-all Show all help options and exit. .TP .BR \-\-help\-gtk Show GTK+ options and exit. .TP .BR \-v , " \-\-verbose" Use libzbd verbose mode (for debug). .TP .BR \-b , " \-\-block " \fIsize\fP Use \fIsize\fP as the unit for displaying a zone position, length and write pointer position instead of the default byte value. .TP .BR \-\-display=DISPLAY Specify the X display to use. .SH AUTHOR .nf Damien Le Moal .fi .SH SEE ALSO .BR zbd (8) ", " gzbd-viewer (8) .SH AVAILABILITY The gzbd utility is part of the libzbd library available from .UR https://\:github.com\:/westerndigitalcorporation\:/libzbd .UE . libzbd-2.0.4/tools/gui/gzbd.c000066400000000000000000000215431436612631500160150ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #define _LARGEFILE64_SOURCE #include #include #include #include #include #include #include #include #include #include #include "gzbd.h" /** * Device control. */ dz_t dz; /** * Signal handling. */ static gboolean dz_process_signal(GIOChannel *source, GIOCondition condition, gpointer user_data) { char buf[32]; ssize_t size; if (condition & G_IO_IN) { size = read(g_io_channel_unix_get_fd(source), buf, sizeof(buf)); if (size > 0) { /* Got signal */ gtk_main_quit(); return TRUE; } } return FALSE; } static void dz_sig_handler(int sig) { /* Propagate signal through the pipe */ write(dz.sig_pipe[1], &sig, sizeof(int)); } static void dz_set_signal_handlers(void) { GIOChannel *sig_channel; long fd_flags; int ret; ret = pipe(dz.sig_pipe); if (ret < 0) { perror("pipe"); exit(1); } fd_flags = fcntl(dz.sig_pipe[1], F_GETFL); if (fd_flags < 0) { perror("Read descriptor flags"); exit(1); } ret = fcntl(dz.sig_pipe[1], F_SETFL, fd_flags | O_NONBLOCK); if (ret < 0) { perror("Write descriptor flags"); exit(1); } /* Install the unix signal handler */ signal(SIGINT, dz_sig_handler); signal(SIGQUIT, dz_sig_handler); signal(SIGTERM, dz_sig_handler); /* Convert the reading end of the pipe into a GIOChannel */ sig_channel = g_io_channel_unix_new(dz.sig_pipe[0]); g_io_channel_set_encoding(sig_channel, NULL, NULL); g_io_channel_set_flags(sig_channel, g_io_channel_get_flags(sig_channel) | G_IO_FLAG_NONBLOCK, NULL); g_io_add_watch(sig_channel, G_IO_IN | G_IO_PRI, dz_process_signal, NULL); } int main(int argc, char **argv) { gboolean init_ret; gboolean verbose = FALSE; GError *error = NULL; int i, ret = 0; GOptionEntry options[] = { { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Set libzbd verbose mode", NULL }, { "block", 'b', 0, G_OPTION_ARG_INT, &dz.block_size, "Use block bytes as the unit for displaying zone " "position, length and write pointer position instead " "of the default byte value", NULL }, { NULL } }; /* Init */ memset(&dz, 0, sizeof(dz)); dz.block_size = 1; for (i = 0; i < DZ_MAX_DEV; i++) dz.dev[i].dev_fd = -1; init_ret = gtk_init_with_args(&argc, &argv, "", options, NULL, &error); if (init_ret == FALSE || error != NULL) { printf("Failed to parse command line arguments: %s\n", error->message); g_error_free(error); return 1; } if (dz.block_size <= 0) { fprintf(stderr, "Invalid block size\n"); return 1; } if (verbose) zbd_set_log_level(ZBD_LOG_DEBUG); dz_set_signal_handlers(); /* Create GUI */ dz_if_create(); /* Check user credentials */ if (getuid() != 0) { dz_if_err("Root privileges are required for running gzbd", "Since gzbd is capable of erasing vast amounts of" " data, only root may run it."); ret = 1; goto out; } /* Add devices listed on command line */ for (i = 1; i < argc; i++) dz_if_add_device(argv[i]); /* Main event loop */ gtk_main(); out: /* Cleanup GUI */ dz_if_destroy(); return ret; } /* * Report zones. */ static int dz_report_zones(dz_dev_t *dzd) { unsigned int i, j = 0; int ret; if (!dzd->zones || !dzd->max_nr_zones) { /* Get list of all zones */ dzd->zone_ro = ZBD_RO_ALL; ret = zbd_list_zones(dzd->dev_fd, 0, 0, dzd->zone_ro, &dzd->zbdz, &dzd->nr_zones); if (ret != 0) return ret; if (!dzd->nr_zones) { /* That should not happen */ return -EIO; } /* Allocate zone array */ dzd->max_nr_zones = dzd->nr_zones; dzd->zones = (dz_dev_zone_t *) calloc(dzd->max_nr_zones, sizeof(dz_dev_zone_t)); if (!dzd->zones) return -ENOMEM; for (i = 0; i < dzd->max_nr_zones; i++) { dzd->zones[i].no = i; dzd->zones[i].visible = 1; memcpy(&dzd->zones[i].info, &dzd->zbdz[i], sizeof(struct zbd_zone)); } return 0; } /* Refresh zone list */ dzd->nr_zones = dzd->max_nr_zones; ret = zbd_report_zones(dzd->dev_fd, 0, 0, dzd->zone_ro, dzd->zbdz, &dzd->nr_zones); if (ret != 0) { fprintf(stderr, "Get zone information failed %d (%s)\n", errno, strerror(errno)); dzd->nr_zones = 0; } /* Apply filter */ for (i = 0; i < dzd->max_nr_zones; i++) { if (j < dzd->nr_zones && zbd_zone_start(&dzd->zones[i].info) == zbd_zone_start(&dzd->zbdz[j])) { memcpy(&dzd->zones[i].info, &dzd->zbdz[j], sizeof(struct zbd_zone)); dzd->zones[i].visible = 1; j++; } else { dzd->zones[i].visible = 0; } } return ret; } /* * Zone operation. */ static int dz_zone_operation(dz_dev_t *dzd) { int zno = dzd->zone_no; off_t ofst, len; int ret; if (zno >= (int)dzd->nr_zones) { fprintf(stderr, "Invalid zone number %d / %u\n", zno, dzd->nr_zones); return -1; } if (zno < 0) { ofst = 0; len = dzd->capacity; } else { ofst = zbd_zone_start(&dzd->zones[zno].info); len = zbd_zone_len(&dzd->zones[zno].info); } ret = zbd_zones_operation(dzd->dev_fd, dzd->zone_op, ofst, len); if (ret != 0) fprintf(stderr, "zbd_zone_operation failed %d\n", ret); return ret; } /* * Command thread routine. */ void *dz_cmd_run(void *data) { dz_dev_t *dzd = data; int do_report_zones = 1; int ret; switch (dzd->cmd_id) { case DZ_CMD_REPORT_ZONES: do_report_zones = 0; ret = dz_report_zones(dzd); break; case DZ_CMD_ZONE_OP: ret = dz_zone_operation(dzd); break; default: fprintf(stderr, "Invalid command ID %d\n", dzd->cmd_id); ret = -1; break; } if (do_report_zones) ret = dz_report_zones(dzd); if (dzd->cmd_dialog) { int response_id; if (ret == 0) response_id = GTK_RESPONSE_OK; else response_id = GTK_RESPONSE_REJECT; gtk_dialog_response(GTK_DIALOG(dzd->cmd_dialog), response_id); } return (void *)((unsigned long) ret); } static GtkWidget *dz_cmd_dialog(char *msg) { GtkWidget *dialog, *content_area; GtkWidget *spinner; dialog = gtk_message_dialog_new(GTK_WINDOW(dz.window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_OTHER, GTK_BUTTONS_NONE, "%s", msg); content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); spinner = gtk_spinner_new(); gtk_widget_show(spinner); gtk_container_add(GTK_CONTAINER(content_area), spinner); gtk_spinner_start(GTK_SPINNER(spinner)); gtk_widget_show_all(dialog); return dialog; } /* * Open a device. */ dz_dev_t *dz_open(char *path) { dz_dev_t *dzd = NULL; int i, ret; /* Get an unused device */ for (i = 0; i < DZ_MAX_DEV; i++) { if (dz.dev[i].dev_fd < 0) { dzd = &dz.dev[i]; break; } } if (!dzd) { dz_if_err("Too many open devices", "At most %d devices can be open", (int)DZ_MAX_DEV); fprintf(stderr, "Too many open devices\n"); return NULL; } /* Open device file */ strncpy(dzd->path, path, sizeof(dzd->path) - 1); dzd->dev_fd = zbd_open(dzd->path, O_RDWR | O_LARGEFILE, &dzd->info); if (dzd->dev_fd < 0) { ret = errno; dz_if_err("Open device failed", "Open %s failed %d (%s)", dzd->path, ret, strerror(ret)); fprintf(stderr, "Open device %s failed %d (%s)\n", dzd->path, ret, strerror(ret)); return NULL; } dzd->capacity = dzd->info.nr_sectors << 9; dzd->block_size = dz.block_size; if (!dzd->block_size) { dzd->block_size = 1; } else if (dzd->info.zone_size % dzd->block_size) { dz_if_err("Invalid block size", "The device zone size is not a multiple of the block size"); fprintf(stderr, "Invalid block size\n"); ret = 1; goto out; } /* Get zone information */ ret = dz_report_zones(dzd); if (ret != 0) goto out; dz.nr_devs++; out: if (ret != 0) { dz_close(dzd); dzd = NULL; } return dzd; } /* * Close a device. */ void dz_close(dz_dev_t *dzd) { if (dzd->dev_fd < 0) return; free(dzd->zbdz); dzd->zbdz = NULL; free(dzd->zones); dzd->zones = NULL; zbd_close(dzd->dev_fd); dzd->dev_fd = -1; memset(dzd, 0, sizeof(dz_dev_t)); dz.nr_devs--; } /* * Execute a command. */ int dz_cmd_exec(dz_dev_t *dzd, int cmd_id, char *msg) { int ret; /* Set command */ dzd->cmd_id = cmd_id; if (msg) /* Create a dialog */ dzd->cmd_dialog = dz_cmd_dialog(msg); else dzd->cmd_dialog = NULL; /* Create command thread */ ret = pthread_create(&dzd->cmd_thread, NULL, dz_cmd_run, dzd); if (ret != 0) goto out; if (dzd->cmd_dialog) { if (gtk_dialog_run(GTK_DIALOG(dzd->cmd_dialog)) == GTK_RESPONSE_OK) ret = 0; else ret = -1; } else { void *cmd_ret; pthread_join(dzd->cmd_thread, &cmd_ret); ret = (long)cmd_ret; } pthread_join(dzd->cmd_thread, NULL); out: if (dzd->cmd_dialog) { gtk_widget_destroy(dzd->cmd_dialog); dzd->cmd_dialog = NULL; } return ret; } libzbd-2.0.4/tools/gui/gzbd.desktop.in000066400000000000000000000003641436612631500176470ustar00rootroot00000000000000[Desktop Entry] Name=gzbd Comment=Manage Zoned Block Devices Keywords=disk;drive;harddisk;hdd;disc;smr;SMR;ssd;zns;ZNS; Exec=pkexec --disable-internal-agent "@bindir@/gzbd" Icon=gzbd Terminal=false Type=Application Categories=GNOME;GTK;System; libzbd-2.0.4/tools/gui/gzbd.h000066400000000000000000000052251436612631500160210ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later */ /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #ifndef __GZBD_H__ #define __GZBD_H__ #include #include #include #include /** * Default refresh interval (milliseconds). */ #define DZ_INTERVAL 1000 /** * Zone information list columns. */ enum { DZ_ZONE_NUM = 0, DZ_ZONE_LIST_COLUMS }; /** * Device command IDs. */ enum { DZ_CMD_REPORT_ZONES, DZ_CMD_ZONE_OP, }; /** * Maximum number of devices that can be open. */ #define DZ_MAX_DEV 32 /** * Device zone information. */ typedef struct dz_dev_zone { int no; int visible; struct zbd_zone info; } dz_dev_zone_t; /** * GUI Tab data. */ typedef struct dz_dev { char path[128]; int opening; int dev_fd; struct zbd_info info; unsigned long long capacity; int block_size; int use_hexa; int zone_ro; unsigned int zone_op; int zone_no; unsigned int max_nr_zones; unsigned int nr_zones; struct zbd_zone *zbdz; dz_dev_zone_t *zones; /** * Command execution. */ int cmd_id; pthread_t cmd_thread; GtkWidget *cmd_dialog; /** * Interface stuff. */ GtkWidget *page; GtkWidget *page_frame; GtkWidget *zfilter_combo; GtkWidget *zlist_frame_label; GtkWidget *zlist_treeview; GtkTreeModel *zlist_model; GtkListStore *zlist_store; unsigned int zlist_start_no; unsigned int zlist_end_no; int zlist_selection; GtkWidget *znum_entry; GtkWidget *zblock_entry; GtkWidget *zones_da; } dz_dev_t; /** * GUI data. */ typedef struct dz { dz_dev_t dev[DZ_MAX_DEV]; int nr_devs; int interval; int block_size; int abort; /** * Interface stuff. */ GtkWidget *window; GtkWidget *vbox; GtkWidget *notebook; GtkWidget *no_dev_frame; GdkRGBA conv_color; GdkRGBA seqnw_color; GdkRGBA seqw_color; GdkRGBA nonw_color; /** * For handling signals. */ int sig_pipe[2]; } dz_t; /** * System time in usecs. */ static inline unsigned long long dz_usec(void) { struct timeval tv; gettimeofday(&tv, NULL); return (unsigned long long) tv.tv_sec * 1000000LL + (unsigned long long) tv.tv_usec; } extern dz_t dz; dz_dev_t *dz_open(char *path); void dz_close(dz_dev_t *dzd); int dz_cmd_exec(dz_dev_t *dzd, int cmd_id, char *msg); void dz_if_err(const char *msg, const char *fmt, ...); void dz_if_create(void); void dz_if_destroy(void); void dz_if_add_device(char *dev_path); dz_dev_t *dz_if_dev_open(char *path); void dz_if_dev_close(dz_dev_t *dzd); void dz_if_dev_update(dz_dev_t *dzd, int do_report_zones); #endif /* __GZBD_H__ */ libzbd-2.0.4/tools/gui/gzbd.png000066400000000000000000000253141436612631500163570ustar00rootroot00000000000000PNG  IHDRzTXtRaw profile type exifxڭYc9m9;[7~M]o#2e,\rI" `7 w]_)9K=8x?{:_z/|Vp|U#ωy% ~|z?o?Q6P;Tw˚G.OZԷW|q1]VxT3^<~O+C77b9XyqkW)RN9XSO;ӊ'%ލsEnRSW?}q{(o{żbTv1oE@G6?A2678 1-ȭ^_4⺿`mc2!_BP1F|38 A0YƜR!8-극h6%D ,T MOXlZCÒe3+VYQRJ)GM5WjjkzZ^z>?:yph7fii:s,gekwy.'Rczg\Rrm=j/5r5^2_5ޮApb9Q1-9 1"Ov_߸ş#9k-|_C >Q~l6u^EPyvdVP/;S]}Trh~Y5jw2}س[҈'@욹`[57aXY:>΅\H7GN0Xfϗ(VnF݇QI_̧1}[E+#ws+yz?ʺG>cwuȹ0 FZݽ-~vc!k.2掾>.sSF:QeSH2ip cfey~Lޥ>-wopDń>0ߋZ}*ЋɎ@# 9__$gIJr(Qg2YLv#6+/H3HSEHj}t!o{ظ31>*{-u"I3K:20,u{rlNwT/7Wh.&xVܳƴbK5R(v4O BzVv=STJ]Y]44q")]sq)qw].)`$ܙWb'՝GðypjsZX!@{6&CpT g?Q#?PgyR|wm⛻R-VOH`C*i98WI#&4[9f 7ܞ3@CAS$h:6?w[d9v$Ȼ~7*^{~6:`:͍lRv^߲32> ~Jf AMĥo;Ч_*+CcRPgRɼAJܝ$$1Z cUŝ@SCwҩ Ȅ ŇU{8Uj[A (R"FcAgx$DUPcLmMX\ '!>4=ev?U^Ii%d\@`Z<۱uun3y`f"-)2 KsQ(7aP]AMufD!FVm(E5hF/yQ*/8"J-n# &L P,D$iNj < R&kfw`tv-'`h4i@g|Fv.))*G֡>BB'oX_Hkk"A@X \%QQo B0$$P* Ir{vĭr $"7S*~27V{0=nEB"_֏!BЖ/2 pB#_قIPXt"Chܟg I0^`ˋ dmp)`@*p?HT B={ZJ ;L >$'j֚aR~GP"P)z(c'q1]I2ȎR"*"2zGNwAQlC%[IqY hBi645a_ J6P+XʈY ӢZllPecd>ٕTW Ĥ+M]TA5F p $ Lf ‡|˓.8;iAPA|AaQnƯJfcS;KG[xI  Tuy: TqO>N '!!t؛V^{wXV@p[C m" 1Hn0 &r),L#E) |&-YQ/rE0/1+Rv 0jz60(D&4K, ຈ.AX8YQT䠇JZ4uP-bjhF UdBa'aՎ^d@V&@!Q`Hʤlc#/zԧر'lyyBT1}a4i~炯Dzh v"'ԎBPldfheT3)"I0I4~8)рpx`G!QA|+9쾽sؖ%F!rowtL3()S;j~kGW¬k\/D~Z}c02}&F6@2̢JH&h"_Ns+Փ2(@fA/F|9SHV*q:0,IIlJfڙ(do&c$a?UGzi-Ռ}C5=`Ȳ\zEwo4h:n5#t:W bYV@ [c簤(W+6@N0> ?t Au xňe.؏9QԤ~[3UwAʌA&*`@-J(m S'˞VuŎ,$.Ռ=HfC<Ϲ-)Gt>[h)DOɀima'Q &6*vi; &KdS:e 6+6G:2dؖ&7(~jrȎ$ ,-eg\xԦT$r>Fv'QHaBV$Ɩ:Loi/51ĆFAQ G)r@/dwEɄY|aFrpw)"ߜl{^>C I RIj[mK3+.!!ĒTn c m@А ꃏzoǷōo"B m 8>FSC[<>kTDmݥ>W0*p3W}VS*ֲ{SЌwh2)$Idxf0 ;,_&d5q [ƽLVrrŎ$ x*NmEFCv| 6$![`]B,T^u_Y>F pM# DZw%a t #Y&ɍE R d%IIȮn(`ò(Dꈇ$k/8BE (g jhj "cПSr_פF=`ߞo|!>㲂fByF =wf\±w*[mPaЙ&%H[ OaN+}@2l  2}tVcoxbAh߁r 55li#;?\Il@-,&.6ȯ.:DRkN0|cAb9Ԧ\~96S#q-km @(S991C:rԭ2T De{tJQMu 'XB}eЍ ȮM*d.p<2)2$P+m55}A#FI `oG % ()4t`m2%fF*'rWűjY`6JNJNJ)cyK} :3(U1Q1Mi56g7_!6U(I>_#v<]^#ǿo0Q +'""0aFO$(BjSP$g~!sejܦ+6j8w/6PEK (ACbDA}%;eBk+xܤ۾M9ڌD1g)J(SJ4֍tJ7sн]2jI@ju12KKuN 6@IJ]m&) h9X>CJl3$tT'p5t ${В!-'F2 PXkp ڬ!03Ƣ` c _8$Q ᩱ FЫ1!ܖ2uemH-z:.:ol(|u,ЀWG'#W=<8xvnQؒN Y 50O#E1ay4s$ pI7ڵLԵ g^L^%MI B!;λ킟 i{ !w~RY7mua"FEWdDt'9؀aM1" Gg.GO)ndL@sG⩃Y$ao}玩;"f##˴-]5.ƵbUAUNQ߹O`9fiBm;@Q1Q;ωctO!ABwk[k NGP C#:#Ǎ~1"pIm6Aw!mT}-C# fPѱ Kɶw5nexpA vZ9 z1׬V/`IlouHK 1t dCSjrqv؉xNZ;{}V*Yb-ЈwxTXVU}֏Q ^RxK DDv[QAiCCPICC profilex}=H@_?"U;8dNVDE EjVL.& IZpc⬫ ~9)HK -b<8ǻ{w^fT2Rɮ Wу 1*1S$<=||,sn%g2'2ݰ76->q%xĠ ?r]vsa?όGxw|NLSonsGEKGDL \1^\d$1wv{GEK`^fb`hdbimlrjioᚙljq_]eomsignhfmfdk][cNKRtsxutzqpvgelTRX°¿sqwpouĭcaeyx|ᄐZX_}|}߫WU\ecjӴպ͈mlnJHNݦ+'6Ҏ>1-;%$)]\a¿٬hgigfg¿ }<BGpLƤTtRNS@fbKGDH pHYs   IDATxkPSWN~nn3fi ATCS)h)G&"qaiY W 4]z`~g$-55-n(), G(=AWYg ա] 0YF' |2=N,PkhG8XDVڣq %L rgwU'EJ& { %w)%/{d|&wyQ(>;Tdi/]N9 ZeL~%Y U@!O $m2eZkC0  $a+睎×^Q6 P>d0؉mbh p>g7tt=Xt:<<$]eZX}tte<YS|@pB^.yg9(`'$zW+61=`@sO{Tf{pf',R͍O (+gv'T<YeW=UVA'e,=ʂ[YgB<Y>C$>zZ%Q~bXa*Y >v$Pe l/d؍ Ub<^!kEPՆ$SWWfD$.a1@ _|:T Xކo!ܬj S ͯbpUYܐ;SqD$w_4]>ƙ9u'`1 Yt >ۭtE`@㭉 }R|>{H]l'J |./"1~{x6ҺA8M xQƝh4CC*- 2%268æGػw?ӓm(6@=#tz4tu5x@؋(9s1ѠG4` \(l+&ǎ (~(0ȫ { M G7:k؇@x Dw &y7]D [nzC l x.~ xG5C]~Mhab =?rH# ,_H>b/)ǾxN4>boD,ќPW[bÌ]"܂v^_MռӧO9~k@TJB% D76;ק*g[Ѱ@B$jѥK0Y>^^t_;/2szf H0d(O?94K8^O%$-194(@Kmޑ[[k 0й11\_eӖWInY1(͛(_Z /G#9V ߱C"C+k# JWGEVrPfL11@OVwq)_쉽%Z2H]fnjbo%WժB[!+TE/r-`6 Ă Y55ZR>JUPh6Ea FsE#f$[$ëU—[ȕ&ݸ#9!VR0d,VMKrT>^̒-7U 8S+= !dxqS H9eeKa j?o/OWE~YDBfϧte?xɗJ򞞪q\ N E[LV[miLEyi~z&y2TZ,uT˓~zB[`;wu! n~)'7Om'$vlNxMG| }-fc|1MBIENDB`libzbd-2.0.4/tools/gui/gzbd_if.c000066400000000000000000000217131436612631500164720ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #include #include #include #include #include #include #include "gzbd.h" static void dz_if_show_nodev(void); static void dz_if_hide_nodev(void); static gboolean dz_if_resize_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data); static void dz_if_delete_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data); static void dz_if_open_cb(GtkWidget *widget, gpointer user_data); static void dz_if_close_cb(GtkWidget *widget, gpointer user_data); static void dz_if_close_page_cb(GtkWidget *widget, gpointer user_data); static void dz_if_exit_cb(GtkWidget *widget, gpointer user_data); void dz_if_err(const char *msg, const char *fmt, ...) { GtkWidget *dialog; dialog = gtk_message_dialog_new(GTK_WINDOW(dz.window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", msg); if (fmt) { va_list args; char secondary[256]; va_start(args, fmt); vsnprintf(secondary, 255, fmt, args); va_end(args); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG(dialog), "%s", secondary); } gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } void dz_if_create(void) { GtkWidget *toolbar; GtkWidget *sep; GtkToolItem *ti; /* Get colors */ gdk_rgba_parse(&dz.conv_color, "Magenta"); gdk_rgba_parse(&dz.seqnw_color, "Green"); gdk_rgba_parse(&dz.seqw_color, "Red"); gdk_rgba_parse(&dz.nonw_color, "RosyBrown"); /* Window */ dz.window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(dz.window), "Zoned Block Device Zone State"); gtk_container_set_border_width(GTK_CONTAINER(dz.window), 10); g_signal_connect((gpointer) dz.window, "delete-event", G_CALLBACK(dz_if_delete_cb), NULL); /* Top vbox */ dz.vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); gtk_widget_show(dz.vbox); gtk_container_add(GTK_CONTAINER(dz.window), dz.vbox); /* Toolbar */ toolbar = gtk_toolbar_new(); gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); gtk_widget_show(toolbar); gtk_box_pack_start(GTK_BOX(dz.vbox), toolbar, FALSE, FALSE, 0); /* Toolbar open button */ ti = gtk_tool_button_new(gtk_image_new_from_icon_name("document-open", GTK_ICON_SIZE_LARGE_TOOLBAR), "Open"); gtk_tool_item_set_tooltip_text(ti, "Open a device"); gtk_tool_item_set_is_important(ti, TRUE); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), ti, -1); g_signal_connect(G_OBJECT(ti), "clicked", G_CALLBACK(dz_if_open_cb), NULL); /* Toolbar close button */ ti = gtk_tool_button_new(gtk_image_new_from_icon_name("window-close", GTK_ICON_SIZE_LARGE_TOOLBAR), "Close"); gtk_tool_item_set_tooltip_text(ti, "Close current device"); gtk_tool_item_set_is_important(ti, TRUE); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), ti, -1); g_signal_connect(G_OBJECT(ti), "clicked", G_CALLBACK(dz_if_close_cb), NULL); /* Separator */ ti = gtk_separator_tool_item_new(); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), ti, -1); /* Toolbar exit button */ ti = gtk_tool_button_new(gtk_image_new_from_icon_name("application-exit", GTK_ICON_SIZE_LARGE_TOOLBAR), "Quit"); gtk_tool_item_set_tooltip_text(ti, "Quit"); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), ti, -1); g_signal_connect(G_OBJECT(ti), "clicked", G_CALLBACK(dz_if_exit_cb), NULL); /* Separator */ sep = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL); gtk_widget_show(sep); gtk_box_pack_start(GTK_BOX(dz.vbox), sep, FALSE, FALSE, 0); /* Initially, no device open: show "no device" frame */ dz_if_show_nodev(); /* Finish setup */ g_signal_connect((gpointer) dz.window, "configure-event", G_CALLBACK(dz_if_resize_cb), NULL); gtk_window_set_default_size(GTK_WINDOW(dz.window), 1024, 768); gtk_widget_show_all(dz.window); } void dz_if_destroy(void) { if ( dz.window ) { gtk_widget_destroy(dz.window); dz.window = NULL; } } void dz_if_add_device(char *dev_path) { GtkWidget *label; GtkWidget *hbox; GtkWidget *button; dz_dev_t *dzd; int page_no; char str[256]; /* Open device */ dzd = dz_if_dev_open(dev_path); if (!dzd) return; dz_if_hide_nodev(); /* Add page */ hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); snprintf(str, sizeof(str) - 1, "%s", dzd->path); label = gtk_label_new(NULL); gtk_label_set_text(GTK_LABEL(label), str); gtk_label_set_use_markup(GTK_LABEL(label), TRUE); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); button = gtk_button_new_from_icon_name("window-close", GTK_ICON_SIZE_BUTTON); gtk_box_pack_start(GTK_BOX(hbox), button, FALSE, FALSE, 0); g_signal_connect((gpointer) button, "clicked", G_CALLBACK(dz_if_close_page_cb), dzd); gtk_widget_show_all(hbox); page_no = gtk_notebook_append_page(GTK_NOTEBOOK(dz.notebook), dzd->page_frame, hbox); dzd->page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(dz.notebook), page_no); gtk_notebook_set_current_page(GTK_NOTEBOOK(dz.notebook), page_no); } static void dz_if_show_nodev(void) { if (dz.notebook) { /* Remove notebook */ gtk_widget_destroy(dz.notebook); dz.notebook = NULL; } if (!dz.no_dev_frame) { GtkWidget *frame; GtkWidget *label; frame = gtk_frame_new(NULL); gtk_widget_show(frame); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); gtk_container_set_border_width(GTK_CONTAINER(frame), 10); gtk_box_pack_start(GTK_BOX(dz.vbox), frame, TRUE, TRUE, 0); label = gtk_label_new(NULL); gtk_widget_show(label); gtk_label_set_text(GTK_LABEL(label), "No device open"); gtk_label_set_use_markup(GTK_LABEL(label), TRUE); gtk_container_add(GTK_CONTAINER(frame), label); dz.no_dev_frame = frame; } } static void dz_if_hide_nodev(void) { if (dz.no_dev_frame) { /* Remove "no device" frame */ gtk_widget_destroy(dz.no_dev_frame); dz.no_dev_frame = NULL; } if (!dz.notebook) { /* Create the notebook */ dz.notebook = gtk_notebook_new(); gtk_notebook_set_tab_pos(GTK_NOTEBOOK(dz.notebook), GTK_POS_TOP); gtk_notebook_set_show_border(GTK_NOTEBOOK(dz.notebook), TRUE); gtk_notebook_set_show_tabs(GTK_NOTEBOOK(dz.notebook), TRUE); gtk_widget_show(dz.notebook); gtk_box_pack_start(GTK_BOX(dz.vbox), dz.notebook, TRUE, TRUE, 0); } } static void dz_if_remove_device(dz_dev_t *dzd) { int page_no = gtk_notebook_page_num(GTK_NOTEBOOK(dz.notebook), dzd->page_frame); /* Close the device */ dz_if_dev_close(dzd); /* Remove the page */ gtk_notebook_remove_page(GTK_NOTEBOOK(dz.notebook), page_no); dzd->page = NULL; if (dz.nr_devs == 0) /* Show "no device" */ dz_if_show_nodev(); } static dz_dev_t *dz_if_get_device(void) { dz_dev_t *dzd = NULL; GtkWidget *page = NULL; int i; if (!dz.notebook) return NULL; page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(dz.notebook), gtk_notebook_get_current_page(GTK_NOTEBOOK(dz.notebook))); for (i = 0; i < DZ_MAX_DEV; i++) { dzd = &dz.dev[i]; if (dzd->dev_fd >= 0 && dzd->page == page) return dzd; } return NULL; } static void dz_if_open_cb(GtkWidget *widget, gpointer user_data) { GtkFileChooser *chooser; GtkFileFilter *filter; GtkWidget *dialog; char *dev_path = NULL; gint res; /* File chooser */ dialog = gtk_file_chooser_dialog_new("Open Zoned Block Device", GTK_WINDOW(dz.window), GTK_FILE_CHOOSER_ACTION_OPEN, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL); chooser = GTK_FILE_CHOOSER(dialog); gtk_file_chooser_set_current_folder(chooser, "/dev/"); filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, "Block Device Files"); gtk_file_filter_add_mime_type(filter, "inode/blockdevice"); gtk_file_chooser_add_filter(chooser, filter); res = gtk_dialog_run(GTK_DIALOG(dialog)); if (res == GTK_RESPONSE_ACCEPT) dev_path = gtk_file_chooser_get_filename(chooser); gtk_widget_destroy(dialog); if (dev_path) { dz_if_add_device(dev_path); g_free(dev_path); } } static void dz_if_close_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd = dz_if_get_device(); if (dzd) dz_if_remove_device(dzd); } static void dz_if_close_page_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; if (dzd) dz_if_remove_device(dzd); } static void dz_if_exit_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd; int i; if (dz.notebook) { for (i = 0; i < DZ_MAX_DEV; i++) { dzd = &dz.dev[i]; if (dzd->dev_fd >= 0) dz_if_remove_device(dzd); } } gtk_main_quit(); } static gboolean dz_if_resize_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) { dz_dev_t *dzd = dz_if_get_device(); if (dzd) dz_if_dev_update(dzd, 0); return FALSE; } static void dz_if_delete_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) { dz_dev_t *dzd; int i; dz.window = NULL; if (dz.notebook) { for (i = 0; i < DZ_MAX_DEV; i++) { dzd = &dz.dev[i]; if (dzd->dev_fd >= 0) dz_if_remove_device(dzd); } } gtk_main_quit(); } libzbd-2.0.4/tools/gui/gzbd_if_dev.c000066400000000000000000001165361436612631500173400ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #include #include #include #include #include #include #include "gzbd.h" static void dz_if_zlist_print_zone_number(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_type(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_cond(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_rwp_recommended(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_nonseq(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_start(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_len(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_capacity(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static void dz_if_zlist_print_zone_wp(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data); static gboolean dz_if_zlist_filter_cb(GtkComboBox *button, gpointer user_data); static void dz_if_zlist_set_block_size_cb(GtkEntry *entry, gpointer user_data); static void dz_if_zlist_set_use_hexa_cb(GtkToggleButton *togglebutton, gpointer user_data); static gboolean dz_if_zlist_entry_visible(GtkTreeModel *model, GtkTreeIter *iter, gpointer data); static void dz_if_zlist_fill(dz_dev_t *dzd); static gboolean dz_if_zlist_refresh_cb(GtkWidget *widget, gpointer user_data); static void dz_if_zlist_scroll_cb(GtkWidget *widget, gpointer user_data); static gboolean dz_if_zlist_select_cb(GtkTreeSelection *selection, GtkTreeModel *model, GtkTreePath *path, gboolean path_currently_selected, gpointer userdata); static void dz_if_znum_set(dz_dev_t *dzd); static void dz_if_znum_set_cb(GtkEntry *entry, gpointer user_data); static void dz_if_zblock_set(dz_dev_t *dzd); static void dz_if_zblock_set_cb(GtkEntry *entry, gpointer user_data); static void dz_if_update_zones(dz_dev_t *dzd); static void dz_if_redraw_zones(dz_dev_t *dzd); static gboolean dz_if_zones_draw_legend_cb(GtkWidget *widget, cairo_t *cr, gpointer user_data); static gboolean dz_if_zones_draw_cb(GtkWidget *widget, cairo_t *cr, gpointer user_data); static gboolean dz_if_zone_open_cb(GtkWidget *widget, gpointer user_data); static gboolean dz_if_zone_close_cb(GtkWidget *widget, gpointer user_data); static gboolean dz_if_zone_finish_cb(GtkWidget *widget, gpointer user_data); static gboolean dz_if_zone_reset_cb(GtkWidget *widget, gpointer user_data); static inline void dz_if_set_margin(GtkWidget *widget, int left, int right, int top, int bottom) { #if GTK_CHECK_VERSION(3, 12, 0) gtk_widget_set_margin_start(widget, left); gtk_widget_set_margin_end(widget, right); #else gtk_widget_set_margin_left(widget, left); gtk_widget_set_margin_right(widget, right); #endif if (top) gtk_widget_set_margin_top(widget, top); if (bottom) gtk_widget_set_margin_bottom(widget, bottom); } static struct dz_if_zinfo_filter { int ro; char *str; } zfilter[] = { { ZBD_RO_ALL, "All zones" }, { ZBD_RO_NOT_WP, "Conventional zones" }, { ZBD_RO_EMPTY, "Empty zones" }, { ZBD_RO_FULL, "Full zones" }, { ZBD_RO_IMP_OPEN, "Implicitly open zones" }, { ZBD_RO_EXP_OPEN, "Explicitly open zones" }, { ZBD_RO_CLOSED, "Closed zones" }, { ZBD_RO_RWP_RECOMMENDED, "Zones needing reset" }, { ZBD_RO_NON_SEQ, "Zones not sequentially written" }, { ZBD_RO_RDONLY, "Read-only zones" }, { ZBD_RO_OFFLINE, "Offline zones" }, { 0, NULL } }; dz_dev_t *dz_if_dev_open(char *path) { GtkWidget *top_vbox, *hbox, *ctrl_hbox, *vbox; GtkWidget *combo, *scrolledwindow; GtkWidget *button, *checkbutton; GtkWidget *frame; GtkWidget *image; GtkWidget *label; GtkWidget *entry; GtkWidget *hbuttonbox; GtkWidget *treeview; GtkCellRenderer *renderer; GtkTreeIter iter; GtkWidget *da; char str[256]; unsigned int i; dz_dev_t *dzd; /* Open the device */ dzd = dz_open(path); if (!dzd) return NULL; /* Create a top frame for the device */ frame = gtk_frame_new(NULL); gtk_widget_show(frame); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_container_set_border_width(GTK_CONTAINER(frame), 10); dzd->page_frame = frame; /* Top vbox */ top_vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); gtk_widget_show(top_vbox); gtk_container_add(GTK_CONTAINER(frame), top_vbox); /* Zone list filter frame */ snprintf(str, sizeof(str) - 1, "%.03F GB, %u B logical blocks, %u B physical blocks", (double) (dzd->info.nr_sectors << 9) / 1000000000, dzd->info.lblock_size, dzd->info.pblock_size); frame = gtk_frame_new(str); gtk_widget_show(frame); gtk_box_pack_start(GTK_BOX(top_vbox), frame, FALSE, TRUE, 0); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); gtk_label_set_use_markup(GTK_LABEL(gtk_frame_get_label_widget(GTK_FRAME(frame))), TRUE); hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); gtk_widget_show(hbox); dz_if_set_margin(hbox, 7, 7, 0, 0); gtk_container_add(GTK_CONTAINER(frame), hbox); /* Zone list filter label */ label = gtk_label_new(NULL); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); gtk_label_set_text(GTK_LABEL(label), "Zone filter"); gtk_label_set_use_markup(GTK_LABEL(label), TRUE); /* Zone list filter */ combo = gtk_combo_box_text_new(); gtk_widget_show(combo); dz_if_set_margin(combo, 7, 7, 10, 5); i = 0; while (zfilter[i].str) { gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo), NULL, zfilter[i].str); i++; } gtk_combo_box_set_active(GTK_COMBO_BOX(combo), 0); gtk_box_pack_start(GTK_BOX(hbox), combo, TRUE, TRUE, 0); dzd->zfilter_combo = combo; g_signal_connect((gpointer) combo, "changed", G_CALLBACK(dz_if_zlist_filter_cb), dzd); /* Block size entry */ label = gtk_label_new("Block size (B)"); gtk_label_set_use_markup(GTK_LABEL(label), TRUE); gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); entry = gtk_entry_new(); snprintf(str, sizeof(str) - 1, "%d", dzd->block_size); gtk_entry_set_text(GTK_ENTRY(entry), str); gtk_widget_show(entry); gtk_box_pack_start(GTK_BOX(hbox), entry, FALSE, FALSE, 0); g_signal_connect((gpointer)entry, "activate", G_CALLBACK(dz_if_zlist_set_block_size_cb), dzd); /* Hexadecimal values */ label = gtk_label_new("Hexadecimal"); gtk_label_set_use_markup(GTK_LABEL(label), TRUE); gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); checkbutton = gtk_check_button_new(); gtk_widget_show(checkbutton); gtk_box_pack_start(GTK_BOX(hbox), checkbutton, FALSE, FALSE, 0); g_signal_connect((gpointer)checkbutton, "toggled", G_CALLBACK(dz_if_zlist_set_use_hexa_cb), dzd); /* Refresh button */ button = gtk_button_new(); gtk_widget_show(button); dz_if_set_margin(button, 0, 7, 10, 5); gtk_box_pack_start(GTK_BOX(hbox), button, FALSE, FALSE, 0); hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); gtk_widget_show(hbox); gtk_container_add(GTK_CONTAINER(button), hbox); image = gtk_image_new_from_icon_name("view-refresh", GTK_ICON_SIZE_BUTTON); gtk_widget_show(image); gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0); label = gtk_label_new("Refresh"); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); g_signal_connect((gpointer) button, "clicked", G_CALLBACK(dz_if_zlist_refresh_cb), dzd); /* Zone list frame */ snprintf(str, sizeof(str) - 1, "%s: %d zones", dzd->path, dzd->nr_zones); frame = gtk_frame_new(str); gtk_widget_show(frame); gtk_box_pack_start(GTK_BOX(top_vbox), frame, TRUE, TRUE, 0); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); dzd->zlist_frame_label = gtk_frame_get_label_widget(GTK_FRAME(frame)); gtk_label_set_use_markup(GTK_LABEL(dzd->zlist_frame_label), TRUE); /* Create zone list */ scrolledwindow = gtk_scrolled_window_new(NULL, NULL); gtk_widget_show(scrolledwindow); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwindow), GTK_SHADOW_IN); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwindow), GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); dz_if_set_margin(scrolledwindow, 7, 7, 10, 10); gtk_container_add(GTK_CONTAINER(frame), scrolledwindow); /* Create zone list store and add rows */ dzd->zlist_store = gtk_list_store_new(DZ_ZONE_LIST_COLUMS, G_TYPE_UINT); /* DZ_ZONE_NUM */ for (i = 0; i < dzd->max_nr_zones; i++) gtk_list_store_append(dzd->zlist_store, &iter); dzd->zlist_model = gtk_tree_model_filter_new(GTK_TREE_MODEL(dzd->zlist_store), NULL); gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(dzd->zlist_model), dz_if_zlist_entry_visible, dzd, NULL); /* Initialize the tree view */ treeview = gtk_tree_view_new_with_model(dzd->zlist_model); gtk_widget_show(treeview); gtk_container_add(GTK_CONTAINER(scrolledwindow), treeview); gtk_tree_view_set_enable_search(GTK_TREE_VIEW(treeview), FALSE); gtk_tree_selection_set_mode(gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)), GTK_SELECTION_SINGLE); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(treeview), TRUE); dzd->zlist_treeview = treeview; dzd->zlist_selection = -1; gtk_tree_selection_set_select_function(gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)), dz_if_zlist_select_cb, dzd, NULL); g_signal_connect((gpointer) gtk_scrollable_get_vadjustment(GTK_SCROLLABLE(treeview)), "value-changed", G_CALLBACK(dz_if_zlist_scroll_cb), dzd); /* Number column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Zone number", renderer, dz_if_zlist_print_zone_number, dzd, NULL); /* Type column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Type", renderer, dz_if_zlist_print_zone_type, dzd, NULL); /* Condition column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Condition", renderer, dz_if_zlist_print_zone_cond, dzd, NULL); /* Need reset column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "RWP Recommended", renderer, dz_if_zlist_print_zone_rwp_recommended, dzd, NULL); /* Non-seq column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Non Seq", renderer, dz_if_zlist_print_zone_nonseq, dzd, NULL); /* Start column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Start", renderer, dz_if_zlist_print_zone_start, dzd, NULL); /* Length column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Length", renderer, dz_if_zlist_print_zone_len, dzd, NULL); /* Capacity column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Capacity", renderer, dz_if_zlist_print_zone_capacity, dzd, NULL); /* Write pointer column */ renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_data_func(GTK_TREE_VIEW(treeview), -1, "Write Pointer", renderer, dz_if_zlist_print_zone_wp, dzd, NULL); /* Fill the model with zone data */ dz_if_zlist_fill(dzd); /* Zone state drawing frame */ frame = gtk_frame_new("Zone Write State"); gtk_widget_show(frame); gtk_box_pack_start(GTK_BOX(top_vbox), frame, FALSE, TRUE, 0); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); gtk_label_set_use_markup(GTK_LABEL(gtk_frame_get_label_widget(GTK_FRAME(frame))), TRUE); vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); gtk_widget_show(vbox); gtk_container_add(GTK_CONTAINER(frame), vbox); da = gtk_drawing_area_new(); gtk_widget_set_size_request(da, -1, 20); gtk_widget_show(da); gtk_container_add(GTK_CONTAINER(vbox), da); g_signal_connect((gpointer) da, "draw", G_CALLBACK(dz_if_zones_draw_legend_cb), dzd); da = gtk_drawing_area_new(); gtk_widget_set_size_request(da, -1, 100); gtk_widget_show(da); gtk_container_add(GTK_CONTAINER(vbox), da); dzd->zones_da = da; g_signal_connect((gpointer) da, "draw", G_CALLBACK(dz_if_zones_draw_cb), dzd); /* Zone control frame */ frame = gtk_frame_new("Zone Control"); gtk_widget_show(frame); gtk_box_pack_start(GTK_BOX(top_vbox), frame, FALSE, TRUE, 0); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); gtk_label_set_use_markup(GTK_LABEL(gtk_frame_get_label_widget(GTK_FRAME(frame))), TRUE); /* Hbox for controls */ ctrl_hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); gtk_widget_show(ctrl_hbox); dz_if_set_margin(ctrl_hbox, 7, 7, 0, 0); gtk_container_add(GTK_CONTAINER(frame), ctrl_hbox); /* Zone number selection entry */ label = gtk_label_new("Zone number"); gtk_label_set_use_markup(GTK_LABEL(label), TRUE); gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(ctrl_hbox), label, FALSE, FALSE, 5); entry = gtk_entry_new(); gtk_entry_set_text(GTK_ENTRY(entry), "-1"); gtk_widget_show(entry); gtk_box_pack_start(GTK_BOX(ctrl_hbox), entry, FALSE, FALSE, 0); dzd->znum_entry = entry; g_signal_connect((gpointer)entry, "activate", G_CALLBACK(dz_if_znum_set_cb), dzd); /* Block selection entry */ label = gtk_label_new("Block"); gtk_label_set_use_markup(GTK_LABEL(label), TRUE); gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(ctrl_hbox), label, FALSE, FALSE, 5); entry = gtk_entry_new(); gtk_entry_set_text(GTK_ENTRY(entry), "-1"); gtk_widget_show(entry); gtk_box_pack_start(GTK_BOX(ctrl_hbox), entry, FALSE, FALSE, 0); dzd->zblock_entry = entry; g_signal_connect((gpointer)entry, "activate", G_CALLBACK(dz_if_zblock_set_cb), dzd); /* Zone control button Box */ hbuttonbox = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL); gtk_widget_show(hbuttonbox); gtk_box_pack_start(GTK_BOX(ctrl_hbox), hbuttonbox, FALSE, FALSE, 0); gtk_container_set_border_width(GTK_CONTAINER(hbuttonbox), 10); gtk_button_box_set_layout(GTK_BUTTON_BOX(hbuttonbox), GTK_BUTTONBOX_START); gtk_box_set_spacing(GTK_BOX(hbuttonbox), 10); /* Open button */ button = gtk_button_new(); gtk_widget_show(button); gtk_container_add(GTK_CONTAINER(hbuttonbox), button); hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); gtk_widget_show(hbox); gtk_container_add(GTK_CONTAINER(button), hbox); image = gtk_image_new_from_icon_name("gtk-connect", GTK_ICON_SIZE_BUTTON); gtk_widget_show(image); gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0); label = gtk_label_new("Open Zone"); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); g_signal_connect((gpointer) button, "clicked", G_CALLBACK(dz_if_zone_open_cb), dzd); /* Close button */ button = gtk_button_new(); gtk_widget_show(button); gtk_container_add(GTK_CONTAINER(hbuttonbox), button); hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); gtk_widget_show(hbox); gtk_container_add(GTK_CONTAINER(button), hbox); image = gtk_image_new_from_icon_name("window-close", GTK_ICON_SIZE_BUTTON); gtk_widget_show(image); gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0); label = gtk_label_new("Close Zone"); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); g_signal_connect((gpointer) button, "clicked", G_CALLBACK(dz_if_zone_close_cb), dzd); /* Finish button */ button = gtk_button_new(); gtk_widget_show(button); gtk_container_add(GTK_CONTAINER(hbuttonbox), button); hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); gtk_widget_show(hbox); gtk_container_add(GTK_CONTAINER(button), hbox); image = gtk_image_new_from_icon_name("go-last", GTK_ICON_SIZE_BUTTON); gtk_widget_show(image); gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0); label = gtk_label_new("Finish Zone"); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); g_signal_connect((gpointer) button, "clicked", G_CALLBACK(dz_if_zone_finish_cb), dzd); /* Reset button */ button = gtk_button_new(); gtk_widget_show(button); gtk_container_add(GTK_CONTAINER(hbuttonbox), button); hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); gtk_widget_show(hbox); gtk_container_add(GTK_CONTAINER(button), hbox); image = gtk_image_new_from_icon_name("go-first", GTK_ICON_SIZE_BUTTON); gtk_widget_show(image); gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0); label = gtk_label_new("Reset Write Ptr"); gtk_widget_show(label); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); g_signal_connect((gpointer) button, "clicked", G_CALLBACK(dz_if_zone_reset_cb), dzd); gtk_widget_show_all(dz.window); return dzd; } void dz_if_dev_close(dz_dev_t *dzd) { /* Close the device */ dz_close(dzd); } void dz_if_dev_update(dz_dev_t *dzd, int do_report_zones) { if (do_report_zones) /* Update zones info */ dz_if_update_zones(dzd); else /* Redraw viewable zone range */ dz_if_redraw_zones(dzd); } static long long dz_if_bytes2blocks(dz_dev_t *dzd, long long bytes) { return bytes / dzd->block_size; } static void dz_if_zlist_print_zone_number(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); /* Bold black font */ g_object_set(renderer, "foreground", "Black", "foreground-set", TRUE, NULL); g_object_set(renderer, "weight", PANGO_WEIGHT_BOLD, "weight-set", FALSE, NULL); snprintf(str, sizeof(str), "%d", i); g_object_set(renderer, "text", str, NULL); } static void dz_if_zlist_print_zone_type(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Normal black font */ g_object_set(renderer, "foreground", "Black", "foreground-set", TRUE, NULL); if (zbd_zone_cnv(z)) strncpy(str, "Conventional", sizeof(str)); else if (zbd_zone_swr(z)) strncpy(str, "Seq write req.", sizeof(str)); else if (zbd_zone_swp(z)) strncpy(str, "Seq write pref.", sizeof(str)); else snprintf(str, sizeof(str), "??? (0x%01x)", zbd_zone_type(z)); g_object_set(renderer, "text", str, NULL); } static void dz_if_zlist_print_zone_cond(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Normal black font by default */ g_object_set(renderer, "foreground", "Black", "foreground-set", TRUE, NULL); if (zbd_zone_not_wp(z)) { strncpy(str, "Not WP", sizeof(str)); } else if (zbd_zone_empty(z)) { g_object_set(renderer, "foreground", "Green", "foreground-set", TRUE, NULL); strncpy(str, "Empty", sizeof(str)); } else if (zbd_zone_full(z)) { g_object_set(renderer, "foreground", "Red", "foreground-set", TRUE, NULL); strncpy(str, "Full", sizeof(str)); } else if (zbd_zone_imp_open(z)) { g_object_set(renderer, "foreground", "Blue", "foreground-set", TRUE, NULL); strncpy(str, "Implicit Open", sizeof(str)); } else if (zbd_zone_exp_open(z)) { g_object_set(renderer, "foreground", "Blue", "foreground-set", TRUE, NULL); strncpy(str, "Explicit Open", sizeof(str)); } else if (zbd_zone_closed(z)) { strncpy(str, "Closed", sizeof(str)); } else if (zbd_zone_rdonly(z)) { strncpy(str, "Read-only", sizeof(str)); } else if (zbd_zone_offline(z)) { strncpy(str, "Offline", sizeof(str)); } else { snprintf(str, sizeof(str), "??? (0x%01x)", zbd_zone_cond(z)); } g_object_set(renderer, "text", str, NULL); } static void dz_if_zlist_print_zone_rwp_recommended(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Zone rwp recommended */ if (zbd_zone_rwp_recommended(z)) { g_object_set(renderer, "foreground", "Red", "foreground-set", TRUE, NULL); strncpy(str, "Yes", sizeof(str)); } else { g_object_set(renderer, "foreground", "Green", "foreground-set", TRUE, NULL); strncpy(str, "No", sizeof(str)); } g_object_set(renderer, "text", str, NULL); } static void dz_if_zlist_print_zone_nonseq(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Zone non seq */ if (zbd_zone_non_seq_resources(z)) { g_object_set(renderer, "foreground", "Red", "foreground-set", TRUE, NULL); strncpy(str, "Yes", sizeof(str)); } else { g_object_set(renderer, "foreground", "Green", "foreground-set", TRUE, NULL); strncpy(str, "No", sizeof(str)); } g_object_set(renderer, "text", str, NULL); } static void dz_if_val_str(dz_dev_t *dzd, char *str, long long val) { char *format; if (dzd->use_hexa) format = "0x%llX"; else format = "%lld"; sprintf(str, format, dz_if_bytes2blocks(dzd, val)); } static void dz_if_zlist_print_zone_start(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Zone start */ g_object_set(renderer, "foreground", "Black", "foreground-set", TRUE, NULL); dz_if_val_str(dzd, str, zbd_zone_start(z)); g_object_set(renderer, "text", str, NULL); } static void dz_if_zlist_print_zone_len(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Zone length */ g_object_set(renderer, "foreground", "Black", "foreground-set", TRUE, NULL); dz_if_val_str(dzd, str, zbd_zone_len(z)); g_object_set(renderer, "text", str, NULL); } static void dz_if_zlist_print_zone_capacity(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Zone capacity */ g_object_set(renderer, "foreground", "Black", "foreground-set", TRUE, NULL); dz_if_val_str(dzd, str, zbd_zone_capacity(z)); g_object_set(renderer, "text", str, NULL); } static void dz_if_zlist_print_zone_wp(GtkTreeViewColumn *col, GtkCellRenderer *renderer, GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; struct zbd_zone *z; char str[64]; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); z = &dzd->zones[i].info; /* Zone wp LBA */ if (zbd_zone_not_wp(z)) { g_object_set(renderer, "foreground", "Grey", "foreground-set", TRUE, NULL); strncpy(str, "N/A", sizeof(str)); } else if (zbd_zone_empty(z)) { g_object_set(renderer, "foreground", "Green", "foreground-set", TRUE, NULL); strncpy(str, "Empty", sizeof(str)); } else if (zbd_zone_full(z)) { g_object_set(renderer, "foreground", "Red", "foreground-set", TRUE, NULL); strncpy(str, "Full", sizeof(str)); } else { g_object_set(renderer, "foreground", "Black", "foreground-set", TRUE, NULL); dz_if_val_str(dzd, str, zbd_zone_wp(z)); } g_object_set(renderer, "text", str, NULL); } static gboolean dz_if_zlist_entry_visible(GtkTreeModel *model, GtkTreeIter *iter, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; int i; gtk_tree_model_get(model, iter, DZ_ZONE_NUM, &i, -1); return dzd->zones[i].visible ? TRUE : FALSE; } static void dz_if_zlist_fill(dz_dev_t *dzd) { GtkTreeModel *model = GTK_TREE_MODEL(dzd->zlist_store); GtkTreeIter iter; unsigned int i; gtk_tree_model_get_iter_first(model, &iter); for (i = 0; i < dzd->max_nr_zones; i++) { gtk_list_store_set(dzd->zlist_store, &iter, DZ_ZONE_NUM, dzd->zones[i].no, -1); gtk_tree_model_iter_next(model, &iter); } gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(dzd->zlist_model)); } static void dz_if_zlist_update_range(dz_dev_t *dzd) { GtkTreePath *start = NULL, *end = NULL; GtkTreeIter iter; if (!dzd->nr_zones || !dzd->zones) { dzd->zlist_start_no = 0; dzd->zlist_end_no = 0; return; } gtk_tree_view_get_visible_range(GTK_TREE_VIEW(dzd->zlist_treeview), &start, &end); if (start) { if (gtk_tree_model_get_iter(dzd->zlist_model, &iter, start) == TRUE) gtk_tree_model_get(dzd->zlist_model, &iter, DZ_ZONE_NUM, &dzd->zlist_start_no, -1); else dzd->zlist_start_no = 0; gtk_tree_path_free(start); } else { dzd->zlist_start_no = 0; } if (end) { if (gtk_tree_model_get_iter(dzd->zlist_model, &iter, end) == TRUE) gtk_tree_model_get(dzd->zlist_model, &iter, DZ_ZONE_NUM, &dzd->zlist_end_no, -1); else dzd->zlist_end_no = dzd->nr_zones - 1; gtk_tree_path_free(end); } else { dzd->zlist_end_no = dzd->nr_zones - 1; } } static void dz_if_zlist_set_view_range(dz_dev_t *dzd, int center) { GtkTreePath *path; float align; int zno = -1; if (!dzd->nr_zones) return; /* Go to zno (center) */ if (center) { zno = dzd->zlist_selection; align = 0.5; } if (zno < 0) { zno = dzd->zlist_start_no; align = 0.0; } path = gtk_tree_path_new_from_indices(zno, -1); if (path) { gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(dzd->zlist_treeview), path, NULL, TRUE, align, 0.0); gtk_tree_path_free(path); } } static void dz_if_redraw_zones(dz_dev_t *dzd) { /* Re-draw zone state */ gtk_widget_queue_draw(dzd->zones_da); } static void dz_if_zlist_scroll_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; /* Update visible zone range in list */ dz_if_redraw_zones(dzd); } static void dz_if_znum_set(dz_dev_t *dzd) { char str[64]; snprintf(str, sizeof(str) - 1, "%d", dzd->zlist_selection); gtk_entry_set_text(GTK_ENTRY(dzd->znum_entry), str); } static void dz_if_zblock_set(dz_dev_t *dzd) { long long block; char str[64]; if (dzd->zlist_selection < 0) { block = -1; strcpy(str, "-1"); } else { block = zbd_zone_start(&dzd->zones[dzd->zlist_selection].info); dz_if_val_str(dzd, str, block); } gtk_entry_set_text(GTK_ENTRY(dzd->zblock_entry), str); } static void dz_if_set_selection(dz_dev_t *dzd, int zno) { if (zno == dzd->zlist_selection) return; dzd->zlist_selection = zno; dz_if_znum_set(dzd); dz_if_zblock_set(dzd); } static gboolean dz_if_zlist_select_cb(GtkTreeSelection *selection, GtkTreeModel *model, GtkTreePath *path, gboolean path_currently_selected, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; GtkTreeIter iter; int zno; if (path_currently_selected) return TRUE; if (!dzd->nr_zones) zno = -1; else if (gtk_tree_model_get_iter(model, &iter, path)) gtk_tree_model_get(model, &iter, DZ_ZONE_NUM, &zno, -1); dz_if_set_selection(dzd, zno); return TRUE; } static void dz_if_zlist_clear_selection(dz_dev_t *dzd) { GtkTreeSelection *sel; if (dzd->zlist_selection < 0) return; sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(dzd->zlist_treeview)); gtk_tree_selection_unselect_all(sel); dz_if_set_selection(dzd, -1); } static void dz_if_zlist_set_selection(dz_dev_t *dzd, int zno) { GtkTreeSelection *sel; GtkTreePath *path; if (zno == dzd->zlist_selection) return; sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(dzd->zlist_treeview)); path = gtk_tree_path_new_from_indices(zno, -1); if (path) { gtk_tree_selection_select_path(sel, path); gtk_tree_path_free(path); } dz_if_set_selection(dzd, zno); } static void dz_if_znum_set_cb(GtkEntry *entry, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; int zno; zno = atoi(gtk_entry_get_text(entry)); if (zno < 0 || zno >= (gint)dzd->max_nr_zones) { dz_if_zlist_clear_selection(dzd); return; } dz_if_zlist_set_selection(dzd, zno); dz_if_zlist_set_view_range(dzd, 1); } static void dz_if_zblock_set_cb(GtkEntry *entry, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; long long block = strtoll(gtk_entry_get_text(entry), NULL, 0); unsigned long long bytes = block * dzd->block_size; struct zbd_zone *z; unsigned int i; int zno = -1; block = dz_if_bytes2blocks(dzd, bytes); if (block < 0 || block >= dz_if_bytes2blocks(dzd, dzd->capacity)) { dz_if_zlist_clear_selection(dzd); return; } /* Search zone */ for (i = 0; i < dzd->max_nr_zones; i++) { z = &dzd->zones[i].info; if (block >= dz_if_bytes2blocks(dzd, zbd_zone_start(z)) && block < dz_if_bytes2blocks(dzd, zbd_zone_start(z) + zbd_zone_len(z))) { zno = i; break; } } dz_if_zlist_set_selection(dzd, zno); dz_if_zlist_set_view_range(dzd, 1); } static void dz_if_refresh_zlist(dz_dev_t *dzd) { char str[256]; /* Update number of zones */ snprintf(str, sizeof(str) - 1, "%s: %d zones", dzd->path, dzd->nr_zones); gtk_label_set_text(GTK_LABEL(dzd->zlist_frame_label), str); gtk_label_set_use_markup(GTK_LABEL(dzd->zlist_frame_label), TRUE); /* Update list store and refilter the view */ dz_if_zlist_fill(dzd); /* Redraw visible zone range */ dz_if_redraw_zones(dzd); } static void dz_if_update_zones(dz_dev_t *dzd) { int ret; /* Update zone information */ ret = dz_cmd_exec(dzd, DZ_CMD_REPORT_ZONES, "Getting zone information..."); if (ret) dz_if_err("Get zone information failed\n", "Error %d (%s)", ret, strerror(ret)); /* Update list */ dz_if_refresh_zlist(dzd); } static gboolean dz_if_zlist_filter_cb(GtkComboBox *button, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; GtkWidget *combo = dzd->zfilter_combo; int zone_ro = ZBD_RO_ALL; gchar *text; int i = 0; text = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(combo)); if (!text) return FALSE; while (zfilter[i].str) { if (strcmp(zfilter[i].str, text) == 0) { zone_ro = zfilter[i].ro; break; } i++; } g_free(text); if (dzd->zone_ro != zone_ro) { dzd->zone_ro = zone_ro; dzd->zlist_start_no = 0; dzd->zlist_end_no = 0; dz_if_update_zones(dzd); dz_if_zlist_clear_selection(dzd); dz_if_zlist_set_view_range(dzd, 0); } return FALSE; } static void dz_if_zlist_set_block_size_cb(GtkEntry *entry, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; char *val_str = (char *) gtk_entry_get_text(entry); int block_size = atoi(val_str); char str[32]; if (!val_str || !dzd) return; if (block_size > 0) dzd->block_size = block_size; else if (dz.block_size) dzd->block_size = dz.block_size; else dzd->block_size = dzd->info.lblock_size; snprintf(str, sizeof(str) - 1, "%d", dzd->block_size); gtk_entry_set_text(entry, str); /* Update list */ dz_if_zlist_fill(dzd); dz_if_zblock_set(dzd); } static void dz_if_zlist_set_use_hexa_cb(GtkToggleButton *togglebutton, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; int use_hexa = gtk_toggle_button_get_active(togglebutton); if (dzd->use_hexa == use_hexa) return; /* Update list */ dzd->use_hexa = use_hexa; dz_if_zlist_fill(dzd); dz_if_zblock_set(dzd); } static gboolean dz_if_zlist_refresh_cb(GtkWidget *widget, gpointer user_data) { dz_if_update_zones((dz_dev_t *) user_data); return FALSE; } static void dz_if_draw_legend(char *str, const GdkRGBA *color, cairo_t *cr, gint *x, gint h) { cairo_text_extents_t te; GdkRGBA border_color; gint w = h / 2; gdk_rgba_parse(&border_color, "Black"); gdk_cairo_set_source_rgba(cr, &border_color); cairo_set_line_width(cr, 2); cairo_rectangle(cr, *x, (h - w) / 2, w, w); cairo_stroke_preserve(cr); gdk_cairo_set_source_rgba(cr, color); cairo_fill(cr); *x += w; cairo_text_extents(cr, str, &te); cairo_move_to(cr, *x + 5 - te.x_bearing, h / 2 - te.height / 2 - te.y_bearing); cairo_show_text(cr, str); *x += te.x_advance + 20; } static gboolean dz_if_zones_draw_legend_cb(GtkWidget *widget, cairo_t *cr, gpointer data) { GtkAllocation allocation; gint h, x = 10; /* Current size */ gtk_widget_get_allocation(widget, &allocation); h = allocation.height; /* Set font */ cairo_select_font_face(cr, "Monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, 10); /* Conventional zone legend */ dz_if_draw_legend("Conventional zone", &dz.conv_color, cr, &x, h); /* Seq unwritten zone legend */ dz_if_draw_legend("Sequential zone unwritten space", &dz.seqnw_color, cr, &x, h); /* Seq written zone legend */ dz_if_draw_legend("Sequential zone written space", &dz.seqw_color, cr, &x, h); /* Non-writable space legend */ dz_if_draw_legend("Non-writable space", &dz.nonw_color, cr, &x, h); return FALSE; } #define DZ_DRAW_WOFST 5 #define DZ_DRAW_HOFST 20 static gboolean dz_if_zones_draw_cb(GtkWidget *widget, cairo_t *cr, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; GtkAllocation allocation; cairo_text_extents_t te; unsigned long long cap = 0, sz; struct zbd_zone *z; GdkRGBA color; long long w, h, x = 0, zw, ww; char str[64]; unsigned int i; /* Current visible range */ dz_if_zlist_update_range(dzd); if (!dzd->zones || !dzd->nr_zones) return FALSE; /* Current size */ gtk_widget_get_allocation(dzd->zones_da, &allocation); w = allocation.width - (DZ_DRAW_WOFST * 2); h = allocation.height; /* Get total viewed capacity */ if (dzd->zlist_end_no >= dzd->max_nr_zones) dzd->zlist_end_no = dzd->max_nr_zones - 1; for (i = dzd->zlist_start_no; i <= dzd->zlist_end_no; i++) { if (dzd->zones[i].visible) cap += zbd_zone_len(&dzd->zones[i].info); } /* Center overall drawing using x offset */ zw = 0; for (i = dzd->zlist_start_no; i <= dzd->zlist_end_no; i++) { if (dzd->zones[i].visible) zw += ((unsigned long long)w * zbd_zone_len(&dzd->zones[i].info)) / cap; } x = DZ_DRAW_WOFST + (w - zw) / 2; /* Draw zones */ for (i = dzd->zlist_start_no; i <= dzd->zlist_end_no; i++) { if (!dzd->zones[i].visible) continue; z = &dzd->zones[i].info; /* Draw zone outline */ zw = (w * zbd_zone_len(z)) / cap; gdk_rgba_parse(&color, "Black"); gdk_cairo_set_source_rgba(cr, &color); cairo_set_line_width(cr, 1); cairo_rectangle(cr, x, DZ_DRAW_HOFST, zw, h - (DZ_DRAW_HOFST * 2)); cairo_stroke_preserve(cr); if (zbd_zone_cnv(z)) gdk_cairo_set_source_rgba(cr, &dz.conv_color); else if (zbd_zone_full(z)) gdk_cairo_set_source_rgba(cr, &dz.seqw_color); else gdk_cairo_set_source_rgba(cr, &dz.seqnw_color); cairo_fill(cr); /* Non-writable space in zone */ if (zbd_zone_capacity(z) < zbd_zone_len(z)) { ww = (zw * (zbd_zone_len(z) - zbd_zone_capacity(z))) / zbd_zone_len(z); if ( ww ) { gdk_cairo_set_source_rgba(cr, &dz.nonw_color); cairo_rectangle(cr, x + zw - ww, DZ_DRAW_HOFST, ww, h - DZ_DRAW_HOFST * 2); cairo_fill(cr); } } if (!zbd_zone_cnv(z) && (zbd_zone_imp_open(z) || zbd_zone_exp_open(z) || zbd_zone_closed(z))) { /* Written space in zone */ ww = (zw * (zbd_zone_wp(z) - zbd_zone_start(z))) / zbd_zone_len(z); if ( ww ) { gdk_cairo_set_source_rgba(cr, &dz.seqw_color); cairo_rectangle(cr, x, DZ_DRAW_HOFST, ww, h - DZ_DRAW_HOFST * 2); cairo_fill(cr); } } /* Set font */ gdk_rgba_parse(&color, "Black"); gdk_cairo_set_source_rgba(cr, &color); cairo_select_font_face(cr, "Monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, 10); /* Write zone number */ sprintf(str, "%05d", dzd->zones[i].no); cairo_text_extents(cr, str, &te); cairo_move_to(cr, x + zw / 2 - te.width / 2 - te.x_bearing, DZ_DRAW_HOFST - te.height / 2); cairo_show_text(cr, str); /* Write zone size */ sz = zbd_zone_len(z); if (sz > 1024 * 1024 *1024) sprintf(str, "%llu GiB", sz / (1024 * 1024 *1024)); else sprintf(str, "%llu MiB", sz / (1024 * 1024)); cairo_set_font_size(cr, 8); cairo_text_extents(cr, str, &te); cairo_move_to(cr, x + zw / 2 - te.width / 2 - te.x_bearing, h - te.height / 2); cairo_show_text(cr, str); x += zw; } return FALSE; } static void dz_if_zone_op(dz_dev_t *dzd, enum zbd_zone_op op, char *op_name, char *msg) { char str[128]; int ret; dzd->zone_no = dzd->zlist_selection; dzd->zone_op = op; ret = dz_cmd_exec(dzd, DZ_CMD_ZONE_OP, msg); if (ret) { if (dzd->zone_no == -1) sprintf(str, "%s all zones failed\n", op_name); else sprintf(str, "%s zone %d failed\n", op_name, dzd->zone_no); dz_if_err(str, "Error %d (%s)", ret, strerror(ret)); } /* Update zone list */ dz_if_refresh_zlist(dzd); } static gboolean dz_if_zone_reset_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; char msg[128]; dz_if_zone_op(dzd, ZBD_OP_RESET, "Reset", msg); return FALSE; } static gboolean dz_if_zone_open_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; dz_if_zone_op(dzd, ZBD_OP_OPEN, "Open", NULL); return FALSE; } static gboolean dz_if_zone_close_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; dz_if_zone_op(dzd, ZBD_OP_CLOSE, "Close", NULL); return FALSE; } static gboolean dz_if_zone_finish_cb(GtkWidget *widget, gpointer user_data) { dz_dev_t *dzd = (dz_dev_t *) user_data; dz_if_zone_op(dzd, ZBD_OP_FINISH, "Finish", NULL); return FALSE; } libzbd-2.0.4/tools/gui/org.gnome.gzbd.policy.in000066400000000000000000000016301436612631500213640ustar00rootroot00000000000000 The libzbd Project https://github.com/westerndigitalcorporation/libzbd gzbd Run gzbd as root Authentication is required to run gzbd as root auth_admin auth_admin auth_admin @bindir@/gzbd true libzbd-2.0.4/tools/viewer/000077500000000000000000000000001436612631500154335ustar00rootroot00000000000000libzbd-2.0.4/tools/viewer/Makefile.am000066400000000000000000000015571436612631500174770ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-3.0-or-later # # SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. AM_LDFLAGS = -lm polkit_action_in_FILES += viewer/org.gnome.gzbd-viewer.policy.in desktop_in_FILES += viewer/gzbd-viewer.desktop.in pixmap_FILES += viewer/gzbd-viewer.png bin_PROGRAMS += gzbd-viewer gzbd_viewer_SOURCES = \ viewer/gzbd_viewer.c \ viewer/gzbd_viewer_if.c \ viewer/gzbd_viewer.h gzbd_viewer_CFLAGS = $(CFLAGS) $(GTK_CFLAGS) gzbd_viewer_LDADD = $(libzbd_ldadd) $(GTK_LIBS) dist_man8_MANS += viewer/gzbd-viewer.8 viewer/org.gnome.gzbd-viewer.policy: viewer/org.gnome.gzbd-viewer.policy.in Makefile $(bin_subst) < viewer/org.gnome.gzbd-viewer.policy.in > viewer/org.gnome.gzbd-viewer.policy viewer/gzbd-viewer.desktop: viewer/gzbd-viewer.desktop.in Makefile $(bin_subst) < viewer/gzbd-viewer.desktop.in > viewer/gzbd-viewer.desktop libzbd-2.0.4/tools/viewer/gzbd-viewer.8000066400000000000000000000044651436612631500177620ustar00rootroot00000000000000.\" SPDX-License-Identifier: GPL-3.0-or-later .\" SPDX-FileCopyrightText: 2020, Western Digital Corporation or its affiliates. .\" Written by Damien Le Moal .\" .TH GZBD-VIEWER 8 .SH NAME gzbd-viewer \- zoned block devices zone state graphical interface .SH SYNOPSIS .B gzbd-viewer [options] .I device .SH DESCRIPTION .B gzbd-viewer is used to dynamically display the state of zones of a zoned block device. Each zone is displayed as a box representing the sector range of the zone. A zone box is filled with different colors based on the zone type and on the use of sectors within the zone. The condition of zones is indicated by highlighting a zone box border with different colors. .B Zone type and usage color codes .TS tab(:); l l. Magenta:Conventional zones Red:Written sectors of a sequential zone Green:Unwritten and usable sectors of a sequential zone Rosy brown:Unusable sectors of a sequential zone .TE .B Zone condition color codes .TS tab(:); l l. Light blue:Explicitly opened zones Dark blue:Implicitly opened zones Dark orange:Closed zones Grey:Offline zones .TE .PP The .I device argument must be the pathname of the target zoned block device. .PP By default, \fBgzbd-viewer\fP will display at most 100 zones using a 10 x 10 grid. This default display size can be changed using options as explained below. .SH OPTIONS .TP .BR \-? , " \-\-help" Show help options and exit. .TP .BR \-\-help\-all Show all help options and exit. .TP .BR \-\-help\-gtk Show GTK+ options and exit. .TP .BR \-v , " \-\-verbose" Use libzbd verbose mode (for debug). .TP .BR \-i , " \-\-interval " \fImsec\fP Set refresh interval to \fImsec\fP milliseconds (default: 500). .TP .BR \-w , " \-\-width " \fIcolumns\fP Display zones in a matrix of \fIcolumns\fP columns. .TP .BR \-h , " \-\-height " \fIrows\fP Display zones in a matrix of \fIrows\fP rows. .TP .BR \-b , " \-\-block " \fIsize\fP Use \fIsize\fP as the unit for displaying a zone position, length and write pointer position instead of the default byte value. .TP .BR \-\-display=DISPLAY Specify the X display to use. .SH AUTHOR .nf Damien Le Moal .fi .SH SEE ALSO .BR zbd (8) ", " gzbd (8) .SH AVAILABILITY The gzbd-viewer utility is part of the libzbd library available from .UR https://\:github.com\:/westerndigitalcorporation\:/libzbd .UE . libzbd-2.0.4/tools/viewer/gzbd-viewer.desktop.in000066400000000000000000000004351436612631500216620ustar00rootroot00000000000000[Desktop Entry] Name=gzbd-viewer Comment=Display the zone state of a Zoned Block Device Keywords=disk;drive;harddisk;hdd;disc;smr;SMR;ssd;zns;ZNS; Exec=pkexec --disable-internal-agent "@bindir@/gzbd-viewer" Icon=gzbd-viewer Terminal=false Type=Application Categories=GNOME;GTK;System; libzbd-2.0.4/tools/viewer/gzbd-viewer.png000066400000000000000000000317601436612631500203750ustar00rootroot00000000000000PNG  IHDR>azTXtRaw profile type exifxڭu9# ބ{fshg6^s {ML斳Ol~?ڣ#{ۧ_?9~5ޛߞt۫.~ӈ׍<_?eSΪ9}:OLk*'>8Le '~.UmӸhv5]s{\tuwܾMWo~\&%B >LC]m,>MWyr|;n~ӯ蜩9f+Š|UG?$D>0W&x}`nLwqY" dfsı}0RRQB&9\SOM r(NbL1Xbz )r*z9s.YK(̥ZZ5XS͵Z[r+z硝;w#8ȣ:qgu+ʫmJiǝvev? 't)vݬru'k$ܜE>5.Np32#ErF;9eRrS`Χ{7Cy?f(u7c~%|C Th?]};y~?y5ɍ`TTW W>s`cLK֭ɡ`K"V\R+%iQt~3 CR|-JWwIPp׵ ;&0:# rX GPē ]i9$F @c+n/MQ2*= ua6-; ȭ*s@nIěFI>hV%1̌ T#@Sk(UQItY) n"$ Ci:A*͐`wd*T& /M8ЯPP BoѶ<6{a.F-atZE< C3LmDQ}@`ZӅ0_n Bcʀu5B(ys} QweSa+ "dEp5(\8`ZPw*+Da2!%{RR9R-BvGԈ0kQ:72+*y$PK-Qx TWs|0= UJ7'Csa}Y+xD1KRqmZ* j@Q 4]yl`;ChMZmPL90BM#J@N .Z #qPi[$Svy;HHP-TeI`GvM{ }K>BqRڅ_$089KBRM S&a#>{Wpg蜇4ؕZ&<2H68@Xt(4pUn^Bn "MKxD ^A?J@\XhϥuHr1ab}c_cNkrQ:P WƝ?pZk-ASc*pGL!' 8>4 S?ɎaK#=S˓!eEh= )'!D@#ڞDqqj(FvAEN`)`Q'kILym'<\A+WA a @qM}pE$u!rx}/#C =LpiV}ZJ$qF[JPF^AD{fA~BVaBdWG|95k1&O4E~+57{_qRC 8rp ЍZa|JX 1MQnēE|7LQwl'䲪{iu y8q$"xiYnYۛjWE9RI`az>ۨ11gENb "ggwKx9:5 xM?ΟhM21(n "M&;JNJ~V>j~pJ&# XpL⭳K9>{#!)?v_ .@Ľj-#JmݻCJ_bs!\VYnEtmI7$e6EfAZkV4ڧ (9l}bcI@a#}Ch[M'[O7*t4I՜R:7ۑ 4N8M ޣ@PA.pڧ wT >]uǗ<ѱfG-owv3%T<\ޚeHP:'W"G0%}ŵXRҗl7~Z; 4& )ۛ¸S`TWƧT5Ÿ63>ƽ^T_U7s^[)=AFT֋0D\SryJ2 gQ QNEgV]  Ș;z6h (p V);ut^fĄG"yGdžhw)_:u #*o&w^H\d! GB'ɠ#2⡿ [ TP#-U۾bvɁ nZ`itADчt{%9T$vEh.}{A3[f0:C%/)Bhok*&͡qnHU]{Aq5wdU':EhXN@Jt:AdiⵗV9!@"hPyOɤ"N͋O@ z &AhY-Ep] A(9G4Ҹ@c=rH->%EZA_wW%mm1!8@(1f !1'1jjpph8 l@~3&@PZ,Z*/ F~(U|;TQծWC z7ȵ0IIg|*ƙ `G`A{}GO<5%kmk-3ljWj&.z=Zh0\'N!69JmMȻQDD.98<Ϗ #?磥$Ҿ!\eoЄ>8IG(A>ii/4sXX% ",>#z+Cjwi9y#ZbΫR` ŹgWԒ 5`6.i[=k^o_%Bu=0fLmϷF:}SX}#ULcUP(X'Q$ _߇7hEW(BZ:ٮD׻E O6D &FwrqiEo*)?n>L98`3d" njoS{? lDYTF)@t2T H{,L,ԉVAv aԪֱa` Rm40TfG#` dڪoQt$xgSiODT JvMQ׻)(O_-C"mm힁&*Ӫ6_AU;ݙ\4O~'U6$H5s{&y%;Lp+..d] w#:-|j]8uvܣ@A:B x<Vg̫.HYE(Ds2_Gt0H& gJ$^8MmQ ?'"xK=5Vrl6c[QRTɓzbq\*sQݶF/mxCtT= BB6*JgQ1 u0ATSqC.u/:޸='f:Wt5A qWDo#Bg\~H2ܽ>EnFs6iVҵ] d@ke-cd;M-hx,Zٸ=Do W92QZ98sU㍿ׂWM[{@T,Z_+ndsғFEb wiA z2f1aq($KJ.jHzH0Y>vAV[.F=дi7Ӛ mZ gzAgvnأZ7A^t$hXq0|iXM_km7Q @r.Xxc !o+RڿNGx =Rv6hL2ѹ D-7+OL}n:&R;D1lxfҶ|gp(* & l2K6:^/w'곗||"rFO= ͽ\6+1|ݠ}7c7x~oŏhl}o}֋,u.3h]ywWt^#< vsz|[KHGǐ)tt,xRn<B o/ b):Shk)A+ԥE`m-kJLX\.Hu\? UxbjiCCPICC profilex}=H@_?"U;8dNVDE EjVL.& IZpc⬫ ~9)HK -b<8ǻ{w^fT2Rɮ Wу 1*1S$<=||,sn%g2'2ݰ76->q%xĠ ?r]vsa?ό|&%K!+@t G~;G8Ptz=G_M$s1.Ǔk֠pI|_vF1rqϲ{#'|x+Ѕ i$t:}U>A<2@P* ao.4ᡇWbزy rrI;1xvvd@EEeTwPLӍ_c#!-pW'ǥKP[SyI;oIP]U[csAn,a߾/w܎` mᅬw_qV% 9Pq֭{ 'O3uu6lO>zs̍[ց$IȲo hi uW?H̹|3N|؆$ *x^/nO#l4^]YZ)c֭[^7?"r%zNu6pVV?\ee>عs>3L\K.1Ɯp9rطo˱j*,YrnS,2 uCx.hH &Eф,i ԏH9P\8 Z[[#D,v\0Qϲ|Q\=!^ &`U: I;Ǽۋ 8wf3,X$T8t|>P^^윜Hm |=(//GYdU&\xwu7wB($]x- $I_:vu(*Oyox]qfJl񎢲#,h`p[q\Kݭ]`s**ٰ Ͼp{oFݨ8.@*I(&; x#VԓtzֺcEi"fƊ.H 7 tzZ^a@F;/(nwͅ*%( Ĭˋi;%7 +,epw yJ`cLY1> HzI׳Wӽ *+O,]#p"KLJ3__$sn ]:l . N`s, +Z'~P$ 4HL9Q#@Ӑ1>͖^J]}Qae99vڠЁy}ɱ8\fEx UbGGn_ Ƞo7b͎)JֻAqϻ\9K/)AY_F&-1m0M`?Bn܂g~PVMXUŁwQiIhNϏ¢X| *--|prPZZ6~`dSZ@5pca`JEU3N'TT'@87ĉ[KS6N`(BuqOꩱde[(TUU{[i%du<IbEe%Y`R\ެ7cuAfY 1AQ=X6i&I;Oе32S)xJ'9XY%\TT`- 4dlhniQePe4 fM3o;(m H_(Euhii( `1H$j 'V .B0D{{j*` .j2C 0o|x477gts 2q{0o| YFI$̚=ի̛͐L*^mg1klL9@W+W~#Ei4@Kkȏ7o*1qKPي@";;{LWDWgh 0JH 74bjÇ 1!??aLU|0DGG'X֏<̟fs|o(, ^l 91aX OQwߢ$A"+; #A#I IP]]3o=UG߇^աP]]90IюǿFooo)O(zN@%`֬[_Pmz(X&BơCa=t0jkAo??ܳԩbFVVL]|qA%zL>UUS6aON'vIvn)!HSk0eJ%ϣ4Ml6baa7(eYx}^|~шJTWO`}d H =hmm@@4 F#G?0hy2W\FSc#rB0+`05@BR$!$J%1-/  BxA AbBM#y$zPG5.?j!Tڹ9X/_F{[+ۆ=PףEE()fwO>p֮Yf{V=#!' BJD!1i="+0 *TUUAn8p]=x=`^ZG - 9#r/#2 hljѣǰxт%hQ^" 1b#ѣ82ֶf[47hǿm͙Oϋu8},^&6o "n7N>u)0ڱ)bhc $ADNhjj±`ݱCdeeaŊ{ՉV_-o| I[]hKd8" : \<$Ips =Ah !@0?aǎt'g<h`|G8x0n9>r2$ hQe<t:þ>ի͸p{}<3hEi $Iš AF{Q \1Phݽ208XnѪ;i @Č'7M—x߯UyKr_|OqqT;% RZu6 K~_9A%)YJ4y*L| LdQ4 =Sa5hРA 4hРA MENIENDB`libzbd-2.0.4/tools/viewer/gzbd_viewer.c000066400000000000000000000174531436612631500201200ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #include #include #include #include #include #include #include #include #include "gzbd_viewer.h" /* * Device control. */ struct gzv gzv; /* * Signal handling. */ static gboolean gzv_process_signal(GIOChannel *source, GIOCondition condition, gpointer user_data) { char buf[32]; ssize_t size; if (condition & G_IO_IN) { size = read(g_io_channel_unix_get_fd(source), buf, sizeof(buf)); if (size > 0) { /* Got signal */ gtk_main_quit(); return TRUE; } } return FALSE; } static void gzv_sig_handler(int sig) { /* Propagate signal through the pipe */ if (write(gzv.sig_pipe[1], &sig, sizeof(int)) < 0) printf("Signal %d processing failed\n", sig); } static void gzv_set_signal_handlers(void) { GIOChannel *sig_channel; long fd_flags; int ret; ret = pipe(gzv.sig_pipe); if (ret < 0) { perror("pipe"); exit(1); } fd_flags = fcntl(gzv.sig_pipe[1], F_GETFL); if (fd_flags < 0) { perror("Read descriptor flags"); exit(1); } ret = fcntl(gzv.sig_pipe[1], F_SETFL, fd_flags | O_NONBLOCK); if (ret < 0) { perror("Write descriptor flags"); exit(1); } /* Install the unix signal handler */ signal(SIGINT, gzv_sig_handler); signal(SIGQUIT, gzv_sig_handler); signal(SIGTERM, gzv_sig_handler); /* Convert the reading end of the pipe into a GIOChannel */ sig_channel = g_io_channel_unix_new(gzv.sig_pipe[0]); g_io_channel_set_encoding(sig_channel, NULL, NULL); g_io_channel_set_flags(sig_channel, g_io_channel_get_flags(sig_channel) | G_IO_FLAG_NONBLOCK, NULL); g_io_add_watch(sig_channel, G_IO_IN | G_IO_PRI, gzv_process_signal, NULL); } /* * Fix offset/length values to the specified block size. */ static void gzv_fix_zone_values(struct zbd_zone *zbdz, int nrz) { int i; if (gzv.block_size == 1) return; for (i = 0; i < nrz; i++) { zbdz->start /= gzv.block_size; zbdz->len /= gzv.block_size; zbdz->capacity /= gzv.block_size; if (!zbd_zone_cnv(zbdz)) zbdz->wp /= gzv.block_size; zbdz++; } } /* * Close a device. */ static void gzv_close(void) { if (gzv.dev_fd < 0) return; zbd_close(gzv.dev_fd); gzv.dev_fd = -1; free(gzv.zones); free(gzv.grid_zones); } static char *gzv_choose_dev(void) { GtkFileChooser *chooser; GtkFileFilter *filter; GtkWidget *dialog; char *path = NULL; gint res; /* File chooser */ dialog = gtk_file_chooser_dialog_new("Open Zoned Block Device", GTK_WINDOW(gzv.window), GTK_FILE_CHOOSER_ACTION_OPEN, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL); chooser = GTK_FILE_CHOOSER(dialog); gtk_file_chooser_set_current_folder(chooser, "/dev"); filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, "Block Device Files"); gtk_file_filter_add_mime_type(filter, "inode/blockdevice"); gtk_file_chooser_add_filter(chooser, filter); res = gtk_dialog_run(GTK_DIALOG(dialog)); if (res == GTK_RESPONSE_ACCEPT) path = gtk_file_chooser_get_filename(chooser); gtk_widget_destroy(dialog); return path; } /* * Open a device. */ static int gzv_open(void) { unsigned int i; int ret; /* Open device file */ gzv.dev_fd = zbd_open(gzv.path, O_RDONLY, &gzv.info); if (gzv.dev_fd < 0) return -1; if (gzv.block_size > 1 && gzv.info.zone_size % gzv.block_size) { fprintf(stderr, "Invalid block size\n"); return 1; } /* Get list of all zones */ ret = zbd_list_zones(gzv.dev_fd, 0, 0, ZBD_RO_ALL, &gzv.zones, &gzv.nr_zones); if (ret != 0) goto out; if (!gzv.nr_zones) { fprintf(stderr, "No zones reported\n"); ret = 1; goto out; } gzv_fix_zone_values(gzv.zones, gzv.nr_zones); for (i = 0; i < gzv.nr_zones; i++) { if (zbd_zone_cnv(&gzv.zones[i])) gzv.nr_conv_zones++; } /* Set defaults */ if (!gzv.nr_col && !gzv.nr_row && gzv.nr_zones < 100) { gzv.nr_col = sqrt(gzv.nr_zones); gzv.nr_row = (gzv.nr_zones + gzv.nr_col - 1) / gzv.nr_col; } else { if (!gzv.nr_col) gzv.nr_col = 10; if (!gzv.nr_row) gzv.nr_row = 10; } gzv.max_row = (gzv.nr_zones + gzv.nr_col - 1) / gzv.nr_col; /* Allocate zone array */ gzv.nr_grid_zones = gzv.nr_col * gzv.nr_row; gzv.grid_zones = calloc(gzv.nr_grid_zones, sizeof(struct gzv_zone)); if (!gzv.grid_zones) { ret = -ENOMEM; goto out; } for (i = 0; i < gzv.nr_grid_zones && i < gzv.nr_zones; i++) { gzv.grid_zones[i].zno = i; gzv.grid_zones[i].zbdz = &gzv.zones[i]; } out: if (ret) gzv_close(); return ret; } int main(int argc, char **argv) { gboolean init_ret; gboolean verbose = FALSE; GError *error = NULL; int ret = 0; GOptionEntry options[] = { { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Set libzbd verbose mode", NULL }, { "interval", 'i', 0, G_OPTION_ARG_INT, &gzv.refresh_interval, "Refresh interval (milliseconds)", NULL }, { "width", 'w', 0, G_OPTION_ARG_INT, &gzv.nr_col, "Number of zones per row (default: 10)", NULL }, { "height", 'h', 0, G_OPTION_ARG_INT, &gzv.nr_row, "Number of rows (default: 10)", NULL }, { "block", 'b', 0, G_OPTION_ARG_INT, &gzv.block_size, "Use block bytes as the unit for displaying zone " "position, length and write pointer position instead " "of the default byte value", NULL }, { NULL } }; /* Init */ memset(&gzv, 0, sizeof(gzv)); gzv.dev_fd = -1; gzv.block_size = 1; init_ret = gtk_init_with_args(&argc, &argv, "", options, NULL, &error); if (init_ret == FALSE || error != NULL) { printf("Failed to parse command line arguments: %s\n", error->message); g_error_free(error); return 1; } if (gzv.refresh_interval < 0) { fprintf(stderr, "Invalid update interval\n"); return 1; } if (gzv.block_size <= 0) { fprintf(stderr, "Invalid block size\n"); return 1; } if (verbose) zbd_set_log_level(ZBD_LOG_DEBUG); /* Set default values and open the device */ if (!gzv.refresh_interval) gzv.refresh_interval = 500; /* Create the main window */ gzv_if_create_window(); /* Check user credentials */ if (getuid() != 0) { gzv_if_err("Root privileges are required for running gzbd-viewer", "Opening a block device file can only be done with " "elevated priviledges"); ret = 1; goto out; } if (argc < 2) { /* No device specified: use the file chooser */ gzv.path = gzv_choose_dev(); if (!gzv.path) { gzv_if_err("No device specified", "Specifying a zoned block device is mandatory"); fprintf(stderr, "No device specified\n"); ret = 1; goto out; } } else { gzv.path = argv[1]; } if (gzv_open()) { ret = errno; gzv_if_err("Open device failed", "Opening %s generated error %d (%s)", gzv.path, ret, strerror(ret)); fprintf(stderr, "Open device %s failed %d (%s)\n", gzv.path, ret, strerror(ret)); ret = 1; goto out; } gzv_set_signal_handlers(); /* Create GUI */ gzv_if_create(); /* Main event loop */ gtk_main(); out: /* Cleanup GUI */ gzv_if_destroy(); return ret; } /* * Report zones. */ int gzv_report_zones(unsigned int zno_start, unsigned int nr_zones) { unsigned int nrz; int ret; if (zno_start >= gzv.nr_zones) return 0; nrz = nr_zones; if (zno_start + nrz > gzv.nr_zones) nrz = gzv.nr_zones - zno_start; /* Get zone information */ ret = zbd_report_zones(gzv.dev_fd, zbd_zone_start(&gzv.zones[zno_start]), nrz * gzv.info.zone_size, ZBD_RO_ALL, &gzv.zones[zno_start], &nrz); if (ret) { fprintf(stderr, "Get zone information failed %d (%s)\n", errno, strerror(errno)); return ret; } gzv_fix_zone_values(&gzv.zones[zno_start], nrz); return 0; } libzbd-2.0.4/tools/viewer/gzbd_viewer.h000066400000000000000000000034001436612631500201100ustar00rootroot00000000000000/* SPDX-License-Identifier: GPL-3.0-or-later */ /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #ifndef __GZVIEWER_H__ #define __GZVIEWER_H__ #include #include #include /* * Device zone information. */ struct gzv_zone { unsigned int zno; struct zbd_zone *zbdz; GtkWidget *da; }; /* * GUI data. */ struct gzv { /* * Parameters. */ int refresh_interval; int block_size; int abort; /* * For handling timer and signals. */ GSource *refresh_timer; unsigned long long last_refresh; int sig_pipe[2]; /* * Interface stuff. */ GdkRGBA color_conv; GdkRGBA color_seq; GdkRGBA color_seqw; GdkRGBA color_nonw; GdkRGBA color_text; GdkRGBA color_oi; GdkRGBA color_oe; GdkRGBA color_cl; GdkRGBA color_of; GtkWidget *window; GtkAdjustment *vadj; /* * Device information. */ char *path; int dev_fd; struct zbd_info info; unsigned int nr_zones; unsigned int nr_conv_zones; struct zbd_zone *zones; /* * Drawn zones. */ unsigned int nr_row; unsigned int nr_col; unsigned int nr_grid_zones; unsigned int max_row; struct gzv_zone *grid_zones; unsigned int grid_zno_first; }; /** * System time in usecs. */ static inline unsigned long long gzv_msec(void) { struct timeval tv; gettimeofday(&tv, NULL); return (unsigned long long) tv.tv_sec * 1000LL + (unsigned long long) tv.tv_usec / 1000; } extern struct gzv gzv; int gzv_report_zones(unsigned int zno_start, unsigned int nr_zones); void gzv_if_err(const char *msg, const char *fmt, ...); void gzv_if_create_window(void); void gzv_if_create(void); void gzv_if_destroy(void); #endif /* __GZWATCH_H__ */ libzbd-2.0.4/tools/viewer/gzbd_viewer_if.c000066400000000000000000000350271436612631500205730ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * SPDX-FileCopyrightText: 2020 Western Digital Corporation or its affiliates. * * Authors: Damien Le Moal (damien.lemoal@wdc.com) */ #include #include #include #include #include "gzbd_viewer.h" static void gzv_set_zone_tooltip(struct gzv_zone *zone) { struct zbd_zone *zbdz = zone->zbdz; char info[512]; char bs[64]; if (!zbdz) { gtk_widget_set_has_tooltip(GTK_WIDGET(zone->da), false); gtk_widget_set_tooltip_markup(GTK_WIDGET(zone->da), NULL); return; } if (gzv.block_size == 1) snprintf(bs, sizeof(bs) - 1, "B"); else snprintf(bs, sizeof(bs) - 1, "%d-B blocks", gzv.block_size); if (zbd_zone_cnv(zbdz)) { snprintf(info, sizeof(info) - 1, "Zone %u:\n" " - Type: %s\n" " - Condition: %s\n" " - Start offset: %llu %s\n" " - Length: %llu %s\n" " - Capacity: %llu %s", zone->zno, zbd_zone_type_str(zbdz, false), zbd_zone_cond_str(zbdz, false), zbd_zone_start(zbdz), bs, zbd_zone_len(zbdz), bs, zbd_zone_capacity(zbdz), bs); } else { snprintf(info, sizeof(info) - 1, "Zone %u:\n" " - Type: %s\n" " - Condition: %s\n" " - Start offset: %llu %s\n" " - Length: %llu %s\n" " - Capacity: %llu %s\n" " - WP offset: +%llu %s", zone->zno, zbd_zone_type_str(zbdz, false), zbd_zone_cond_str(zbdz, false), zbd_zone_start(zbdz), bs, zbd_zone_len(zbdz), bs, zbd_zone_capacity(zbdz), bs, zbd_zone_wp(zbdz) - zbd_zone_start(zbdz), bs); } gtk_widget_set_tooltip_markup(GTK_WIDGET(zone->da), info); gtk_widget_set_has_tooltip(GTK_WIDGET(zone->da), true); } static void gzv_if_update(void) { struct zbd_zone *zbdz; unsigned int i, z; if (gzv.grid_zno_first >= gzv.nr_zones) gzv.grid_zno_first = gzv.nr_zones / gzv.nr_col; if (gzv_report_zones(gzv.grid_zno_first, gzv.nr_grid_zones)) goto out; z = gzv.grid_zno_first; for (i = 0; i < gzv.nr_grid_zones; i++) { gzv.grid_zones[i].zno = z; zbdz = gzv.grid_zones[i].zbdz; if (z >= gzv.nr_zones) { if (zbdz) gtk_widget_hide(gzv.grid_zones[i].da); gzv.grid_zones[i].zbdz = NULL; } else { gzv.grid_zones[i].zbdz = &gzv.zones[z]; if (!zbdz) gtk_widget_show(gzv.grid_zones[i].da); } gzv_set_zone_tooltip(&gzv.grid_zones[i]); gtk_widget_queue_draw(gzv.grid_zones[i].da); z++; } out: gzv.last_refresh = gzv_msec(); } static gboolean gzv_if_timer_cb(gpointer user_data) { if (gzv.last_refresh + gzv.refresh_interval <= gzv_msec()) gzv_if_update(); return TRUE; } static gboolean gzv_if_resize_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) { gzv_if_update(); return FALSE; } static void gzv_if_delete_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) { gzv.window = NULL; gtk_main_quit(); } static void gzv_if_zone_draw_nonwritable(struct zbd_zone *zbdz, cairo_t *cr, GtkAllocation *allocation) { long long w; if (zbd_zone_capacity(zbdz) == zbd_zone_len(zbdz)) return; /* Non-writable space in zone */ w = (long long)allocation->width * (zbd_zone_len(zbdz) - zbd_zone_capacity(zbdz)) / zbd_zone_len(zbdz); if (w > allocation->width) w = allocation->width; gdk_cairo_set_source_rgba(cr, &gzv.color_nonw); cairo_rectangle(cr, allocation->width - w, 0, w, allocation->height); cairo_fill(cr); } static void gzv_if_zone_draw_written(struct zbd_zone *zbdz, cairo_t *cr, GtkAllocation *allocation) { long long w; if (zbd_zone_wp(zbdz) == zbd_zone_start(zbdz)) return; /* Written space in zone */ w = (long long)allocation->width * (zbd_zone_wp(zbdz) - zbd_zone_start(zbdz)) / zbd_zone_len(zbdz); if (w > allocation->width) w = allocation->width; gdk_cairo_set_source_rgba(cr, &gzv.color_seqw); cairo_rectangle(cr, 0, 0, w, allocation->height); cairo_fill(cr); } static void gzv_if_zone_draw_num(struct gzv_zone *zone, cairo_t *cr, GtkAllocation *allocation) { cairo_text_extents_t te; char str[16]; /* Draw zone number */ gdk_cairo_set_source_rgba(cr, &gzv.color_text); cairo_select_font_face(cr, "Monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, 10); sprintf(str, "%05d", zone->zno); cairo_text_extents(cr, str, &te); cairo_move_to(cr, allocation->width / 2 - te.width / 2 - te.x_bearing, (allocation->height + te.height) / 2); cairo_show_text(cr, str); } static gboolean gzv_if_zone_draw_cb(GtkWidget *widget, cairo_t *cr, gpointer user_data) { struct gzv_zone *zone = user_data; struct zbd_zone *zbdz = zone->zbdz; GtkAllocation allocation; /* Current size */ gtk_widget_get_allocation(zone->da, &allocation); gtk_render_background(gtk_widget_get_style_context(widget), cr, 0, 0, allocation.width, allocation.height); if (!zbdz) return TRUE; /* Draw zone background */ if (zbd_zone_cnv(zbdz)) { gdk_cairo_set_source_rgba(cr, &gzv.color_conv); goto out_fill; } if (zbd_zone_full(zbdz)) { gdk_cairo_set_source_rgba(cr, &gzv.color_seqw); goto out_fill; } if (zbd_zone_offline(zbdz)) { gdk_cairo_set_source_rgba(cr, &gzv.color_of); goto out_fill; } gdk_cairo_set_source_rgba(cr, &gzv.color_seq); if (zbd_zone_empty(zbdz)) goto out_fill; /* Opened or closed zones */ cairo_rectangle(cr, 0, 0, allocation.width, allocation.height); cairo_fill(cr); gzv_if_zone_draw_nonwritable(zbdz, cr, &allocation); gzv_if_zone_draw_written(zbdz, cr, &allocation); /* State highlight */ if (zbd_zone_imp_open(zbdz)) gdk_cairo_set_source_rgba(cr, &gzv.color_oi); else if (zbd_zone_exp_open(zbdz)) gdk_cairo_set_source_rgba(cr, &gzv.color_oe); else gdk_cairo_set_source_rgba(cr, &gzv.color_cl); cairo_set_line_width(cr, 10); cairo_rectangle(cr, 0, 0, allocation.width, allocation.height); cairo_stroke(cr); /* Draw zone number */ gzv_if_zone_draw_num(zone, cr, &allocation); return TRUE; out_fill: cairo_rectangle(cr, 0, 0, allocation.width, allocation.height); cairo_fill(cr); gzv_if_zone_draw_nonwritable(zbdz, cr, &allocation); /* Draw zone number */ gzv_if_zone_draw_num(zone, cr, &allocation); return TRUE; } static gboolean gzv_if_scroll_cb(GtkWidget *widget, GdkEventScroll *scroll, gpointer user_data) { unsigned int row = gtk_adjustment_get_value(gzv.vadj); unsigned int new_row = row; switch (scroll->direction) { case GDK_SCROLL_UP: if (row > 0) new_row = row - 1; break; case GDK_SCROLL_DOWN: if (row < gzv.max_row) new_row = row + 1; break; case GDK_SCROLL_LEFT: case GDK_SCROLL_RIGHT: case GDK_SCROLL_SMOOTH: default: break; } if (new_row != row) gtk_adjustment_set_value(gzv.vadj, new_row); return TRUE; } static gboolean gzv_if_scroll_value_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) { unsigned int zno, row = gtk_adjustment_get_value(gzv.vadj); if (row >= gzv.max_row) row = gzv.max_row - 1; zno = row * gzv.nr_col; if (zno != gzv.grid_zno_first) { gzv.grid_zno_first = zno; gzv_if_update(); } return TRUE; } static void gzv_if_draw_legend(char *str, const GdkRGBA *color, cairo_t *cr, gint *x, gint y) { cairo_text_extents_t te; GdkRGBA border_color; gint w = 10; gdk_rgba_parse(&border_color, "Black"); gdk_cairo_set_source_rgba(cr, &border_color); cairo_set_line_width(cr, 2); cairo_rectangle(cr, *x, y - w / 2, w, w); cairo_stroke_preserve(cr); gdk_cairo_set_source_rgba(cr, color); cairo_fill(cr); *x += w; cairo_text_extents(cr, str, &te); cairo_move_to(cr, *x + 5 - te.x_bearing, y - te.height / 2 - te.y_bearing); cairo_show_text(cr, str); *x += te.x_advance + 20; } static gboolean gzv_if_draw_legend_cb(GtkWidget *widget, cairo_t *cr, gpointer data) { gint x = 10, y = 10; /* Set font */ cairo_select_font_face(cr, "Monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, 10); /* Conv zone legend */ gzv_if_draw_legend("Conventional zone", &gzv.color_conv, cr, &x, y); /* Seq zone legend */ gzv_if_draw_legend("Sequential zone (unwritten)", &gzv.color_seq, cr, &x, y); /* Seq written zone legend */ gzv_if_draw_legend("Sequential zone (written)", &gzv.color_seqw, cr, &x, y); /* Non-writable space legend */ gzv_if_draw_legend("Non-writable space", &gzv.color_nonw, cr, &x, y); /* Second row */ x = 10; y += 20; /* Offline zone legend */ gzv_if_draw_legend("Offline zone", &gzv.color_of, cr, &x, y); /* Implicit open zone legend */ gzv_if_draw_legend("Implicitly opened zone", &gzv.color_oi, cr, &x, y); /* Explicit open zone legend */ gzv_if_draw_legend("Explicitly opened zone", &gzv.color_oe, cr, &x, y); /* Closed open zone legend */ gzv_if_draw_legend("Closed zone", &gzv.color_cl, cr, &x, y); return FALSE; } static void gzv_if_get_da_size(unsigned int *w, unsigned int *h) { GdkDisplay *disp = gdk_display_get_default(); GdkMonitor *mon = gdk_display_get_primary_monitor(disp); GdkRectangle geom; gdk_monitor_get_geometry(mon, &geom); *w = (geom.width - 200) / gzv.nr_col; if (*w > 150) *w = 150; *h = (geom.height - 200) / gzv.nr_row; if (*h > 60) *h = 60; } void gzv_if_create_window(void) { if (gzv.window) return; gzv.window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(gzv.window), "Zoned Block Device Zone State"); gtk_container_set_border_width(GTK_CONTAINER(gzv.window), 10); g_signal_connect((gpointer) gzv.window, "delete-event", G_CALLBACK(gzv_if_delete_cb), NULL); } void gzv_if_err(const char *msg, const char *fmt, ...) { GtkWidget *dialog; dialog = gtk_message_dialog_new(GTK_WINDOW(gzv.window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", msg); if (fmt) { va_list args; char secondary[256]; va_start(args, fmt); vsnprintf(secondary, 255, fmt, args); va_end(args); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG(dialog), "%s", secondary); } gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } void gzv_if_create(void) { GtkWidget *top_vbox, *vbox, *frame, *hbox, *scrollbar, *grid, *da; GtkAdjustment *vadj; struct gzv_zone *zone; unsigned int r, c, z = 0; unsigned int da_w, da_h; char str[128]; /* Get colors */ gdk_rgba_parse(&gzv.color_conv, "Magenta"); /* Conv zones */ gdk_rgba_parse(&gzv.color_seq, "Green"); /* Seq zones */ gdk_rgba_parse(&gzv.color_seqw, "Red"); /* Seq written/full */ gdk_rgba_parse(&gzv.color_nonw, "RosyBrown"); /* Non-writable */ gdk_rgba_parse(&gzv.color_text, "Black"); gdk_rgba_parse(&gzv.color_oe, "Blue"); /* Exp open zones */ gdk_rgba_parse(&gzv.color_oi, "DeepSkyBlue"); /* Imp open zones */ gdk_rgba_parse(&gzv.color_cl, "DarkOrange"); /* Closed zones */ gdk_rgba_parse(&gzv.color_of, "Grey"); /* Offline zones */ /* Top vbox */ top_vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); gtk_widget_show(top_vbox); gtk_container_add(GTK_CONTAINER(gzv.window), top_vbox); /* Create a top frame */ if (!gzv.nr_conv_zones) snprintf(str, sizeof(str) - 1, "%s: %u sequential zones", gzv.path, gzv.nr_zones); else snprintf(str, sizeof(str) - 1, "%s: %u zones (%u conventional + %u sequential)", gzv.path, gzv.nr_zones, gzv.nr_conv_zones, gzv.nr_zones - gzv.nr_conv_zones); frame = gtk_frame_new(str); gtk_box_pack_start(GTK_BOX(top_vbox), frame, TRUE, TRUE, 0); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); gtk_label_set_use_markup(GTK_LABEL(gtk_frame_get_label_widget(GTK_FRAME(frame))), TRUE); gtk_frame_set_label_align(GTK_FRAME(frame), 0.05, 0.5); gtk_widget_show(frame); /* hbox for grid and scrollbar */ hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); gtk_widget_show(hbox); gtk_container_set_border_width(GTK_CONTAINER(hbox), 10); gtk_container_add(GTK_CONTAINER(frame), hbox); /* Add a grid */ grid = gtk_grid_new(); gtk_container_set_border_width(GTK_CONTAINER(grid), 10); gtk_grid_set_row_homogeneous(GTK_GRID(grid), true); gtk_grid_set_row_spacing(GTK_GRID(grid), 2); gtk_grid_set_column_homogeneous(GTK_GRID(grid), true); gtk_grid_set_column_spacing(GTK_GRID(grid), 2); gtk_box_pack_start(GTK_BOX(hbox), grid, TRUE, TRUE, 0); gtk_widget_show(grid); gzv_if_get_da_size(&da_w, &da_h); for (r = 0; r < gzv.nr_row; r++) { for (c = 0; c < gzv.nr_col; c++) { zone = &gzv.grid_zones[z]; da = gtk_drawing_area_new(); gtk_widget_set_size_request(da, da_w, da_h); gtk_widget_set_hexpand(da, TRUE); gtk_widget_set_halign(da, GTK_ALIGN_FILL); gtk_widget_show(da); zone->da = da; gtk_grid_attach(GTK_GRID(grid), da, c, r, 1, 1); g_signal_connect(da, "draw", G_CALLBACK(gzv_if_zone_draw_cb), zone); z++; } } /* Add scrollbar */ vadj = gtk_adjustment_new(0, 0, gzv.max_row, 1, 1, gzv.nr_row); gzv.vadj = vadj; g_signal_connect(vadj, "value-changed", G_CALLBACK(gzv_if_scroll_value_cb), NULL); scrollbar = gtk_scrollbar_new(GTK_ORIENTATION_VERTICAL, vadj); gtk_widget_show(scrollbar); gtk_box_pack_start(GTK_BOX(hbox), scrollbar, FALSE, FALSE, 0); gtk_widget_add_events(scrollbar, GDK_SCROLL_MASK); gtk_widget_add_events(gzv.window, GDK_SCROLL_MASK); g_signal_connect(gzv.window, "scroll-event", G_CALLBACK(gzv_if_scroll_cb), NULL); /* Legend frame */ frame = gtk_frame_new("Legend"); gtk_box_pack_start(GTK_BOX(top_vbox), frame, FALSE, TRUE, 0); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); gtk_label_set_use_markup(GTK_LABEL(gtk_frame_get_label_widget(GTK_FRAME(frame))), TRUE); gtk_frame_set_label_align(GTK_FRAME(frame), 0.05, 0.5); gtk_widget_show(frame); vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); gtk_container_set_border_width(GTK_CONTAINER(vbox), 10); gtk_container_add(GTK_CONTAINER(frame), vbox); gtk_widget_show(vbox); da = gtk_drawing_area_new(); gtk_widget_set_size_request(da, -1, 40); gtk_widget_show(da); gtk_container_add(GTK_CONTAINER(vbox), da); g_signal_connect((gpointer) da, "draw", G_CALLBACK(gzv_if_draw_legend_cb), NULL); /* Finish setup */ g_signal_connect(gzv.window, "configure-event", G_CALLBACK(gzv_if_resize_cb), NULL); /* Add timer for automatic refresh */ gzv.refresh_timer = g_timeout_source_new(gzv.refresh_interval); g_source_set_name(gzv.refresh_timer, "refresh-timer"); g_source_set_can_recurse(gzv.refresh_timer, FALSE); g_source_set_callback(gzv.refresh_timer, gzv_if_timer_cb, NULL, NULL); gzv.last_refresh = gzv_msec(); g_source_attach(gzv.refresh_timer, NULL); gtk_widget_show_all(gzv.window); gzv_if_update(); } void gzv_if_destroy(void) { if (gzv.refresh_timer) { g_source_destroy(gzv.refresh_timer); gzv.refresh_timer = NULL; } if (gzv.window) { gtk_widget_destroy(gzv.window); gzv.window = NULL; } } libzbd-2.0.4/tools/viewer/org.gnome.gzbd-viewer.policy.in000066400000000000000000000016731436612631500234070ustar00rootroot00000000000000 The libzbd Project https://github.com/westerndigitalcorporation/libzbd gzbd-viewer Run gzbd-viewer as root Authentication is required to run gzbd-viewer as root auth_admin auth_admin auth_admin @bindir@/gzbd-viewer true