pax_global_header00006660000000000000000000000064126363151770014525gustar00rootroot0000000000000052 comment=0079634a08dec2f049a636f0045e4b6a3846ae2b f3-6.0/000077500000000000000000000000001263631517700117025ustar00rootroot00000000000000f3-6.0/.gitignore000066400000000000000000000000351263631517700136700ustar00rootroot00000000000000cscope.out *.swp *.d *.o *~ f3-6.0/LICENSE000066400000000000000000001045131263631517700127130ustar00rootroot00000000000000 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 . f3-6.0/Makefile000066400000000000000000000020331263631517700133400ustar00rootroot00000000000000CC ?= gcc CFLAGS += -std=c99 -Wall -Wextra -pedantic -MMD -ggdb TARGETS = f3write f3read EXPERIMENTAL_TARGETS = f3probe f3brew f3fix PREFIX = /usr/local INSTALL = install LN = ln all: $(TARGETS) experimental: $(EXPERIMENTAL_TARGETS) install: all $(INSTALL) -d $(PREFIX)/bin $(INSTALL) -oroot -groot -m755 $(TARGETS) $(PREFIX)/bin $(INSTALL) -d $(PREFIX)/share/man/man1 $(INSTALL) -oroot -groot -m644 f3read.1 $(PREFIX)/share/man/man1 $(LN) -sf f3read.1 $(PREFIX)/share/man/man1/f3write.1 install-experimental: experimental $(INSTALL) -d $(PREFIX)/bin $(INSTALL) -oroot -groot -m755 $(EXPERIMENTAL_TARGETS) $(PREFIX)/bin f3write: utils.o f3write.o $(CC) -o $@ $^ -lm f3read: utils.o f3read.o $(CC) -o $@ $^ f3probe: libutils.o libdevs.o libprobe.o f3probe.o $(CC) -o $@ $^ -lm -ludev f3brew: libutils.o libdevs.o f3brew.o $(CC) -o $@ $^ -lm -ludev f3fix: libutils.o f3fix.o $(CC) -o $@ $^ -lparted -include *.d PHONY: cscope clean cscope: cscope -b *.c *.h clean: rm -f *.o *.d cscope.out $(TARGETS) $(EXPERIMENTAL_TARGETS) f3-6.0/README.md000066400000000000000000000047321263631517700131670ustar00rootroot00000000000000## Compile stable software on Linux, Apple Mac, Windows/Cygwin, and FreeBSD ``` make ``` ## Compile experimental applications on Linux ### Install dependencies - f3probe and f3brew require version 1 of the library libudev to compile. On Ubuntu, you can install this library with the following command: ``` sudo apt-get install libudev1 libudev-dev ``` - f3fix requires version 0 of the library libparted to compile. On Ubuntu, you can install this library with the following command: ``` sudo apt-get install libparted0-dev ``` ### Compile experimental applications ``` make experimental ``` NOTES: - Experimental software might compile on non-Linux platforms, but there is no guarantee given that they are only tested on Linux. - Please do not e-mail me saying that you want an experimental software to run on your platform; I already know that. - If you want experimental software to run on your platform, help to port them, or find someone that can port them for you. If you do port the software, please send me a patch to help others. - Currently, f3probe, f3brew, and f3fix are experimental. ## Use example of f3write/f3read ``` $ ./f3write /media/michel/5EBD-5C80/ $ ./f3read /media/michel/5EBD-5C80/ ``` Please replace "/media/michel/5EBD-5C80/" with the appropriate path. USB devices are mounted in "/Volumes" on Macs. For more information see http://oss.digirati.com.br/f3/ ## Files changelog - Change log for package maintainers f3read.1 - Man page for f3read and f3write In order to read this manual page, run `man ./f3read.1` To install the page, run `install --owner=root --group=root --mode=644 f3read.1 /usr/share/man/man1` LICENSE - License (GPLv3) Makefile - make(1) file README - This file *.h and *.c - C code of F3 ### Bash scripts Although the simple scripts listed in this section are ready for use, they are really meant to help you to write your own scripts. So you can personalize F3 to your specific needs. f3write.h2w - Script to create files exactly like H2testw. Use example: `f3write.h2w /media/michel/5EBD-5C80/` log-f3wr - Script that runs f3write and f3read, and records their output into a log file. Use example: `log-f3wr log-filename /media/michel/5EBD-5C80/` Please notice that all scripts and use examples above assume that f3write, f3read, and the scripts are in the same folder. f3-6.0/changelog000066400000000000000000000037361263631517700135650ustar00rootroot00000000000000Version 6.0 - Dec 24, 2015 * f3probe: new algorithm. * f3fix: deal with sectors whose sizes are not 512B. * add f3brew (experimental). Version 5.0 - Dec 24, 2014 * add f3probe (experimental). * add f3fix (experimental). * fix building issue on Macs. Version 4.0 - Sep 9, 2014 * add support for FreeBSD. * add optional parameter --end-at=NUM to F3. * add scripts f3write.h2w and log-f3wr. * unify Makefile. Version 3.0 - May 14, 2014 * fix bug first reported by John Lussmyer. * add support for Windows/Cygwin. * add a change log (this) and a man page. * adopt h2testw's file format. Version 2.2 - Feb 8, 2013 * add optional parameter --start-at=NUM to F3. * remove arbitrary limit on filenames. * fix bug first reported by Martin Theiss. * minor code refinements. Version 2.1 - Mar 7, 2012 * report version and copyright in help message. * made f3write remove old F3 files in order. * refined flow control algorithm of f3write. * verify that "all" F3 files are present. * added a rough approximation of posix_fadvise for Macs. Version 2.0 - Dec 20, 2011 * added a very simple Makefile. * reviewed code. * added support for Macs. * f3write now reports proper progress. * added progress printout in f3read. * improved precision of speed measurements. * formated code following Linux's coding style. Version 1.1.3 - Sep 21, 2010 * fixes some warning issued by GCC when compiling f3read.c on 64bits machines. Nicolai Abruzzese was the first one to report this issue. Version 1.1.2 - Aug 31, 2010 * handles an I/O error reported by Misha Aizatulin. Version 1.1.1 - Aug 16, 2010 * fixes some warnings issued by gcc when the parameter -Wall is used to compile the source. Version 1.1 - Aug 10, 2010 * adds a nice report at the end of the output of f3read. * works fine with large memory cards. Version 1.0 - Aug 02, 2010 * Initial release. f3-6.0/f3brew.c000066400000000000000000000272331263631517700132450ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include "version.h" #include "libutils.h" #include "libdevs.h" /* Argp's global variables. */ const char *argp_program_version = "F3 BREW " F3_STR_VERSION; /* Arguments. */ static char adoc[] = ""; static char doc[] = "F3 Block REad and Write -- assess the media of " "a block device writing blocks, resetting the drive, and " "reading the blocks back"; static struct argp_option options[] = { {"debug", 'd', NULL, OPTION_HIDDEN, "Enable debugging; only needed if none --debug-* option used", 1}, {"debug-real-size", 'r', "SIZE_BYTE", OPTION_HIDDEN, "Real size of the emulated drive", 0}, {"debug-fake-size", 'f', "SIZE_BYTE", OPTION_HIDDEN, "Fake size of the emulated drive", 0}, {"debug-wrap", 'w', "N", OPTION_HIDDEN, "Wrap parameter of the emulated drive", 0}, {"debug-block-order", 'b', "ORDER", OPTION_HIDDEN, "Block size of the emulated drive is 2^ORDER Bytes", 0}, {"debug-cache-order", 'c', "ORDER", OPTION_HIDDEN, "Cache size of the emulated drive is 2^ORDER blocks", 0}, {"debug-strict-cache", 'o', NULL, OPTION_HIDDEN, "Force the cache to be strict", 0}, {"debug-keep-file", 'k', NULL, OPTION_HIDDEN, "Don't remove file used for emulating the drive", 0}, {"reset-type", 's', "TYPE", 0, "Reset method to use during the probe", 2}, {"start-at", 'h', "BLOCK", 0, "Where test begins; the default is block zero", 0}, {"end-at", 'e', "BLOCK", 0, "Where test ends; the default is the very last block", 0}, {"do-not-write", 'W', NULL, 0, "Do not write blocks", 0}, {"do-not-read", 'R', NULL, 0, "Do not read blocks", 0}, { 0 } }; struct args { char *filename; /* Debugging options. */ bool debug; bool keep_file; /* Behavior options. */ enum reset_type reset_type; bool test_write; bool test_read; /* 3 free bytes. */ /* Geometry. */ uint64_t real_size_byte; uint64_t fake_size_byte; int wrap; int block_order; int cache_order; int strict_cache; /* What to do. */ uint64_t first_block; uint64_t last_block; }; static error_t parse_opt(int key, char *arg, struct argp_state *state) { struct args *args = state->input; long long ll; switch (key) { case 'd': args->debug = true; break; case 'r': ll = arg_to_ll_bytes(state, arg); if (ll < 0) argp_error(state, "Real size must be greater or equal to zero"); args->real_size_byte = ll; args->debug = true; break; case 'f': ll = arg_to_ll_bytes(state, arg); if (ll < 0) argp_error(state, "Fake size must be greater or equal to zero"); args->fake_size_byte = ll; args->debug = true; break; case 'w': ll = arg_to_ll_bytes(state, arg); if (ll < 0 || ll >= 64) argp_error(state, "Wrap must be in the interval [0, 63]"); args->wrap = ll; args->debug = true; break; case 'b': ll = arg_to_ll_bytes(state, arg); if (ll != 0 && (ll < 9 || ll > 20)) argp_error(state, "Block order must be in the interval [9, 20] or be zero"); args->block_order = ll; args->debug = true; break; case 'c': ll = arg_to_ll_bytes(state, arg); if (ll < -1 || ll > 64) argp_error(state, "Cache order must be in the interval [-1, 64]"); args->cache_order = ll; args->debug = true; break; case 'o': args->strict_cache = true; args->debug = true; break; case 'k': args->keep_file = true; args->debug = true; break; case 's': ll = arg_to_ll_bytes(state, arg); if (ll < 0 || ll >= RT_MAX) argp_error(state, "Reset type must be in the interval [0, %i]", RT_MAX - 1); args->reset_type = ll; break; case 'h': ll = arg_to_ll_bytes(state, arg); if (ll < 0) argp_error(state, "The first block must be greater or equal to zero"); args->first_block = ll; break; case 'e': ll = arg_to_ll_bytes(state, arg); if (ll < 0) argp_error(state, "The last block must be greater or equal to zero"); args->last_block = ll; break; case 'W': args->test_write = false; break; case 'R': args->test_read = false; break; case ARGP_KEY_INIT: args->filename = NULL; break; case ARGP_KEY_ARG: if (args->filename) argp_error(state, "Wrong number of arguments; only one is allowed"); args->filename = arg; break; case ARGP_KEY_END: if (!args->filename) argp_error(state, "The disk device was not specified"); if (args->debug && !dev_param_valid(args->real_size_byte, args->fake_size_byte, args->wrap, args->block_order)) argp_error(state, "The debugging parameters are not valid"); if (args->first_block > args->last_block) argp_error(state, "The first block parameter must be less or equal to the last block parameter. They are now: first_block=%" PRIu64 " > last_block=%" PRIu64, args->first_block, args->last_block); break; default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = {options, parse_opt, adoc, doc, NULL, NULL, NULL}; static void write_blocks(struct device *dev, uint64_t first_block, uint64_t last_block) { const int block_order = dev_get_block_order(dev); const int block_size = dev_get_block_size(dev); char stack[align_head(block_order) + BIG_BLOCK_SIZE_BYTE]; char *buffer = align_mem(stack, block_order); char *stamp_blk = buffer; char *flush_blk = buffer + BIG_BLOCK_SIZE_BYTE; uint64_t offset = first_block << block_order; uint64_t pos, first_pos = first_block; assert(BIG_BLOCK_SIZE_BYTE >= block_size); for (pos = first_block; pos <= last_block; pos++) { fill_buffer_with_block(stamp_blk, block_order, offset, 0); stamp_blk += block_size; offset += block_size; if (stamp_blk == flush_blk || pos == last_block) { if (dev_write_blocks(dev, buffer, first_pos, pos)) warn("Failed to write blocks from 0x%" PRIx64 " to 0x%" PRIx64, first_pos, pos); stamp_blk = buffer; first_pos = pos + 1; } } } /* XXX Properly handle return errors. */ static void test_write_blocks(struct device *dev, uint64_t first_block, uint64_t last_block) { printf("Writing blocks from 0x%" PRIx64 " to 0x%" PRIx64 "...", first_block, last_block); fflush(stdout); write_blocks(dev, first_block, last_block); printf(" Done\n\n"); } enum block_state { bs_unknown, bs_good, bs_bad, bs_overwritten, }; struct block_range { enum block_state state; int block_order; uint64_t start_sector_offset; uint64_t end_sector_offset; /* Only used by state bs_overwritten. */ uint64_t found_sector_offset; }; static const char *block_state_to_str(enum block_state state) { const char *conv_array[] = { [bs_unknown] = "Unknown", [bs_good] = "Good", [bs_bad] = "Bad", [bs_overwritten] = "Overwritten", }; return conv_array[state]; } static int is_block(uint64_t offset, int block_order) { return !(((1ULL << block_order) - 1) & offset); } static void print_offset(uint64_t offset, int block_order) { assert(is_block(offset, block_order)); printf("block 0x%" PRIx64, offset >> block_order); } static void print_block_range(const struct block_range *range) { printf("[%s] from ", block_state_to_str(range->state)); print_offset(range->start_sector_offset, range->block_order); printf(" to "); print_offset(range->end_sector_offset, range->block_order); switch (range->state) { case bs_good: case bs_bad: break; case bs_overwritten: printf(", found "); print_offset(range->found_sector_offset, range->block_order); break; default: assert(0); break; } printf("\n"); } static void validate_block(uint64_t expected_sector_offset, const char *probe_blk, int block_order, struct block_range *range) { uint64_t found_sector_offset; enum block_state state; bool push_range; if (validate_buffer_with_block(probe_blk, block_order, &found_sector_offset, 0)) state = bs_bad; /* Bad block. */ else if (expected_sector_offset == found_sector_offset) state = bs_good; /* Good block. */ else state = bs_overwritten; /* Overwritten block. */ push_range = (range->state != state) || ( state == bs_overwritten && ( (expected_sector_offset - range->start_sector_offset) != (found_sector_offset - range->found_sector_offset) ) ); if (push_range) { if (range->state != bs_unknown) print_block_range(range); range->state = state; range->start_sector_offset = expected_sector_offset; range->end_sector_offset = expected_sector_offset; range->found_sector_offset = found_sector_offset; } else { range->end_sector_offset = expected_sector_offset; } } static void read_blocks(struct device *dev, uint64_t first_block, uint64_t last_block) { const int block_size = dev_get_block_size(dev); const int block_order = dev_get_block_order(dev); char stack[align_head(block_order) + BIG_BLOCK_SIZE_BYTE]; char *buffer = align_mem(stack, block_order); uint64_t expected_sector_offset = first_block << block_order; uint64_t first_pos = first_block; uint64_t step = (BIG_BLOCK_SIZE_BYTE >> block_order) - 1; struct block_range range = { .state = bs_unknown, .block_order = block_order, .start_sector_offset = 0, .end_sector_offset = 0, .found_sector_offset = 0, }; assert(BIG_BLOCK_SIZE_BYTE >= block_size); while (first_pos <= last_block) { char *probe_blk = buffer; uint64_t pos, next_pos = first_pos + step; if (next_pos > last_block) next_pos = last_block; if (dev_read_blocks(dev, buffer, first_pos, next_pos)) warn("Failed to read blocks from 0x%" PRIx64 " to 0x%" PRIx64, first_pos, next_pos); for (pos = first_pos; pos <= next_pos; pos++) { validate_block(expected_sector_offset, probe_blk, block_order, &range); expected_sector_offset += block_size; probe_blk += block_size; } first_pos = next_pos + 1; } if (range.state != bs_unknown) print_block_range(&range); else assert(first_block > last_block); } /* XXX Properly handle return errors. */ static void test_read_blocks(struct device *dev, uint64_t first_block, uint64_t last_block) { printf("Reading blocks from 0x%" PRIx64 " to 0x%" PRIx64 ":\n", first_block, last_block); read_blocks(dev, first_block, last_block); printf("\n"); } int main(int argc, char **argv) { struct args args = { /* Defaults. */ .debug = false, .keep_file = false, .reset_type = RT_MANUAL_USB, .test_write = true, .test_read = true, .real_size_byte = 1ULL << 31, .fake_size_byte = 1ULL << 34, .wrap = 31, .block_order = 0, .cache_order = -1, .strict_cache = false, .first_block = 0, .last_block = -1ULL, }; struct device *dev; uint64_t very_last_block; /* Read parameters. */ argp_parse(&argp, argc, argv, 0, NULL, &args); print_header(stdout, "brew"); dev = args.debug ? create_file_device(args.filename, args.real_size_byte, args.fake_size_byte, args.wrap, args.block_order, args.cache_order, args.strict_cache, args.keep_file) : create_block_device(args.filename, args.reset_type); if (!dev) { fprintf(stderr, "\nApplication cannot continue, finishing...\n"); exit(1); } printf("Physical block size: 2^%i Bytes\n\n", dev_get_block_order(dev)); very_last_block = (dev_get_size_byte(dev) >> dev_get_block_order(dev)) - 1; if (args.first_block > very_last_block) args.first_block = very_last_block; if (args.last_block > very_last_block) args.last_block = very_last_block; if (args.test_write) test_write_blocks(dev, args.first_block, args.last_block); if (args.test_write && args.test_read) { const char *final_dev_filename; assert(!dev_reset(dev)); final_dev_filename = dev_get_filename(dev); if (strcmp(args.filename, final_dev_filename)) printf("\nWARNING: device `%s' moved to `%s' due to the reset\n\n", args.filename, final_dev_filename); } if (args.test_read) test_read_blocks(dev, args.first_block, args.last_block); free_device(dev); return 0; } f3-6.0/f3fix.c000066400000000000000000000145621263631517700130750ustar00rootroot00000000000000#include #include #include #include #include "version.h" #include "libutils.h" /* Argp's global variables. */ const char *argp_program_version = "F3 Fix " F3_STR_VERSION; /* Arguments. */ static char adoc[] = ""; static char doc[] = "F3 Fix -- edit the partition table of " "a fake flash drive to have a single partition that fully covers " "the real capacity of the drive"; static struct argp_option options[] = { {"disk-type", 'd', "TYPE", 0, "Disk type of the partition table", 2}, {"fs-type", 'f', "TYPE", 0, "Type of the file system of the partition", 0}, {"boot", 'b', NULL, 0, "Mark the partition for boot", 0}, {"no-boot", 'n', NULL, 0, "Do not mark the partition for boot", 0}, {"first-sec", 'a', "SEC-NUM", 0, "Sector where the partition starts", 0}, {"last-sec", 'l', "SEC-NUM", 0, "Sector where the partition ends", 0}, {"list-disk-types", 'k', NULL, 0, "List all supported disk types", 3}, {"list-fs-types", 's', NULL, 0, "List all supported types of file systems", 0}, { 0 } }; struct args { bool list_disk_types; bool list_fs_types; bool boot; /* 29 free bytes. */ const char *dev_filename; PedDiskType *disk_type; PedFileSystemType *fs_type; PedSector first_sec; PedSector last_sec; }; static long long arg_to_long_long(const struct argp_state *state, const char *arg) { char *end; long long ll = strtoll(arg, &end, 0); if (!arg) argp_error(state, "An integer must be provided"); if (!*arg || *end) argp_error(state, "`%s' is not an integer", arg); return ll; } static error_t parse_opt(int key, char *arg, struct argp_state *state) { struct args *args = state->input; long long ll; switch (key) { case 'd': args->disk_type = ped_disk_type_get(arg); if (!args->disk_type) argp_error(state, "Disk type `%s' is not supported; use --list-disk-types to see the supported types", arg); break; case 'f': args->fs_type = ped_file_system_type_get(arg); if (!args->fs_type) argp_error(state, "File system type `%s' is not supported; use --list-fs-types to see the supported types", arg); break; case 'b': args->boot = true; break; case 'n': args->boot = false; break; case 'a': ll = arg_to_long_long(state, arg); if (ll < 0) argp_error(state, "First sector must be greater or equal to 0"); args->first_sec = ll; break; case 'l': ll = arg_to_long_long(state, arg); if (ll < 0) argp_error(state, "Last sector must be greater or equal to 0"); args->last_sec = ll; break; case 'k': args->list_disk_types = true; break; case 's': args->list_fs_types = true; break; case ARGP_KEY_INIT: args->dev_filename = NULL; args->last_sec = -1; break; case ARGP_KEY_ARG: if (args->dev_filename) argp_error(state, "Wrong number of arguments; only one is allowed"); args->dev_filename = arg; break; case ARGP_KEY_END: if (args->list_disk_types || args->list_fs_types) break; if (!args->dev_filename) argp_error(state, "The disk device was not specified"); if (args->last_sec < 0) argp_error(state, "Option --last-sec is required"); if (args->first_sec > args->last_sec) argp_error(state, "Option --fist_sec must be less or equal to option --last_sec"); break; default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = {options, parse_opt, adoc, doc, NULL, NULL, NULL}; static void list_disk_types(void) { PedDiskType *type; int i = 0; printf("Disk types:\n"); for (type = ped_disk_type_get_next(NULL); type; type = ped_disk_type_get_next(type)) { printf("%s\t", type->name); i++; if (i == 5) { printf("\n"); i = 0; } } if (i > 0) printf("\n"); printf("\n"); } static void list_fs_types(void) { PedFileSystemType *fs_type; int i = 0; printf("File system types:\n"); for (fs_type = ped_file_system_type_get_next(NULL); fs_type; fs_type = ped_file_system_type_get_next(fs_type)) { printf("%s\t", fs_type->name); i++; if (i == 5) { printf("\n"); i = 0; } } if (i > 0) printf("\n"); printf("\n"); } static PedSector map_sector_to_logical_sector(PedSector sector, int logical_sector_size) { assert(logical_sector_size >= 512); assert(logical_sector_size % 512 == 0); return sector / (logical_sector_size / 512); } /* 0 on failure, 1 otherwise. */ static int fix_disk(PedDevice *dev, PedDiskType *type, PedFileSystemType *fs_type, int boot, PedSector start, PedSector end) { PedDisk *disk; PedPartition *part; PedGeometry *geom; PedConstraint *constraint; int ret = 0; disk = ped_disk_new_fresh(dev, type); if (!disk) goto out; start = map_sector_to_logical_sector(start, dev->sector_size); end = map_sector_to_logical_sector(end, dev->sector_size); part = ped_partition_new(disk, PED_PARTITION_NORMAL, fs_type, start, end); if (!part) goto disk; if (boot && !ped_partition_set_flag(part, PED_PARTITION_BOOT, 1)) goto part; geom = ped_geometry_new(dev, start, end - start + 1); if (!geom) goto part; constraint = ped_constraint_exact(geom); ped_geometry_destroy(geom); if (!constraint) goto part; ret = ped_disk_add_partition(disk, part, constraint); ped_constraint_destroy(constraint); if (!ret) goto part; /* ped_disk_print(disk); */ ret = ped_disk_commit(disk); goto disk; part: ped_partition_destroy(part); disk: ped_disk_destroy(disk); out: return ret; } int main (int argc, char *argv[]) { struct args args = { /* Defaults. */ .list_disk_types = false, .list_fs_types = false, .boot = true, .disk_type = ped_disk_type_get("msdos"), .fs_type = ped_file_system_type_get("fat32"), .first_sec = 2048, /* Skip first 1MB. */ }; PedDevice *dev; int ret; /* Read parameters. */ argp_parse(&argp, argc, argv, 0, NULL, &args); print_header(stdout, "fix"); if (args.list_disk_types) list_disk_types(); if (args.list_fs_types) list_fs_types(); if (args.list_disk_types || args.list_fs_types) { /* If the user has asked for the types, * she doesn't want to fix the drive yet. */ return 0; } /* XXX If @dev is a partition, refer the user to * the disk of this partition. */ dev = ped_device_get(args.dev_filename); if (!dev) return 1; ret = !fix_disk(dev, args.disk_type, args.fs_type, args.boot, args.first_sec, args.last_sec); printf("Drive `%s' was successfully fixed\n", args.dev_filename); ped_device_destroy(dev); return ret; } f3-6.0/f3probe.c000066400000000000000000000346361263631517700134220ustar00rootroot00000000000000#define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include "version.h" #include "libprobe.h" #include "libutils.h" /* Argp's global variables. */ const char *argp_program_version = "F3 Probe " F3_STR_VERSION; /* Arguments. */ static char adoc[] = ""; static char doc[] = "F3 Probe -- probe a block device for " "counterfeit flash memory. If counterfeit, " "f3probe identifies the fake type and real memory size"; static struct argp_option options[] = { {"debug", 'd', NULL, OPTION_HIDDEN, "Enable debugging; only needed if none --debug-* option used", 1}, {"debug-real-size", 'r', "SIZE_BYTE", OPTION_HIDDEN, "Real size of the emulated drive", 0}, {"debug-fake-size", 'f', "SIZE_BYTE", OPTION_HIDDEN, "Fake size of the emulated drive", 0}, {"debug-wrap", 'w', "N", OPTION_HIDDEN, "Wrap parameter of the emulated drive", 0}, {"debug-block-order", 'b', "ORDER", OPTION_HIDDEN, "Block size of the emulated drive is 2^ORDER Bytes", 0}, {"debug-cache-order", 'c', "ORDER", OPTION_HIDDEN, "Cache size of the emulated drive is 2^ORDER blocks", 0}, {"debug-strict-cache", 'o', NULL, OPTION_HIDDEN, "Force the cache to be strict", 0}, {"debug-keep-file", 'k', NULL, OPTION_HIDDEN, "Don't remove file used for emulating the drive", 0}, {"debug-unit-test", 'u', NULL, OPTION_HIDDEN, "Run a unit test; it ignores all other debug options", 0}, {"destructive", 'n', NULL, 0, "Do not restore blocks of the device after probing it", 2}, {"min-memory", 'l', NULL, 0, "Trade speed for less use of memory", 0}, {"reset-type", 's', "TYPE", 0, "Reset method to use during the probe", 0}, {"time-ops", 't', NULL, 0, "Time reads, writes, and resets", 0}, { 0 } }; struct args { char *filename; /* Debugging options. */ bool debug; bool unit_test; bool keep_file; /* Behavior options. */ bool save; bool min_mem; enum reset_type reset_type; bool time_ops; /* 1 free bytes. */ /* Geometry. */ uint64_t real_size_byte; uint64_t fake_size_byte; int wrap; int block_order; int cache_order; int strict_cache; }; static error_t parse_opt(int key, char *arg, struct argp_state *state) { struct args *args = state->input; long long ll; switch (key) { case 'd': args->debug = true; break; case 'r': ll = arg_to_ll_bytes(state, arg); if (ll < 0) argp_error(state, "Real size must be greater or equal to zero"); args->real_size_byte = ll; args->debug = true; break; case 'f': ll = arg_to_ll_bytes(state, arg); if (ll < 0) argp_error(state, "Fake size must be greater or equal to zero"); args->fake_size_byte = ll; args->debug = true; break; case 'w': ll = arg_to_ll_bytes(state, arg); if (ll < 0 || ll >= 64) argp_error(state, "Wrap must be in the interval [0, 63]"); args->wrap = ll; args->debug = true; break; case 'b': ll = arg_to_ll_bytes(state, arg); if (ll != 0 && (ll < 9 || ll > 20)) argp_error(state, "Block order must be in the interval [9, 20] or be zero"); args->block_order = ll; args->debug = true; break; case 'c': ll = arg_to_ll_bytes(state, arg); if (ll < -1 || ll > 64) argp_error(state, "Cache order must be in the interval [-1, 64]"); args->cache_order = ll; args->debug = true; break; case 'o': args->strict_cache = true; args->debug = true; break; case 'k': args->keep_file = true; args->debug = true; break; case 'u': args->unit_test = true; break; case 'n': args->save = false; break; case 'l': args->min_mem = true; break; case 's': ll = arg_to_ll_bytes(state, arg); if (ll < 0 || ll >= RT_MAX) argp_error(state, "Reset type must be in the interval [0, %i]", RT_MAX - 1); args->reset_type = ll; break; case 't': args->time_ops = true; break; case ARGP_KEY_INIT: args->filename = NULL; break; case ARGP_KEY_ARG: if (args->filename) argp_error(state, "Wrong number of arguments; only one is allowed"); args->filename = arg; break; case ARGP_KEY_END: if (!args->filename) argp_error(state, "The disk device was not specified"); if (args->debug && !dev_param_valid(args->real_size_byte, args->fake_size_byte, args->wrap, args->block_order)) argp_error(state, "The debugging parameters are not valid"); break; default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = {options, parse_opt, adoc, doc, NULL, NULL, NULL}; struct unit_test_item { uint64_t real_size_byte; uint64_t fake_size_byte; int wrap; int block_order; int cache_order; int strict_cache; }; static const struct unit_test_item ftype_to_params[] = { /* Smallest good drive. */ {1ULL << 21, 1ULL << 21, 21, 9, -1, false}, /* Good, 4KB-block, 1GB drive. */ {1ULL << 30, 1ULL << 30, 30, 12, -1, false}, /* Bad drive. */ {0, 1ULL << 30, 30, 9, -1, false}, /* Geometry of a real limbo drive. */ {1777645568ULL, 32505331712ULL, 35, 9, -1, false}, /* Wraparound drive. */ {1ULL << 31, 1ULL << 34, 31, 9, -1, false}, /* Chain drive. */ {1ULL << 31, 1ULL << 34, 32, 9, -1, false}, /* Extreme case for memory usage (limbo drive). */ {(1ULL<<20)+512,1ULL << 40, 40, 9, -1, false}, /* Geomerty of a real limbo drive with 256MB of strict cache. */ {7600799744ULL, 67108864000ULL, 36, 9, 19, true}, /* The drive before with a non-strict cache. */ {7600799744ULL, 67108864000ULL, 36, 9, 19, false}, /* The devil drive I. */ {0, 1ULL << 40, 40, 9, 21, true}, /* The devil drive II. */ {0, 1ULL << 40, 40, 9, 21, false}, }; #define UNIT_TEST_N_CASES \ ((int)(sizeof(ftype_to_params)/sizeof(struct unit_test_item))) static int unit_test(const char *filename) { int i, success = 0; for (i = 0; i < UNIT_TEST_N_CASES; i++) { const struct unit_test_item *item = &ftype_to_params[i]; enum fake_type origin_type = dev_param_to_type( item->real_size_byte, item->fake_size_byte, item->wrap, item->block_order); uint64_t item_cache_byte = item->cache_order < 0 ? 0 : 1ULL << (item->cache_order + item->block_order); double f_real = item->real_size_byte; double f_fake = item->fake_size_byte; double f_cache = item_cache_byte; const char *unit_real = adjust_unit(&f_real); const char *unit_fake = adjust_unit(&f_fake); const char *unit_cache = adjust_unit(&f_cache); enum fake_type fake_type; uint64_t real_size_byte, announced_size_byte, cache_size_block; int wrap, need_reset, block_order, max_probe_blocks; struct device *dev; dev = create_file_device(filename, item->real_size_byte, item->fake_size_byte, item->wrap, item->block_order, item->cache_order, item->strict_cache, false); assert(dev); max_probe_blocks = probe_device_max_blocks(dev); assert(!probe_device(dev, &real_size_byte, &announced_size_byte, &wrap, &cache_size_block, &need_reset, &block_order)); free_device(dev); fake_type = dev_param_to_type(real_size_byte, announced_size_byte, wrap, block_order); /* Report */ printf("Test %i\t\ttype/real size/fake size/module/cache size/reset/block size\n", i + 1); printf("\t\t%s/%.2f %s/%.2f %s/2^%i Byte/%.2f %s/no/2^%i Byte\n", fake_type_to_name(origin_type), f_real, unit_real, f_fake, unit_fake, item->wrap, f_cache, unit_cache, item->block_order); if (real_size_byte == item->real_size_byte && announced_size_byte == item->fake_size_byte && wrap == item->wrap && /* probe_device() returns an upper bound of * the cache size. */ item_cache_byte <= (cache_size_block << block_order) && !need_reset && block_order == item->block_order) { success++; printf("\t\tPerfect!\tMax # of probed blocks: %i\n\n", max_probe_blocks); } else { double ret_f_real = real_size_byte; double ret_f_fake = announced_size_byte; double ret_f_cache = cache_size_block << block_order; const char *ret_unit_real = adjust_unit(&ret_f_real); const char *ret_unit_fake = adjust_unit(&ret_f_fake); const char *ret_unit_cache = adjust_unit(&ret_f_cache); printf("\tError\t%s/%.2f %s/%.2f %s/2^%i Byte/%.2f %s/%s/2^%i Byte\n\n", fake_type_to_name(fake_type), ret_f_real, ret_unit_real, ret_f_fake, ret_unit_fake, wrap, ret_f_cache, ret_unit_cache, need_reset ? "yes" : "no", block_order); } } printf("SUMMARY: "); if (success == UNIT_TEST_N_CASES) printf("Perfect!\n"); else printf("Missed %i tests out of %i\n", UNIT_TEST_N_CASES - success, UNIT_TEST_N_CASES); return 0; } static void report_size(const char *prefix, uint64_t bytes, int block_order) { double f = bytes; const char *unit = adjust_unit(&f); printf("%s %.2f %s (%" PRIu64 " blocks)\n", prefix, f, unit, bytes >> block_order); } static void report_order(const char *prefix, int order) { double f = (1ULL << order); const char *unit = adjust_unit(&f); printf("%s %.2f %s (2^%i Bytes)\n", prefix, f, unit, order); } static void report_cache(const char *prefix, uint64_t cache_size_block, int need_reset, int order) { double f = (cache_size_block << order); const char *unit = adjust_unit(&f); printf("%s %.2f %s (%" PRIu64 " blocks), need-reset=%s\n", prefix, f, unit, cache_size_block, need_reset ? "yes" : "no"); } static void report_probe_time(const char *prefix, uint64_t usec) { char str[TIME_STR_SIZE]; usec_to_str(usec, str); printf("%s %s\n", prefix, str); } static void report_ops(const char *op, uint64_t count, uint64_t time_us) { char str1[TIME_STR_SIZE], str2[TIME_STR_SIZE]; usec_to_str(time_us, str1); usec_to_str(count > 0 ? time_us / count : 0, str2); printf("%10s: %s / %" PRIu64 " = %s\n", op, str1, count, str2); } static int test_device(struct args *args) { struct timeval t1, t2; struct device *dev, *pdev, *sdev; enum fake_type fake_type; uint64_t real_size_byte, announced_size_byte, cache_size_block; int wrap, need_reset, block_order; uint64_t read_count, read_time_us; uint64_t write_count, write_time_us; uint64_t reset_count, reset_time_us; const char *final_dev_filename; dev = args->debug ? create_file_device(args->filename, args->real_size_byte, args->fake_size_byte, args->wrap, args->block_order, args->cache_order, args->strict_cache, args->keep_file) : create_block_device(args->filename, args->reset_type); if (!dev) { fprintf(stderr, "\nApplication cannot continue, finishing...\n"); exit(1); } if (args->time_ops) { pdev = create_perf_device(dev); assert(pdev); dev = pdev; } else { pdev = NULL; } if (args->save) { sdev = create_safe_device(dev, probe_device_max_blocks(dev), args->min_mem); if (!sdev) { if (!args->min_mem) fprintf(stderr, "Out of memory, try `f3probe --min-memory %s'\n", dev_get_filename(dev)); else fprintf(stderr, "Out of memory, try `f3probe --destructive %s'\nPlease back your data up before using option --destructive.\nAlternatively, you could use a machine with more memory to run f3probe.\n", dev_get_filename(dev)); exit(1); } dev = sdev; } printf("WARNING: Probing normally takes from a few seconds to 15 minutes, but\n"); printf(" it can take longer. Please be patient.\n\n"); assert(!gettimeofday(&t1, NULL)); /* XXX Have a better error handling to recover * the state of the drive. */ assert(!probe_device(dev, &real_size_byte, &announced_size_byte, &wrap, &cache_size_block, &need_reset, &block_order)); assert(!gettimeofday(&t2, NULL)); if (!args->debug && args->reset_type == RT_MANUAL_USB) { printf("CAUTION\t\tCAUTION\t\tCAUTION\n"); printf("No more resets are needed, so do not unplug the drive\n"); fflush(stdout); } /* Keep free_device() as close of probe_device() as possible to * make sure that the written blocks are recovered when * @args->save is true. */ if (args->time_ops) perf_device_sample(pdev, &read_count, &read_time_us, &write_count, &write_time_us, &reset_count, &reset_time_us); if (args->save) { uint64_t very_last_pos = real_size_byte >> block_order; printf("Probe finished, recovering blocks..."); fflush(stdout); if (very_last_pos > 0) { very_last_pos--; sdev_recover(sdev, very_last_pos); } printf(" Done\n"); sdev_flush(sdev); } final_dev_filename = strdup(dev_get_filename(dev)); assert(final_dev_filename); free_device(dev); if (args->save || (!args->debug && args->reset_type == RT_MANUAL_USB)) printf("\n"); if (strcmp(args->filename, final_dev_filename)) printf("WARNING: device `%s' moved to `%s' due to the resets\n\n", args->filename, final_dev_filename); fake_type = dev_param_to_type(real_size_byte, announced_size_byte, wrap, block_order); switch (fake_type) { case FKTY_GOOD: printf("Good news: The device `%s' is the real thing\n", final_dev_filename); break; case FKTY_BAD: printf("Bad news: The device `%s' is damaged\n", final_dev_filename); break; case FKTY_LIMBO: case FKTY_WRAPAROUND: case FKTY_CHAIN: { uint64_t last_good_sector = (real_size_byte >> 9) - 1; assert(block_order >= 9); printf("Bad news: The device `%s' is a counterfeit of type %s\n\n" "You can \"fix\" this device using the following command:\n" "f3fix --last-sec=%" PRIu64 " %s\n", final_dev_filename, fake_type_to_name(fake_type), last_good_sector, final_dev_filename); break; } default: assert(0); break; } printf("\nDevice geometry:\n"); report_size("\t *Usable* size:", real_size_byte, block_order); report_size("\t Announced size:", announced_size_byte, block_order); report_order("\t Module:", wrap); report_cache("\tApproximate cache size:", cache_size_block, need_reset, block_order); report_order("\t Physical block size:", block_order); report_probe_time("\nProbe time:", diff_timeval_us(&t1, &t2)); if (args->time_ops) { printf(" Operation: total time / count = avg time\n"); report_ops("Read", read_count, read_time_us); report_ops("Write", write_count, write_time_us); report_ops("Reset", reset_count, reset_time_us); } free((void *)final_dev_filename); return 0; } int main(int argc, char **argv) { struct args args = { /* Defaults. */ .debug = false, .unit_test = false, .keep_file = false, .save = true, .min_mem = false, .reset_type = RT_USB, .time_ops = false, .real_size_byte = 1ULL << 31, .fake_size_byte = 1ULL << 34, .wrap = 31, .block_order = 0, .cache_order = -1, .strict_cache = false, }; /* Read parameters. */ argp_parse(&argp, argc, argv, 0, NULL, &args); print_header(stdout, "probe"); if (args.unit_test) return unit_test(args.filename); return test_device(&args); } f3-6.0/f3read.1000066400000000000000000000024751263631517700131400ustar00rootroot00000000000000.\"Text automatically generated by txt2man .TH F3 "1" "December 2015" "F3 6.0" "test real flash memory capacity" .SH NAME \fBf3write, f3read \fP- test real flash memory capacity .SH SYNOPSIS .nf .fam C \fBf3write\fP [\fB--start-at\fP=NUM] [\fB--end-at\fP=NUM] \fBf3read\fP [\fB--start-at\fP=NUM] [\fB--end-at\fP=NUM] .fam T .fi .fam T .fi .SH DESCRIPTION F3 (Fight Flash Fraud or Fight Fake Flash) tests the full capacity of a flash card (flash drive, flash disk, pendrive). It writes to the card and then checks if can read it. It will assure you haven't been sold a card with a smaller capacity than stated. .PP When writing to flash drive, \fBf3write\fP fills the filesystem with 1GB files named N.h2w, where N is a number (i.e. /[0-9]+/). .PP WARNING: all data on the tested disk might be lost! .SH OPTIONS .TP \fB--start-at\fP=NUM Initial number of file names. Default value is 1. .TP \fB--end-at\fP=NUM Final number of file names. Default value is "infinity". .SH EXAMPLE To write over a flash drive mounted at /media/TEST: .PP .nf .fam C $ f3write /media/TEST .fam T .fi To read this flash drive: .PP .nf .fam C $ f3read /media/TEST .fam T .fi .SH AUTHOR F3 was written by Michel Machado . This manual page was first written by Joao Eriberto Mota Filho . f3-6.0/f3read.c000066400000000000000000000151461263631517700132210ustar00rootroot00000000000000#define _POSIX_C_SOURCE 200112L #define _XOPEN_SOURCE 600 #include #include #include #include #include #include #include #include #include #include #include #include "utils.h" static inline void update_dt(struct timeval *dt, const struct timeval *t1, const struct timeval *t2) { dt->tv_sec += t2->tv_sec - t1->tv_sec; dt->tv_usec += t2->tv_usec - t1->tv_usec; if (dt->tv_usec >= 1000000) { dt->tv_sec++; dt->tv_usec -= 1000000; } } #define TOLERANCE 2 #define PRINT_STATUS(s) printf("%s%7" PRIu64 "/%9" PRIu64 "/%7" PRIu64 "/%7" \ PRIu64, (s), *ptr_ok, *ptr_corrupted, *ptr_changed, *ptr_overwritten) #define BLANK " " #define CLEAR ("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" \ "\b\b\b\b\b\b\b\b\b\b\b\b\b") static void validate_file(const char *path, int number, uint64_t *ptr_ok, uint64_t *ptr_corrupted, uint64_t *ptr_changed, uint64_t *ptr_overwritten, uint64_t *ptr_size, int *ptr_read_all, struct timeval *ptr_dt, int progress) { char *full_fn; const char *filename; uint8_t sector[SECTOR_SIZE], *p, *ptr_end; FILE *f; int fd; int offset_match, error_count; size_t sectors_read; uint64_t offset, expected_offset; int final_errno; struct timeval t1, t2; /* Progress time. */ struct timeval pt1 = { .tv_sec = -1000, .tv_usec = 0 }; *ptr_ok = *ptr_corrupted = *ptr_changed = *ptr_overwritten = 0; full_fn = full_fn_from_number(&filename, path, number); assert(full_fn); printf("Validating file %s ... %s", filename, progress ? BLANK : ""); fflush(stdout); #ifdef __CYGWIN__ /* We don't need write access, but some kernels require that * the file descriptor passed to fdatasync(2) to be writable. */ f = fopen(full_fn, "rb+"); #else f = fopen(full_fn, "rb"); #endif if (!f) err(errno, "Can't open file %s", full_fn); fd = fileno(f); assert(fd >= 0); /* If the kernel follows our advice, f3read won't ever read from cache * even when testing small memory cards without a remount, and * we should have a better reading-speed measurement. */ assert(!fdatasync(fd)); assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED)); /* Obtain initial time. */ assert(!gettimeofday(&t1, NULL)); /* Help the kernel to help us. */ assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)); ptr_end = sector + SECTOR_SIZE; sectors_read = fread(sector, SECTOR_SIZE, 1, f); final_errno = errno; expected_offset = (uint64_t)number * GIGABYTES; while (sectors_read > 0) { uint64_t rn; assert(sectors_read == 1); offset = *((uint64_t *) sector); offset_match = offset == expected_offset; rn = offset; p = sector + sizeof(offset); error_count = 0; for (; error_count <= TOLERANCE && p < ptr_end; p += sizeof(rn)) { rn = random_number(rn); if (rn != *((__typeof__(rn) *) p)) error_count++; } sectors_read = fread(sector, SECTOR_SIZE, 1, f); final_errno = errno; expected_offset += SECTOR_SIZE; if (offset_match) { if (error_count == 0) (*ptr_ok)++; else if (error_count <= TOLERANCE) (*ptr_changed)++; else (*ptr_corrupted)++; } else if (error_count <= TOLERANCE) (*ptr_overwritten)++; else (*ptr_corrupted)++; if (progress) { struct timeval pt2; assert(!gettimeofday(&pt2, NULL)); /* Avoid often printouts. */ if (delay_ms(&pt1, &pt2) >= 200) { PRINT_STATUS(CLEAR); fflush(stdout); pt1 = pt2; } } } assert(!gettimeofday(&t2, NULL)); update_dt(ptr_dt, &t1, &t2); *ptr_read_all = feof(f); *ptr_size = ftell(f); PRINT_STATUS(progress ? CLEAR : ""); if (!*ptr_read_all) { assert(ferror(f)); printf(" - NOT fully read due to \"%s\"", strerror(final_errno)); } printf("\n"); fclose(f); free(full_fn); } static void report(const char *prefix, uint64_t i) { double f = (double) (i * SECTOR_SIZE); const char *unit = adjust_unit(&f); printf("%s %.2f %s (%" PRIu64 " sectors)\n", prefix, f, unit, i); } static inline double dt_to_s(struct timeval *dt) { double ret = (double)dt->tv_sec + ((double)dt->tv_usec / 1000000.); assert(ret >= 0); return ret > 0 ? ret : 1; } static void iterate_files(const char *path, const long *files, long start_at, long end_at, int progress) { uint64_t tot_ok, tot_corrupted, tot_changed, tot_overwritten, tot_size; struct timeval tot_dt = { .tv_sec = 0, .tv_usec = 0 }; double read_speed; const char *unit; int and_read_all = 1; int or_missing_file = 0; int number = start_at; tot_ok = tot_corrupted = tot_changed = tot_overwritten = tot_size = 0; printf(" SECTORS " " ok/corrupted/changed/overwritten\n"); while (*files >= 0) { uint64_t sec_ok, sec_corrupted, sec_changed, sec_overwritten, file_size; int read_all; or_missing_file = or_missing_file || (*files != number); for (; number < *files; number++) { char *full_fn; const char *filename; full_fn = full_fn_from_number(&filename, "", number); assert(full_fn); printf("Missing file %s\n", filename); free(full_fn); } number++; validate_file(path, *files, &sec_ok, &sec_corrupted, &sec_changed, &sec_overwritten, &file_size, &read_all, &tot_dt, progress); tot_ok += sec_ok; tot_corrupted += sec_corrupted; tot_changed += sec_changed; tot_overwritten += sec_overwritten; tot_size += file_size; and_read_all = and_read_all && read_all; files++; } assert(tot_size / SECTOR_SIZE == (tot_ok + tot_corrupted + tot_changed + tot_overwritten)); /* Notice that not reporting `missing' files after the last file * in @files is important since @end_at could be very large. */ report("\n Data OK:", tot_ok); report("Data LOST:", tot_corrupted + tot_changed + tot_overwritten); report("\t Corrupted:", tot_corrupted); report("\tSlightly changed:", tot_changed); report("\t Overwritten:", tot_overwritten); if (or_missing_file) printf("WARNING: Not all F3 files in the range %li to %li are available\n", start_at + 1, end_at + 1); if (!and_read_all) printf("WARNING: Not all data was read due to I/O error(s)\n"); /* Reading speed. */ read_speed = (double)tot_size / dt_to_s(&tot_dt); unit = adjust_unit(&read_speed); printf("Average reading speed: %.2f %s/s\n", read_speed, unit); } int main(int argc, char **argv) { long start_at, end_at; const char *path; const long *files; int progress; int rc; rc = parse_args("read", argc, argv, &start_at, &end_at, &path); if (rc) return rc; files = ls_my_files(path, start_at, end_at); /* If stdout isn't a terminal, supress progress. */ progress = isatty(STDOUT_FILENO); iterate_files(path, files, start_at, end_at, progress); free((void *)files); return 0; } f3-6.0/f3write.c000066400000000000000000000245101263631517700134330ustar00rootroot00000000000000#define _POSIX_C_SOURCE 200112L #define _XOPEN_SOURCE 600 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "utils.h" static uint64_t fill_buffer(void *buf, size_t size, uint64_t offset) { uint8_t *p, *ptr_next_sector, *ptr_end; uint64_t rn; assert(size > 0); assert(size % SECTOR_SIZE == 0); assert(SECTOR_SIZE >= sizeof(offset) + sizeof(rn)); assert((SECTOR_SIZE - sizeof(offset)) % sizeof(rn) == 0); p = buf; ptr_end = p + size; while (p < ptr_end) { rn = offset; memmove(p, &offset, sizeof(offset)); ptr_next_sector = p + SECTOR_SIZE; p += sizeof(offset); for (; p < ptr_next_sector; p += sizeof(rn)) { rn = random_number(rn); memmove(p, &rn, sizeof(rn)); } assert(p == ptr_next_sector); offset += SECTOR_SIZE; } return offset; } struct flow { /* Total number of bytes to be written. */ uint64_t total_size; /* Total number of bytes already written. */ uint64_t total_written; /* If true, show progress. */ int progress; /* Writing rate in bytes. */ int block_size; /* Increment to apply to @blocks_per_delay. */ int step; /* Blocks to write before measurement. */ int blocks_per_delay; /* Delay in miliseconds. */ int delay_ms; /* Number of measurements after reaching FW_STEADY state. */ uint64_t measurements; /* Number of measured blocks. */ uint64_t measured_blocks; /* State. */ enum {FW_INC, FW_DEC, FW_SEARCH, FW_STEADY} state; /* Number of characters to erase before printing out progress. */ int erase; /* * Initialized while measuring */ /* Number of blocks written since last measurement. */ int written_blocks; /* Range of blocks_per_delay while in FW_SEARCH state. */ int bpd1, bpd2; /* Time measurements. */ struct timeval t1, t2; }; static inline void move_to_inc_at_start(struct flow *fw) { fw->step = 1; fw->state = FW_INC; } static void init_flow(struct flow *fw, uint64_t total_size, int progress) { fw->total_size = total_size; fw->total_written = 0; fw->progress = progress; fw->block_size = 1024; /* 1KB */ fw->blocks_per_delay = 1; /* 1KB/s */ fw->delay_ms = 1000; /* 1s */ fw->measurements = 0; fw->measured_blocks = 0; fw->erase = 0; assert(fw->block_size > 0); assert(fw->block_size % SECTOR_SIZE == 0); move_to_inc_at_start(fw); } static inline void start_measurement(struct flow *fw) { fw->written_blocks = 0; assert(!gettimeofday(&fw->t1, NULL)); } static inline void repeat_ch(char ch, int count) { while (count > 0) { printf("%c", ch); count--; } } static void erase(int count) { if (count <= 0) return; repeat_ch('\b', count); repeat_ch(' ', count); repeat_ch('\b', count); } /* Average writing speed in byte/s. */ static inline double get_avg_speed(struct flow *fw) { return (double)(fw->measured_blocks * fw->block_size * 1000) / (double)(fw->measurements * fw->delay_ms); } static int pr_time(double sec) { int has_h, has_m; int c, tot; tot = printf(" -- "); assert(tot > 0); has_h = sec >= 3600; if (has_h) { double h = floor(sec / 3600); c = printf("%i:", (int)h); assert(c > 0); tot += c; sec -= h * 3600; } has_m = has_h || sec >= 60; if (has_m) { double m = floor(sec / 60); if (has_h) c = printf("%02i:", (int)m); else c = printf("%i:", (int)m); assert(c > 0); tot += c; sec -= m * 60; } if (has_m) c = printf("%02i", (int)round(sec)); else c = printf("%is", (int)round(sec)); assert(c > 0); return tot + c; } static inline void update_mean(struct flow *fw) { fw->measurements++; fw->measured_blocks += fw->written_blocks; } static inline void move_to_steady(struct flow *fw) { update_mean(fw); fw->state = FW_STEADY; } static void move_to_search(struct flow *fw, int bpd1, int bpd2) { assert(bpd1 > 0); assert(bpd2 >= bpd1); fw->blocks_per_delay = (bpd1 + bpd2) / 2; if (bpd2 - bpd1 <= 3) { move_to_steady(fw); return; } fw->bpd1 = bpd1; fw->bpd2 = bpd2; fw->state = FW_SEARCH; } static inline void dec_step(struct flow *fw) { if (fw->blocks_per_delay - fw->step > 0) { fw->blocks_per_delay -= fw->step; fw->step *= 2; } else move_to_search(fw, 1, fw->blocks_per_delay + fw->step / 2); } static inline void inc_step(struct flow *fw) { fw->blocks_per_delay += fw->step; fw->step *= 2; } static inline void move_to_inc(struct flow *fw) { move_to_inc_at_start(fw); inc_step(fw); } static inline void move_to_dec(struct flow *fw) { fw->step = 1; fw->state = FW_DEC; dec_step(fw); } static void measure(int fd, struct flow *fw) { long delay; fw->written_blocks++; fw->total_written += fw->block_size; if (fw->written_blocks < fw->blocks_per_delay) return; assert(!fdatasync(fd)); assert(!gettimeofday(&fw->t2, NULL)); /* Help the kernel to help us. */ assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED)); delay = delay_ms(&fw->t1, &fw->t2); switch (fw->state) { case FW_INC: if (delay > fw->delay_ms) { move_to_search(fw, fw->blocks_per_delay - fw->step / 2, fw->blocks_per_delay); } else if (delay < fw->delay_ms) { inc_step(fw); } else move_to_steady(fw); break; case FW_DEC: if (delay > fw->delay_ms) { dec_step(fw); } else if (delay < fw->delay_ms) { move_to_search(fw, fw->blocks_per_delay, fw->blocks_per_delay + fw->step / 2); } else move_to_steady(fw); break; case FW_SEARCH: if (fw->bpd2 - fw->bpd1 <= 3) { move_to_steady(fw); break; } if (delay > fw->delay_ms) { fw->bpd2 = fw->blocks_per_delay; fw->blocks_per_delay = (fw->bpd1 + fw->bpd2) / 2; } else if (delay < fw->delay_ms) { fw->bpd1 = fw->blocks_per_delay; fw->blocks_per_delay = (fw->bpd1 + fw->bpd2) / 2; } else move_to_steady(fw); break; case FW_STEADY: update_mean(fw); if (delay <= fw->delay_ms) { move_to_inc(fw); } else if (fw->blocks_per_delay > 1) { move_to_dec(fw); } break; default: assert(0); } if (fw->progress) { /* Instantaneous speed. */ double inst_speed = (double)fw->blocks_per_delay * fw->block_size * 1000 / fw->delay_ms; const char *unit = adjust_unit(&inst_speed); double percent; /* The following shouldn't be necessary, but sometimes * the initial free space isn't exactly reported * by the kernel; this issue has been seen on Macs. */ if (fw->total_size < fw->total_written) fw->total_size = fw->total_written; percent = (double)fw->total_written * 100 / fw->total_size; erase(fw->erase); fw->erase = printf("%.2f%% -- %.2f %s/s", percent, inst_speed, unit); assert(fw->erase > 0); if (fw->measurements > 0) fw->erase += pr_time( (fw->total_size - fw->total_written) / get_avg_speed(fw)); fflush(stdout); } start_measurement(fw); } static inline void end_measurement(int fd, struct flow *fw) { assert(!fdatasync(fd)); /* Help the kernel to help us. */ assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED)); erase(fw->erase); fw->erase = 0; fflush(stdout); } static int create_and_fill_file(const char *path, long number, size_t size, struct flow *fw) { char *full_fn; const char *filename; int fd, fine; char buf[fw->block_size]; size_t remaining; uint64_t offset; ssize_t written; assert(size > 0); assert(size % fw->block_size == 0); /* Create the file. */ fine = 0; full_fn = full_fn_from_number(&filename, path, number); assert(full_fn); printf("Creating file %s ... ", filename); fflush(stdout); fd = open(full_fn, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (fd < 0) { if (errno == ENOSPC) { printf("No space left.\n"); goto out; } err(errno, "Can't create file %s", full_fn); } assert(fd >= 0); /* Write content. */ fine = 1; offset = (uint64_t)number * GIGABYTES; remaining = size; start_measurement(fw); while (remaining > 0) { offset = fill_buffer(buf, fw->block_size, offset); written = write(fd, buf, fw->block_size); if (written < 0) { if (errno == ENOSPC) { fine = 0; break; } else err(errno, "Write to file %s failed", full_fn); } assert(written == fw->block_size); remaining -= written; measure(fd, fw); } assert(!fine || remaining == 0); end_measurement(fd, fw); close(fd); printf("OK!\n"); out: free(full_fn); return fine; } static inline uint64_t get_freespace(const char *path) { struct statvfs fs; assert(!statvfs(path, &fs)); return (uint64_t)fs.f_frsize * (uint64_t)fs.f_bfree; } static inline void pr_freespace(uint64_t fs) { double f = (double)fs; const char *unit = adjust_unit(&f); printf("Free space: %.2f %s\n", f, unit); } static int fill_fs(const char *path, long start_at, long end_at, int progress) { uint64_t free_space; struct flow fw; long i; free_space = get_freespace(path); pr_freespace(free_space); if (free_space <= 0) { printf("No space!\n"); return 1; } /* If the amount of data to write is less than the space available, * update @free_space to improve estimate of time to finish. */ i = end_at - start_at + 1; if (i > 0 && (uint64_t)i <= (free_space >> 30)) free_space = (uint64_t)i << 30; init_flow(&fw, free_space, progress); for (i = start_at; i <= end_at; i++) if (!create_and_fill_file(path, i, GIGABYTES, &fw)) break; /* Final report. */ pr_freespace(get_freespace(path)); /* Writing speed. */ if (fw.measurements > 0) { double speed = get_avg_speed(&fw); const char *unit = adjust_unit(&speed); printf("Average writing speed: %.2f %s/s\n", speed, unit); } else printf("Writing speed not available\n"); return 0; } static void unlink_old_files(const char *path, long start_at, long end_at) { const long *files = ls_my_files(path, start_at, end_at); const long *number = files; while (*number >= 0) { char *full_fn; const char *filename; full_fn = full_fn_from_number(&filename, path, *number); assert(full_fn); printf("Removing old file %s ...\n", filename); if (unlink(full_fn)) err(errno, "Can't remove file %s", full_fn); number++; free(full_fn); } free((void *)files); } int main(int argc, char **argv) { long start_at, end_at; const char *path; int progress; int rc; rc = parse_args("write", argc, argv, &start_at, &end_at, &path); if (rc) return rc; unlink_old_files(path, start_at, end_at); /* If stdout isn't a terminal, supress progress. */ progress = isatty(STDOUT_FILENO); return fill_fs(path, start_at, end_at, progress); } f3-6.0/f3write.h2w000077500000000000000000000001471263631517700137140ustar00rootroot00000000000000#!/bin/bash $(dirname $0)/f3write "$@" || exit 1 FILES=("${@: -1}/*.h2w") truncate --size=/1M $FILES f3-6.0/libdevs.c000066400000000000000000000774271263631517700135170ustar00rootroot00000000000000#define _GNU_SOURCE #define _POSIX_C_SOURCE 200809L #define _FILE_OFFSET_BITS 64 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "libutils.h" #include "libdevs.h" static const char const *ftype_to_name[FKTY_MAX] = { [FKTY_GOOD] = "good", [FKTY_BAD] = "bad", [FKTY_LIMBO] = "limbo", [FKTY_WRAPAROUND] = "wraparound", [FKTY_CHAIN] = "chain", }; const char *fake_type_to_name(enum fake_type fake_type) { assert(fake_type < FKTY_MAX); return ftype_to_name[fake_type]; } int dev_param_valid(uint64_t real_size_byte, uint64_t announced_size_byte, int wrap, int block_order) { int block_size; /* Check general ranges. */ if (real_size_byte > announced_size_byte || wrap < 0 || wrap >= 64 || block_order < 9 || block_order > 20) return false; /* Check alignment of the sizes. */ block_size = 1 << block_order; if (real_size_byte % block_size || announced_size_byte % block_size) return false; /* If good, @wrap must make sense. */ if (real_size_byte == announced_size_byte) { uint64_t two_wrap = ((uint64_t)1) << wrap; return announced_size_byte <= two_wrap; } return true; } enum fake_type dev_param_to_type(uint64_t real_size_byte, uint64_t announced_size_byte, int wrap, int block_order) { uint64_t two_wrap; assert(dev_param_valid(real_size_byte, announced_size_byte, wrap, block_order)); if (real_size_byte == announced_size_byte) return FKTY_GOOD; if (real_size_byte == 0) return FKTY_BAD; /* real_size_byte < announced_size_byte */ two_wrap = ((uint64_t)1) << wrap; if (two_wrap <= real_size_byte) return FKTY_WRAPAROUND; if (two_wrap < announced_size_byte) return FKTY_CHAIN; return FKTY_LIMBO; } struct device { uint64_t size_byte; int block_order; int (*read_blocks)(struct device *dev, char *buf, uint64_t first_pos, uint64_t last_pos); int (*write_blocks)(struct device *dev, const char *buf, uint64_t first_pos, uint64_t last_pos); int (*reset)(struct device *dev); void (*free)(struct device *dev); const char *(*get_filename)(struct device *dev); }; uint64_t dev_get_size_byte(struct device *dev) { return dev->size_byte; } int dev_get_block_order(struct device *dev) { return dev->block_order; } int dev_get_block_size(struct device *dev) { return 1 << dev->block_order; } const char *dev_get_filename(struct device *dev) { return dev->get_filename(dev); } int dev_read_blocks(struct device *dev, char *buf, uint64_t first_pos, uint64_t last_pos) { if (first_pos > last_pos) return false; assert(last_pos < (dev->size_byte >> dev->block_order)); return dev->read_blocks(dev, buf, first_pos, last_pos); } int dev_write_blocks(struct device *dev, const char *buf, uint64_t first_pos, uint64_t last_pos) { if (first_pos > last_pos) return false; assert(last_pos < (dev->size_byte >> dev->block_order)); return dev->write_blocks(dev, buf, first_pos, last_pos); } int dev_reset(struct device *dev) { return dev->reset ? dev->reset(dev) : 0; } void free_device(struct device *dev) { if (dev->free) dev->free(dev); free(dev); } struct file_device { /* This must be the first field. See dev_fdev() for details. */ struct device dev; const char *filename; int fd; uint64_t real_size_byte; uint64_t address_mask; uint64_t cache_mask; uint64_t *cache_entries; char *cache_blocks; }; static inline struct file_device *dev_fdev(struct device *dev) { return (struct file_device *)dev; } static int fdev_read_block(struct device *dev, char *buf, uint64_t block_pos) { struct file_device *fdev = dev_fdev(dev); const int block_size = dev_get_block_size(dev); const int block_order = dev_get_block_order(dev); off_t off_ret, offset = block_pos << block_order; int done; offset &= fdev->address_mask; if ((uint64_t)offset >= fdev->real_size_byte) { uint64_t cache_pos; if (!fdev->cache_blocks) goto no_block; /* No cache available. */ cache_pos = block_pos & fdev->cache_mask; if (fdev->cache_entries && fdev->cache_entries[cache_pos] != block_pos) goto no_block; memmove(buf, &fdev->cache_blocks[cache_pos << block_order], block_size); return 0; } off_ret = lseek(fdev->fd, offset, SEEK_SET); if (off_ret < 0) return - errno; assert(off_ret == offset); done = 0; do { ssize_t rc = read(fdev->fd, buf + done, block_size - done); assert(rc >= 0); if (!rc) { /* Tried to read beyond the end of the file. */ assert(!done); memset(buf, 0, block_size); done += block_size; } done += rc; } while (done < block_size); return 0; no_block: memset(buf, 0, block_size); return 0; } static int fdev_read_blocks(struct device *dev, char *buf, uint64_t first_pos, uint64_t last_pos) { const int block_size = dev_get_block_size(dev); uint64_t pos; for (pos = first_pos; pos <= last_pos; pos++) { int rc = fdev_read_block(dev, buf, pos); if (rc) return rc; buf += block_size; } return 0; } static int write_all(int fd, const char *buf, size_t count) { size_t done = 0; do { ssize_t rc = write(fd, buf + done, count - done); if (rc < 0) { /* The write() failed. */ return errno; } done += rc; } while (done < count); return 0; } static int fdev_write_block(struct device *dev, const char *buf, uint64_t block_pos) { struct file_device *fdev = dev_fdev(dev); const int block_size = dev_get_block_size(dev); const int block_order = dev_get_block_order(dev); off_t off_ret, offset = block_pos << block_order; offset &= fdev->address_mask; if ((uint64_t)offset >= fdev->real_size_byte) { /* Block beyond real memory. */ uint64_t cache_pos; if (!fdev->cache_blocks) return 0; /* No cache available. */ cache_pos = block_pos & fdev->cache_mask; memmove(&fdev->cache_blocks[cache_pos << block_order], buf, block_size); if (fdev->cache_entries) fdev->cache_entries[cache_pos] = block_pos; return 0; } off_ret = lseek(fdev->fd, offset, SEEK_SET); if (off_ret < 0) return - errno; assert(off_ret == offset); return write_all(fdev->fd, buf, block_size); } static int fdev_write_blocks(struct device *dev, const char *buf, uint64_t first_pos, uint64_t last_pos) { const int block_size = dev_get_block_size(dev); uint64_t pos; for (pos = first_pos; pos <= last_pos; pos++) { int rc = fdev_write_block(dev, buf, pos); if (rc) return rc; buf += block_size; } return 0; } static void fdev_free(struct device *dev) { struct file_device *fdev = dev_fdev(dev); free(fdev->cache_blocks); free(fdev->cache_entries); free((void *)fdev->filename); assert(!close(fdev->fd)); } static const char *fdev_get_filename(struct device *dev) { return dev_fdev(dev)->filename; } struct device *create_file_device(const char *filename, uint64_t real_size_byte, uint64_t fake_size_byte, int wrap, int block_order, int cache_order, int strict_cache, int keep_file) { struct file_device *fdev; fdev = malloc(sizeof(*fdev)); if (!fdev) goto error; fdev->filename = strdup(filename); if (!fdev->filename) goto fdev; fdev->cache_mask = 0; fdev->cache_entries = NULL; fdev->cache_blocks = NULL; if (cache_order >= 0) { fdev->cache_mask = (((uint64_t)1) << cache_order) - 1; if (strict_cache) { size_t size = sizeof(*fdev->cache_entries) << cache_order; fdev->cache_entries = malloc(size); if (!fdev->cache_entries) goto cache; memset(fdev->cache_entries, 0, size); } fdev->cache_blocks = malloc(((uint64_t)1) << (cache_order + block_order)); if (!fdev->cache_blocks) goto cache; } fdev->fd = open(filename, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); if (fdev->fd < 0) { err(errno, "Can't create file `%s'", filename); goto cache; } if (!keep_file) { /* Unlinking the file now guarantees that it won't exist if * there is a crash. */ assert(!unlink(filename)); } if (!block_order) { struct stat fd_stat; blksize_t block_size; assert(!fstat(fdev->fd, &fd_stat)); block_size = fd_stat.st_blksize; block_order = ilog2(block_size); assert(block_size == (1 << block_order)); } if (!dev_param_valid(real_size_byte, fake_size_byte, wrap, block_order)) goto keep_file; fdev->real_size_byte = real_size_byte; fdev->address_mask = (((uint64_t)1) << wrap) - 1; fdev->dev.size_byte = fake_size_byte; fdev->dev.block_order = block_order; fdev->dev.read_blocks = fdev_read_blocks; fdev->dev.write_blocks = fdev_write_blocks; fdev->dev.reset = NULL; fdev->dev.free = fdev_free; fdev->dev.get_filename = fdev_get_filename; return &fdev->dev; keep_file: if (keep_file) unlink(filename); assert(!close(fdev->fd)); cache: free(fdev->cache_blocks); free(fdev->cache_entries); /* filename: this label is not being used. */ free((void *)fdev->filename); fdev: free(fdev); error: return NULL; } struct block_device { /* This must be the first field. See dev_bdev() for details. */ struct device dev; const char *filename; int fd; }; static inline struct block_device *dev_bdev(struct device *dev) { return (struct block_device *)dev; } static int read_all(int fd, char *buf, size_t count) { size_t done = 0; do { ssize_t rc = read(fd, buf + done, count - done); if (rc < 0) { assert(errno == EIO); return - errno; } assert(rc != 0); /* We should never hit the end of the file. */ done += rc; } while (done < count); return 0; } static int bdev_read_blocks(struct device *dev, char *buf, uint64_t first_pos, uint64_t last_pos) { struct block_device *bdev = dev_bdev(dev); const int block_order = dev_get_block_order(dev); size_t length = (last_pos - first_pos + 1) << block_order; off_t offset = first_pos << block_order; off_t off_ret = lseek(bdev->fd, offset, SEEK_SET); if (off_ret < 0) return - errno; assert(off_ret == offset); return read_all(bdev->fd, buf, length); } static int bdev_write_blocks(struct device *dev, const char *buf, uint64_t first_pos, uint64_t last_pos) { struct block_device *bdev = dev_bdev(dev); const int block_order = dev_get_block_order(dev); size_t length = (last_pos - first_pos + 1) << block_order; off_t offset = first_pos << block_order; off_t off_ret = lseek(bdev->fd, offset, SEEK_SET); int rc; if (off_ret < 0) return - errno; assert(off_ret == offset); rc = write_all(bdev->fd, buf, length); if (rc) return rc; rc = fsync(bdev->fd); if (rc) return rc; return posix_fadvise(bdev->fd, 0, 0, POSIX_FADV_DONTNEED); } static inline int bdev_open(const char *filename) { return open(filename, O_RDWR | O_DIRECT); } static struct udev_device *map_dev_to_usb_dev(struct udev_device *dev) { struct udev_device *usb_dev; /* The device pointed to by dev contains information about * the USB device. * In order to get information about the USB device, * get the parent device with the subsystem/devtype pair of * "usb"/"usb_device". * This will be several levels up the tree, * but the function will find it. */ usb_dev = udev_device_get_parent_with_subsystem_devtype( dev, "usb", "usb_device"); /* @usb_dev is not referenced, and will be freed when * the child (i.e. @dev) is freed. * See udev_device_get_parent_with_subsystem_devtype() for * details. */ return udev_device_ref(usb_dev); } static struct udev_device *dev_from_block_fd(struct udev *udev, int block_fd) { struct stat fd_stat; if (fstat(block_fd, &fd_stat)) { warn("Can't fstat() FD %i", block_fd); return NULL; } if (!S_ISBLK(fd_stat.st_mode)) { warnx("FD %i is not a block device", block_fd); return NULL; } return udev_device_new_from_devnum(udev, 'b', fd_stat.st_rdev); } static struct udev_monitor *create_monitor(struct udev *udev, const char *subsystem, const char *devtype) { struct udev_monitor *mon; int mon_fd, flags; mon = udev_monitor_new_from_netlink(udev, "udev"); assert(mon); assert(!udev_monitor_filter_add_match_subsystem_devtype(mon, subsystem, devtype)); assert(!udev_monitor_enable_receiving(mon)); mon_fd = udev_monitor_get_fd(mon); assert(mon_fd >= 0); flags = fcntl(mon_fd, F_GETFL); assert(flags >= 0); assert(!fcntl(mon_fd, F_SETFL, flags & ~O_NONBLOCK)); return mon; } static uint64_t get_udev_dev_size_byte(struct udev_device *dev) { const char *str_size_sector = udev_device_get_sysattr_value(dev, "size"); char *end; long long size_sector; if (!str_size_sector) return 0; size_sector = strtoll(str_size_sector, &end, 10); assert(!*end); return size_sector * 512LL; } static int wait_for_reset(struct udev *udev, const char *id_serial, uint64_t original_size_byte, const char **pfinal_dev_filename) { bool done = false, went_to_zero = false, already_changed_size = false; struct udev_monitor *mon; int rc; mon = create_monitor(udev, "block", "disk"); if (!mon) { warnx("%s(): Can't instantiate a monitor", __func__); rc = - ENOMEM; goto out; } do { struct udev_device *dev; const char *dev_id_serial, *action; uint64_t new_size_byte; const char *devnode; dev = udev_monitor_receive_device(mon); if (!dev) { warnx("%s(): Can't monitor device", __func__); rc = - ENOMEM; goto mon; } dev_id_serial = udev_device_get_property_value(dev, "ID_SERIAL"); if (!dev_id_serial || strcmp(dev_id_serial, id_serial)) goto next; action = udev_device_get_action(dev); new_size_byte = get_udev_dev_size_byte(dev); if (!strcmp(action, "add")) { /* Deal with the case in wich the user pulls * the USB device. * * DO NOTHING. */ } else if (!strcmp(action, "change")) { /* Deal with the case in wich the user pulls * the memory card from the card reader. */ if (!new_size_byte) { /* Memory card removed. */ went_to_zero = true; goto next; } if (!went_to_zero) goto next; } else { /* Ignore all other actions. */ goto next; } if (new_size_byte != original_size_byte) { /* This is an edge case. */ if (!already_changed_size) { already_changed_size = true; went_to_zero = false; printf("\nThe drive changed its size of %" PRIu64 " Bytes to %" PRIu64 " Bytes after the reset.\nPlease try to unplug and plug it back again...", original_size_byte, new_size_byte); fflush(stdout); goto next; } printf("\nThe reset failed. The drive has not returned to its original size.\n\n"); fflush(stdout); rc = - ENXIO; goto mon; } devnode = strdup(udev_device_get_devnode(dev)); if (!devnode) { warnx("%s(): Out of memory", __func__); rc = - ENOMEM; goto mon; } free((void *)*pfinal_dev_filename); *pfinal_dev_filename = devnode; done = true; next: udev_device_unref(dev); } while (!done); rc = 0; mon: assert(!udev_monitor_unref(mon)); out: return rc; } static int bdev_manual_usb_reset(struct device *dev) { struct block_device *bdev = dev_bdev(dev); struct udev *udev; struct udev_device *udev_dev, *usb_dev; const char *id_serial; int rc; if (bdev->fd < 0) { /* We don't have a device open. * This can happen when the previous reset failed, and * a reset is being called again. */ rc = - EBADF; goto out; } udev = udev_new(); if (!udev) { warnx("Can't load library udev"); rc = - EOPNOTSUPP; goto out; } /* Identify which drive we are going to reset. */ udev_dev = dev_from_block_fd(udev, bdev->fd); if (!udev_dev) { warnx("Library udev can't find device `%s'", dev_get_filename(dev)); rc = - EINVAL; goto udev; } usb_dev = map_dev_to_usb_dev(udev_dev); if (!usb_dev) { warnx("Block device `%s' is not backed by a USB device", dev_get_filename(dev)); rc = - EINVAL; goto udev_dev; } id_serial = udev_device_get_property_value(udev_dev, "ID_SERIAL"); if (!id_serial) { warnx("%s(): Out of memory", __func__); rc = - ENOMEM; goto usb_dev; } /* Close @bdev->fd before the drive is removed to increase * the chance that the device will receive the same filename. * The code is robust enough to deal with the case the drive doesn't * receive the same file name, though. */ assert(!close(bdev->fd)); bdev->fd = -1; printf("Please unplug and plug back the USB drive. Waiting..."); fflush(stdout); rc = wait_for_reset(udev, id_serial, dev_get_size_byte(dev), &bdev->filename); if (rc) { assert(rc < 0); goto usb_dev; } printf(" Thanks\n\n"); bdev->fd = bdev_open(bdev->filename); if (bdev->fd < 0) { rc = - errno; warn("Can't REopen device `%s'", bdev->filename); goto usb_dev; } rc = 0; usb_dev: udev_device_unref(usb_dev); udev_dev: udev_device_unref(udev_dev); udev: assert(!udev_unref(udev)); out: return rc; } static struct udev_device *map_block_to_usb_dev(struct udev *udev, int block_fd) { struct udev_device *dev, *usb_dev; dev = dev_from_block_fd(udev, block_fd); if (!dev) return NULL; usb_dev = map_dev_to_usb_dev(dev); udev_device_unref(dev); return usb_dev; } /* Return an open fd to the underlying hardware of the block device. */ static int usb_fd_from_block_dev(int block_fd, int open_flags) { struct udev *udev; struct udev_device *usb_dev; const char *usb_filename; int usb_fd; udev = udev_new(); if (!udev) { warnx("Can't load library udev"); usb_fd = -EOPNOTSUPP; goto out; } usb_dev = map_block_to_usb_dev(udev, block_fd); if (!usb_dev) { warnx("Block device is not backed by a USB device"); usb_fd = -EINVAL; goto udev; } usb_filename = udev_device_get_devnode(usb_dev); if (!usb_filename) { warnx("%s(): Out of memory", __func__); usb_fd = -ENOMEM; goto usb_dev; } usb_fd = open(usb_filename, open_flags | O_NONBLOCK); if (usb_fd < 0) { usb_fd = - errno; warn("Can't open device `%s'", usb_filename); goto usb_dev; } usb_dev: udev_device_unref(usb_dev); udev: assert(!udev_unref(udev)); out: return usb_fd; } static int bdev_usb_reset(struct device *dev) { struct block_device *bdev = dev_bdev(dev); int usb_fd; if (bdev->fd < 0) { /* We don't have a device open. * This can happen when the previous reset failed, and * a reset is being called again. */ return - EBADF; } usb_fd = usb_fd_from_block_dev(bdev->fd, O_WRONLY); if (usb_fd < 0) return usb_fd; assert(!close(bdev->fd)); bdev->fd = -1; assert(!ioctl(usb_fd, USBDEVFS_RESET)); assert(!close(usb_fd)); bdev->fd = bdev_open(bdev->filename); if (bdev->fd < 0) { int rc = - errno; warn("Can't REopen device `%s'", bdev->filename); return rc; } return 0; } static int bdev_none_reset(struct device *dev) { UNUSED(dev); return 0; } static void bdev_free(struct device *dev) { struct block_device *bdev = dev_bdev(dev); if (bdev->fd >= 0) assert(!close(bdev->fd)); free((void *)bdev->filename); } static const char *bdev_get_filename(struct device *dev) { return dev_bdev(dev)->filename; } static struct udev_device *map_partition_to_disk(struct udev_device *dev) { struct udev_device *disk_dev; disk_dev = udev_device_get_parent_with_subsystem_devtype( dev, "block", "disk"); /* @disk_dev is not referenced, and will be freed when * the child (i.e. @dev) is freed. * See udev_device_get_parent_with_subsystem_devtype() for * details. */ return udev_device_ref(disk_dev); } /* XXX This is borrowing from glibc. * A better solution would be to return proper errors, * so callers write their own messages. */ extern const char *__progname; struct device *create_block_device(const char *filename, enum reset_type rt) { struct block_device *bdev; struct udev *udev; struct udev_device *fd_dev, *usb_dev; const char *s; int block_size, block_order; bdev = malloc(sizeof(*bdev)); if (!bdev) goto error; bdev->filename = strdup(filename); if (!bdev->filename) goto bdev; bdev->fd = bdev_open(filename); if (bdev->fd < 0) { if (errno == EACCES && getuid()) { fprintf(stderr, "Your user doesn't have access to device `%s'.\n" "Try to run this program as root:\n" "sudo %s %s\n" "In case you don't have access to root, use f3write/f3read.\n", filename, __progname, filename); } else { err(errno, "Can't open device `%s'", filename); } goto filename; } /* Make sure that @bdev->fd is a disk, not a partition, and that * it is in fact backed by a USB device. */ udev = udev_new(); if (!udev) { warnx("Can't load library udev"); goto fd; } fd_dev = dev_from_block_fd(udev, bdev->fd); if (!fd_dev) { fprintf(stderr, "Can't create udev device from `%s'\n", filename); goto udev; } assert(!strcmp(udev_device_get_subsystem(fd_dev), "block")); s = udev_device_get_devtype(fd_dev); if (!strcmp(s, "partition")) { struct udev_device *disk_dev = map_partition_to_disk(fd_dev); assert(disk_dev); s = udev_device_get_devnode(disk_dev); fprintf(stderr, "Device `%s' is a partition of disk device `%s'.\n" "You must run %s on the disk device as follows:\n" "%s %s\n", filename, s, __progname, __progname, s); udev_device_unref(disk_dev); goto fd_dev; } else if (strcmp(s, "disk")) { fprintf(stderr, "Device `%s' is not a disk, but `%s'", filename, s); goto fd_dev; } usb_dev = map_dev_to_usb_dev(fd_dev); if (!usb_dev) { fprintf(stderr, "Device `%s' is not backed by a USB device", filename); goto fd_dev; } udev_device_unref(usb_dev); udev_device_unref(fd_dev); assert(!udev_unref(udev)); switch (rt) { case RT_MANUAL_USB: bdev->dev.reset = bdev_manual_usb_reset; break; case RT_USB: bdev->dev.reset = bdev_usb_reset; break; case RT_NONE: bdev->dev.reset = bdev_none_reset; break; default: assert(0); } assert(!ioctl(bdev->fd, BLKGETSIZE64, &bdev->dev.size_byte)); assert(!ioctl(bdev->fd, BLKSSZGET, &block_size)); block_order = ilog2(block_size); assert(block_size == (1 << block_order)); bdev->dev.block_order = block_order; bdev->dev.read_blocks = bdev_read_blocks; bdev->dev.write_blocks = bdev_write_blocks; bdev->dev.free = bdev_free; bdev->dev.get_filename = bdev_get_filename; return &bdev->dev; fd_dev: udev_device_unref(fd_dev); udev: assert(!udev_unref(udev)); fd: assert(!close(bdev->fd)); filename: free((void *)bdev->filename); bdev: free(bdev); error: return NULL; } struct perf_device { /* This must be the first field. See dev_pdev() for details. */ struct device dev; struct device *shadow_dev; uint64_t read_count; uint64_t read_time_us; uint64_t write_count; uint64_t write_time_us; uint64_t reset_count; uint64_t reset_time_us; }; static inline struct perf_device *dev_pdev(struct device *dev) { return (struct perf_device *)dev; } static int pdev_read_blocks(struct device *dev, char *buf, uint64_t first_pos, uint64_t last_pos) { struct perf_device *pdev = dev_pdev(dev); struct timeval t1, t2; int rc; assert(!gettimeofday(&t1, NULL)); rc = pdev->shadow_dev->read_blocks(pdev->shadow_dev, buf, first_pos, last_pos); assert(!gettimeofday(&t2, NULL)); pdev->read_count += last_pos - first_pos + 1; pdev->read_time_us += diff_timeval_us(&t1, &t2); return rc; } static int pdev_write_blocks(struct device *dev, const char *buf, uint64_t first_pos, uint64_t last_pos) { struct perf_device *pdev = dev_pdev(dev); struct timeval t1, t2; int rc; assert(!gettimeofday(&t1, NULL)); rc = pdev->shadow_dev->write_blocks(pdev->shadow_dev, buf, first_pos, last_pos); assert(!gettimeofday(&t2, NULL)); pdev->write_count += last_pos - first_pos + 1; pdev->write_time_us += diff_timeval_us(&t1, &t2); return rc; } static int pdev_reset(struct device *dev) { struct perf_device *pdev = dev_pdev(dev); struct timeval t1, t2; int rc; assert(!gettimeofday(&t1, NULL)); rc = dev_reset(pdev->shadow_dev); assert(!gettimeofday(&t2, NULL)); pdev->reset_count++; pdev->reset_time_us += diff_timeval_us(&t1, &t2); return rc; } static void pdev_free(struct device *dev) { struct perf_device *pdev = dev_pdev(dev); free_device(pdev->shadow_dev); } static const char *pdev_get_filename(struct device *dev) { return dev_get_filename(dev_pdev(dev)->shadow_dev); } struct device *pdev_detach_and_free(struct device *dev) { struct perf_device *pdev = dev_pdev(dev); struct device *shadow_dev = pdev->shadow_dev; pdev->shadow_dev = NULL; pdev->dev.free = NULL; free_device(&pdev->dev); return shadow_dev; } struct device *create_perf_device(struct device *dev) { struct perf_device *pdev; pdev = malloc(sizeof(*pdev)); if (!pdev) return NULL; pdev->shadow_dev = dev; pdev->read_count = 0; pdev->read_time_us = 0; pdev->write_count = 0; pdev->write_time_us = 0; pdev->reset_count = 0; pdev->reset_time_us = 0; pdev->dev.size_byte = dev->size_byte; pdev->dev.block_order = dev->block_order; pdev->dev.read_blocks = pdev_read_blocks; pdev->dev.write_blocks = pdev_write_blocks; pdev->dev.reset = pdev_reset; pdev->dev.free = pdev_free; pdev->dev.get_filename = pdev_get_filename; return &pdev->dev; } void perf_device_sample(struct device *dev, uint64_t *pread_count, uint64_t *pread_time_us, uint64_t *pwrite_count, uint64_t *pwrite_time_us, uint64_t *preset_count, uint64_t *preset_time_us) { struct perf_device *pdev = dev_pdev(dev); if (pread_count) *pread_count = pdev->read_count; if (pread_time_us) *pread_time_us = pdev->read_time_us; if (pwrite_count) *pwrite_count = pdev->write_count; if (pwrite_time_us) *pwrite_time_us = pdev->write_time_us; if (preset_count) *preset_count = pdev->reset_count; if (preset_time_us) *preset_time_us = pdev->reset_time_us; } #define SDEV_BITMAP_WORD long #define SDEV_BITMAP_BITS_PER_WORD (8*sizeof(SDEV_BITMAP_WORD)) struct safe_device { /* This must be the first field. See dev_sdev() for details. */ struct device dev; struct device *shadow_dev; char *saved_blocks; uint64_t *sb_positions; SDEV_BITMAP_WORD *sb_bitmap; uint64_t sb_n; uint64_t sb_max; }; static inline struct safe_device *dev_sdev(struct device *dev) { return (struct safe_device *)dev; } static int sdev_read_blocks(struct device *dev, char *buf, uint64_t first_pos, uint64_t last_pos) { struct safe_device *sdev = dev_sdev(dev); return sdev->shadow_dev->read_blocks(sdev->shadow_dev, buf, first_pos, last_pos); } static int sdev_is_block_saved(struct safe_device *sdev, uint64_t pos) { lldiv_t idx; SDEV_BITMAP_WORD set_bit; if (!sdev->sb_bitmap) { uint64_t i; /* Running without bitmap. */ for (i = 0; i < sdev->sb_n; i++) if (sdev->sb_positions[i] == pos) { /* The block is already saved. */ return true; } return false; } idx = lldiv(pos, SDEV_BITMAP_BITS_PER_WORD); set_bit = (SDEV_BITMAP_WORD)1 << idx.rem; return !!(sdev->sb_bitmap[idx.quot] & set_bit); } static void sdev_mark_blocks(struct safe_device *sdev, uint64_t first_pos, uint64_t last_pos) { uint64_t pos; for (pos = first_pos; pos <= last_pos; pos++) { if (sdev->sb_bitmap) { lldiv_t idx = lldiv(pos, SDEV_BITMAP_BITS_PER_WORD); SDEV_BITMAP_WORD set_bit = (SDEV_BITMAP_WORD)1 << idx.rem; sdev->sb_bitmap[idx.quot] |= set_bit; } sdev->sb_positions[sdev->sb_n] = pos; sdev->sb_n++; } } /* Load blocks into cache. */ static int sdev_load_blocks(struct safe_device *sdev, uint64_t first_pos, uint64_t last_pos) { const int block_order = dev_get_block_order(sdev->shadow_dev); char *block_buf = (char *)align_mem(sdev->saved_blocks, block_order) + (sdev->sb_n << block_order); int rc; assert(sdev->sb_n + (last_pos - first_pos + 1) < sdev->sb_max); rc = sdev->shadow_dev->read_blocks(sdev->shadow_dev, block_buf, first_pos, last_pos); if (rc) return rc; /* Bookkeeping. */ sdev_mark_blocks(sdev, first_pos, last_pos); return 0; } static int sdev_save_block(struct safe_device *sdev, uint64_t first_pos, uint64_t last_pos) { uint64_t pos, start_pos; int rc; start_pos = first_pos; for (pos = first_pos; pos <= last_pos; pos++) { if (sdev_is_block_saved(sdev, pos)) { if (start_pos < pos) { /* The blocks haven't been saved before. * Save them now. */ rc = sdev_load_blocks(sdev, start_pos, pos - 1); if (rc) return rc; } else if (start_pos == pos) { /* Do nothing. */ } else { assert(0); } start_pos = pos + 1; } } if (start_pos <= last_pos) { rc = sdev_load_blocks(sdev, start_pos, last_pos); if (rc) return rc; } return 0; } static int sdev_write_blocks(struct device *dev, const char *buf, uint64_t first_pos, uint64_t last_pos) { struct safe_device *sdev = dev_sdev(dev); int rc = sdev_save_block(sdev, first_pos, last_pos); if (rc) return rc; return sdev->shadow_dev->write_blocks(sdev->shadow_dev, buf, first_pos, last_pos); } static int sdev_reset(struct device *dev) { return dev_reset(dev_sdev(dev)->shadow_dev); } static void sdev_carefully_recover(struct safe_device *sdev, char *buffer, uint64_t first_pos, uint64_t last_pos) { const int block_size = dev_get_block_size(sdev->shadow_dev); uint64_t pos; int rc = sdev->shadow_dev->write_blocks(sdev->shadow_dev, buffer, first_pos, last_pos); if (!rc) return; for (pos = first_pos; pos <= last_pos; pos++) { int rc = sdev->shadow_dev->write_blocks(sdev->shadow_dev, buffer, pos, pos); if (rc) { /* Do not abort, try to recover all bocks. */ warn("Failed to recover block 0x%" PRIx64 " due to a write error", pos); } buffer += block_size; } } static uint64_t sdev_bitmap_length(struct device *dev) { const int block_order = dev_get_block_order(dev); lldiv_t idx = lldiv(dev_get_size_byte(dev) >> block_order, SDEV_BITMAP_BITS_PER_WORD); return (idx.quot + (idx.rem ? 1 : 0)) * sizeof(SDEV_BITMAP_WORD); } void sdev_recover(struct device *dev, uint64_t very_last_pos) { struct safe_device *sdev = dev_sdev(dev); const int block_order = dev_get_block_order(sdev->shadow_dev); char *first_block = align_mem(sdev->saved_blocks, block_order); uint64_t i, first_pos, last_pos; char *start_buf; int has_seq; has_seq = false; for (i = 0; i < sdev->sb_n; i++) { uint64_t pos = sdev->sb_positions[i]; if (!has_seq) { if (pos > very_last_pos) continue; last_pos = first_pos = pos; start_buf = first_block + (i << block_order); has_seq = true; continue; } if (pos <= very_last_pos && pos == last_pos + 1) { last_pos++; continue; } sdev_carefully_recover(sdev, start_buf, first_pos, last_pos); has_seq = pos <= very_last_pos; if (has_seq) { last_pos = first_pos = pos; start_buf = first_block + (i << block_order); } } if (has_seq) { sdev_carefully_recover(sdev, start_buf, first_pos, last_pos); has_seq = false; } } void sdev_flush(struct device *dev) { struct safe_device *sdev = dev_sdev(dev); if (sdev->sb_n <= 0) return; sdev->sb_n = 0; if (sdev->sb_bitmap) memset(sdev->sb_bitmap, 0, sdev_bitmap_length(sdev->shadow_dev)); } static void sdev_free(struct device *dev) { struct safe_device *sdev = dev_sdev(dev); sdev_recover(dev, UINT_LEAST64_MAX); sdev_flush(dev); free(sdev->sb_bitmap); free(sdev->sb_positions); free(sdev->saved_blocks); free_device(sdev->shadow_dev); } static const char *sdev_get_filename(struct device *dev) { return dev_get_filename(dev_sdev(dev)->shadow_dev); } struct device *create_safe_device(struct device *dev, uint64_t max_blocks, int min_memory) { struct safe_device *sdev; const int block_order = dev_get_block_order(dev); uint64_t length; sdev = malloc(sizeof(*sdev)); if (!sdev) goto error; length = align_head(block_order) + (max_blocks << block_order); sdev->saved_blocks = malloc(length); if (!sdev->saved_blocks) goto sdev; sdev->sb_positions = malloc(max_blocks * sizeof(*sdev->sb_positions)); if (!sdev->sb_positions) goto saved_blocks; if (!min_memory) { length = sdev_bitmap_length(dev); sdev->sb_bitmap = malloc(length); if (!sdev->sb_bitmap) goto offsets; memset(sdev->sb_bitmap, 0, length); } else { sdev->sb_bitmap = NULL; } sdev->shadow_dev = dev; sdev->sb_n = 0; sdev->sb_max = max_blocks; sdev->dev.size_byte = dev->size_byte; sdev->dev.block_order = block_order; sdev->dev.read_blocks = sdev_read_blocks; sdev->dev.write_blocks = sdev_write_blocks; sdev->dev.reset = sdev_reset; sdev->dev.free = sdev_free; sdev->dev.get_filename = sdev_get_filename; return &sdev->dev; offsets: free(sdev->sb_positions); saved_blocks: free(sdev->saved_blocks); sdev: free(sdev); error: return NULL; } f3-6.0/libdevs.h000066400000000000000000000050251263631517700135050ustar00rootroot00000000000000#ifndef HEADER_LIBDEVS_H #define HEADER_LIBDEVS_H #include /* * Device model */ enum fake_type { /* Device is good. */ FKTY_GOOD, /* Device is at least partially damaged. */ FKTY_BAD, /* Device discards data after a given limit. */ FKTY_LIMBO, /* Device overwrites data after a given limit. */ FKTY_WRAPAROUND, /* Device is a sequence of wraparound and limbo regions. */ FKTY_CHAIN, FKTY_MAX }; const char *fake_type_to_name(enum fake_type fake_type); int dev_param_valid(uint64_t real_size_byte, uint64_t announced_size_byte, int wrap, int block_order); enum fake_type dev_param_to_type(uint64_t real_size_byte, uint64_t announced_size_byte, int wrap, int block_order); /* * Abstract device */ struct device; /* * Properties */ uint64_t dev_get_size_byte(struct device *dev); int dev_get_block_order(struct device *dev); int dev_get_block_size(struct device *dev); /* File name of the device. * This information is important because the filename may change due to resets. */ const char *dev_get_filename(struct device *dev); /* * Methods */ /* One should use the following constant as the size of the buffer needed to * batch writes or reads. * * It must be a power of 2 greater than, or equal to 2^20. * The current vaule is 1MB. */ #define BIG_BLOCK_SIZE_BYTE (1 << 20) int dev_read_blocks(struct device *dev, char *buf, uint64_t first_pos, uint64_t last_pos); int dev_write_blocks(struct device *dev, const char *buf, uint64_t first_pos, uint64_t last_pos); int dev_reset(struct device *dev); void free_device(struct device *dev); /* * Concrete devices */ struct device *create_file_device(const char *filename, uint64_t real_size_byte, uint64_t fake_size_byte, int wrap, int block_order, int cache_order, int strict_cache, int keep_file); enum reset_type { RT_MANUAL_USB = 0, RT_USB, RT_NONE, RT_MAX }; struct device *create_block_device(const char *filename, enum reset_type rt); struct device *create_perf_device(struct device *dev); void perf_device_sample(struct device *dev, uint64_t *pread_count, uint64_t *pread_time_us, uint64_t *pwrite_count, uint64_t *pwrite_time_us, uint64_t *preset_count, uint64_t *preset_time_us); /* Detach the shadow device of @pdev, free @pdev, and return * the shadow device. */ struct device *pdev_detach_and_free(struct device *dev); struct device *create_safe_device(struct device *dev, uint64_t max_blocks, int min_memory); void sdev_recover(struct device *dev, uint64_t very_last_pos); void sdev_flush(struct device *dev); #endif /* HEADER_LIBDEVS_H */ f3-6.0/libprobe.c000066400000000000000000000534361263631517700136570ustar00rootroot00000000000000#include #include #include #include #include #include #include /* For time(). */ #include /* For gettimeofday(). */ #include "libutils.h" #include "libprobe.h" static int write_blocks(struct device *dev, uint64_t first_pos, uint64_t last_pos, uint64_t salt) { const int block_order = dev_get_block_order(dev); const int block_size = dev_get_block_size(dev); /* Aligning these pointers is necessary to directly read and write * the block device. * For the file device, this is superfluous. */ char stack[align_head(block_order) + BIG_BLOCK_SIZE_BYTE]; char *buffer = align_mem(stack, block_order); char *stamp_blk = buffer; char *flush_blk = buffer + BIG_BLOCK_SIZE_BYTE; uint64_t offset = first_pos << block_order; uint64_t pos, write_pos = first_pos; for (pos = first_pos; pos <= last_pos; pos++) { fill_buffer_with_block(stamp_blk, block_order, offset, salt); stamp_blk += block_size; offset += block_size; if (stamp_blk == flush_blk || pos == last_pos) { if (dev_write_blocks(dev, buffer, write_pos, pos) && dev_write_blocks(dev, buffer, write_pos, pos)) return true; stamp_blk = buffer; write_pos = pos + 1; } } return false; } static int high_level_reset(struct device *dev, uint64_t start_pos, uint64_t cache_size_block, int need_reset, uint64_t salt) { if (write_blocks(dev, start_pos, start_pos + cache_size_block - 1, salt)) return true; /* Reset. */ if (need_reset && dev_reset(dev) && dev_reset(dev)) return true; return false; } /* Statistics used by bisect() in order to optimize the proportion * between writes and resets. */ struct bisect_stats { int write_count; int reset_count; uint64_t write_time_us; uint64_t reset_time_us; }; static void init_bisect_stats(struct bisect_stats *stats) { memset(stats, 0, sizeof(*stats)); } #define MAX_N_BLOCK_ORDER 10 static uint64_t estimate_n_bisect_blocks(struct bisect_stats *pstats) { double t_w_us, t_2w_us, t_r_us; uint64_t n_block_order; if (pstats->write_count < 10 || pstats->reset_count < 1) { /* There is not enough measurements. */ return (1 << 4) - 1; } /* Let 2^n be the total number of blocks on the drive. * Let p be the total number of passes. * Let w = (2^m - 1) be the number of blocks written on each pass, * where m >= 1. * * A pass is an iteration of the loop in search_edge(), that is, * a call to write_test_blocks(), dev_reset(), and probe_test_blocks(). * * The reason to have w = (2^m - 1) instead of w = 2^m is because * the former leads to a clean relationship between n, p, and m * when m is constant: 2^n / (w + 1)^p = 1 => p = n/m * * Let Tr be the time to reset the device. * Let Tw be the time to write a block to @dev. * Let Tw' be the time to write a block to the underlying device * of @dev, that is, without overhead due to chaining multiple * struct device. For example, when struct safe_device is used * Tw > Tw'. * Let Trd be the time to read a block from @dev. * * Notice that each single-block pass reduces the search space in half, * and that to reduce the search space in half writing blocks, * one has to increase m of one. * * Thus, in order to be better writing more blocks than * going for another pass, the following relation must be true: * * Tr + Tw + Tw' >= (w - 1)(Tw + Tw') * * The relation above assumes Trd = 0. * * The left side of the relation above is the time to do _another_ * pass writing a single block, whereas the right side is the time to * stay in the same pass and write (w - 1) more blocks. * In order words, if there is no advantage to write more blocks, * we stick to single-block passes. * * Tw' is there to account for any operation that writes * the blocks back (e.g. using struct safe_device), otherwise * processing operations related per written blocks that is not * being accounted for (e.g. reading the blocks back to test). * * Solving the relation for w: w <= Tr/(Tw + Tw') + 2 * * However, we are not interested in any w, but only those of * of the form (2^m - 1) to make sure that we are not better off * calling another pass. Thus, solving the previous relation for m: * * m <= log_2(Tr/(Tw + Tw') + 3) * * We approximate Tw' making it equal to Tw. */ t_w_us = (double)pstats->write_time_us / pstats->write_count; t_r_us = (double)pstats->reset_time_us / pstats->reset_count; t_2w_us = t_w_us > 0. ? 2. * t_w_us : 1.; /* Avoid zero division. */ n_block_order = ilog2(round(t_r_us / t_2w_us + 3.)); /* Bound the maximum number of blocks per pass to limit * the necessary amount of memory struct safe_device pre-allocates. */ if (n_block_order > MAX_N_BLOCK_ORDER) n_block_order = MAX_N_BLOCK_ORDER; return (1 << n_block_order) - 1; } /* Write blocks whose offsets are after @left_pos and before @right_pos. */ static int write_bisect_blocks(struct device *dev, uint64_t left_pos, uint64_t right_pos, uint64_t n_blocks, uint64_t salt, uint64_t *pa, uint64_t *pb, uint64_t *pmax_idx) { uint64_t pos, last_pos; assert(n_blocks >= 1); /* Find coeficients of function a*idx + b where idx <= max_idx. */ assert(left_pos < right_pos); assert(right_pos - left_pos >= 2); *pb = left_pos + 1; *pa = round((right_pos - *pb - 1.) / (n_blocks + 1.)); *pa = !*pa ? 1ULL : *pa; *pmax_idx = (right_pos - *pb - 1) / *pa; if (*pmax_idx >= n_blocks) { /* Shift the zero of the function to the right. * This avoids picking the leftmost block when a more * informative block to the right is available. */ *pb += *pa; *pmax_idx = n_blocks - 1; } last_pos = *pa * *pmax_idx + *pb; assert(last_pos < right_pos); /* Write test blocks. */ for (pos = *pb; pos <= last_pos; pos += *pa) if (write_blocks(dev, pos, pos, salt)) return true; return false; } static int is_block_good(struct device *dev, uint64_t pos, int *pis_good, uint64_t salt) { const int block_size = dev_get_block_size(dev); const int block_order = dev_get_block_order(dev); char stack[align_head(block_order) + block_size]; char *probe_blk = align_mem(stack, block_order); uint64_t found_offset; if (dev_read_blocks(dev, probe_blk, pos, pos) && dev_read_blocks(dev, probe_blk, pos, pos)) return true; *pis_good = !validate_buffer_with_block(probe_blk, block_order, &found_offset, salt) && found_offset == (pos << block_order); return false; } static int probe_bisect_blocks(struct device *dev, uint64_t *pleft_pos, uint64_t *pright_pos, uint64_t salt, uint64_t a, uint64_t b, uint64_t max_idx) { /* Signed variables. */ int64_t left_idx = 0; int64_t right_idx = max_idx; while (left_idx <= right_idx) { int64_t idx = (left_idx + right_idx) / 2; uint64_t pos = a * idx + b; int is_good; if (is_block_good(dev, pos, &is_good, salt)) return true; if (is_good) { left_idx = idx + 1; *pleft_pos = pos; } else { right_idx = idx - 1; *pright_pos = pos; } } return false; } /* This function assumes that the block at @left_pos is good, and * that the block at @*pright_pos is bad. */ static int bisect(struct device *dev, struct bisect_stats *pstats, uint64_t left_pos, uint64_t *pright_pos, uint64_t reset_pos, uint64_t cache_size_block, int need_reset, uint64_t salt) { uint64_t gap = *pright_pos - left_pos; struct timeval t1, t2; assert(*pright_pos > left_pos); while (gap >= 2) { uint64_t a, b, max_idx; uint64_t n_blocks = estimate_n_bisect_blocks(pstats); assert(!gettimeofday(&t1, NULL)); if (write_bisect_blocks(dev, left_pos, *pright_pos, n_blocks, salt, &a, &b, &max_idx)) return true; assert(!gettimeofday(&t2, NULL)); pstats->write_count += max_idx + 1; pstats->write_time_us += diff_timeval_us(&t1, &t2); /* Reset. */ assert(!gettimeofday(&t1, NULL)); if (high_level_reset(dev, reset_pos, cache_size_block, need_reset, salt)) return true; assert(!gettimeofday(&t2, NULL)); pstats->reset_count++; pstats->reset_time_us += diff_timeval_us(&t1, &t2); if (probe_bisect_blocks(dev, &left_pos, pright_pos, salt, a, b, max_idx)) return true; gap = *pright_pos - left_pos; } assert(gap == 1); return false; } static int count_good_blocks(struct device *dev, uint64_t *pcount, uint64_t first_pos, uint64_t last_pos, uint64_t salt) { const int block_size = dev_get_block_size(dev); const int block_order = dev_get_block_order(dev); char stack[align_head(block_order) + BIG_BLOCK_SIZE_BYTE]; char *buffer = align_mem(stack, block_order); uint64_t expected_sector_offset = first_pos << block_order; uint64_t start_pos = first_pos; uint64_t step = (BIG_BLOCK_SIZE_BYTE >> block_order) - 1; uint64_t count = 0; assert(BIG_BLOCK_SIZE_BYTE >= block_size); while (start_pos <= last_pos) { char *probe_blk = buffer; uint64_t pos, next_pos = start_pos + step; if (next_pos > last_pos) next_pos = last_pos; if (dev_read_blocks(dev, buffer, start_pos, next_pos) && dev_read_blocks(dev, buffer, start_pos, next_pos)) return true; for (pos = start_pos; pos <= next_pos; pos++) { uint64_t found_sector_offset; if (!validate_buffer_with_block(probe_blk, block_order, &found_sector_offset, salt) && expected_sector_offset == found_sector_offset) count++; expected_sector_offset += block_size; probe_blk += block_size; } start_pos = next_pos + 1; } *pcount = count; return false; } static int assess_reset_effect(struct device *dev, uint64_t *pcache_size_block, int *pneed_reset, int *pdone, uint64_t first_pos, uint64_t last_pos, uint64_t salt) { uint64_t write_target = (last_pos + 1) - first_pos; uint64_t b4_reset_count_block, after_reset_count_block; if (count_good_blocks(dev, &b4_reset_count_block, first_pos, last_pos, salt)) return true; if (!b4_reset_count_block) { /* The drive has no cache whatsoever. */ *pcache_size_block = 0; *pneed_reset = false; *pdone = true; return false; } /* Reset. */ if (dev_reset(dev) && dev_reset(dev)) return true; if (count_good_blocks(dev, &after_reset_count_block, first_pos, last_pos, salt)) return true; if (after_reset_count_block < write_target) { assert(after_reset_count_block <= b4_reset_count_block); *pneed_reset = after_reset_count_block < b4_reset_count_block; *pcache_size_block = *pneed_reset ? after_reset_count_block : write_target; *pdone = true; return false; } *pdone = false; return false; } static inline uint64_t uint64_rand(void) { return ((uint64_t)rand() << 32) | rand(); } static uint64_t uint64_rand_range(uint64_t a, uint64_t b) { uint64_t r = uint64_rand(); assert(a <= b); return a + (r % (b - a + 1)); } #define N_BLOCK_SAMPLES 64 static int probabilistic_test(struct device *dev, uint64_t first_pos, uint64_t last_pos, int *pfound_a_bad_block, uint64_t salt) { uint64_t gap; int i, n, is_linear; if (first_pos > last_pos) goto not_found; /* Let g be the number of good blocks between * @first_pos and @last_pos including them. * Let b be the number of bad and overwritten blocks between * @first_pos and @last_pos including them. * * The probability Pr_g of sampling a good block at random between * @first_pos and @last_pos is Pr_g = g / (g + b), and * the probability Pr_1b that among k block samples at least * one block is bad is Pr_1b = 1 - Pr_g^k. * * Assuming Pr_g <= 95% and k = 64, Pr_1b >= 96.2%. * That is, with high probability (i.e. Pr_1b), * one can find at least a bad block with k samples * when most blocks are good (Pr_g). */ /* Test @samples. */ gap = last_pos - first_pos + 1; is_linear = gap <= N_BLOCK_SAMPLES; n = is_linear ? gap : N_BLOCK_SAMPLES; for (i = 0; i < n; i++) { uint64_t sample_pos = is_linear ? first_pos + i : uint64_rand_range(first_pos, last_pos); int is_good; if (is_block_good(dev, sample_pos, &is_good, salt)) return true; if (!is_good) { /* Found a bad block. */ *pfound_a_bad_block = true; return false; } } not_found: *pfound_a_bad_block = false; return false; } static int uint64_cmp(const void *pa, const void *pb) { const uint64_t *pia = pa; const uint64_t *pib = pb; return *pia - *pib; } static int find_a_bad_block(struct device *dev, uint64_t left_pos, uint64_t *pright_pos, int *found_a_bad_block, uint64_t reset_pos, uint64_t cache_size_block, int need_reset, uint64_t salt) { /* We need to list all sampled blocks because * we need a sorted array; read the code to find the why. * If the sorted array were not needed, one could save the seed * of the random sequence and repeat the sequence to read the blocks * after writing them. */ uint64_t samples[N_BLOCK_SAMPLES]; uint64_t gap, prv_sample; int n, i; if (*pright_pos <= left_pos + 1) goto not_found; /* The code below relies on the same analytical result derived * in probabilistic_test(). */ /* Fill up @samples. */ gap = *pright_pos - left_pos - 1; if (gap <= N_BLOCK_SAMPLES) { n = gap; for (i = 0; i < n; i++) samples[i] = left_pos + 1 + i; /* Write @samples. */ if (write_blocks(dev, left_pos + 1, *pright_pos - 1, salt)) return true; } else { n = N_BLOCK_SAMPLES; for (i = 0; i < n; i++) samples[i] = uint64_rand_range(left_pos + 1, *pright_pos - 1); /* Sort entries of @samples to minimize reads. * As soon as one finds a bad block, one can stop and ignore * the remaining blocks because the found bad block is * the leftmost bad block. */ qsort(samples, n, sizeof(uint64_t), uint64_cmp); /* Write @samples. */ prv_sample = left_pos; for (i = 0; i < n; i++) { if (samples[i] == prv_sample) continue; prv_sample = samples[i]; if (write_blocks(dev, prv_sample, prv_sample, salt)) return true; } } /* Reset. */ if (high_level_reset(dev, reset_pos, cache_size_block, need_reset, salt)) return true; /* Test @samples. */ prv_sample = left_pos; for (i = 0; i < n; i++) { int is_good; if (samples[i] == prv_sample) continue; prv_sample = samples[i]; if (is_block_good(dev, prv_sample, &is_good, salt)) return true; if (!is_good) { /* Found the leftmost bad block. */ *pright_pos = prv_sample; *found_a_bad_block = true; return false; } } not_found: *found_a_bad_block = false; return false; } /* Both need to be a power of 2 and larger than, or equal to 2^block_order. */ #define MIN_CACHE_SIZE_BYTE (1ULL << 20) #define MAX_CACHE_SIZE_BYTE (1ULL << 30) static int find_cache_size(struct device *dev, uint64_t left_pos, uint64_t *pright_pos, uint64_t *pcache_size_block, int *pneed_reset, int *pgood_drive, const uint64_t salt) { const int block_order = dev_get_block_order(dev); uint64_t write_target = MIN_CACHE_SIZE_BYTE >> block_order; uint64_t final_write_target = MAX_CACHE_SIZE_BYTE >> block_order; uint64_t first_pos, last_pos, end_pos; int done; /* * Basis * * The key difference between the basis and the inductive step is * the fact that the basis always calls assess_reset_effect(). * This difference is not for correctness, that is, one can remove it, * and fold the basis into the inductive step. * However, this difference is an important speedup because many * fake drives do not have permanent cache. */ assert(write_target > 0); assert(write_target < final_write_target); last_pos = end_pos = *pright_pos - 1; /* This convoluted test is needed because * the variables are unsigned. * In a simplified form, it tests the following: * *pright_pos - write_target > left_pos */ if (*pright_pos > left_pos + write_target) { first_pos = *pright_pos - write_target; } else if (*pright_pos > left_pos + 1) { /* There's no room to write @write_target blocks, * so write what's possible. */ first_pos = left_pos + 1; } else { goto good; } if (write_blocks(dev, first_pos, last_pos, salt)) goto bad; if (assess_reset_effect(dev, pcache_size_block, pneed_reset, &done, first_pos, end_pos, salt)) goto bad; if (done) { *pright_pos = first_pos; *pgood_drive = false; return false; } /* * Inductive step */ while (write_target < final_write_target) { int found_a_bad_block; write_target <<= 1; last_pos = first_pos - 1; if (first_pos > left_pos + write_target) first_pos -= write_target; else if (first_pos > left_pos + 1) first_pos = left_pos + 1; else break; /* Cannot write any further. */ /* Write @write_target blocks before * the previously written blocks. */ if (write_blocks(dev, first_pos, last_pos, salt)) goto bad; if (probabilistic_test(dev, first_pos, end_pos, &found_a_bad_block, salt)) goto bad; if (found_a_bad_block) { if (assess_reset_effect(dev, pcache_size_block, pneed_reset, &done, first_pos, end_pos, salt)) goto bad; assert(done); *pright_pos = first_pos; *pgood_drive = false; return false; } } good: *pright_pos = end_pos + 1; *pcache_size_block = 0; *pneed_reset = false; *pgood_drive = true; return false; bad: /* *pright_pos does not change. */ *pcache_size_block = 0; *pneed_reset = false; *pgood_drive = false; return true; } static int find_wrap(struct device *dev, uint64_t left_pos, uint64_t *pright_pos, uint64_t reset_pos, uint64_t cache_size_block, int need_reset, uint64_t salt) { uint64_t offset, high_bit, pos = left_pos + 1; int is_good, block_order; /* * Basis */ /* Make sure that there is at least a good block at the beginning * of the drive. */ if (pos >= *pright_pos) return false; if (write_blocks(dev, pos, pos, salt) || high_level_reset(dev, reset_pos, cache_size_block, need_reset, salt) || is_block_good(dev, pos, &is_good, salt) || !is_good) return true; /* * Inductive step */ block_order = dev_get_block_order(dev); offset = pos << block_order; high_bit = clp2(pos); if (high_bit <= pos) high_bit <<= 1; pos += high_bit; while (pos < *pright_pos) { char stack[align_head(block_order) + (1 << block_order)]; char *probe_blk = align_mem(stack, block_order); uint64_t found_offset; if (dev_read_blocks(dev, probe_blk, pos, pos) && dev_read_blocks(dev, probe_blk, pos, pos)) return true; if (!validate_buffer_with_block(probe_blk, block_order, &found_offset, salt) && found_offset == offset) { *pright_pos = high_bit; return false; } high_bit <<= 1; pos = high_bit + left_pos + 1; } return false; } uint64_t probe_device_max_blocks(struct device *dev) { const int block_order = dev_get_block_order(dev); uint64_t num_blocks = dev_get_size_byte(dev) >> block_order; int n = ceiling_log2(num_blocks); /* Make sure that there is no overflow in the formula below. * The number 10 is arbitrary here, that is, it's not tight. */ assert(MAX_N_BLOCK_ORDER < sizeof(int) - 10); return /* find_cache_size() */ (MAX_CACHE_SIZE_BYTE >> (block_order - 1)) + /* find_wrap() */ 1 + /* The number below is just an educated guess. */ 128 * ( /* bisect() * * The number of used blocks is (p * w); see comments * in estimate_n_bisect_blocks() for the definition of * the variables. * * p * w = n/m * (2^m - 1) < n/m * 2^m = n * (2^m / m) * * Let f(m) be 2^m / m. One can prove that * f(m + 1) >= f(m) for all m >= 1. * Therefore, the following bound is true. * * p * w < n * f(max_m) */ ((n << MAX_N_BLOCK_ORDER) / MAX_N_BLOCK_ORDER) + /* find_a_bad_block() */ N_BLOCK_SAMPLES ); } int probe_device(struct device *dev, uint64_t *preal_size_byte, uint64_t *pannounced_size_byte, int *pwrap, uint64_t *pcache_size_block, int *pneed_reset, int *pblock_order) { const uint64_t dev_size_byte = dev_get_size_byte(dev); const int block_order = dev_get_block_order(dev); struct bisect_stats stats; uint64_t salt, cache_size_block; uint64_t left_pos, right_pos, mid_drive_pos, reset_pos; int need_reset, good_drive, wrap, found_a_bad_block; assert(block_order <= 20); /* @left_pos must point to a good block. * We just point to the last block of the first 1MB of the card * because this region is reserved for partition tables. * * Given that all writing is confined to the interval * (@left_pos, @right_pos), we avoid losing the partition table. */ left_pos = (1ULL << (20 - block_order)) - 1; /* @right_pos must point to a bad block. * We just point to the block after the very last block. */ right_pos = dev_size_byte >> block_order; /* @left_pos cannot be equal to @right_pos since * @left_pos points to a good block, and @right_pos to a bad block. */ if (left_pos >= right_pos) { cache_size_block = 0; need_reset = false; goto bad; } /* I, Michel Machado, define that any drive with less than * this number of blocks is fake. */ mid_drive_pos = clp2(right_pos / 2); assert(left_pos < mid_drive_pos); assert(mid_drive_pos < right_pos); /* This call is needed due to rand(). */ srand(time(NULL)); salt = uint64_rand(); if (find_cache_size(dev, mid_drive_pos - 1, &right_pos, &cache_size_block, &need_reset, &good_drive, salt)) goto bad; assert(mid_drive_pos <= right_pos); reset_pos = right_pos; if (find_wrap(dev, left_pos, &right_pos, reset_pos, cache_size_block, need_reset, salt)) goto bad; wrap = ceiling_log2(right_pos << block_order); init_bisect_stats(&stats); if (!good_drive) { if (mid_drive_pos < right_pos) right_pos = mid_drive_pos; if (bisect(dev, &stats, left_pos, &right_pos, reset_pos, cache_size_block, need_reset, salt)) goto bad; } do { if (find_a_bad_block(dev, left_pos, &right_pos, &found_a_bad_block, reset_pos, cache_size_block, need_reset, salt)) goto bad; if (found_a_bad_block && bisect(dev, &stats, left_pos, &right_pos, reset_pos, cache_size_block, need_reset, salt)) goto bad; } while (found_a_bad_block); if (right_pos == left_pos + 1) { /* Bad drive. */ right_pos = 0; } *preal_size_byte = right_pos << block_order; *pwrap = wrap; goto out; bad: *preal_size_byte = 0; *pwrap = ceiling_log2(dev_size_byte); out: *pannounced_size_byte = dev_size_byte; *pcache_size_block = cache_size_block; *pneed_reset = need_reset; *pblock_order = block_order; return false; } f3-6.0/libprobe.h000066400000000000000000000005501263631517700136510ustar00rootroot00000000000000#ifndef HEADER_LIBPROBE_H #define HEADER_LIBPROBE_H #include #include "libdevs.h" uint64_t probe_device_max_blocks(struct device *dev); int probe_device(struct device *dev, uint64_t *preal_size_byte, uint64_t *pannounced_size_byte, int *pwrap, uint64_t *pcache_size_block, int *pneed_reset, int *pblock_order); #endif /* HEADER_LIBPROBE_H */ f3-6.0/libutils.c000066400000000000000000000112651263631517700137020ustar00rootroot00000000000000#include /* For fprintf(). */ #include /* For strtoll(). */ #include #include #include "libutils.h" #include "version.h" /* Count the number of 1 bits. */ static int pop(uint64_t x) { int n = 0; while (x) { n++; x = x & (x - 1); } return n; } int ilog2(uint64_t x) { x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); x = x | (x >> 32); return pop(x) - 1; } uint64_t clp2(uint64_t x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); x = x | (x >> 32); return x + 1; } const char *adjust_unit(double *ptr_bytes) { const char *units[] = { "Byte", "KB", "MB", "GB", "TB", "PB", "EB" }; int i = 0; double final = *ptr_bytes; while (i < 7 && final >= 1024) { final /= 1024; i++; } *ptr_bytes = final; return units[i]; } #define USEC_IN_A_MSEC 1000ULL #define USEC_IN_A_SEC (1000*USEC_IN_A_MSEC) #define USEC_IN_A_MIN (60*USEC_IN_A_SEC) #define USEC_IN_AN_HOUR (60*USEC_IN_A_MIN) #define USEC_IN_A_DAY (24*USEC_IN_AN_HOUR) int usec_to_str(uint64_t usec, char *str) { int has_d, has_h, has_m, has_s; lldiv_t div; int c, tot = 0; has_d = usec >= USEC_IN_A_DAY; if (has_d) { div = lldiv(usec, USEC_IN_A_DAY); usec = div.rem; c = sprintf(str + tot, "%i days", (int)div.quot); assert(c > 0); tot += c; } has_h = usec >= USEC_IN_AN_HOUR; if (has_h) { div = lldiv(usec, USEC_IN_AN_HOUR); usec = div.rem; c = sprintf(str + tot, "%s%i:", has_d ? " " : "", (int)div.quot); assert(c > 0); tot += c; } has_m = has_h || usec >= USEC_IN_A_MIN; if (has_m) { div = lldiv(usec, USEC_IN_A_MIN); usec = div.rem; if (has_h) c = sprintf(str + tot, "%02i", (int)div.quot); else c = sprintf(str + tot, "%i'", (int)div.quot); assert(c > 0); tot += c; } has_s = usec >= USEC_IN_A_SEC; if (has_s) { div = lldiv(usec, USEC_IN_A_SEC); usec = div.rem; if (has_h) c = sprintf(str + tot, ":%02i", (int)div.quot); else if (has_m) c = sprintf(str + tot, "%02i\"", (int)div.quot); else if (has_d) c = sprintf(str + tot, "%is", (int)div.quot); else c = sprintf(str + tot, "%i.%02is", (int)div.quot, (int)(usec / (10 * USEC_IN_A_MSEC))); assert(c > 0); tot += c; } if (has_d || has_h || has_m || has_s) return tot; if (usec >= USEC_IN_A_MSEC) { div = lldiv(usec, USEC_IN_A_MSEC); usec = div.rem; c = sprintf(str + tot, "%i.%ims", (int)div.quot, (int)(usec / 100)); } else { c = sprintf(str + tot, "%ius", (int)usec); } assert(c > 0); tot += c; return tot; } void *align_mem(void *p, int order) { uintptr_t ip = (uintptr_t)p; uintptr_t head = align_head(order); return (void *)( (ip + head) & ~head ); } void print_header(FILE *f, const char *name) { fprintf(f, "F3 %s " F3_STR_VERSION "\n" "Copyright (C) 2010 Digirati Internet LTDA.\n" "This is free software; see the source for copying conditions.\n" "\n", name); } long long arg_to_ll_bytes(const struct argp_state *state, const char *arg) { char *end; long long ll = strtoll(arg, &end, 0); if (end == arg) argp_error(state, "An integer must be provided"); /* Deal with units. */ switch (*end) { case 's': case 'S': /* Sectors */ ll <<= 9; end++; break; case 'k': case 'K': /* KB */ ll <<= 10; end++; break; case 'm': case 'M': /* MB */ ll <<= 20; end++; break; case 'g': case 'G': /* GB */ ll <<= 30; end++; break; case 't': case 'T': /* TB */ ll <<= 40; end++; break; } if (*end) argp_error(state, "`%s' is not an integer", arg); return ll; } static inline uint64_t next_random_number(uint64_t random_number) { return random_number * 4294967311ULL + 17; } void fill_buffer_with_block(void *buf, int block_order, uint64_t offset, uint64_t salt) { uint64_t *int64_array = buf; int i, num_int64 = 1 << (block_order - 3); uint64_t random_number = offset ^ salt; assert(block_order >= 9); /* The offset is known by drives, * so one doesn't have to encrypt it. * Plese don't add @salt here! */ int64_array[0] = offset; /* Thanks to @salt, a drive has to guess the seeed. */ for (i = 1; i < num_int64; i++) int64_array[i] = random_number = next_random_number(random_number); } int validate_buffer_with_block(const void *buf, int block_order, uint64_t *pfound_offset, uint64_t salt) { const uint64_t *int64_array = buf; int i, num_int64 = 1 << (block_order - 3); uint64_t found_offset = int64_array[0]; uint64_t random_number = found_offset ^ salt; assert(block_order >= 9); for (i = 1; i < num_int64; i++) { random_number = next_random_number(random_number); if (int64_array[i] != random_number) return true; } *pfound_offset = found_offset; return false; } f3-6.0/libutils.h000066400000000000000000000032421263631517700137030ustar00rootroot00000000000000#ifndef HEADER_LIBUTILS_H #define HEADER_LIBUTILS_H #include #include /* For struct argp_state. */ #include /* For struct timeval. */ #define UNUSED(x) ((void)x) int ilog2(uint64_t x); /* Least power of 2 greater than or equal to x. */ uint64_t clp2(uint64_t x); static inline int ceiling_log2(uint64_t x) { return ilog2(clp2(x)); } const char *adjust_unit(double *ptr_bytes); #define TIME_STR_SIZE 128 int usec_to_str(uint64_t usec, char *str); /* * The functions align_head() and align_mem() are used to align pointers. * * The following example allocates two block on stack and makes sure that * the blocks are aligned with the block size. * * // The number 2 below means two blocks. * char stack[align_head(block_order) + (2 << block_order)]; * char *stamp_blk, *probe_blk; * stamp_blk = align_mem(stack, block_order); * probe_blk = stamp_blk + block_size; */ static inline int align_head(int order) { return (1 << order) - 1; } void *align_mem(void *p, int order); void print_header(FILE *f, const char *name); long long arg_to_ll_bytes(const struct argp_state *state, const char *arg); /* Dependent on the byte order of the processor (i.e. endianness). */ void fill_buffer_with_block(void *buf, int block_order, uint64_t offset, uint64_t salt); /* Dependent on the byte order of the processor (i.e. endianness). */ int validate_buffer_with_block(const void *buf, int block_order, uint64_t *pfound_offset, uint64_t salt); static inline uint64_t diff_timeval_us(const struct timeval *t1, const struct timeval *t2) { return (t2->tv_sec - t1->tv_sec) * 1000000ULL + t2->tv_usec - t1->tv_usec; } #endif /* HEADER_LIBUTILS_H */ f3-6.0/log-f3wr000077500000000000000000000002441263631517700132700ustar00rootroot00000000000000#!/bin/bash LOG=$1 $(dirname $0)/f3write "${@:2}" 2>&1 | tee -a "${LOG}" && \ echo -e "\n\n" >> "${LOG}" && \ $(dirname $0)/f3read "${@:2}" 2>&1 | tee -a "${LOG}" f3-6.0/utils.c000066400000000000000000000120501263631517700132040ustar00rootroot00000000000000#define _GNU_SOURCE #if __APPLE__ && __MACH__ #define _DARWIN_C_SOURCE #include /* For fcntl(). */ #endif /* Apple Macintosh */ #include #include #include #include #include #include #include #include #include #include #include "version.h" #include "utils.h" const char *adjust_unit(double *ptr_bytes) { const char *units[] = { "Byte", "KB", "MB", "GB", "TB", "PB", "EB" }; int i = 0; double final = *ptr_bytes; while (i < 7 && final >= 1024) { final /= 1024; i++; } *ptr_bytes = final; return units[i]; } int is_my_file(const char *filename) { const char *p = filename; if (!p || !isdigit(*p)) return 0; /* Skip digits. */ do { p++; } while (isdigit(*p)); return (p[0] == '.') && (p[1] == 'h') && (p[2] == '2') && (p[3] == 'w') && (p[4] == '\0'); } char *full_fn_from_number(const char **filename, const char *path, long num) { char *str; assert(asprintf(&str, "%s/%li.h2w", path, num + 1) > 0); *filename = str + strlen(path) + 1; return str; } /* Parse @param and return the start-at parameter. * The string must be of the format "--start-at=NUM"; otherwise it returns -1. */ #define START_AT_TEXT "--start-at=" #define END_AT_TEXT "--end-at=" static inline int is_param(const char *text, const char *param) { return !strncmp(param, text, strlen(text)); } static long parse_long_param(const char *param) { char *endptr; long value; /* Skip text. */ while (*param != '=') { if (*param == '\0') return -1; param++; } param++; /* Skip '='. */ value = strtol(param, &endptr, 10); if (*endptr != '\0') return -1; return (value <= 0 || value == LONG_MAX) ? -1 : value - 1; } static int parse_param(const char *param, long *pstart_at, long *pend_at) { if (is_param(START_AT_TEXT, param)) *pstart_at = parse_long_param(param); else if (is_param(END_AT_TEXT, param)) *pend_at = parse_long_param(param); else return 1; return 0; } int parse_args(const char *name, int argc, char **argv, long *pstart_at, long *pend_at, const char **ppath) { *pstart_at = 0; *pend_at = LONG_MAX - 1; switch (argc) { case 2: *ppath = argv[1]; break; case 3: if (parse_param(argv[1], pstart_at, pend_at)) goto error; *ppath = argv[2]; break; case 4: if (parse_param(argv[1], pstart_at, pend_at)) goto error; if (parse_param(argv[2], pstart_at, pend_at)) goto error; *ppath = argv[3]; break; default: goto error; } if (*pstart_at >= 0 && *pend_at >= 0 && *pstart_at <= *pend_at) return 0; error: print_header(stderr, name); fprintf(stderr, "Usage: f3%s [%sNUM] [%sNUM] \n", name, START_AT_TEXT, END_AT_TEXT); return 1; } static long number_from_filename(const char *filename) { const char *p; long num; assert(is_my_file(filename)); p = filename; num = 0; do { num = num * 10 + (*p - '0'); p++; } while (isdigit(*p)); return num - 1; } /* Don't call this function directly, use ls_my_files() instead. */ static long *__ls_my_files(DIR *dir, long start_at, long end_at, int *pcount, int *pindex) { struct dirent *entry; const char *filename; long number, *ret; int my_index; entry = readdir(dir); if (!entry) { ret = malloc(sizeof(long) * (*pcount + 1)); assert(ret); *pindex = *pcount - 1; ret[*pcount] = -1; closedir(dir); return ret; } filename = entry->d_name; if (!is_my_file(filename)) return __ls_my_files(dir, start_at, end_at, pcount, pindex); /* Cache @number because @entry may go away. */ number = number_from_filename(filename); /* Ignore files before @start_at and after @end_at. */ if (number < start_at || end_at < number) return __ls_my_files(dir, start_at, end_at, pcount, pindex); (*pcount)++; ret = __ls_my_files(dir, start_at, end_at, pcount, &my_index); ret[my_index] = number; *pindex = my_index - 1; return ret; } /* To be used with qsort(3). */ static int cmpintp(const void *p1, const void *p2) { return *(const long *)p1 - *(const long *)p2; } const long *ls_my_files(const char *path, long start_at, long end_at) { DIR *dir = opendir(path); int my_count; int my_index; long *ret; if (!dir) err(errno, "Can't open path %s", path); my_count = 0; ret = __ls_my_files(dir, start_at, end_at, &my_count, &my_index); assert(my_index == -1); qsort(ret, my_count, sizeof(*ret), cmpintp); return ret; } void print_header(FILE *f, const char *name) { fprintf(f, "F3 %s " F3_STR_VERSION "\n" "Copyright (C) 2010 Digirati Internet LTDA.\n" "This is free software; see the source for copying conditions.\n" "\n", name); } #if __APPLE__ && __MACH__ /* This function is a _rough_ approximation of fdatasync(2). */ int fdatasync(int fd) { return fcntl(fd, F_FULLFSYNC); } /* This function is a _rough_ approximation of posix_fadvise(2). */ int posix_fadvise(int fd, off_t offset, off_t len, int advice) { UNUSED(offset); UNUSED(len); switch (advice) { case POSIX_FADV_SEQUENTIAL: return fcntl(fd, F_RDAHEAD, 1); case POSIX_FADV_DONTNEED: return fcntl(fd, F_NOCACHE, 1); default: assert(0); } } #endif /* Apple Macintosh */ f3-6.0/utils.h000066400000000000000000000026721263631517700132220ustar00rootroot00000000000000#ifndef HEADER_UTILS_H #define HEADER_UTILS_H #include /* For type FILE. */ #include /* For struct timeval. */ #include /* For type uint64_t. */ #define SECTOR_SIZE (512) #define GIGABYTES (1024 * 1024 * 1024) const char *adjust_unit(double *ptr_bytes); /* Return true if @filename matches the regex /^[0-9]+\.h2w$/ */ int is_my_file(const char *filename); /* Caller must free(3) the returned pointer. */ char *full_fn_from_number(const char **filename, const char *path, long num); static inline long delay_ms(const struct timeval *t1, const struct timeval *t2) { return (t2->tv_sec - t1->tv_sec) * 1000 + (t2->tv_usec - t1->tv_usec) / 1000; } int parse_args(const char *name, int argc, char **argv, long *pstart_at, long *pend_at, const char **ppath); const long *ls_my_files(const char *path, long start_at, long end_at); void print_header(FILE *f, const char *name); static inline uint64_t random_number(uint64_t prv_number) { return prv_number * 4294967311ULL + 17; } #define UNUSED(x) ((void)x) #if __APPLE__ && __MACH__ #include /* For type off_t. */ #define POSIX_FADV_SEQUENTIAL 2 /* Expect sequential page references. */ #define POSIX_FADV_DONTNEED 4 /* Don't need these pages. */ int fdatasync(int fd); int posix_fadvise(int fd, off_t offset, off_t len, int advice); #endif /* Apple Macintosh */ #ifdef __FreeBSD__ #define fdatasync(fd) fsync(fd) #endif #endif /* HEADER_UTILS_H */ f3-6.0/version.h000066400000000000000000000001571263631517700135430ustar00rootroot00000000000000#ifndef HEADER_VERSION_H #define HEADER_VERSION_H #define F3_STR_VERSION "6.0" #endif /* HEADER_VERSION_H */