pax_global_header 0000666 0000000 0000000 00000000064 14771250033 0014514 g ustar 00root root 0000000 0000000 52 comment=8439d3a5f4abf1b057986be8876922b5d58474ed
f3-9.0/ 0000775 0000000 0000000 00000000000 14771250033 0011674 5 ustar 00root root 0000000 0000000 f3-9.0/.github/ 0000775 0000000 0000000 00000000000 14771250033 0013234 5 ustar 00root root 0000000 0000000 f3-9.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14771250033 0015271 5 ustar 00root root 0000000 0000000 f3-9.0/.github/workflows/test.yml 0000664 0000000 0000000 00000006366 14771250033 0017006 0 ustar 00root root 0000000 0000000 ---
name: Test
on:
push:
branches:
- master
pull_request: {}
jobs:
Linux:
strategy:
fail-fast: false
matrix:
volume:
- /tmp
- .
- relative-path
- /
asroot:
- name: ''
sudo: ''
- name: ' as root'
sudo: 'sudo '
name: Linux ${{ matrix.volume }}${{ matrix.asroot.name }}
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- run: sudo apt-get install -y libparted-dev libudev-dev
- run: make all extra
- if: matrix.volume == 'relative-path'
run: mkdir relative-path
- if: matrix.volume == '/'
run: sudo chmod a+w /
- run: ./f3write -V
- run: ./f3write --help
- run: ${{ matrix.asroot.sudo }}./f3write -s 2 -e 4 -w 50000 ${{ matrix.volume }}
- run: stat ${{ matrix.volume }}/2.h2w
- run: stat ${{ matrix.volume }}/3.h2w
- run: stat ${{ matrix.volume }}/4.h2w
- run: ./f3read -V
- run: ./f3read --help
- run: ${{ matrix.asroot.sudo }}./f3read -s 2 -e 4 -r 50000 ${{ matrix.volume }}
MacOS:
strategy:
fail-fast: false
matrix:
volume:
- /tmp
- .
- relative-path
# MacOS denies `sudo chmod a+w /`
#- /
asroot:
- name: ''
sudo: ''
- name: ' as root'
sudo: 'sudo '
name: MacOS ${{ matrix.volume }}${{ matrix.asroot.name }}
runs-on: macos-12
steps:
- uses: actions/checkout@v3
- run: brew install argp-standalone
- run: make
- if: matrix.volume == 'relative-path'
run: mkdir relative-path
- run: ./f3write -V
- run: ./f3write --help
- run: ${{ matrix.asroot.sudo }}./f3write -s 2 -e 4 -w 50000 ${{ matrix.volume }}
- run: stat ${{ matrix.volume }}/2.h2w
- run: stat ${{ matrix.volume }}/3.h2w
- run: stat ${{ matrix.volume }}/4.h2w
- run: ./f3read -V
- run: ./f3read --help
- run: ${{ matrix.asroot.sudo }}./f3read -s 2 -e 4 -r 50000 ${{ matrix.volume }}
Cygwin:
strategy:
fail-fast: false
matrix:
volume:
- cygwin: /cygdrive/c
windows: 'C:'
- cygwin: .
windows: .
- cygwin: relative-path
windows: relative-path
- cygwin: /
windows: 'C:\cygwin'
name: Cygwin ${{ matrix.volume.cygwin }}
runs-on: windows-2022
steps:
- uses: actions/checkout@v3
- uses: cygwin/cygwin-install-action@v2
with:
packages: gcc-core libargp-devel make
- run: "$Env:LDFLAGS = '-Wl,--stack,4000000'; make"
- if: matrix.volume.windows == 'relative-path'
run: New-Item -ItemType Directory -Path relative-path
- run: '& .\f3write.exe -V'
- run: '& .\f3write.exe --help'
- run: '& .\f3write.exe -s 2 -e 4 -w 50000 ${{ matrix.volume.cygwin }}'
- run: 'Get-Item ${{ matrix.volume.windows }}\2.h2w'
- run: 'Get-Item ${{ matrix.volume.windows }}\3.h2w'
- run: 'Get-Item ${{ matrix.volume.windows }}\4.h2w'
- run: '& .\f3read.exe -V'
- run: '& .\f3read.exe --help'
- run: '& .\f3read.exe -s 2 -e 4 -r 50000 ${{ matrix.volume.cygwin }}'
f3-9.0/.gitignore 0000664 0000000 0000000 00000000050 14771250033 0013657 0 ustar 00root root 0000000 0000000 cscope.out
*.swp
*.d
*.o
*~
doc/_build f3-9.0/Dockerfile 0000664 0000000 0000000 00000000456 14771250033 0013673 0 ustar 00root root 0000000 0000000 FROM ubuntu:22.04
RUN apt-get update && \
apt-get install -y --no-install-recommends \
gcc \
less \
libparted-dev \
libudev1 \
libudev-dev \
make \
udev
COPY . /f3
WORKDIR /f3
RUN make install
RUN make install-extra
CMD less README.rst
f3-9.0/LICENSE 0000664 0000000 0000000 00000104515 14771250033 0012707 0 ustar 00root root 0000000 0000000 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-9.0/Makefile 0000664 0000000 0000000 00000002610 14771250033 0013333 0 ustar 00root root 0000000 0000000 CC ?= gcc
CFLAGS += -std=c99 -Wall -Wextra -pedantic -MMD -ggdb
TARGETS = f3write f3read
EXTRA_TARGETS = f3probe f3brew f3fix
PREFIX = /usr/local
INSTALL = install
LN = ln
ifndef OS
OS = $(shell uname -s)
endif
ifneq ($(OS), Linux)
ARGP = /usr/local
ifeq ($(OS), Darwin)
ifneq ($(shell command -v brew),)
ARGP = $(shell brew --prefix)
endif
endif
CFLAGS += -I$(ARGP)/include
LDFLAGS += -L$(ARGP)/lib -largp
endif
all: $(TARGETS)
extra: $(EXTRA_TARGETS)
docker:
docker build -f Dockerfile -t f3:latest .
install: all
$(INSTALL) -d $(DESTDIR)$(PREFIX)/bin
$(INSTALL) -m755 $(TARGETS) $(DESTDIR)$(PREFIX)/bin
$(INSTALL) -d $(DESTDIR)$(PREFIX)/share/man/man1
$(INSTALL) -m644 f3read.1 $(DESTDIR)$(PREFIX)/share/man/man1
$(LN) -sf f3read.1 $(DESTDIR)$(PREFIX)/share/man/man1/f3write.1
install-extra: extra
$(INSTALL) -d $(DESTDIR)$(PREFIX)/bin
$(INSTALL) -m755 $(EXTRA_TARGETS) $(DESTDIR)$(PREFIX)/bin
f3write: utils.o libflow.o f3write.o
$(CC) -o $@ $^ $(LDFLAGS) -lm
f3read: utils.o libflow.o f3read.o
$(CC) -o $@ $^ $(LDFLAGS) -lm
f3probe: libutils.o libdevs.o libprobe.o f3probe.o
$(CC) -o $@ $^ $(LDFLAGS) -lm -ludev
f3brew: libutils.o libdevs.o f3brew.o
$(CC) -o $@ $^ $(LDFLAGS) -lm -ludev
f3fix: libutils.o f3fix.o
$(CC) -o $@ $^ $(LDFLAGS) -lparted
-include *.d
PHONY: cscope clean
cscope:
cscope -b *.c *.h
clean:
rm -f *.o *.d cscope.out $(TARGETS) $(EXTRA_TARGETS)
f3-9.0/README.rst 0000664 0000000 0000000 00000030407 14771250033 0013367 0 ustar 00root root 0000000 0000000 f3 - Fight Flash Fraud
======================
f3 is a simple tool that tests flash cards capacity and performance to
see if they live up to claimed specifications. It fills the device with
pseudorandom data and then checks if it returns the same on reading.
F3 stands for Fight Flash Fraud, or Fight Fake Flash.
**Table of Contents**
- `Examples <#examples>`__
- `Installation <#installation>`__
- `Other resources <#other-resources>`__
.. _examples:
.. highlight:: console
Examples
========
We'll use :code:`/dev/sdX` as a placeholder here, you need to replace
:code:`X` with a lowercase letter so that it matches the device you
want to use.
:code:`lsblk` will show you an overview of your current devices.
Testing performance with f3read/f3write
---------------------------------------
Use these two programs in this order. f3write will write large files to
your mounted disk and f3read will check if the flash disk contains
exactly the written files::
$ ./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.
If you have installed f3read and f3write, you can remove the "./" that
is shown before their names.
Quick capacity tests with f3probe
---------------------------------
f3probe is the fastest drive test and suitable for large disks because
it only writes what's necessary to test the drive. It operates directly
on the (unmounted) block device and needs to be run as a privileged
user::
# ./f3probe --destructive --time-ops /dev/sdX
.. warning:: This will destroy any previously stored data on your disk!
Correcting capacity to actual size with f3fix
---------------------------------------------
f3fix creates a partition that fits the actual size of the fake drive.
Use f3probe's output to determine the parameters for f3fix::
# ./f3fix --last-sec=16477878 /dev/sdX
Installation
============
Download and Compile
--------------------
The files of the stable version of F3 are
`here `__. The
following command uncompresses the files::
$ unzip f3-9.0.zip
.. highlight:: bash
Compile stable software on Linux or FreeBSD
-------------------------------------------
To build::
make
If you want to install f3write and f3read, run the following command::
make install
Compile stable software on Windows/Cygwin
-----------------------------------------
f3write and f3read can be installed on Windows, but currently f3probe, f3fix,
and f3brew `require Linux <#the-extra-applications-for-linux>`__. To use them
on a Windows machine, use the `Docker Installation <#docker>`__. For f3write
and f3read, read on.
If you haven't already, install the following Cygwin packages and their dependencies:
- `gcc-core`
- `make`
- `libargp-devel`
To build, you need special flags::
export LDFLAGS="$LDFLAGS -Wl,--stack,4000000 -largp"
make
If you want to install f3write and f3read, run the following command::
make install
Compile stable software on Apple Mac
------------------------------------
f3write and f3read can be installed on Mac, but currently f3probe, f3fix, and
f3brew `require Linux <#the-extra-applications-for-linux>`__. To use them on
Mac, use the `Docker Installation <#docker>`__. For f3write and f3read, read
on.
Using HomeBrew
~~~~~~~~~~~~~~
If you have Homebrew already installed in your computer, the command
below will install F3::
brew install f3
Using MacPorts
~~~~~~~~~~~~~~
If you use MacPorts instead, use the following command::
port install f3
Compiling the latest development version from the source code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Most of the f3 source code builds fine using Xcode, the only dependency
missing is the GNU C library "argp". You can build argp from scratch, or
use the version provided by HomeBrew and MacPorts as "argp-standalone"
The following steps have been tested on OS X El Capitan 10.11.
1) Install Apple command line tools::
xcode-select --install
See http://osxdaily.com/2014/02/12/install-command-line-tools-mac-os-x/
for details.
2) Install Homebrew or MacPorts
HomeBrew::
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
See https://brew.sh/ for details.
MacPorts: https://www.macports.org/install.php
3) Install argp library::
brew install argp-standalone
See https://formulae.brew.sh/formula/argp-standalone and
https://www.freshports.org/devel/argp-standalone/ for more
information.
Or, for MacPorts::
port install argp-standalone
See https://trac.macports.org/browser/trunk/dports/sysutils/f3/Portfile
for more information.
4) Build F3::
When using Homebrew, you can just run::
make
When using MacPorts, you will need to pass the location where MacPorts
installed argp-standalone::
make ARGP=/opt/local
Docker
------
Quick Start
~~~~~~~~~~~
A pre-built `image `__
is available over at Docker Hub, ready to be used. With docker started, just
run::
docker run -it --rm --device peron/f3 []
For example, to probe a drive mounted at /dev/sdX::
docker run -it --rm --device /dev/sdX peron/f3 f3probe --destructive --time-ops /dev/sdX
Optionally, you can also build your own container *if* you don't want to use the
pre-built image. From this directory, run::
make docker
or::
docker build -t f3:latest .
To run f3 commands using your newly built Docker image::
docker run -it --rm --device f3:latest []
docker run -it --rm --device /dev/sdX f3:latest f3probe --destructive --time-ops /dev/sdX
docker run -it --rm -v /path/to/mounted/device:/mnt/ f3:latest f3write /mnt/
docker run -it --rm -v /path/to/mounted/device:/mnt/ f3:latest f3read /mnt/
Drive Permissions / Passthrough
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Getting the drive device to map into the Docker container is tricky for Mac and
Windows. Passing through devices on Mac and Windows is a well-documented issue
(`[github]
`__
`[stackexchange]
`__
`[tty]
`__)
On Linux it should just work, but on Mac or Windows, Docker tends to map the
drive as a normal directory rather than a mounted drive and you will get an
error like :code:`f3probe: Can't open device '/opt/usb': Is a directory`, that
is if you can map it at all.
To solve this, we can use docker-machine to create a VirtualBox VM
(boot2docker), in which to run the Docker container. Since VirtualBox *can*
handle device pass-through, we can pass the device through to the VirtualBox VM
which can then pass the device through to the Docker container. Milad Alizadeh
wrote up some good instructions `here
`__
which are geared towards USB devices, but it shouldn't be too hard to adapt to
other drive types. Here's what I typed into my Mac terminal (probably
similar for Windows, but untested)::
docker-machine create -d virtualbox default
docker-machine stop
vboxmanage modifyvm default --usb on
docker-machine start
vboxmanage usbfilter add 0 --target default --name flashdrive --vendorid 0x0123 --productid 0x4567
eval $(docker-machine env default)
For the usbfilter add command, note that the "name" argument is the new name
you're giving the filter so you can name it whatever you want.
:code:`--vendorid` and :code:`--productid` can be found on Mac in "System
Information" under "USB". You can also try searching for the right device in
:code:`vboxmanage list usbhost`.
Alternatively, you may opt to add the device through the VirtualBox GUI
application instead::
docker-machine create -d virtualbox default
docker-machine stop
# open VirtualBox and manually add the drive device before proceeding to the next command
docker-machine start
eval $(docker-machine env default)
Once you've run the above commands, unplug and replug the flash drive and run::
docker-machine ssh default "lsblk"
to list the devices. Search for the correct drive - the "SIZE" column may be
helpful in locating the device of interest. For example, :code:`sdb` is a common
mount point for a USB drive. Now you should be able to run the command from
Quick Start::
docker run --rm -it --device /dev/sdX peron/f3 f3probe --destructive --time-ops /dev/sdX
You may find it useful to enter a bash prompt in the Docker container to poke
around the filesystem::
docker run --rm -it --device /dev/sdX peron/f3 bash
so that you can run commands like :code:`ls /dev/*`.
The extra applications for Linux
--------------------------------
Install dependencies
~~~~~~~~~~~~~~~~~~~~
f3probe and f3brew require version 1 of the library libudev, and f3fix
requires version 0 of the library libparted to compile. On Ubuntu, you
can install these libraries with the following command::
sudo apt-get install libudev1 libudev-dev libparted-dev
If you are running a version of Ubuntu before 20.04.1, replace the package `libparted-dev`
on the command line above with `libparted0-dev`.
On Fedora, you can install these libraries with the following command::
sudo dnf install systemd-devel parted-devel
Compile the extra applications
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::
make extra
.. note::
- The extra applications are only compiled and tested on Linux
platform.
- Please do not e-mail me saying that you want the extra
applications to run on your platform; I already know that.
- If you want the extra applications to run on your platform, help
to port them, or find someone that can port them for you. If you
do port any of them, please send me a patch to help others.
- The extra applications are f3probe, f3brew, and f3fix.
If you want to install the extra applications, run the following
command::
make install-extra
Other resources
===============
Graphical User Interfaces
-------------------------
Thanks to our growing community of flash fraud fighters,
we have the following graphical user interfaces (GUI) available for F3:
`F3 QT `__ is a Linux GUI that uses
QT. F3 QT supports ``f3write``, ``f3read``, ``f3probe``, and ``f3fix``. Author:
Tianze.
`F3XSwift `__ is a Mac GUI. F3XSwift supports ``f3write`` and ``f3read``. Author:
Volker Runkel.
Please support the above projects by testing them and giving feedback to their
authors. This will improve their code as it has improved mine.
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.
Flakyflash
----------
If your flash isn't fraudulent (or you've run f3fix to "fix" it) but
you're still seeing some sporadic data corruption, then you may have
"flaky flash." If your flash is formatted using the FAT file system,
then you can use `Flakyflash `__
to find the flaky data clusters and mark them as bad in the FAT. This
may allow you to get a little more use out of your flash, but you
should still consider it as failing and replace it ASAP.
f3-9.0/changelog 0000664 0000000 0000000 00000006271 14771250033 0013554 0 ustar 00root root 0000000 0000000 Version 9.0 - Mar 27, 2025
* f3read/f3write: Avoid the execution stack to list files
* f3read/f3write: Add dynamic buffers
* f3read/f3write: chroot(2) to source/target dir if allowed
* Portability improvements for Ubuntu, ARM, OpenBSD, and Apple
* Automated test of the code with GitHub Actions
* Improved documentation
Version 8.0 - Oct 29, 2020
* f3read: add parameter --max-read-rate
* f3read: report speed, percentage, remaining time like f3write
* f3write: improve speed measurement (commit 791acdc32627...)
* f3probe: handle rare assertion failure (issue #82 ENODATA)
Version 7.2 - Jun 19, 2019
* f3write: keep up with extremely fast NVM drives (issue #117)
* f3write: improve measurement of write speed (issue #102)
* f3write: handle rare assertion failure (issue #111)
* f3probe: handle rare assertion failure (issue #82)
Version 7.1 - Jul 27, 2018
* fix compilation issues on non-Linux OSs
* f3write: make parameter --max-write-rate work precisely
* f3probe: change default reset type to RT_NONE
Version 7.0 - Dec 21, 2017
* stable version of f3probe, f3fix, and f3brew (Linux only)
* f3write: improved write speed and dealing with write failures
Version 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.
* formatted 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-9.0/doc/ 0000775 0000000 0000000 00000000000 14771250033 0012441 5 ustar 00root root 0000000 0000000 f3-9.0/doc/Makefile 0000664 0000000 0000000 00000016646 14771250033 0014116 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " epub3 to make an epub3"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
@echo " dummy to check syntax errors of document sources"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/f3.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/f3.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/f3"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/f3"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: epub3
epub3:
$(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3
@echo
@echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
.PHONY: dummy
dummy:
$(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy
@echo
@echo "Build finished. Dummy builder generates no files."
f3-9.0/doc/conf.py 0000664 0000000 0000000 00000027233 14771250033 0013747 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# f3 documentation build configuration file, created by
# sphinx-quickstart on Thu Nov 16 11:28:09 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'f3'
copyright = '2017, Michel Machado'
author = 'Michel Machado'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '9.0'
# The full version, including alpha/beta/rc tags.
release = '9.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Disable default code block language being set to Python.
highlight_language = 'none'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
html_theme_options = { 'show_related': True }
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# " v documentation" by default.
#
# html_title = 'f3 vX.0'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'f3doc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'f3.tex', 'f3 Documentation',
'Michel Machado', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'f3', 'f3 Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'f3', 'f3 Documentation',
author, 'f3', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The basename for the epub file. It defaults to the project name.
# epub_basename = project
# The HTML theme for the epub output. Since the default themes are not
# optimized for small screen space, using the same theme for HTML and epub
# output is usually not wise. This defaults to 'epub', a theme designed to save
# visual space.
#
# epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#
# epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#
# epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#
# epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#
# epub_pre_files = []
# HTML files that should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#
# epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#
# epub_tocdepth = 3
# Allow duplicate toc entries.
#
# epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#
# epub_tocscope = 'default'
# Fix unsupported image types using the Pillow.
#
# epub_fix_images = False
# Scale large images.
#
# epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# epub_show_urls = 'inline'
# If false, no index is generated.
#
# epub_use_index = True
f3-9.0/doc/contribute.rst 0000664 0000000 0000000 00000007457 14771250033 0015366 0 ustar 00root root 0000000 0000000 Contribute
==========
Help wanted
-----------
I maintain this project in my spare time, and I no longer have been able
to answer all questions and address all feedback that I receive.
Nevertheless, I still think that F3's users can stop flash
counterfeiters, but I need a little bit of help to keep moving forward.
How can you help?
- If F3 has helped you, consider signaling this to other users staring
F3 on `GitHub `__. The larger the number of stars a project has, the more
confident new users are to try it out.
- If you know a journalist, or are one, suggest to him or her writing
an article about fake flash. The media has not been covering this
subject, and having more users aware that fake flash exists will make
counterfeiters' life harder.
- If you own fake flash, consider donating them to me. I've been
working on ``f3probe`` to tell in a few seconds if a flash drive is
fake or not. I expect that ``f3probe`` will be a game changer, but I
lack a diverse set of fake flash samples to check my hypotheses.
Before you mail me the card, e-mail me the output you got from
``f3write``, ``f3read``, and (if possible) ``f3probe`` as well as the
size the card was expected to be; I'm trying to amass a diverse set
of fake flash, not necessarily a large number of them.
- If you know how to use F3 well on your platform, write a blog entry
about it, and let me know the link so I can post it on this page. You
can also send me your name and e-mail to publish on this page as
someone that can help other users of your platform.
- (New) If you have a dual-boot machine with Windows and Linux, write a
blog entry that compares h2testw, f3write/f3read, FakeFlashTest.exe,
and f3probe. If you do this comparison, please send me the link to
publish it on this page.
- If you are able to test F3 on your platform, send me your name and
e-mail, and I'll send to you a request to test new code when it is
available on GitHub before I release it as stable to everyone. I only
have Linux boxes, so other platforms are specially helpful.
- If you are able to code, improve F3. I want to keep the code small to
easily audit it, so focus on things that will either address a real
need, for example, users' requests, or to simplify the code, or fix
bugs, or make F3 work on a new platform, or improve the
documentation. If you want, I can list your contact on this page as
well, so people can reach out to you directly.
- If you know how to code a graphic user interface, please create one
for the platforms you can. This would increase the number of users
that, in turn, would win ground against the counterfeiters. I'll add a
link to your application on this page.
- Tell your friends about F3, teach them how to use it, publish a video
about F3, find ways to help me to better organize our efforts, spread
the word, ask for your money back when you buy a fake drive, etc.
I've originally implemented F3 to address a personal need, but you have
turned it into a great tool. Let's work closer to bring it to the next
level!
Repository
----------
The Git repository is kept `here `__.
Author
------
Michel Machado. E-mail me at michel at digirati dot com dot br.
Please try to figure out the solution for your question on your own, or
ask for help from a nearby friend before you e-mail me. My spare time is
very limited. For reporting bugs, requesting features, and making
suggestions, open an issue on GitHub
`here `__ to allow other users
to help me.
Copyright and License
---------------------
F3 is licensed under the `GNU General Public License (GPL) version
3 `__.
Copyright (c) 2010 `Digirati `__.
f3-9.0/doc/history.rst 0000664 0000000 0000000 00000005423 14771250033 0014700 0 ustar 00root root 0000000 0000000 History
=======
I started this project when I bought a 32GB microSDHC card for my
Android phone back in 2010, and found out that this card always fails
when one fills it up. Googling about this issue, I arrived at the blogs
`Fight Flash Fraud `__ and
`SOSFakeFlash `__, which recommend
the software H2testw (see
`here `__
or
`here `__)
to test flash memories.
I downloaded H2testw and found two issues with it: (1) it is for Windows
only, and (2) it is not open source. However, its author, Harald
Bögeholz, was kind enough to include a text file that explains what it
does, and provided the pseudo random number generator used in H2testw.
F3 is my GPLv3 implementation of the algorithm of H2testw,
and other tools that I have been implementing to speed up the
identification of fake drives as well as making them usable:
``f3probe``, ``f3fix``, and ``f3brew``. My implementation of H2testw,
which I've broken into two applications named ``f3write`` and
``f3read``, runs on Linux, Macs, Windows/Cygwin, and FreeBSD.
``f3probe`` is the fastest way to identify fake drives and their real
sizes. ``f3fix`` enables users to use the real capacity of fake drives
without losing data. ``f3brew`` helps developers to infer how fake
drives work. ``f3probe``, ``f3fix``, and ``f3brew`` currently runs only
on Linux.
Change log
----------
Starting at version 2.0, F3 supports the platform Mac. Mac users may
want to check out Thijs Kuipers'
`page `__
for help.
Starting at version 3.0, F3 supports the platform Windows/Cygwin, and
adopts H2testw's file format. People interested in exchanging files
between F3 and H2testw should read the `section <#comp_h2testw>`__ about
it to understand the caveats.
Starting at version 4.0, F3 supports the platform FreeBSD. **Mac
users:** Version 4.0 does not compile on Macs. The issue has been fixed
on version 5.0.
Starting at version 5.0, F3 includes ``f3probe`` and ``f3fix`` as
experimental, and for Linux only.
Starting at version 6.0, F3 includes ``f3brew`` as experimental, and for
Linux only. Linux users may want to check out Vasiliy Kaygorodov's
`page `__
or Ahmed Essam's
`page `__
for help.
Starting at version 7.0, ``f3probe``, ``f3fix``, and ``f3brew`` are stable.
They are for Linux only.
f3-9.0/doc/index.rst 0000664 0000000 0000000 00000000673 14771250033 0014310 0 ustar 00root root 0000000 0000000 .. f3 documentation master file, created by
sphinx-quickstart on Thu Nov 16 11:28:09 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
f3 - Fight Flash Fraud
======================
Contents:
.. toctree::
:maxdepth: 2
introduction
usage
history
contribute
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
f3-9.0/doc/introduction.rst 0000777 0000000 0000000 00000000000 14771250033 0017611 2../README.rst ustar 00root root 0000000 0000000 f3-9.0/doc/usage.rst 0000664 0000000 0000000 00000112224 14771250033 0014301 0 ustar 00root root 0000000 0000000 Usage
=====
.. contents::
.. highlight:: console
How to use f3write and f3read
-----------------------------
If you prefer watching a video than reading the text below, check out
Spatry's Cup of Linux's video demo of F3 on YouTube
`here `__.
My implementation of H2testw is composed of two applications:
``f3write``, and ``f3read``. ``f3write`` fills a file system up with 1GB
files named N.h2w, where N is a number. Whereas, ``f3read`` validates
those files. If the content of all N.h2w files is valid, the drive is
fine. The last file may be less than 1GB since ``f3write`` takes all
available space for data. Below the result on my fake card:
::
$ ./f3write /media/michel/5EBD-5C80/
Free space: 28.83 GB
Creating file 1.h2w ... OK!
Creating file 2.h2w ... OK!
Creating file 3.h2w ... OK!
Creating file 4.h2w ... OK!
Creating file 5.h2w ... OK!
Creating file 6.h2w ... OK!
Creating file 7.h2w ... OK!
Creating file 8.h2w ... OK!
Creating file 9.h2w ... OK!
Creating file 10.h2w ... OK!
Creating file 11.h2w ... OK!
Creating file 12.h2w ... OK!
Creating file 13.h2w ... OK!
Creating file 14.h2w ... OK!
Creating file 15.h2w ... OK!
Creating file 16.h2w ... OK!
Creating file 17.h2w ... OK!
Creating file 18.h2w ... OK!
Creating file 19.h2w ... OK!
Creating file 20.h2w ... OK!
Creating file 21.h2w ... OK!
Creating file 22.h2w ... OK!
Creating file 23.h2w ... OK!
Creating file 24.h2w ... OK!
Creating file 25.h2w ... OK!
Creating file 26.h2w ... OK!
Creating file 27.h2w ... OK!
Creating file 28.h2w ... OK!
Creating file 29.h2w ... OK!
Free space: 0.00 Byte
Average Writing speed: 2.60 MB/s
$ ./f3read /media/michel/5EBD-5C80/
SECTORS ok/corrupted/changed/overwritten
Validating file 1.h2w ... 0/ 2097152/ 0/ 0
Validating file 2.h2w ... 0/ 2097152/ 0/ 0
Validating file 3.h2w ... 0/ 2097152/ 0/ 0
Validating file 4.h2w ... 0/ 2097152/ 0/ 0
Validating file 5.h2w ... 0/ 2097152/ 0/ 0
Validating file 6.h2w ... 0/ 2097152/ 0/ 0
Validating file 7.h2w ... 0/ 2097152/ 0/ 0
Validating file 8.h2w ... 0/ 2097152/ 0/ 0
Validating file 9.h2w ... 0/ 2097152/ 0/ 0
Validating file 10.h2w ... 0/ 2097152/ 0/ 0
Validating file 11.h2w ... 0/ 2097152/ 0/ 0
Validating file 12.h2w ... 0/ 2097152/ 0/ 0
Validating file 13.h2w ... 0/ 2097152/ 0/ 0
Validating file 14.h2w ... 0/ 2097152/ 0/ 0
Validating file 15.h2w ... 0/ 2097152/ 0/ 0
Validating file 16.h2w ... 0/ 2097152/ 0/ 0
Validating file 17.h2w ... 0/ 2097152/ 0/ 0
Validating file 18.h2w ... 0/ 2097152/ 0/ 0
Validating file 19.h2w ... 0/ 2097152/ 0/ 0
Validating file 20.h2w ... 0/ 2097152/ 0/ 0
Validating file 21.h2w ... 0/ 2097152/ 0/ 0
Validating file 22.h2w ... 0/ 2097152/ 0/ 0
Validating file 23.h2w ... 0/ 2097152/ 0/ 0
Validating file 24.h2w ... 1916384/ 180768/ 0/ 0
Validating file 25.h2w ... 186816/ 1910336/ 0/ 0
Validating file 26.h2w ... 0/ 2097152/ 0/ 0
Validating file 27.h2w ... 0/ 2097152/ 0/ 0
Validating file 28.h2w ... 0/ 2097152/ 0/ 0
Validating file 29.h2w ... 28224/ 1705280/ 0/ 0
Data OK: 1.02 GB (2131424 sectors)
Data LOST: 27.81 GB (58322336 sectors)
Corrupted: 27.81 GB (58322336 sectors)
Slightly changed: 0.00 Byte (0 sectors)
Overwritten: 0.00 Byte (0 sectors)
Average Reading speed: 9.54 MB/s
This report shows that my flash card is pretty much garbage since it can
only hold 1.02GB. ``f3write`` only writes to free space, and will not
overwrite existing files as long as they aren't named N.h2w. However, as
the previous report shows, files from 1.h2w to 23.h2w were written
before 24.h2w and yet had all their content destroyed. Therefore, it is
not wise to test nonempty cards because if the card has a problem, it
may erase the old files.
When ``f3read`` reads a sector (i.e. 512 bytes, the unit of
communication with the card), ``f3read`` can check if the sector was
correctly written by ``f3write``, and figure out in which file the
sector should be and in which position in that file the sector should
be. Thus, if a sector is well formed, or with a few bits flipped, but
read in an unexpected position, ``f3read`` counts it as overwritten.
Slightly changed sectors, are sectors at right position with a few bits
flipped.
Notice that ``f3write`` doesn't overwrite sectors by itself, it's done
by the drive as a way to difficult a user to uncover its fault. The way
the drive overwrites sectors is arbitrary. From the point of view of a
file system, what ``f3read`` sees, the way the drive wraps around seems
often contrived, but, from the drive's view, it is just an address
manipulation.
The last lines of the output of ``f3write`` and ``f3read`` provide good
estimates of the writing and reading speeds of the tested card. This
information can be used to check if the claimed class of the card is
correct. Check this
`link `__ out for
more information about classes. Note that the speeds provided by F3 are
estimates, don't take them as perfect since they suffer influence even
from other processes in your machine. Also, be aware that your card
reader and USB port can limit the throughput of the drive.
Later I bought a second card that works just fine; I got the following
output running F3 on it:
::
$ ./f3write /media/michel/6135-3363/
Free space: 29.71 GB
Creating file 1.h2w ... OK!
Creating file 2.h2w ... OK!
Creating file 3.h2w ... OK!
Creating file 4.h2w ... OK!
Creating file 5.h2w ... OK!
Creating file 6.h2w ... OK!
Creating file 7.h2w ... OK!
Creating file 8.h2w ... OK!
Creating file 9.h2w ... OK!
Creating file 10.h2w ... OK!
Creating file 11.h2w ... OK!
Creating file 12.h2w ... OK!
Creating file 13.h2w ... OK!
Creating file 14.h2w ... OK!
Creating file 15.h2w ... OK!
Creating file 16.h2w ... OK!
Creating file 17.h2w ... OK!
Creating file 18.h2w ... OK!
Creating file 19.h2w ... OK!
Creating file 20.h2w ... OK!
Creating file 21.h2w ... OK!
Creating file 22.h2w ... OK!
Creating file 23.h2w ... OK!
Creating file 24.h2w ... OK!
Creating file 25.h2w ... OK!
Creating file 26.h2w ... OK!
Creating file 27.h2w ... OK!
Creating file 28.h2w ... OK!
Creating file 29.h2w ... OK!
Creating file 30.h2w ... OK!
Free space: 0.00 Byte
Average Writing speed: 4.90 MB/s
$ ./f3read /media/michel/6135-3363/
SECTORS ok/corrupted/changed/overwritten
Validating file 1.h2w ... 2097152/ 0/ 0/ 0
Validating file 2.h2w ... 2097152/ 0/ 0/ 0
Validating file 3.h2w ... 2097152/ 0/ 0/ 0
Validating file 4.h2w ... 2097152/ 0/ 0/ 0
Validating file 5.h2w ... 2097152/ 0/ 0/ 0
Validating file 6.h2w ... 2097152/ 0/ 0/ 0
Validating file 7.h2w ... 2097152/ 0/ 0/ 0
Validating file 8.h2w ... 2097152/ 0/ 0/ 0
Validating file 9.h2w ... 2097152/ 0/ 0/ 0
Validating file 10.h2w ... 2097152/ 0/ 0/ 0
Validating file 11.h2w ... 2097152/ 0/ 0/ 0
Validating file 12.h2w ... 2097152/ 0/ 0/ 0
Validating file 13.h2w ... 2097152/ 0/ 0/ 0
Validating file 14.h2w ... 2097152/ 0/ 0/ 0
Validating file 15.h2w ... 2097152/ 0/ 0/ 0
Validating file 16.h2w ... 2097152/ 0/ 0/ 0
Validating file 17.h2w ... 2097152/ 0/ 0/ 0
Validating file 18.h2w ... 2097152/ 0/ 0/ 0
Validating file 19.h2w ... 2097152/ 0/ 0/ 0
Validating file 20.h2w ... 2097152/ 0/ 0/ 0
Validating file 21.h2w ... 2097152/ 0/ 0/ 0
Validating file 22.h2w ... 2097152/ 0/ 0/ 0
Validating file 23.h2w ... 2097152/ 0/ 0/ 0
Validating file 24.h2w ... 2097152/ 0/ 0/ 0
Validating file 25.h2w ... 2097152/ 0/ 0/ 0
Validating file 26.h2w ... 2097152/ 0/ 0/ 0
Validating file 27.h2w ... 2097152/ 0/ 0/ 0
Validating file 28.h2w ... 2097152/ 0/ 0/ 0
Validating file 29.h2w ... 2097152/ 0/ 0/ 0
Validating file 30.h2w ... 1491904/ 0/ 0/ 0
Data OK: 29.71 GB (62309312 sectors)
Data LOST: 0.00 Byte (0 sectors)
Corrupted: 0.00 Byte (0 sectors)
Slightly changed: 0.00 Byte (0 sectors)
Overwritten: 0.00 Byte (0 sectors)
Average Reading speed: 9.42 MB/s
Since ``f3write`` and ``f3read`` are independent, ``f3read`` can be used
as many times as one wants, although ``f3write`` is needed only once.
This allows one to easily repeat a test of a card as long as the N.h2w
files are still available.
As a final remark, if you want to run ``f3write`` and ``f3read`` with a
single command, check out the ``log-f3wr`` shell script
`here `__.
This script runs ``f3write`` and ``f3read``, and records their output
into a log file. Use example:
``log-f3wr log-filename /media/michel/5EBD-5C80/``
.. raw:: html
.. raw:: html
Users' notes
~~~~~~~~~~~~
Randy Champoux has brought to my attention that ``f3read`` could
eventually read data from the system cache instead of from the flash
card. Since version 2.0, F3 eliminates this possibility as long as the
kernel honors the system call ``posix_fadvise(2)`` with advice
``POSIX_FADV_DONTNEED``. Linux has and honor
``posix_fadvise(2)/POSIX_FADV_DONTNEED``, the Mac does not have the
system call, and I don't know if Windows/Cygwin, or FreeBSD honors it.
In doubt about this issue, just disconnect and connect back the device
after ``f3write`` runs and before calling ``f3read``.
Notice that the issue pointed by Randy Champoux is entirely an OS
matter, that is, it doesn't change if the drive being tested is fake or
not. In 2014, I've run into a "smarter" fake card that tries hard to
behave like a good one using its internal cache to fool the test. In
practice, these newer cards can only mislead ``f3read`` with a limited
number of blocks, but those looking for a precise, repeatable report
should follow the advice of disconnecting and connecting back the device
before ``f3read`` runs. Consider the real example of a fake drive that
presents this behavior. The drive announces a size of 128GB but its real
capacity is less than 8GB:
::
$ ./f3write --end-at=16 /media/michel/DISK_IMG/ && ./f3read /media/michel/DISK_IMG/
Free space: 124.97 GB
Creating file 1.h2w ... OK!
Creating file 2.h2w ... OK!
Creating file 3.h2w ... OK!
Creating file 4.h2w ... OK!
Creating file 5.h2w ... OK!
Creating file 6.h2w ... OK!
Creating file 7.h2w ... OK!
Creating file 8.h2w ... OK!
Creating file 9.h2w ... OK!
Creating file 10.h2w ... OK!
Creating file 11.h2w ... OK!
Creating file 12.h2w ... OK!
Creating file 13.h2w ... OK!
Creating file 14.h2w ... OK!
Creating file 15.h2w ... OK!
Creating file 16.h2w ... OK!
Free space: 108.97 GB
Average writing speed: 2.87 MB/s
SECTORS ok/corrupted/changed/overwritten
Validating file 1.h2w ... 2097152/ 0/ 0/ 0
Validating file 2.h2w ... 2097152/ 0/ 0/ 0
Validating file 3.h2w ... 2097152/ 0/ 0/ 0
Validating file 4.h2w ... 2097152/ 0/ 0/ 0
Validating file 5.h2w ... 2097152/ 0/ 0/ 0
Validating file 6.h2w ... 2097152/ 0/ 0/ 0
Validating file 7.h2w ... 2097152/ 0/ 0/ 0
Validating file 8.h2w ... 266176/ 1830976/ 0/ 0
Validating file 9.h2w ... 0/ 2097152/ 0/ 0
Validating file 10.h2w ... 0/ 2097152/ 0/ 0
Validating file 11.h2w ... 0/ 2097152/ 0/ 0
Validating file 12.h2w ... 0/ 2097152/ 0/ 0
Validating file 13.h2w ... 0/ 2097152/ 0/ 0
Validating file 14.h2w ... 0/ 2097152/ 0/ 0
Validating file 15.h2w ... 0/ 2097152/ 0/ 0
Validating file 16.h2w ... 523920/ 1573232/ 0/ 0
Data OK: 7.38 GB (15470160 sectors)
Data LOST: 8.62 GB (18084272 sectors)
Corrupted: 8.62 GB (18084272 sectors)
Slightly changed: 0.00 Byte (0 sectors)
Overwritten: 0.00 Byte (0 sectors)
Average reading speed: 12.73 MB/s
After disconnecting the drive and connecting it back, ``f3read``
produced the following output:
::
$ ./f3read /media/michel/DISK_IMG/
SECTORS ok/corrupted/changed/overwritten
Validating file 1.h2w ... 2097152/ 0/ 0/ 0
Validating file 2.h2w ... 2097152/ 0/ 0/ 0
Validating file 3.h2w ... 2097152/ 0/ 0/ 0
Validating file 4.h2w ... 2097152/ 0/ 0/ 0
Validating file 5.h2w ... 2097152/ 0/ 0/ 0
Validating file 6.h2w ... 2097152/ 0/ 0/ 0
Validating file 7.h2w ... 2097152/ 0/ 0/ 0
Validating file 8.h2w ... 266176/ 1830976/ 0/ 0
Validating file 9.h2w ... 0/ 2097152/ 0/ 0
Validating file 10.h2w ... 0/ 2097152/ 0/ 0
Validating file 11.h2w ... 0/ 2097152/ 0/ 0
Validating file 12.h2w ... 0/ 2097152/ 0/ 0
Validating file 13.h2w ... 0/ 2097152/ 0/ 0
Validating file 14.h2w ... 0/ 2097152/ 0/ 0
Validating file 15.h2w ... 0/ 2097152/ 0/ 0
Validating file 16.h2w ... 0/ 2097152/ 0/ 0
Data OK: 7.13 GB (14946240 sectors)
Data LOST: 8.87 GB (18608192 sectors)
Corrupted: 8.87 GB (18608192 sectors)
Slightly changed: 0.00 Byte (0 sectors)
Overwritten: 0.00 Byte (0 sectors)
Average reading speed: 12.50 MB/s
Notice that file 16.h2w, that last file ``f3write`` wrote, has no longer
good sectors. What happened is that the last sectors of 16.h2w were in
the internal cache of the drive when ``f3read`` ran right after
``f3write``, but were not there after the forced reset. The internal
cache will fool any test that doesn't write beyond the real capacity of
the drive plus the size of the internal cache, and does not hard reset
the drive. One can estimate the size of this cache as follows: 523920 \*
512B ~ 256MB.
Tom Metro once ran ``f3write`` on a 16GB flash drive formatted with ext2
file system, and obtained puzzling free space at the end of
``f3write``'s output:
::
% ./f3write /media/Kodi/
Free space: 14.50 GB
Creating file 1.h2w ... OK!
Creating file 2.h2w ... OK!
Creating file 3.h2w ... OK!
Creating file 4.h2w ... OK!
Creating file 5.h2w ... OK!
Creating file 6.h2w ... OK!
Creating file 7.h2w ... OK!
Creating file 8.h2w ... OK!
Creating file 9.h2w ... OK!
Creating file 10.h2w ... OK!
Creating file 11.h2w ... OK!
Creating file 12.h2w ... OK!
Creating file 13.h2w ... OK!
Creating file 14.h2w ... OK!
Free space: 755.80 MB
Average writing speed: 13.77 MB/s
This happened because ext2 and some other file systems reserve space for
special purposes. So they don't allow ``f3write`` to use that reserved
space. It's mostly safe to ignore that free space. If one wants to use
all space possible, there're two options: (1) using a file system that
doesn't reserve space (e.g. FAT), or (2) reducing the reserved space. How
to go for the second option depends on the used file system. The
`page `__
explains how to reduce the reserved space on ext2, ext3, and ext4 file
systems.
Elliot Macneille has ran into an application that reports the size of
one of its good flash cards as 15.71GB, whereas ``f3read`` only finds
14.63GB. Details on how space is accounted varies with operating system,
applications, file system used to format the drive, etc. However, there
is a common source for this problem that often explains most of the
difference: part of the computer industry (including F3) takes 1GB as
being 2^30 bytes, whereas the rest of the industry assumes that 1GB is
equal to 10^9 bytes. Some people use GiB for the first definition, but
its use is not universal, and some users even get confused when they see
this unit. With this information in mind, the mystery is easily solved:
14.63GiB \* 2^30 / 10^9 = 15.71GB.
When Art Gibbens tested a flash card hosted in a camera connected to his
Linux box, at some point F3 didn't show progress, and could not be
killed. After a reboot, the card was read only. Using an adapter to
connect his card directly to his machine, he recreated the partition of
the card, and successfully ran F3 with the card in the adapter. Thus,
Art's experience is a good warning if you're testing your card in a
device other than an adapter. Please, don't take it as a bug of F3. I'm
aware of only two things that can make a process "survive" a kill
signal: hardware failures, and/or bugs in the kernel. F3 doesn't run in
kernel mode, so Art's camera is likely the root of the problem.
Darrell Johnson has reported that a flash card he got stopped working
after he filled it up. This could be that the only memory chip the card
had died, but it is just speculation since Darrell was not able to
obtain more information. The important message here is that if you test
your card with F3, or just copy files into it, and it stops working,
it's not your fault because writing files to a card shouldn't damage it
if it is a legitimate card.
Username Kris,
`here `__,
asked what's the difference between "dosfsck -vtr /dev/sda1" and F3.
dosfsck(8) makes two assumptions that F3 does not: (1) one needs write
access to the device being tested, not the file system in it; (2)
hardware may fail, but it won't lie. The first assumption implies that
one likely needs root's rights to run dosfsck, what is just a small
inconvenience for simple uses. The second assumption is troublesome
because a fake card may be able to persuade dosfsck(8) to report it's
fine, or not report the whole problem, or give users the illusion the
memory card was fixed when it wasn't. I singled dosfsck(8) out because
of the question about it, but those two assumptions are true for fsck
software for other file systems and badblocks(8) as well.
Mac user Athanasios Tourtouras noticed that Spotlight of OS X, which
runs in the background, also indexes the content of removable drives.
Although Spotlight does not interferes with ``f3write/f3read``, its
indexing takes away around 2MB/s of bandwidth, so ``f3write/f3read``
will run slower as well as their speed measurements will underestimate
the real capacity of the drive. Not to mention that you likely don't
want to index test files. You can disable the indexing of removable
drives including the flash drive to Spotlight's exclude list by going to
System Preferences / Spotlight / Privacy.
.. raw:: html
.. raw:: html
On the compatibility with H2testw's file format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Starting at version 3.0, F3 generates files following H2testw's file
format. This feature should help users that use both applications and/or
interact with users that use the other application. However, there are
two caveats explained in this section that users should be aware.
**Verifying files created by H2testw with F3read.** The caveat here is
that H2testw only writes files whose size is a multiple of 1MB, whereas
F3write fills up the memory card. Thus, verifying files created by
H2testw with F3read works, but, likely, will not test approximately 1MB
of space that H2testw does not write.
**Verifying files created by ``f3write`` with H2testw.** The caveat here
is that H2testw requires that all files have sizes that are multiple of
1MB. When it is not the case for a single file, H2testw rejects all
files, and issues the message "Please delete files \*.h2w." This problem
often comes up with the last file ``f3write`` generates to fill up the
space available in the memory card being tested. The solution is to
truncate the size of the last file ``f3write`` generates to the closest
multiple of 1MB. Assuming the last file is 30.h2w, the following command
does exactly that:
::
$ truncate --size=/1M /media/michel/6135-3363/30.h2w
If you want to exchange files with H2testw users often, check out the
``f3write.h2w`` shell script
`here `__.
This script calls ``truncate`` after ``f3write`` runs successfully.
f3probe - the fastest drive test
--------------------------------
H2testw's algorithm has been the gold standard for detecting fake flash
(see
`here `__
and
`here `__)
because it is robust against all counterfeits. However, as drives'
capacity grows, the time to test these newer drives becomes so painful
that one rarely runs H2testw's algorithm on a whole drive, but only a
fraction of it. See question "Why test only 25% or 32GB?" on `this
FAQ `__
for a defense of this approach.
The problem with this approach is that drives are still getting bigger,
and counterfeiters may, in the future, be able to profit with fake drives
whose real capacity are large enough to fool these partial tests. This
problem is not new. For example, Steve Si implemented
`FakeFlashTest.exe `__,
which has successfully reduced the amount of time to test drives, and is
still able to give a good estimate of the real size of fake drives. Yet,
`FakeFlashTest.exe's
algorithm `__
is not a definitive answer to the problem because FakeFlashTest.exe's
algorithm still needs to write to at least all good memory of tested
drives.
When a drive is fake, ``f3probe`` writes the size of the cache of the
drive a couple times, and a small number of blocks as the example in the
next section shows. From the example in the next section, the fake drive
has 7.86GB (16477879 blocks) of usable memory, but advertises itself as
being a 15.33GB (32155648 blocks) drive. It is worth noticing that given
that 7.86GB / 15.33GB ~ 51.2%, this fake drive already violates the 25%
recommendation mentioned above. ``f3probe`` wrote 2158 blocks to find
the real size of the drive, whereas FakeFlashTest.exe would have written
at least 16477879 blocks. That is, ``f3probe`` wrote no more than 2158 /
16477879 ~ 0.01% of all that FakeFlashTest.exe would have written. Even
if FakeFlashTest.exe wrote only 1% of the real size of the drive,
``f3probe`` would still write only 1% of what FakeFlashTest.exe would
write under this hypothetical, two-order improvement! Moreover,
``f3probe`` provides the exact geometry of the drive, what allows one to
"fix" the drive using the highest capacity possible.
When a drive is not fake, ``f3probe`` writes about half of its size, or
2GB, whichever is smaller. Thus, if the previous drive were not fake,
``f3probe`` would've written 2GB, and FakeFlashTest.exe 15.33GB. While
the difference 2GB / 15.33GB ~ 13.05% is much smaller, it is still
large. When a fake drive has some cache, ``f3probe`` will slow down, but
given that ``f3probe`` is optimized to deal with these cases it is still
fast. I do not know how FakeFlashTest.exe deal with drives that have
cache. If FakeFlashTest.exe simply ignores a drive's cache, it may over
estimate the size of fake drives.
This breakthrough against counterfeiters was only possible because
``f3probe``'s algorithm assumes a tight model of how fake drives work.
In spite of the fact that I have not found a drive, fake or not, that
confuses ``f3probe``, I've marked ``f3probe`` as experimental for now
because this model has not been battle proven. Although there is a
chance of finding out that the model is incomplete, there is also a
chance that the model can be simplified if one can be sure that not all
types of fake flash the model predicts really exist; the latter chance
holds a promise of even higher testing speeds. Of course, efficient
flash tests like the one implemented in ``f3probe`` may slow down as
fake chips become "smarter". For now, though, ``f3probe`` gives us the
upper hand over counterfeiters.
Finally, thanks to ``f3probe`` being free software, and once ``f3probe``
is battle proven, ``f3probe`` could be embedded on smartphones, cameras,
MP3 players, and other devices to stop once and for all the
proliferation of fake flash.
How to use f3probe
~~~~~~~~~~~~~~~~~~
Different from ``f3write/f3read`` that works on the file system of the
drive, ``f3probe`` works directly over the block device that controls
the drive. In practice, this means three requirements. First, one has to
have root access (i.e. superuser account) on the machine that will run
the test. Second, the user must know how to find the block device of the
drive. Third, you must be careful on the previous requirement to avoid
messing your machine up. If you don't have root access, you can't use
``f3probe``; use ``f3write/f3read`` in this case. The use example below
helps with the second requirement, but don't forget that you are the one
responsible for doing it right!
The command lsblk(8) is handy to find the block device of the drive. In
the example below, which I got running lsblk on my laptop, an experienced
user can quickly identify that my flash drive that is mounted at
"/media/michel/A902-D705" is block device "/dev/sdb". If you don't have
much experience, you may want to run lsblk before connecting the drive
to your computer, and to run lsblk again after connecting the drive to
easily identify what was added to the output of lsblk. Checking out the
content of folder "/media/michel/A902-D705" to confirm that it's the
correct drive is a good idea as well. The block device "sdb" is the disk
(see column "TYPE"), and "sdb1" is the first and only partition of my
flash drive; your drive may have none or more partitions. You want to
choose the drive, not a partition.
::
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 232.9G 0 disk
+-sda1 8:1 0 218G 0 part /
+-sda2 8:2 0 1K 0 part
+-sda5 8:5 0 15G 0 part [SWAP]
sdb 8:16 1 15.3G 0 disk
+-sdb1 8:17 1 15.3G 0 part /media/michel/A902-D705
sr0 11:0 1 1024M 0 rom
If you get confused between "sdb" and "sdb1", don't worry, ``f3probe``
will report the mistake and point out the proper one. However, I cannot
emphasize it enough, you MUST identify the correct drive. If I had
chosen "sda", ``f3probe`` may have messed my computer. Once the device
is chosen, just prefix it with "/dev/" to obtain its full name.
Once you have carefully identified the device, you run ``f3probe`` like
in the example below (please use the correct device!):
::
$ sudo ./f3probe --destructive --time-ops /dev/sdb
[sudo] password for michel:
F3 probe 9.0
Copyright (C) 2010 Digirati Internet LTDA.
This is free software; see the source for copying conditions.
WARNING: Probing normally takes from a few seconds to 15 minutes, but
it can take longer. Please be patient.
Bad news: The device `/dev/sdb' is a counterfeit of type limbo
You can "fix" this device using the following command:
f3fix --last-sec=16477878 /dev/sdb
Device geometry:
*Usable* size: 7.86 GB (16477879 blocks)
Announced size: 15.33 GB (32155648 blocks)
Module: 16.00 GB (2^34 Bytes)
Approximate cache size: 0.00 Byte (0 blocks), need-reset=yes
Physical block size: 512.00 Byte (2^9 Bytes)
Probe time: 1'13"
Operation: total time / count = avg time
Read: 472.1ms / 4198 = 112us
Write: 55.48s / 2158 = 25.7ms
Reset: 17.88s / 14 = 1.27s
There is a lot in the previous example. First, it took one minute and 13
seconds for ``f3probe`` to identify that this 16GB drive had only
7.86GB. Second, I used command sudo(8) to run ``f3probe`` as root.
Third, I used option "--time-ops" to add the last four lines of the
output; these lines show the time taken to read, write, and reset the
drive during the test. The rest of this section covers the other aspects
of this output.
The option --destructive instructs ``f3probe`` to disregard the content
of the drive to speed up the test. Without option --destructive, one
would see a line "Probe finished, recovering blocks... Done" in the
previous output to let the user know that ``f3probe`` has recovered all
blocks in the drive to their original state. While the conservative mode
is very convenient, you should not rely too much on it. If ``f3probe``
crashes, the conservative mode won't work. Moreover, depending on the
fake drive, the conservative mode may not recover the drive to its exact
original state. In case you are running ``f3probe`` on a
memory-constrained computer (e.g. an old Raspberry Pi board), you can
still run it in conservative mode reducing the amount of memory needed
with option "--min-memory". If you don't have memory to test a large
drive even using option "--min-memory", you need to use option
"--destructive". The conservative mode is the default in the hope that
it will eventually save you from a mistake.
The line "Bad news: The device \`/dev/sdb' is a counterfeit of type
limbo" summarizes the results presented below this line. The types of
drives are good, damaged (seriously failing), limbo (the most common
type of fake drives), wraparound (a rare, if existing at all, type of
fake drives), and chain (a rare type of fake drives). If you ever find
wraparound and chain drives, please consider donating them to my
collection.
The probe time of 1'13" includes the time to run the probe algorithm,
take measurements, and the time to perform all operations on the drive.
But it doesn't include the time to recover the saved blocks (if this
feature is enabled). Therefore, the test would take roughly another
55.48s (i.e. total write time) to write all blocks back to the drive. As
some will notice, the time to perform all operations on the drive is
what dominates the probe time: 472.1ms + 55.48s + 17.88s = 1'13". It's
worth noticing that read and write speed estimates derived from the
times of these operations are not accurate because they mix sequential
and random accesses.
The next example gives you the chance to practice reading ``f3probe``'s
outputs:
::
$ sudo ./f3probe --time-ops /dev/sdc
[sudo] password for michel:
F3 probe 9.0
Copyright (C) 2010 Digirati Internet LTDA.
This is free software; see the source for copying conditions.
WARNING: Probing normally takes from a few seconds to 15 minutes, but
it can take longer. Please be patient.
Probe finished, recovering blocks... Done
Good news: The device `/dev/sdc' is the real thing
Device geometry:
*Usable* size: 3.77 GB (7913472 blocks)
Announced size: 3.77 GB (7913472 blocks)
Module: 4.00 GB (2^32 Bytes)
Approximate cache size: 0.00 Byte (0 blocks), need-reset=no
Physical block size: 512.00 Byte (2^9 Bytes)
Probe time: 10'06"
Operation: total time / count = avg time
Read: 2'22" / 3724018 = 38us
Write: 7'41" / 3719233 = 124us
Reset: 379.7ms / 1 = 379.7ms
This second drive is a good one; it has all blocks necessary to hold its
announced size of 3.77GB, what is roughly 4GB.
The next section shows how to fix the 16GB drive using ``f3fix`` as
suggested by ``f3probe``.
Users' notes
~~~~~~~~~~~~
Philip de Lisle has a SD card reader on this laptop that is not backed
by a USB port. So when he tries ``f3probe /dev/mmcblk0``, he gets the
error message: ``Device `/dev/mmcblk0' is not backed by a USB device``.
This happens because the current version of ``f3probe`` only works on
devices that are mounted at a USB port; a future release of ``f3probe``
may lift this restriction. In the meanwhile, one can work around this
restriction using an external USB card reader.
How to "fix" a fake drive
-------------------------
You should not easily settle down for a fake drive, fight back and get
your money back! Doing so will help you and others. If you are still
reading this section, you already realized that you own a fake drive,
and would like to be able to use it without losing data.
As shown in the previous section, my 16GB fake drive can only hold
7.86GB. Moreover, ``f3probe`` suggested how I can use ``f3fix`` to fix
my drive. ``f3fix`` fixes fake drives creating a partition that includes
only the usable memory of the drive. ``f3fix`` takes a few seconds to
finish.
The execution of ``f3fix`` on my fake drive went as follows:
::
$ sudo ./f3fix --last-sec=16477878 /dev/sdb
F3 fix 9.0
Copyright (C) 2010 Digirati Internet LTDA.
This is free software; see the source for copying conditions.
Error: Partition(s) 1 on /dev/sdc have been written, but we have been unable to inform the kernel of the change, probably because it/they are in use. As a result, the old partition(s) will remain in use. You should reboot now before making further changes.
Drive `/dev/sdc' was successfully fixed
If ``f3fix`` reports that you need to force the kernel to reload the new
partition table, as shown above, just unplug and plug the drive back.
Once the new partition is available, format it:
::
$ sudo mkfs.vfat /dev/sdb1
mkfs.fat 3.0.26 (2014-03-07)
At this point your card should be working fine, just mount the new
partition to access it. However, before using the drive, test all its
blocks with ``f3write/f3read``. The test of my card went as follows:
::
$ ./f3write /media/michel/8A34-CED2/
Free space: 7.84 GB
Creating file 1.h2w ... OK!
Creating file 2.h2w ... OK!
Creating file 3.h2w ... OK!
Creating file 4.h2w ... OK!
Creating file 5.h2w ... OK!
Creating file 6.h2w ... OK!
Creating file 7.h2w ... OK!
Creating file 8.h2w ... OK!
Free space: 0.00 Byte
Average writing speed: 4.64 MB/s
$ ./f3read /media/michel/8A34-CED2/
SECTORS ok/corrupted/changed/overwritten
Validating file 1.h2w ... 2097152/ 0/ 0/ 0
Validating file 2.h2w ... 2097152/ 0/ 0/ 0
Validating file 3.h2w ... 2097152/ 0/ 0/ 0
Validating file 4.h2w ... 2097152/ 0/ 0/ 0
Validating file 5.h2w ... 2097152/ 0/ 0/ 0
Validating file 6.h2w ... 2097152/ 0/ 0/ 0
Validating file 7.h2w ... 2097152/ 0/ 0/ 0
Validating file 8.h2w ... 1763608/ 0/ 0/ 0
Data OK: 7.84 GB (16443672 sectors)
Data LOST: 0.00 Byte (0 sectors)
Corrupted: 0.00 Byte (0 sectors)
Slightly changed: 0.00 Byte (0 sectors)
Overwritten: 0.00 Byte (0 sectors)
Average reading speed: 16.54 MB/s
As reported by ``f3write/f3read`` above, the real memory of my fake
drive is in good shape. But it may not be the case for yours. For
example, the following is ``f3read``'s output for another 16GB drive
with real size of 7GB fixed as described in this section:
::
SECTORS ok/corrupted/changed/overwritten
Validating file 1.h2w ... 2097152/ 0/ 0/ 0
Validating file 2.h2w ... 2097152/ 0/ 0/ 0
Validating file 3.h2w ... 2097088/ 64/ 0/ 0
Validating file 4.h2w ... 2097152/ 0/ 0/ 0
Validating file 5.h2w ... 2088960/ 8192/ 0/ 0
Validating file 6.h2w ... 2097152/ 0/ 0/ 0
Validating file 7.h2w ... 2037632/ 0/ 0/ 0
Data OK: 6.97 GB (14612288 sectors)
Data LOST: 4.03 MB (8256 sectors)
Corrupted: 4.03 MB (8256 sectors)
Slightly changed: 0.00 Byte (0 sectors)
Overwritten: 0.00 Byte (0 sectors)
Average reading speed: 946.46 KB/s
If you get some sectors corrupted, repeat the ``f3write/f3read`` test.
Some drives recover from these failures on a second full write cycle.
However, if the corrupted sectors persist, the drive is junk because
not only is it a fake drive, but its real memory is already failing.
Good luck!
f3-9.0/f3brew.c 0000664 0000000 0000000 00000027415 14771250033 0013241 0 ustar 00root root 0000000 0000000 #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[] = "";
/* The capital "E" in "REad" in the string below is not a typo.
* It shows from where the name B-RE-W comes.
*/
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-9.0/f3fix.c 0000664 0000000 0000000 00000014562 14771250033 0013067 0 ustar 00root root 0000000 0000000 #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-9.0/f3probe.c 0000664 0000000 0000000 00000036023 14771250033 0013404 0 ustar 00root root 0000000 0000000 #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},
/* Geometry 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;
}
sdev = 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 (sdev) {
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 fake_type == FKTY_GOOD ? 0 : 100 + fake_type;
}
int main(int argc, char **argv)
{
struct args args = {
/* Defaults. */
.debug = false,
.unit_test = false,
.keep_file = false,
.save = true,
.min_mem = false,
/* RT_NONE is the only reliable reset type against fake flash.
* See issue #81 for details:
* https://github.com/AltraMayor/f3/issues/81
*
* A side benefit of this reset type is that it works on
* non-USB-backed drives, such as card readers that are
* commonly built in laptops.
* See issue #79 for details:
* https://github.com/AltraMayor/f3/issues/79
*
* A negative side effect is that f3probe runs slower
* for cases in which RT_USB would work. But users can
* still request the reset type RT_USB by
* passing --reset-type=1
*/
.reset_type = RT_NONE,
.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-9.0/f3read.1 0000664 0000000 0000000 00000002663 14771250033 0013131 0 ustar 00root root 0000000 0000000 .\"Text automatically generated by txt2man
.TH F3 "1" "October 2020" "F3 9.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 SEE ALSO
For detailed information about the F3 tools, see:
.PP
https://fight-flash-fraud.readthedocs.io/en/stable/
.SH AUTHOR
F3 was written by Michel Machado .
This manual page was first written by Joao Eriberto Mota Filho .
f3-9.0/f3read.c 0000664 0000000 0000000 00000025567 14771250033 0013223 0 ustar 00root root 0000000 0000000 #define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 600
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "utils.h"
#include "libflow.h"
#include "version.h"
/* Argp's global variables. */
const char *argp_program_version = "F3 Read " F3_STR_VERSION;
/* Arguments. */
static char adoc[] = "";
static char doc[] = "F3 Read -- validate .h2w files to test "
"the real capacity of the drive";
static struct argp_option options[] = {
{"start-at", 's', "NUM", 0,
"First NUM.h2w file to be read", 1},
{"end-at", 'e', "NUM", 0,
"Last NUM.h2w file to be read", 0},
{"max-read-rate", 'r', "KB/s", 0,
"Maximum read rate", 0},
{"show-progress", 'p', "NUM", 0,
"Show progress if NUM is not zero", 0},
{ 0 }
};
struct args {
long start_at;
long end_at;
long max_read_rate;
int show_progress;
const char *dev_path;
};
static error_t parse_opt(int key, char *arg, struct argp_state *state)
{
struct args *args = state->input;
long l;
switch (key) {
case 's':
l = arg_to_long(state, arg);
if (l <= 0)
argp_error(state,
"NUM must be greater than zero");
args->start_at = l - 1;
break;
case 'e':
l = arg_to_long(state, arg);
if (l <= 0)
argp_error(state,
"NUM must be greater than zero");
args->end_at = l - 1;
break;
case 'r':
l = arg_to_long(state, arg);
if (l <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_read_rate = l;
break;
case 'p':
args->show_progress = !!arg_to_long(state, arg);
break;
case ARGP_KEY_INIT:
args->dev_path = NULL;
break;
case ARGP_KEY_ARG:
if (args->dev_path)
argp_error(state,
"Wrong number of arguments; only one is allowed");
args->dev_path = arg;
break;
case ARGP_KEY_END:
if (!args->dev_path)
argp_error(state,
"The disk path was not specified");
if (args->start_at > args->end_at)
argp_error(state,
"Option --start-at must be less or equal to option --end-at");
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = {options, parse_opt, adoc, doc, NULL, NULL, NULL};
struct file_stats {
uint64_t secs_ok;
uint64_t secs_corrupted;
uint64_t secs_changed;
uint64_t secs_overwritten;
uint64_t bytes_read;
int read_all;
};
static inline void zero_fstats(struct file_stats *stats)
{
memset(stats, 0, sizeof(*stats));
}
#define TOLERANCE 2
static void check_sector(char *_sector, uint64_t expected_offset,
struct file_stats *stats)
{
uint64_t *sector = (uint64_t *)_sector;
uint64_t rn;
const int num_int64 = SECTOR_SIZE >> 3;
int error_count, i;
rn = sector[0];
error_count = 0;
for (i = 1; error_count <= TOLERANCE && i < num_int64; i++) {
rn = random_number(rn);
if (rn != sector[i])
error_count++;
}
if (expected_offset == sector[0]) {
if (error_count == 0)
stats->secs_ok++;
else if (error_count <= TOLERANCE)
stats->secs_changed++;
else
stats->secs_corrupted++;
} else if (error_count <= TOLERANCE)
stats->secs_overwritten++;
else
stats->secs_corrupted++;
}
static uint64_t check_buffer(char *buf, size_t size, uint64_t expected_offset,
struct file_stats *stats)
{
char *beyond_buf = buf + size;
assert(size % SECTOR_SIZE == 0);
while (buf < beyond_buf) {
check_sector(buf, expected_offset, stats);
buf += SECTOR_SIZE;
expected_offset += SECTOR_SIZE;
}
return expected_offset;
}
static ssize_t 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) {
if (errno == EINTR)
continue;
return - errno;
}
if (rc == 0)
break;
done += rc;
} while (done < count);
return done;
}
static ssize_t check_chunk(struct dynamic_buffer *dbuf, int fd,
uint64_t *p_expected_offset, uint64_t chunk_size,
struct file_stats *stats)
{
char *buf = dbuf_get_buf(dbuf, chunk_size);
size_t len = dbuf_get_len(dbuf);
ssize_t tot_bytes_read = 0;
while (chunk_size > 0) {
size_t turn_size = chunk_size <= len ? chunk_size : len;
ssize_t bytes_read = read_all(fd, buf, turn_size);
if (bytes_read < 0) {
stats->bytes_read += tot_bytes_read;
return bytes_read;
}
if (bytes_read == 0)
break;
tot_bytes_read += bytes_read;
chunk_size -= bytes_read;
*p_expected_offset = check_buffer(buf, bytes_read,
*p_expected_offset, stats);
}
stats->bytes_read += tot_bytes_read;
return tot_bytes_read;
}
static inline void print_status(const struct file_stats *stats)
{
printf("%7" PRIu64 "/%9" PRIu64 "/%7" PRIu64 "/%7" PRIu64,
stats->secs_ok, stats->secs_corrupted, stats->secs_changed,
stats->secs_overwritten);
}
static void validate_file(const char *path, int number, struct flow *fw,
struct file_stats *stats)
{
char *full_fn;
const char *filename;
int fd, saved_errno;
ssize_t bytes_read;
uint64_t expected_offset;
struct dynamic_buffer dbuf;
zero_fstats(stats);
full_fn = full_fn_from_number(&filename, path, number);
assert(full_fn);
printf("Validating file %s ... ", filename);
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.
*/
fd = open(full_fn, O_RDWR);
#else
fd = open(full_fn, O_RDONLY);
#endif
if (fd < 0)
err(errno, "Can't open file %s", full_fn);
/* 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.
*/
if (fdatasync(fd) < 0) {
int saved_errno = errno;
/* The issue https://github.com/AltraMayor/f3/issues/211
* motivated the warning below.
*/
printf("\nWARNING:\nThe operating system returned errno=%i for fdatasync(): %s\nThis error is unexpected and you may find more information on the log of the kernel (e.g. command dmesg(1) on Linux).\n\n",
saved_errno, strerror(saved_errno));
exit(saved_errno);
}
assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED));
/* Help the kernel to help us. */
assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL));
dbuf_init(&dbuf);
saved_errno = 0;
expected_offset = (uint64_t)number * GIGABYTES;
start_measurement(fw);
while (true) {
bytes_read = check_chunk(&dbuf, fd, &expected_offset,
get_rem_chunk_size(fw), stats);
if (bytes_read == 0)
break;
if (bytes_read < 0) {
saved_errno = - bytes_read;
break;
}
if (measure(fd, fw, bytes_read) < 0) {
saved_errno = errno;
break;
}
}
if (end_measurement(fd, fw) < 0) {
/* If a write failure has happened before, preserve it. */
if (!saved_errno)
saved_errno = errno;
}
print_status(stats);
stats->read_all = bytes_read == 0;
if (!stats->read_all) {
assert(saved_errno);
printf(" - NOT fully read due to \"%s\"",
strerror(saved_errno));
} else if (saved_errno) {
printf(" - %s", strerror(saved_errno));
}
printf("\n");
dbuf_free(&dbuf);
close(fd);
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 uint64_t get_total_size(const char *path, const long *files)
{
uint64_t total_size = 0;
while (*files >= 0) {
struct stat st;
int ret;
const char *filename;
char *full_fn = full_fn_from_number(&filename, path, *files);
assert(full_fn);
ret = stat(full_fn, &st);
if (ret < 0)
err(errno, "Can't stat file %s", full_fn);
if ((st.st_mode & S_IFMT) != S_IFREG)
err(EINVAL, "File %s is not a regular file", full_fn);
assert(st.st_size >= 0);
total_size += st.st_size;
free(full_fn);
files++;
}
return total_size;
}
static inline void pr_avg_speed(double speed)
{
const char *unit = adjust_unit(&speed);
printf("Average reading speed: %.2f %s/s\n", speed, unit);
}
static void iterate_files(const char *path, const long *files,
long start_at, long end_at, long max_read_rate, int progress)
{
uint64_t tot_ok, tot_corrupted, tot_changed, tot_overwritten, tot_size;
int and_read_all = 1;
int or_missing_file = 0;
long number = start_at;
struct flow fw;
struct timeval t1, t2;
UNUSED(end_at);
init_flow(&fw, get_total_size(path, files), max_read_rate,
progress, NULL);
tot_ok = tot_corrupted = tot_changed = tot_overwritten = tot_size = 0;
printf(" SECTORS "
" ok/corrupted/changed/overwritten\n");
assert(!gettimeofday(&t1, NULL));
while (*files >= 0) {
struct file_stats stats;
or_missing_file = or_missing_file || (*files != number);
for (; number < *files; number++) {
const char *filename;
char *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, &fw, &stats);
tot_ok += stats.secs_ok;
tot_corrupted += stats.secs_corrupted;
tot_changed += stats.secs_changed;
tot_overwritten += stats.secs_overwritten;
tot_size += stats.bytes_read;
and_read_all = and_read_all && stats.read_all;
files++;
}
assert(!gettimeofday(&t2, NULL));
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, number);
if (!and_read_all)
printf("WARNING: Not all data was read due to I/O error(s)\n");
/* Reading speed. */
if (has_enough_measurements(&fw)) {
pr_avg_speed(get_avg_speed(&fw));
} else {
/* If the drive is too fast for the measurements above,
* try a coarse approximation of the reading speed.
*/
int64_t total_time_ms = delay_ms(&t1, &t2);
if (total_time_ms > 0) {
pr_avg_speed(get_avg_speed_given_time(&fw,
total_time_ms));
} else {
printf("Reading speed not available\n");
}
}
}
int main(int argc, char **argv)
{
const long *files;
struct args args = {
/* Defaults. */
.start_at = 0,
.end_at = LONG_MAX - 1,
.max_read_rate = 0,
/* If stdout isn't a terminal, suppress progress. */
.show_progress = isatty(STDOUT_FILENO),
};
/* Read parameters. */
argp_parse(&argp, argc, argv, 0, NULL, &args);
print_header(stdout, "read");
adjust_dev_path(&args.dev_path);
files = ls_my_files(args.dev_path, args.start_at, args.end_at);
iterate_files(args.dev_path, files, args.start_at, args.end_at,
args.max_read_rate, args.show_progress);
free((void *)files);
return 0;
}
f3-9.0/f3write.c 0000664 0000000 0000000 00000022117 14771250033 0013426 0 ustar 00root root 0000000 0000000 #define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 600
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "utils.h"
#include "libflow.h"
#include "version.h"
/* Argp's global variables. */
const char *argp_program_version = "F3 Write " F3_STR_VERSION;
/* Arguments. */
static char adoc[] = "";
static char doc[] = "F3 Write -- fill a drive out with .h2w files "
"to test its real capacity";
static struct argp_option options[] = {
{"start-at", 's', "NUM", 0,
"First NUM.h2w file to be written", 1},
{"end-at", 'e', "NUM", 0,
"Last NUM.h2w file to be written", 0},
{"max-write-rate", 'w', "KB/s", 0,
"Maximum write rate", 0},
{"show-progress", 'p', "NUM", 0,
"Show progress if NUM is not zero", 0},
{ 0 }
};
struct args {
long start_at;
long end_at;
long max_write_rate;
int show_progress;
const char *dev_path;
};
static error_t parse_opt(int key, char *arg, struct argp_state *state)
{
struct args *args = state->input;
long l;
switch (key) {
case 's':
l = arg_to_long(state, arg);
if (l <= 0)
argp_error(state,
"NUM must be greater than zero");
args->start_at = l - 1;
break;
case 'e':
l = arg_to_long(state, arg);
if (l <= 0)
argp_error(state,
"NUM must be greater than zero");
args->end_at = l - 1;
break;
case 'w':
l = arg_to_long(state, arg);
if (l <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_write_rate = l;
break;
case 'p':
args->show_progress = !!arg_to_long(state, arg);
break;
case ARGP_KEY_INIT:
args->dev_path = NULL;
break;
case ARGP_KEY_ARG:
if (args->dev_path)
argp_error(state,
"Wrong number of arguments; only one is allowed");
args->dev_path = arg;
break;
case ARGP_KEY_END:
if (!args->dev_path)
argp_error(state,
"The disk path was not specified");
if (args->start_at > args->end_at)
argp_error(state,
"Option --start-at must be less or equal to option --end-at");
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = {options, parse_opt, adoc, doc, NULL, NULL, NULL};
static uint64_t fill_buffer(void *buf, size_t size, uint64_t offset)
{
const int num_int64 = SECTOR_SIZE >> 3;
uint8_t *p, *ptr_end;
assert(size > 0);
assert(size % SECTOR_SIZE == 0);
p = buf;
ptr_end = p + size;
while (p < ptr_end) {
uint64_t *sector = (uint64_t *)p;
int i;
sector[0] = offset;
for (i = 1; i < num_int64; i++)
sector[i] = random_number(sector[i - 1]);
p += SECTOR_SIZE;
offset += SECTOR_SIZE;
}
return offset;
}
/* XXX Avoid duplicate this function, which was copied from libdevs.c. */
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 write_chunk(struct dynamic_buffer *dbuf, int fd, size_t chunk_size,
uint64_t *poffset)
{
char *buf = dbuf_get_buf(dbuf, chunk_size);
size_t len = dbuf_get_len(dbuf);
while (chunk_size > 0) {
size_t turn_size = chunk_size <= len ? chunk_size : len;
int ret;
chunk_size -= turn_size;
*poffset = fill_buffer(buf, turn_size, *poffset);
ret = write_all(fd, buf, turn_size);
if (ret)
return ret;
}
return 0;
}
/* Return true when disk is full. */
static int create_and_fill_file(const char *path, long number, size_t size,
int *phas_suggested_max_write_rate, struct flow *fw)
{
char *full_fn;
const char *filename;
int fd, saved_errno;
size_t remaining;
uint64_t offset;
struct dynamic_buffer dbuf;
assert(size > 0);
assert(size % fw->block_size == 0);
/* Create the file. */
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");
free(full_fn);
return true;
}
err(errno, "Can't create file %s", full_fn);
}
assert(fd >= 0);
/* Write content. */
dbuf_init(&dbuf);
saved_errno = 0;
offset = (uint64_t)number * GIGABYTES;
remaining = size;
start_measurement(fw);
while (remaining > 0) {
uint64_t write_size = get_rem_chunk_size(fw);
if (write_size > remaining)
write_size = remaining;
saved_errno = write_chunk(&dbuf, fd, write_size, &offset);
if (saved_errno)
break;
remaining -= write_size;
if (measure(fd, fw, write_size) < 0) {
saved_errno = errno;
break;
}
}
if (end_measurement(fd, fw) < 0) {
/* If a write failure has happened before, preserve it. */
if (!saved_errno)
saved_errno = errno;
}
dbuf_free(&dbuf);
close(fd);
free(full_fn);
if (saved_errno == 0 || saved_errno == ENOSPC) {
if (saved_errno == 0)
assert(remaining == 0);
printf("OK!\n");
return saved_errno == ENOSPC;
}
/* Something went wrong. */
assert(saved_errno);
printf("Write failure: %s\n", strerror(saved_errno));
if (saved_errno == EIO && !*phas_suggested_max_write_rate) {
*phas_suggested_max_write_rate = true;
printf("\nWARNING:\nThe write error above may be due to your memory card overheating\nunder constant, maximum write rate. You can test this hypothesis\ntouching your memory card. If it is hot, you can try f3write\nagain, once your card has cooled down, using parameter --max-write-rate=2048\nto limit the maximum write rate to 2MB/s, or another suitable rate.\n\n");
}
return false;
}
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 inline void pr_avg_speed(double speed)
{
const char *unit = adjust_unit(&speed);
printf("Average writing speed: %.2f %s/s\n", speed, unit);
}
static int flush_chunk(const struct flow *fw, int fd)
{
UNUSED(fw);
if (fdatasync(fd) < 0)
return -1; /* Caller can read errno(3). */
/* Help the kernel to help us. */
assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED));
return 0;
}
static int fill_fs(const char *path, long start_at, long end_at,
long max_write_rate, int progress)
{
uint64_t free_space;
struct flow fw;
long i;
int has_suggested_max_write_rate = max_write_rate > 0;
struct timeval t1, t2;
free_space = get_freespace(path);
pr_freespace(free_space);
if (free_space <= 0) {
printf("No space!\n");
return 1;
}
i = end_at - start_at + 1;
if (i > 0 && (uint64_t)i <= (free_space >> 30)) {
/* The amount of data to write is less than the space available,
* update @free_space to improve estimate of time to finish.
*/
free_space = (uint64_t)i << 30;
} else {
/* There are more data to write than space available.
* Reduce @end_at to reduce the number of error messages
* when multiple write failures happens.
*
* One should not subtract the value below of one because
* the expression (free_space >> 30) is an integer division,
* that is, it ignores the remainder.
*/
end_at = start_at + (free_space >> 30);
}
init_flow(&fw, free_space, max_write_rate, progress, flush_chunk);
assert(!gettimeofday(&t1, NULL));
for (i = start_at; i <= end_at; i++)
if (create_and_fill_file(path, i, GIGABYTES,
&has_suggested_max_write_rate, &fw))
break;
assert(!gettimeofday(&t2, NULL));
/* Final report. */
pr_freespace(get_freespace(path));
/* Writing speed. */
if (has_enough_measurements(&fw)) {
pr_avg_speed(get_avg_speed(&fw));
} else {
/* If the drive is too fast for the measurements above,
* try a coarse approximation of the writing speed.
*/
int64_t total_time_ms = delay_ms(&t1, &t2);
if (total_time_ms > 0) {
pr_avg_speed(get_avg_speed_given_time(&fw,
total_time_ms));
} 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)
{
struct args args = {
/* Defaults. */
.start_at = 0,
.end_at = LONG_MAX - 1,
.max_write_rate = 0,
/* If stdout isn't a terminal, suppress progress. */
.show_progress = isatty(STDOUT_FILENO),
};
/* Read parameters. */
argp_parse(&argp, argc, argv, 0, NULL, &args);
print_header(stdout, "write");
adjust_dev_path(&args.dev_path);
unlink_old_files(args.dev_path, args.start_at, args.end_at);
return fill_fs(args.dev_path, args.start_at, args.end_at,
args.max_write_rate, args.show_progress);
}
f3-9.0/f3write.h2w 0000775 0000000 0000000 00000000157 14771250033 0013707 0 ustar 00root root 0000000 0000000 #!/usr/bin/env bash
$(dirname $0)/f3write "$@" || exit 1
FILES=("${@: -1}/*.h2w")
truncate --size=/1M $FILES
f3-9.0/libdevs.c 0000664 0000000 0000000 00000100344 14771250033 0013472 0 ustar 00root root 0000000 0000000 #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) {
if (errno == EINTR)
continue;
if (errno == EIO || errno == ENODATA) {
/* These errors are "expected",
* so ignore them.
*/
} else {
/* Execution should not come here. */
err(errno,
"%s(): unexpected error code from read(2) = %i",
__func__, errno);
}
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 which the user pulls
* the USB device.
*
* DO NOTHING.
*/
} else if (!strcmp(action, "change")) {
/* Deal with the case in which 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;
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. */
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;
}
if (rt != RT_NONE) {
/* Make sure that @bdev->fd is backed by a USB device. */
struct udev_device *usb_dev = map_dev_to_usb_dev(fd_dev);
if (!usb_dev) {
fprintf(stderr,
"Device `%s' is not backed by a USB device.\n"
"You must disable reset, run %s as follows:\n"
"%s --reset-type=%i %s\n",
filename, __progname, __progname, RT_NONE,
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-9.0/libdevs.h 0000664 0000000 0000000 00000005025 14771250033 0013477 0 ustar 00root root 0000000 0000000 #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 value 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-9.0/libflow.c 0000664 0000000 0000000 00000021543 14771250033 0013503 0 ustar 00root root 0000000 0000000 #define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 600
#include
#include
#include
#include
#include
#include
#include "libflow.h"
#include "utils.h"
static inline void move_to_inc_at_start(struct flow *fw)
{
fw->step = 1;
fw->state = FW_INC;
}
void init_flow(struct flow *fw, uint64_t total_size,
long max_process_rate, int progress,
flow_func_flush_chunk_t func_flush_chunk)
{
fw->total_size = total_size;
fw->total_processed = 0;
fw->progress = progress;
fw->block_size = 512; /* Bytes */
fw->blocks_per_delay = 1; /* 512B/s */
fw->delay_ms = 1000; /* 1s */
fw->max_process_rate = max_process_rate <= 0
? DBL_MAX : max_process_rate * 1024.;
fw->measured_blocks = 0;
fw->measured_time_ms = 0;
fw->erase = 0;
fw->func_flush_chunk = func_flush_chunk;
fw->processed_blocks = 0;
fw->acc_delay_us = 0;
assert(fw->block_size > 0);
assert(fw->block_size % SECTOR_SIZE == 0);
move_to_inc_at_start(fw);
}
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);
}
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 void report_progress(struct flow *fw, double inst_speed)
{
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_processed)
fw->total_size = fw->total_processed;
percent = (double)fw->total_processed * 100 / fw->total_size;
erase(fw->erase);
fw->erase = printf("%.2f%% -- %.2f %s/s",
percent, inst_speed, unit);
assert(fw->erase > 0);
if (has_enough_measurements(fw))
fw->erase += pr_time(
(fw->total_size - fw->total_processed) /
get_avg_speed(fw));
fflush(stdout);
}
static inline void __start_measurement(struct flow *fw)
{
assert(!gettimeofday(&fw->t1, NULL));
}
void start_measurement(struct flow *fw)
{
/*
* The report below is especially useful when a single measurement spans
* multiple files; this happens when a drive is faster than 1GB/s.
*/
if (fw->progress)
report_progress(fw, fw->blocks_per_delay * fw->block_size *
1000.0 / fw->delay_ms);
__start_measurement(fw);
}
static inline void move_to_steady(struct flow *fw)
{
fw->state = FW_STEADY;
}
static void move_to_search(struct flow *fw, int64_t bpd1, int64_t 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 inline int is_rate_above(const struct flow *fw,
uint64_t delay, double inst_speed)
{
/* We use logical or here to enforce the lowest limit. */
return delay > fw->delay_ms || inst_speed > fw->max_process_rate;
}
static inline int is_rate_below(const struct flow *fw,
uint64_t delay, double inst_speed)
{
/* We use logical and here to enforce both limits. */
return delay <= fw->delay_ms && inst_speed < fw->max_process_rate;
}
static inline int flush_chunk(const struct flow *fw, int fd)
{
if (fw->func_flush_chunk)
return fw->func_flush_chunk(fw, fd);
return 0;
}
/* XXX Avoid duplicate this function, which was copied from libutils.h. */
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;
}
int measure(int fd, struct flow *fw, long processed)
{
ldiv_t result = ldiv(processed, fw->block_size);
struct timeval t2;
uint64_t delay;
double bytes_k, inst_speed;
assert(result.rem == 0);
fw->processed_blocks += result.quot;
fw->total_processed += processed;
if (fw->processed_blocks < fw->blocks_per_delay)
return 0;
assert(fw->processed_blocks == fw->blocks_per_delay);
if (flush_chunk(fw, fd) < 0)
return -1; /* Caller can read errno(3). */
assert(!gettimeofday(&t2, NULL));
delay = (diff_timeval_us(&fw->t1, &t2) + fw->acc_delay_us) / 1000;
/* Instantaneous speed in bytes per second. */
bytes_k = fw->blocks_per_delay * fw->block_size * 1000.0;
inst_speed = bytes_k / delay;
if (delay < fw->delay_ms && inst_speed > fw->max_process_rate) {
/* Wait until inst_speed == fw->max_process_rate
* (if possible).
*/
double wait_ms = round((bytes_k - delay * fw->max_process_rate)
/ fw->max_process_rate);
if (wait_ms < 0) {
/* Wait what is possible. */
wait_ms = fw->delay_ms - delay;
} else if (delay + wait_ms < fw->delay_ms) {
/* wait_ms is not the largest possible value, so
* force the flow algorithm to keep increasing it.
* Otherwise, the delay to print progress may be
* too small.
*/
wait_ms++;
}
if (wait_ms > 0) {
/* Slow down. */
msleep(wait_ms);
/* Adjust measurements. */
delay += wait_ms;
inst_speed = bytes_k / delay;
}
}
/* Update mean. */
fw->measured_blocks += fw->processed_blocks;
fw->measured_time_ms += delay;
switch (fw->state) {
case FW_INC:
if (is_rate_above(fw, delay, inst_speed)) {
move_to_search(fw,
fw->blocks_per_delay - fw->step / 2,
fw->blocks_per_delay);
} else if (is_rate_below(fw, delay, inst_speed)) {
inc_step(fw);
} else
move_to_steady(fw);
break;
case FW_DEC:
if (is_rate_above(fw, delay, inst_speed)) {
dec_step(fw);
} else if (is_rate_below(fw, delay, inst_speed)) {
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 (is_rate_above(fw, delay, inst_speed)) {
fw->bpd2 = fw->blocks_per_delay;
fw->blocks_per_delay = (fw->bpd1 + fw->bpd2) / 2;
} else if (is_rate_below(fw, delay, inst_speed)) {
fw->bpd1 = fw->blocks_per_delay;
fw->blocks_per_delay = (fw->bpd1 + fw->bpd2) / 2;
} else
move_to_steady(fw);
break;
case FW_STEADY: {
if (delay <= fw->delay_ms) {
if (inst_speed < fw->max_process_rate) {
move_to_inc(fw);
} else if (inst_speed > fw->max_process_rate) {
move_to_dec(fw);
}
} else if (fw->blocks_per_delay > 1) {
move_to_dec(fw);
}
break;
}
default:
assert(0);
}
if (fw->progress)
report_progress(fw, inst_speed);
/* Reset accumulators. */
fw->processed_blocks = 0;
fw->acc_delay_us = 0;
__start_measurement(fw);
return 0;
}
int end_measurement(int fd, struct flow *fw)
{
struct timeval t2;
int saved_errno;
int ret = 0;
if (fw->processed_blocks <= 0)
goto out;
if (flush_chunk(fw, fd) < 0) {
saved_errno = errno;
ret = -1;
goto out;
}
/* Save time in between closing ongoing file and creating a new file. */
assert(!gettimeofday(&t2, NULL));
fw->acc_delay_us += diff_timeval_us(&fw->t1, &t2);
out:
/* Erase progress information. */
erase(fw->erase);
fw->erase = 0;
fflush(stdout);
if (ret < 0) {
/* Propagate errno(3) to caller. */
errno = saved_errno;
}
return ret;
}
static inline void __dbuf_free(struct dynamic_buffer *dbuf)
{
if (dbuf->buf != dbuf->backup_buf)
free(dbuf->buf);
}
void dbuf_free(struct dynamic_buffer *dbuf)
{
__dbuf_free(dbuf);
dbuf->buf = NULL;
dbuf->len = 0;
dbuf->max_buf = true;
}
char *dbuf_get_buf(struct dynamic_buffer *dbuf, size_t size)
{
/* If enough buffer, or it's already the largest buffer, return it. */
if (size <= dbuf->len || dbuf->max_buf)
return dbuf->buf;
/*
* Allocate a new buffer.
*/
__dbuf_free(dbuf);
do {
dbuf->buf = malloc(size);
if (dbuf->buf != NULL) {
dbuf->len = size;
return dbuf->buf;
} else {
dbuf->max_buf = true;
}
size /= 2;
} while (size > sizeof(dbuf->backup_buf));
/* A larger buffer is not available; failsafe. */
dbuf->buf = dbuf->backup_buf;
dbuf->len = sizeof(dbuf->backup_buf);
return dbuf->buf;
}
f3-9.0/libflow.h 0000664 0000000 0000000 00000006010 14771250033 0013500 0 ustar 00root root 0000000 0000000 #ifndef HEADER_LIBFLOW_H
#define HEADER_LIBFLOW_H
#include
#include
struct flow;
typedef int (*flow_func_flush_chunk_t)(const struct flow *fw, int fd);
struct flow {
/* Total number of bytes to be processed. */
uint64_t total_size;
/* Total number of bytes already processed. */
uint64_t total_processed;
/* If true, show progress. */
int progress;
/* Block size in bytes. */
int block_size;
/* Delay intended between measurements in milliseconds. */
unsigned int delay_ms;
/* Increment to apply to @blocks_per_delay. */
int64_t step;
/* Blocks to process before measurement. */
int64_t blocks_per_delay;
/* Maximum processing rate in bytes per second. */
double max_process_rate;
/* Number of measured blocks. */
uint64_t measured_blocks;
/* Measured time. */
uint64_t measured_time_ms;
/* State. */
enum {FW_INC, FW_DEC, FW_SEARCH, FW_STEADY} state;
/* Number of characters to erase before printing out progress. */
int erase;
/*
* Methods
*/
flow_func_flush_chunk_t func_flush_chunk;
/*
* Initialized while measuring
*/
/* Number of blocks processed since last measurement. */
int64_t processed_blocks;
/*
* Accumulated delay before @processed_blocks reaches @blocks_per_delay
* in microseconds.
*/
uint64_t acc_delay_us;
/* Range of blocks_per_delay while in FW_SEARCH state. */
int64_t bpd1, bpd2;
/* Time measurements. */
struct timeval t1;
};
/* If @max_process_rate <= 0, the maximum processing rate is infinity.
* The unit of @max_process_rate is KB per second.
*/
void init_flow(struct flow *fw, uint64_t total_size,
long max_process_rate, int progress,
flow_func_flush_chunk_t func_flush_chunk);
void start_measurement(struct flow *fw);
int measure(int fd, struct flow *fw, long processed);
int end_measurement(int fd, struct flow *fw);
static inline int has_enough_measurements(const struct flow *fw)
{
return fw->measured_time_ms > fw->delay_ms;
}
static inline double get_avg_speed_given_time(struct flow *fw,
uint64_t total_time_ms)
{
return (double)(fw->measured_blocks * fw->block_size * 1000) /
total_time_ms;
}
/* Average writing speed in byte/s. */
static inline double get_avg_speed(struct flow *fw)
{
return get_avg_speed_given_time(fw, fw->measured_time_ms);
}
static inline uint64_t get_rem_chunk_size(struct flow *fw)
{
assert(fw->blocks_per_delay > fw->processed_blocks);
return (fw->blocks_per_delay - fw->processed_blocks) * fw->block_size;
}
struct dynamic_buffer {
char *buf;
size_t len;
bool max_buf;
char backup_buf[1 << 21]; /* 2MB */
};
static inline void dbuf_init(struct dynamic_buffer *dbuf)
{
dbuf->buf = dbuf->backup_buf;
dbuf->len = sizeof(dbuf->backup_buf);
dbuf->max_buf = false;
}
void dbuf_free(struct dynamic_buffer *dbuf);
/*
* Although the returned buffer may be smaller than @size,
* this function never returns NULL.
*/
char *dbuf_get_buf(struct dynamic_buffer *dbuf, size_t size);
static inline size_t dbuf_get_len(const struct dynamic_buffer *dbuf)
{
return dbuf->len;
}
#endif /* HEADER_LIBFLOW_H */
f3-9.0/libprobe.c 0000664 0000000 0000000 00000053745 14771250033 0013654 0 ustar 00root root 0000000 0000000 #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 coefficients 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;
/* Although unexpected, some fake cards do recover blocks after
* a reset! This behavior is not consistent, though.
* The first reported case is found here:
* https://github.com/AltraMayor/f3/issues/50
*/
if (b4_reset_count_block < write_target ||
after_reset_count_block < write_target) {
*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 < 8*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-9.0/libprobe.h 0000664 0000000 0000000 00000000550 14771250033 0013643 0 ustar 00root root 0000000 0000000 #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-9.0/libutils.c 0000664 0000000 0000000 00000011265 14771250033 0013674 0 ustar 00root root 0000000 0000000 #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.
* Please don't add @salt here!
*/
int64_array[0] = offset;
/* Thanks to @salt, a drive has to guess the seed. */
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-9.0/libutils.h 0000664 0000000 0000000 00000003242 14771250033 0013675 0 ustar 00root root 0000000 0000000 #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-9.0/log-f3wr 0000775 0000000 0000000 00000000254 14771250033 0013263 0 ustar 00root root 0000000 0000000 #!/usr/bin/env 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-9.0/utils.c 0000664 0000000 0000000 00000012543 14771250033 0013205 0 ustar 00root root 0000000 0000000 #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
#include "version.h"
#include "utils.h"
void adjust_dev_path(const char **dev_path)
{
if (chdir(*dev_path)) {
err(errno, "Can't change working directory to %s at %s()", *dev_path, __func__);
}
*dev_path = ".";
if (!chroot(*dev_path)) {
assert(!chdir("/"));
} else if (errno != EPERM) {
err(errno, "Can't change root directory to %s at %s()", *dev_path, __func__);
}
}
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;
}
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;
}
static inline bool include_this_file(const char *filename,
long start_at, long end_at, long *number)
{
if (!is_my_file(filename))
return false;
*number = number_from_filename(filename);
return start_at <= *number && *number <= end_at;
}
static long count_files(const char *path, long start_at, long end_at)
{
DIR *dir = opendir(path);
struct dirent *entry;
long dummy, total = 0;
if (!dir)
err(errno, "Can't open path %s at %s()", path, __func__);
entry = readdir(dir);
while (entry) {
if (include_this_file(entry->d_name, start_at, end_at, &dummy))
total++;
entry = readdir(dir);
}
closedir(dir);
return total;
}
/* Don't call this function directly, use ls_my_files() instead. */
static long *__ls_my_files(const char *path, long start_at, long end_at,
long *pcount)
{
long total_files = count_files(path, start_at, end_at);
DIR *dir;
struct dirent *entry;
long *ret, index;
assert(total_files >= 0);
ret = malloc(sizeof(*ret) * (total_files + 1));
assert(ret);
dir = opendir(path);
if (!dir)
err(errno, "Can't open path %s at %s()", path, __func__);
entry = readdir(dir);
index = 0;
while (entry) {
long number;
if (include_this_file(entry->d_name, start_at, end_at,
&number)) {
if (index >= total_files) {
/* The folder @path received more files
* before we finished scanning it.
*/
closedir(dir);
free(ret);
return NULL;
}
ret[index++] = number;
}
entry = readdir(dir);
}
closedir(dir);
ret[index] = -1;
*pcount = index;
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)
{
long *ret, my_count;
do {
ret = __ls_my_files(path, start_at, end_at, &my_count);
} while (!ret);
qsort(ret, my_count, sizeof(*ret), cmpintp);
return ret;
}
long arg_to_long(const struct argp_state *state, const char *arg)
{
char *end;
long l = strtol(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 l;
}
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 */
#if (__APPLE__ && __MACH__) || defined(__OpenBSD__)
void msleep(double wait_ms)
{
assert(!usleep(wait_ms * 1000));
}
#else /* Apple Macintosh / OpenBSD */
#include /* For clock_gettime() and clock_nanosleep(). */
void msleep(double wait_ms)
{
struct timespec req;
int ret;
assert(!clock_gettime(CLOCK_MONOTONIC, &req));
/* Add @wait_ms to @req. */
if (wait_ms > 1000) {
time_t sec = wait_ms / 1000;
wait_ms -= sec * 1000;
assert(wait_ms > 0);
req.tv_sec += sec;
}
req.tv_nsec += wait_ms * 1000000;
/* Round @req up. */
if (req.tv_nsec >= 1000000000) {
ldiv_t result = ldiv(req.tv_nsec, 1000000000);
req.tv_sec += result.quot;
req.tv_nsec = result.rem;
}
do {
ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
&req, NULL);
} while (ret == EINTR);
assert(ret == 0);
}
#endif /* Apple Macintosh / OpenBSD */
f3-9.0/utils.h 0000664 0000000 0000000 00000003757 14771250033 0013221 0 ustar 00root root 0000000 0000000 #ifndef HEADER_UTILS_H
#define HEADER_UTILS_H
#include /* For type FILE. */
#include /* For struct timeval. */
#include /* For type uint64_t. */
#include /* For struct argp_state. */
#define SECTOR_SIZE (512)
#define GIGABYTES (1024 * 1024 * 1024)
void adjust_dev_path(const char **dev_path);
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 int64_t delay_ms(const struct timeval *t1,
const struct timeval *t2)
{
return (int64_t)(t2->tv_sec - t1->tv_sec) * 1000 +
(t2->tv_usec - t1->tv_usec) / 1000;
}
void msleep(double wait_ms);
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)
long arg_to_long(const struct argp_state *state, const char *arg);
#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
#ifdef __OpenBSD__
#define POSIX_FADV_SEQUENTIAL 2 /* Expect sequential page references. */
#define POSIX_FADV_DONTNEED 4 /* Don't need these pages. */
/*
* OpenBSD doesn't have posix_fadvise() (...).
* There is some code [in F3] to emulate posix_fadvise for MacOS
* but it uses various fcntl(2) commands that we don't have [in OpenBSD].
*
* -- Stuart Henderson, OpenBSD developer
*/
#define posix_fadvise(fd, offset, len, advice) (0)
#endif /* OpenBSD */
#endif /* HEADER_UTILS_H */
f3-9.0/version.h 0000664 0000000 0000000 00000000157 14771250033 0013535 0 ustar 00root root 0000000 0000000 #ifndef HEADER_VERSION_H
#define HEADER_VERSION_H
#define F3_STR_VERSION "9.0"
#endif /* HEADER_VERSION_H */