pax_global_header 0000666 0000000 0000000 00000000064 15175127362 0014523 g ustar 00root root 0000000 0000000 52 comment=67b8a5d546cbe41b0072c2e62aefe165e4675b61
f3-10.0/ 0000775 0000000 0000000 00000000000 15175127362 0011753 5 ustar 00root root 0000000 0000000 f3-10.0/.agents/ 0000775 0000000 0000000 00000000000 15175127362 0013312 5 ustar 00root root 0000000 0000000 f3-10.0/.agents/rules/ 0000775 0000000 0000000 00000000000 15175127362 0014444 5 ustar 00root root 0000000 0000000 f3-10.0/.agents/rules/coding-style.md 0000664 0000000 0000000 00000005407 15175127362 0017375 0 ustar 00root root 0000000 0000000 ---
trigger: model_decision
description: After generating or editing code
---
# F3 Coding Style
## 1. General Principles
- **Language**: C (C17 standard as specified in the Makefile).
- **Line Length**: Maximum 80 columns. The only exception is for literal strings to facilitate grep-ability of output messages.
- **Portability**: Uses POSIX features and includes OS-specific blocks (e.g., `__APPLE__`, `__OpenBSD__`, `__CYGWIN__`) where necessary.
## 2. Formatting and Indentation
- **Indentation**: Uses **Tabs** for indentation.
- **Braces**: K&R style. Opening braces `{` are on the same line as the statement (`if`, `while`, `for`, `switch`, `struct`, and function definitions).
- **Whitespace**:
- Space after keywords (`if`, `while`, `for`, `switch`, `do`).
- No space between function name and the opening parenthesis `(`.
- Pointers: `char *ptr` (space before the asterisk, not after).
- Alignment: Struct member assignments and function parameters are often aligned using tabs when spanning multiple lines.
## 3. Naming Conventions
- **Files**: Lowercase with `snake_case` (e.g., `f3read.c`, `libutils.h`).
- **Variables and Functions**: `snake_case` (e.g., `check_chunk`, `bytes_read`).
- **Types (structs, enums, typedefs)**: `snake_case` (e.g., `struct block_stats`, `enum block_state`).
- **Macros and Constants**: `UPPER_CASE` (e.g., `SECTOR_ORDER`, `UNUSED`).
- **Enum Members**: Lowercase with a short prefix (e.g., `bs_unknown`, `bs_good`).
## 4. Functions and Variables
- **Scope**: Internal helper functions are marked `static`. Small, performance-critical functions are marked `static inline`.
- **Declarations**: Variables are declared at the beginning of their scope.
- **Initialization**: Structs are often initialized using designated initializers or `memset`.
## 5. Macros
- **Safety**: Multi-line macros use the `do { ... } while (0)` idiom.
- **Parentheses**: Arguments and the final expression are wrapped in parentheses to prevent precedence issues.
- **Alignment**: Backslashes `\` in multi-line macros are aligned.
## 6. Error Handling and Correctness
- **Assertions**: Heavy use of `assert()` for internal state verification and "can't happen" cases.
- **Error Propagation**: Uses `goto out` patterns for resource cleanup or direct returns of error codes (e.g., `errno`).
- **Safety**: Prefers `snprintf` over `sprintf`.
## 7. Headers and Includes
- **Include Guards**: Format `HEADER_FILENAME_H` (e.g., `#ifndef HEADER_LIBUTILS_H`).
- **Order**: Standard library headers followed by local project headers.
- **Documentation**: Comments in headers are often aligned using tabs for readability.
## 8. Comments
- **Style**: Uses C-style comments `/* ... */`.
- **Placement**: Comments are placed above the code they describe or as trailing comments aligned with tabs. f3-10.0/.github/ 0000775 0000000 0000000 00000000000 15175127362 0013313 5 ustar 00root root 0000000 0000000 f3-10.0/.github/workflows/ 0000775 0000000 0000000 00000000000 15175127362 0015350 5 ustar 00root root 0000000 0000000 f3-10.0/.github/workflows/test.yml 0000664 0000000 0000000 00000015663 15175127362 0017065 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-24.04
steps:
- uses: actions/checkout@v3
- run: sudo apt-get update && 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: build/f3write -V
- run: build/f3write --help
- run: ${{ matrix.asroot.sudo }}build/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: build/f3read -V
- run: build/f3read --help
- run: ${{ matrix.asroot.sudo }}build/f3read -s 2 -e 4 -r 50000 ${{ matrix.volume }}
- run: build/f3probe -V
- run: build/f3probe --help
- run: build/f3brew -V
- run: build/f3brew --help
- run: build/f3fix -V
- run: build/f3fix --help
- name: Create loop device for f3probe, f3brew, and f3fix tests
id: loop
run: |
dd if=/dev/zero of=dummy.img bs=1M count=10
sudo losetup -fP dummy.img
echo "dev=$(sudo losetup -j dummy.img | cut -d: -f1)" >> $GITHUB_OUTPUT
- run: sudo build/f3probe ${{ steps.loop.outputs.dev }}
- run: sudo build/f3brew --reset-type=2 -h 0 -e 4 ${{ steps.loop.outputs.dev }}
- run: sudo build/f3fix --first-sec 1 --last-sec 10 ${{ steps.loop.outputs.dev }}
- name: Cleanup loop device
if: always()
run: |
if [ -n "${{ steps.loop.outputs.dev }}" ]; then
sudo losetup -d ${{ steps.loop.outputs.dev }}
fi
rm -f dummy.img
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-14
steps:
- uses: actions/checkout@v3
- run: brew install argp-standalone
- run: make
- if: matrix.volume == 'relative-path'
run: mkdir relative-path
- run: build/f3write -V
- run: build/f3write --help
- run: ${{ matrix.asroot.sudo }}build/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: build/f3read -V
- run: build/f3read --help
- run: ${{ matrix.asroot.sudo }}build/f3read -s 2 -e 4 -r 50000 ${{ matrix.volume }}
OpenBSD:
strategy:
fail-fast: false
matrix:
volume:
- /tmp
- .
- relative-path
asroot:
- name: ''
sudo: ''
- name: ' as root'
sudo: 'sudo '
exclude:
- volume: .
asroot: { name: ' as root', sudo: 'sudo ' }
- volume: relative-path
asroot: { name: ' as root', sudo: 'sudo ' }
name: OpenBSD ${{ matrix.volume }}${{ matrix.asroot.name }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Test on OpenBSD
uses: cross-platform-actions/action@v0.25.0
with:
operating_system: openbsd
version: '7.5'
run: |
sudo pkg_add argp-standalone gmake
gmake
if [ "${{ matrix.volume }}" = "relative-path" ]; then
mkdir relative-path
fi
build/f3write -V
build/f3write --help
${{ matrix.asroot.sudo }}build/f3write -s 2 -e 4 -w 50000 ${{ matrix.volume }}
stat ${{ matrix.volume }}/2.h2w
stat ${{ matrix.volume }}/3.h2w
stat ${{ matrix.volume }}/4.h2w
build/f3read -V
build/f3read --help
${{ matrix.asroot.sudo }}build/f3read -s 2 -e 4 -r 50000 ${{ matrix.volume }}
FreeBSD:
strategy:
fail-fast: false
matrix:
volume:
- /tmp
- .
- relative-path
asroot:
- name: ''
sudo: ''
- name: ' as root'
sudo: 'sudo '
exclude:
- volume: .
asroot: { name: ' as root', sudo: 'sudo ' }
- volume: relative-path
asroot: { name: ' as root', sudo: 'sudo ' }
name: FreeBSD ${{ matrix.volume }}${{ matrix.asroot.name }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Test on FreeBSD
uses: cross-platform-actions/action@v0.25.0
with:
operating_system: freebsd
version: '14.1'
run: |
sudo pkg install -y argp-standalone gmake
gmake
if [ "${{ matrix.volume }}" = "relative-path" ]; then
mkdir relative-path
fi
build/f3write -V
build/f3write --help
${{ matrix.asroot.sudo }}build/f3write -s 2 -e 4 -w 50000 ${{ matrix.volume }}
stat ${{ matrix.volume }}/2.h2w
stat ${{ matrix.volume }}/3.h2w
stat ${{ matrix.volume }}/4.h2w
build/f3read -V
build/f3read --help
${{ matrix.asroot.sudo }}build/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: '& .\build\f3write.exe -V'
- run: '& .\build\f3write.exe --help'
- run: '& .\build\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: '& .\build\f3read.exe -V'
- run: '& .\build\f3read.exe --help'
- run: '& .\build\f3read.exe -s 2 -e 4 -r 50000 ${{ matrix.volume.cygwin }}'
f3-10.0/.gitignore 0000664 0000000 0000000 00000000103 15175127362 0013735 0 ustar 00root root 0000000 0000000 *.swp
*~
doc/_build
build/
a/
cscope.out
perf.data
perf.data.old
f3-10.0/.vscode/ 0000775 0000000 0000000 00000000000 15175127362 0013314 5 ustar 00root root 0000000 0000000 f3-10.0/.vscode/gdb-sudo.sh 0000775 0000000 0000000 00000000075 15175127362 0015361 0 ustar 00root root 0000000 0000000 #!/bin/bash
#sudo /usr/bin/gdb "$@"
pkexec /usr/bin/gdb "$@"
f3-10.0/.vscode/launch.json 0000664 0000000 0000000 00000003564 15175127362 0015471 0 ustar 00root root 0000000 0000000 {
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "f3brew test",
"type": "cppdbg",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/build/f3brew",
"args": ["--debug", "--fix-cmd", "test"],
"MIMode": "gdb",
},
{
"name": "f3probe unit-test",
"type": "cppdbg",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/build/f3probe",
"args": ["--debug-unit-test", "test"],
"MIMode": "gdb",
},
{
"name": "f3probe simple test",
"type": "cppdbg",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/build/f3probe",
"args": ["--debug", "--destructive", "--verbose", "test"],
"MIMode": "gdb",
},
{
"name": "f3probe test",
"type": "cppdbg",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/build/f3probe",
"args": ["--debug-real-size=1G", "--debug-fake-size=1T", "--debug-wrap=40", "--debug-cache-order=21", "--debug-strict-cache", "--destructive", "--verbose", "test"],
"MIMode": "gdb",
// Uncomment the following line to run under sudo:
//"miDebuggerPath": "${workspaceFolder}/.vscode/gdb-sudo.sh"
},
{
// Create folder "a" before launching.
"name": "f3write a",
"type": "cppdbg",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/build/f3write",
"args": ["--end-at=5", "a"],
"MIMode": "gdb",
},
{
// Create folder "a" before launching.
"name": "f3read a",
"type": "cppdbg",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/build/f3read",
"args": ["a"],
"MIMode": "gdb",
}
]
} f3-10.0/.vscode/settings.json 0000664 0000000 0000000 00000001137 15175127362 0016051 0 ustar 00root root 0000000 0000000 {
"makefile.launchConfigurations": [
{
"cwd": "${workspaceFolder}",
"binaryPath": "${workspaceFolder}/build/f3brew",
"binaryArgs": []
},
{
"cwd": "${workspaceFolder}",
"binaryPath": "${workspaceFolder}/build/f3fix",
"binaryArgs": []
},
{
"cwd": "${workspaceFolder}",
"binaryPath": "${workspaceFolder}/build/f3probe",
"binaryArgs": []
},
{
"cwd": "${workspaceFolder}",
"binaryPath": "${workspaceFolder}/build/f3read",
"binaryArgs": []
},
{
"cwd": "${workspaceFolder}",
"binaryPath": "${workspaceFolder}/build/f3write",
"binaryArgs": []
}
]
} f3-10.0/.vscode/tasks.json 0000664 0000000 0000000 00000000522 15175127362 0015333 0 ustar 00root root 0000000 0000000 {
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "make",
"type": "shell",
"command": "make",
"args": ["all", "extra"],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": "$gcc"
}
]
} f3-10.0/Dockerfile 0000664 0000000 0000000 00000000456 15175127362 0013752 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-10.0/LICENSE 0000664 0000000 0000000 00000104515 15175127362 0012766 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-10.0/Makefile 0000664 0000000 0000000 00000004413 15175127362 0013415 0 ustar 00root root 0000000 0000000 CC ?= gcc
CFLAGS += -std=c17 -Wall -Wextra -pedantic -MMD -ggdb
BUILD_DIR = build
SRC_DIR = src
TARGETS = $(BUILD_DIR)/f3write $(BUILD_DIR)/f3read
EXTRA_TARGETS = $(BUILD_DIR)/f3probe $(BUILD_DIR)/f3brew $(BUILD_DIR)/f3fix
PREFIX = /usr/local
INSTALL = install
LN = ln
UNLINK = unlink
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 man/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
uninstall: uninstall-extra
cd $(DESTDIR)$(PREFIX)/bin ; rm $(notdir $(TARGETS))
rm -f $(DESTDIR)$(PREFIX)/share/man/man1/f3read.1
$(UNLINK) $(DESTDIR)$(PREFIX)/share/man/man1/f3write.1
uninstall-extra:
cd $(DESTDIR)$(PREFIX)/bin ; rm $(notdir $(EXTRA_TARGETS))
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c | $(BUILD_DIR)
$(CC) $(CFLAGS) -c $< -o $@
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
$(BUILD_DIR)/f3write: $(BUILD_DIR)/libutils.o $(BUILD_DIR)/libfile.o $(BUILD_DIR)/libflow.o $(BUILD_DIR)/f3write.o
$(CC) -o $@ $^ $(LDFLAGS) -lm
$(BUILD_DIR)/f3read: $(BUILD_DIR)/libutils.o $(BUILD_DIR)/libfile.o $(BUILD_DIR)/libflow.o $(BUILD_DIR)/f3read.o
$(CC) -o $@ $^ $(LDFLAGS) -lm
$(BUILD_DIR)/f3probe: $(BUILD_DIR)/libutils.o $(BUILD_DIR)/libflow.o $(BUILD_DIR)/libdevs.o $(BUILD_DIR)/libprobe.o $(BUILD_DIR)/f3probe.o
$(CC) -o $@ $^ $(LDFLAGS) -lm -ludev
$(BUILD_DIR)/f3brew: $(BUILD_DIR)/libutils.o $(BUILD_DIR)/libflow.o $(BUILD_DIR)/libdevs.o $(BUILD_DIR)/f3brew.o
$(CC) -o $@ $^ $(LDFLAGS) -lm -ludev
$(BUILD_DIR)/f3fix: $(BUILD_DIR)/libutils.o $(BUILD_DIR)/f3fix.o
$(CC) -o $@ $^ $(LDFLAGS) -lparted
-include $(BUILD_DIR)/*.d
.PHONY: cscope clean uninstall uninstall-extra
cscope:
cscope -b $(SRC_DIR)/*.c $(SRC_DIR)/*.h
clean:
rm -rf $(BUILD_DIR) cscope.out
f3-10.0/README.rst 0000664 0000000 0000000 00000032010 15175127362 0013436 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::
$ build/f3write /media/michel/5EBD-5C80/
$ build/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::
# build/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::
# build/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-10.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-Gui `__ It's a GUI for Linux using Flatpak.
It already includes ``f3write``, ``f3read``, ``f3probe``, and ``f3fix``. Other features
include automatically formatting the newly fixed partition using ``f3fix``. Author:
Daniel Tavares.
`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.
`Fake-USB-Tester `__ is a Linux GUI
written in Python and Qt5. Fake-USB-Tester supports ``f3write``, ``f3read``,
and ``f3probe``. Author: shampuan.
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
- ``man/f3read.1`` - Man page for f3read and f3write
In order to read this manual page, run ``man build/f3read.1``.
To install the page, run
``install --owner=root --group=root --mode=644 man/f3read.1 /usr/share/man/man1``.
- ``LICENSE`` - License (GPLv3)
- ``Makefile`` - make(1) file
- ``README`` - This file
- ``src/*.h`` and ``src/*.c`` - C code of F3
- ``flake.nix`` - nix package manager configuration allowing automatic building and or installation of repository contents.
- ``flake.lock`` - specifies build dependency package versions so the nix package manager can build 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:
- ``scripts/f3write.h2w`` - Script to create files exactly like H2testw.
Use example: ``scripts/f3write.h2w /media/michel/5EBD-5C80/``.
- ``scripts/log-f3wr`` - Script that runs f3write and f3read, and records
their output into a log file.
Use example: ``scripts/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-10.0/changelog 0000664 0000000 0000000 00000007071 15175127362 0013632 0 ustar 00root root 0000000 0000000 Version 10.0 - Apr 29, 2026
* f3probe: New probing algorithm and --verbose flag
* f3brew: Progress report and rate limiting (i.e., --max-write-rate and --max-read-rate)
* f3brew: Add --fix-cmd flag
* f3write/f3read: Report per-file min/max and average speeds
* GitHub Actions: FreeBSD and OpenBSD support
* Move codebase from C99 to C17 and refactor project
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-10.0/doc/ 0000775 0000000 0000000 00000000000 15175127362 0012520 5 ustar 00root root 0000000 0000000 f3-10.0/doc/Makefile 0000664 0000000 0000000 00000016646 15175127362 0014175 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-10.0/doc/conf.py 0000664 0000000 0000000 00000027235 15175127362 0014030 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 = '10.0'
# The full version, including alpha/beta/rc tags.
release = '10.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-10.0/doc/contribute.rst 0000664 0000000 0000000 00000007474 15175127362 0015444 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 opening an issue on GitHub to offer
donating it to anyone willing to help with the development of F3.
Even if having someone accepting your offer is a long shot,
it's a bet in the right direction: growing our community.
To help someone identify how your fake drive can support their tests,
include in the issue the output you got from ``f3write``, ``f3read``, and
(if possible) ``f3probe`` as well as the size the card was expected to be.
The output of ``f3probe`` is particularly useful when you use the parameters
``--verbose``, ``--destructive``, and ``--time-ops``.
- Improve this documentation. New users would benefit from your perspective
on how F3 works and how to use it. Create a pull request with your
improvements and I'll prioritize reviewing it.
- 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.
- If you have a dual-boot machine with Windows and Linux, write a
blog entry that compares h2testw vs f3write/f3read, FakeFlashTest.exe and
ValiDrive vs f3probe. If you do this comparison, please send me the link to
publish it on this page.
- 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-10.0/doc/history.rst 0000664 0000000 0000000 00000005423 15175127362 0014757 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-10.0/doc/index.rst 0000664 0000000 0000000 00000000673 15175127362 0014367 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-10.0/doc/introduction.rst 0000777 0000000 0000000 00000000000 15175127362 0017670 2../README.rst ustar 00root root 0000000 0000000 f3-10.0/doc/usage.rst 0000664 0000000 0000000 00000112353 15175127362 0014363 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:
::
$ build/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
$ build/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:
::
$ build/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
$ build/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:
``scripts/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:
::
$ build/f3write --end-at=16 /media/michel/DISK_IMG/ && build/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:
::
$ build/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:
::
% build/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
``scripts/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 build/f3probe --destructive --time-ops /dev/sdb
[sudo] password for michel:
F3 probe 10.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 build/f3probe --time-ops /dev/sdc
[sudo] password for michel:
F3 probe 10.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 build/f3fix --last-sec=16477878 /dev/sdb
F3 fix 10.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:
::
$ build/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
$ build/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-10.0/flake.lock 0000664 0000000 0000000 00000001071 15175127362 0013706 0 ustar 00root root 0000000 0000000 {
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1766314097,
"narHash": "sha256-laJftWbghBehazn/zxVJ8NdENVgjccsWAdAqKXhErrM=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "306ea70f9eb0fb4e040f8540e2deab32ed7e2055",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
f3-10.0/flake.nix 0000664 0000000 0000000 00000003045 15175127362 0013557 0 ustar 00root root 0000000 0000000 {
description = "F3 - Fight flash fraud";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
};
outputs = { self, nixpkgs }: {
packages = nixpkgs.lib.genAttrs [ "aarch64-linux" "x86_64-linux" "aarch64-darwin" ] (system:
let
pkgs = import nixpkgs { inherit system; };
in
{
f3 = pkgs.stdenv.mkDerivation {
pname = "f3";
version = builtins.head (builtins.match ''.*#define[[:space:]]+F3_STR_VERSION[[:space:]]+"([0-9.]+)".*'' (builtins.readFile (self + "/src/version.h")));
src = ./.;
nativeBuildInputs = [ pkgs.clang ];
buildInputs = pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux [
pkgs.systemd
pkgs.parted
]
++ pkgs.lib.optionals pkgs.stdenv.hostPlatform.isDarwin [ pkgs.argp-standalone ];
installPhase = ''
runHook preInstall
mkdir -p $out/bin
make install PREFIX=$out
make install-extra PREFIX=$out
runHook postInstall
'';
meta = with pkgs.lib; {
description = "F3 - Fight flash fraud";
license = licenses.gpl3;
maintainers = [ maintainers.llamato ];
platforms = platforms.unix;
};
};
devShells.${system}.default = pkgs.mkShell {
buildInputs = with pkgs; [
cmake
gcc
gdb
];
};
});
defaultPackage = {
x86_64-linux = self.packages.x86_64-linux.f3;
aarch64-linux = self.packages.aarch64-linux.f3;
aarch64-darwin = self.packages.aarch64-darwin.f3;
};
};
} f3-10.0/man/ 0000775 0000000 0000000 00000000000 15175127362 0012526 5 ustar 00root root 0000000 0000000 f3-10.0/man/f3read.1 0000664 0000000 0000000 00000002664 15175127362 0013764 0 ustar 00root root 0000000 0000000 .\"Text automatically generated by txt2man
.TH F3 "1" "October 2020" "F3 10.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-10.0/scripts/ 0000775 0000000 0000000 00000000000 15175127362 0013442 5 ustar 00root root 0000000 0000000 f3-10.0/scripts/f3write.h2w 0000775 0000000 0000000 00000000157 15175127362 0015455 0 ustar 00root root 0000000 0000000 #!/usr/bin/env bash
$(dirname $0)/f3write "$@" || exit 1
FILES=("${@: -1}/*.h2w")
truncate --size=/1M $FILES
f3-10.0/scripts/log-f3wr 0000775 0000000 0000000 00000000254 15175127362 0015031 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-10.0/src/ 0000775 0000000 0000000 00000000000 15175127362 0012542 5 ustar 00root root 0000000 0000000 f3-10.0/src/f3brew.c 0000664 0000000 0000000 00000040253 15175127362 0014102 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 "version.h"
#include "libutils.h"
#include "libdevs.h"
#include "libflow.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", 'a', "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", 'm', "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},
{"fix-cmd", 'x', NULL, 0,
"Show how to call f3fix to fix the drive", 0},
{"max-read-rate", 'r', "KB/s", 0,
"Maximum read rate", 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},
{"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;
bool fix_cmd;
/* Geometry. */
uint64_t real_size_byte;
uint64_t fake_size_byte;
int wrap;
unsigned int block_order;
int cache_order;
int strict_cache;
/* What to do. */
uint64_t first_block;
uint64_t last_block;
/* Flow control and reporting. */
long max_read_rate;
long max_write_rate;
int show_progress;
};
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 'a':
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 'm':
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 < SECTOR_ORDER || ll > MEGABYTE_ORDER))
argp_error(state,
"Block order must be in the interval [%i, %i] or be zero",
SECTOR_ORDER, MEGABYTE_ORDER);
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 'r':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_read_rate = ll;
break;
case 'w':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_write_rate = ll;
break;
case 'p':
args->show_progress = !!arg_to_ll_bytes(state, arg);
break;
case 'W':
args->test_write = false;
break;
case 'R':
args->test_read = false;
break;
case 'x':
args->fix_cmd = 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");
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, struct flow *fw,
uint64_t first_block, uint64_t last_block)
{
const unsigned int block_size = dev_get_block_size(dev);
const unsigned int block_order = dev_get_block_order(dev);
uint64_t offset = first_block << block_order;
uint64_t first_pos = first_block;
struct dynamic_buffer dbuf;
dbuf_init(&dbuf);
start_measurement(fw);
while (first_pos <= last_block) {
const uint64_t max_blocks_to_write = last_block - first_pos + 1;
uint64_t blocks_to_write =
MIN(get_rem_chunk_blocks(fw), max_blocks_to_write);
size_t buf_len = blocks_to_write << block_order;
char *buffer, *stamp_blk;
uint64_t pos, next_pos;
buffer = dbuf_get_buf(&dbuf, block_order, &buf_len);
blocks_to_write = buf_len >> block_order;
assert(blocks_to_write > 0);
next_pos = first_pos + blocks_to_write;
stamp_blk = buffer;
for (pos = first_pos; pos < next_pos; pos++) {
fill_buffer_with_block(stamp_blk, block_order, offset, 0);
stamp_blk += block_size;
offset += block_size;
}
if (dev_write_blocks(dev, buffer, first_pos, next_pos - 1)) {
clear_progress(fw);
warn("Failed to write blocks from 0x%" PRIx64
" to 0x%" PRIx64, first_pos, next_pos - 1);
}
measure(fw, blocks_to_write, NULL);
first_pos = next_pos;
}
end_measurement(fw);
dbuf_free(&dbuf);
}
/* XXX Properly handle return errors. */
static void test_write_blocks(struct device *dev,
uint64_t first_block, uint64_t last_block,
long max_write_rate, int show_progress)
{
const unsigned int block_order = dev_get_block_order(dev);
const uint64_t total_blocks = last_block - first_block + 1;
struct flow fw;
printf("Writing block%s from 0x%" PRIx64 " to 0x%" PRIx64 "... ",
first_block != last_block ? "s" : "", first_block, last_block);
fflush(stdout);
init_flow(&fw, block_order, total_blocks, max_write_rate,
FW_MAX_BLOCKS_PER_DELAY_NONE,
show_progress ? printf_flush_cb : dummy_cb, 0);
write_blocks(dev, &fw, first_block, last_block);
printf("Done\n");
print_avg_seq_speed(&fw, "write", false);
printf("\n");
}
struct block_range {
enum block_state state;
unsigned int block_order;
uint64_t start_block;
uint64_t end_block;
/* Only used by state bs_overwritten. */
uint64_t found_block;
};
#define INIT_UNKNOWN_RANGE(block_order) { \
.state = bs_unknown, \
.block_order = (block_order), \
.start_block = 0, \
.end_block = UINT64_MAX, \
.found_block = 0 \
}
static void print_block_range(const struct block_range *range)
{
printf("[%s] from block 0x%" PRIx64 " to 0x%" PRIx64,
block_state_to_str(range->state),
range->start_block, range->end_block);
switch (range->state) {
case bs_good:
case bs_bad:
case bs_changed:
break;
case bs_overwritten:
printf(", found block 0x%" PRIx64, range->found_block);
break;
default:
assert(0);
break;
}
printf("\n");
}
static inline bool is_block(uint64_t offset, unsigned int block_order)
{
return !(((1ULL << block_order) - 1) & offset);
}
static void update_good_range(struct block_range *good_range,
const struct block_range *range)
{
uint64_t good_range_blocks, range_blocks;
if (range->state != bs_good)
return;
good_range_blocks =
good_range->end_block - good_range->start_block + 1;
range_blocks = range->end_block - range->start_block + 1;
if (range_blocks > good_range_blocks)
*good_range = *range;
}
static void validate_block(struct flow *fw, uint64_t block,
const char *probe_blk, unsigned int block_order,
struct block_range *range, struct block_range *good_range,
struct block_stats *stats)
{
const uint64_t expected_offset = block << block_order;
uint64_t found_offset;
enum block_state state = validate_block_update_stats(probe_blk,
block_order, expected_offset, &found_offset, 0, stats);
const uint64_t found_block = found_offset >> block_order;
bool push_range;
assert(is_block(found_offset, block_order));
push_range = (range->state != state) || (
state == bs_overwritten
&& (
(block - range->start_block)
!=
(found_block - range->found_block)
)
);
if (push_range) {
if (range->state != bs_unknown) {
clear_progress(fw);
print_block_range(range);
update_good_range(good_range, range);
}
range->state = state;
range->start_block = block;
range->end_block = block;
range->found_block = found_block;
} else {
range->end_block = block;
}
}
static void read_blocks(struct device *dev, struct flow *fw,
uint64_t first_block, uint64_t last_block, struct block_stats *stats,
struct block_range *good_range)
{
const unsigned int block_size = dev_get_block_size(dev);
const unsigned int block_order = dev_get_block_order(dev);
uint64_t first_pos = first_block;
struct block_range range = INIT_UNKNOWN_RANGE(block_order);
struct dynamic_buffer dbuf;
dbuf_init(&dbuf);
start_measurement(fw);
while (first_pos <= last_block) {
const uint64_t max_blocks_to_read = last_block - first_pos + 1;
uint64_t blocks_to_read =
MIN(get_rem_chunk_blocks(fw), max_blocks_to_read);
size_t buf_len = blocks_to_read << block_order;
char *buffer, *probe_blk;
uint64_t pos, next_pos;
buffer = dbuf_get_buf(&dbuf, block_order, &buf_len);
blocks_to_read = buf_len >> block_order;
assert(blocks_to_read > 0);
next_pos = first_pos + blocks_to_read;
if (dev_read_blocks(dev, buffer, first_pos, next_pos - 1)) {
clear_progress(fw);
warn("Failed to read blocks from 0x%" PRIx64
" to 0x%" PRIx64, first_pos, next_pos - 1);
}
probe_blk = buffer;
for (pos = first_pos; pos < next_pos; pos++) {
validate_block(fw, pos, probe_blk, block_order,
&range, good_range, stats);
probe_blk += block_size;
}
measure(fw, blocks_to_read, NULL);
first_pos = next_pos;
}
end_measurement(fw);
dbuf_free(&dbuf);
if (range.state != bs_unknown) {
print_block_range(&range);
update_good_range(good_range, &range);
} else {
assert(first_block > last_block);
}
}
static void print_fix_cmd(const char *filename,
const struct block_range *good_range)
{
const uint64_t first_1MB_block =
MEGABYTE_SIZE >> good_range->block_order;
const unsigned int shift = good_range->block_order - SECTOR_ORDER;
const uint64_t first_good_sector = good_range->start_block << shift;
const uint64_t last_good_sector =
((good_range->end_block + 1) << shift) - 1;
uint64_t size_byte;
assert(MEGABYTE_ORDER >= good_range->block_order);
assert(good_range->block_order >= SECTOR_ORDER);
/* Set size_byte. */
if (good_range->state != bs_good) {
size_byte = 0;
} else if (good_range->end_block >= first_1MB_block) {
const uint64_t start_block =
good_range->start_block <= first_1MB_block
? first_1MB_block
: good_range->start_block;
size_byte = (good_range->end_block - start_block + 1) <<
good_range->block_order;
} else {
size_byte = 0;
}
if (size_byte < MEGABYTE_SIZE) {
printf("There is no good region large enough to \"fix\" this device.\n\n");
return;
}
printf("You can \"fix\" this device using the following command:\n");
if (good_range->start_block < first_1MB_block) {
printf("f3fix --last-sec=%" PRIu64 " %s\n\n",
last_good_sector, filename);
return;
}
printf("f3fix --first-sec=%" PRIu64 " --last-sec=%" PRIu64 " %s\n\n",
first_good_sector, last_good_sector, filename);
}
/* XXX Properly handle return errors. */
static void test_read_blocks(struct device *dev,
uint64_t first_block, uint64_t last_block,
long max_read_rate, int show_progress, bool fix_cmd)
{
const unsigned int block_order = dev_get_block_order(dev);
const uint64_t total_blocks = last_block - first_block + 1;
struct flow fw;
struct block_stats stats = { 0, 0, 0, 0 };
struct block_range good_range = INIT_UNKNOWN_RANGE(block_order);
printf("Reading block%s from 0x%" PRIx64 " to 0x%" PRIx64 ":\n",
first_block != last_block ? "s" : "", first_block, last_block);
init_flow(&fw, block_order, total_blocks, max_read_rate,
FW_MAX_BLOCKS_PER_DELAY_NONE,
show_progress ? printf_flush_cb : dummy_cb, 0);
read_blocks(dev, &fw, first_block, last_block, &stats, &good_range);
print_stats(&stats, block_order, "block");
print_avg_seq_speed(&fw, "read", false);
printf("\n");
if (fix_cmd)
print_fix_cmd(dev_get_filename(dev), &good_range);
}
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,
.fix_cmd = false,
.real_size_byte = 2 * GIGABYTE_SIZE,
.fake_size_byte = 16 * GIGABYTE_SIZE,
.wrap = 31,
.block_order = SECTOR_ORDER,
.cache_order = -1,
.strict_cache = false,
.first_block = 0,
.last_block = -1ULL,
.max_read_rate = FW_MAX_PROCESS_RATE_NONE,
.max_write_rate = FW_MAX_PROCESS_RATE_NONE,
/* If stdout isn't a terminal, suppress progress. */
.show_progress = isatty(STDOUT_FILENO),
};
struct device *dev;
unsigned int block_order;
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);
}
block_order = dev_get_block_order(dev);
printf("Physical block size: 2^%i Byte%s\n\n",
block_order, block_order != 0 ? "s" : "");
very_last_block = (dev_get_size_byte(dev) >> block_order) - 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,
args.max_write_rate, args.show_progress);
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,
args.max_read_rate, args.show_progress, args.fix_cmd);
free_device(dev);
return 0;
} f3-10.0/src/f3fix.c 0000664 0000000 0000000 00000014355 15175127362 0013735 0 ustar 00root root 0000000 0000000 #define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 600
#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 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_ll_bytes(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_ll_bytes(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,
unsigned int logical_sector_size)
{
assert(logical_sector_size >= SECTOR_SIZE);
assert((logical_sector_size & (SECTOR_SIZE - 1)) == 0);
return sector / (logical_sector_size >> SECTOR_ORDER);
}
/* 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"),
/* Skip first 1MB to avoid the partition table. */
.first_sec = MEGABYTE_SIZE / SECTOR_SIZE,
};
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-10.0/src/f3probe.c 0000664 0000000 0000000 00000040146 15175127362 0014253 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 "version.h"
#include "libprobe.h"
#include "libutils.h"
#include "libdevs.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", 'a', "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", 'm', "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},
{"time-ops", 't', NULL, 0,
"Time reads, writes, and resets", 0},
{"verbose", 'v', NULL, 0,
"Show detailed progress", 0},
{"show-progress", 'p', "NUM", 0,
"Show progress if NUM is not zero", 0},
{"max-read-rate", 'r', "KB/s", 0,
"Maximum read rate", 0},
{"max-write-rate", 'w', "KB/s", 0,
"Maximum write rate", 0},
{ 0 }
};
struct args {
char *filename;
/* Debugging options. */
bool debug;
bool unit_test;
bool keep_file;
/* Behavior options. */
bool save;
bool min_mem;
bool time_ops;
bool verbose;
bool show_progress;
/* Flow control. */
long max_read_rate;
long max_write_rate;
/* Geometry. */
uint64_t real_size_byte;
uint64_t fake_size_byte;
int wrap;
unsigned 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 'a':
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 'm':
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 < SECTOR_ORDER || ll > MEGABYTE_ORDER))
argp_error(state,
"Block order must be in the interval [%i, %i] or be zero",
SECTOR_ORDER, MEGABYTE_ORDER);
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 't':
args->time_ops = true;
break;
case 'v':
args->verbose = true;
break;
case 'p':
args->show_progress = !!arg_to_ll_bytes(state, arg);
break;
case 'r':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_read_rate = ll;
break;
case 'w':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_write_rate = ll;
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;
unsigned int block_order;
int cache_order;
int strict_cache;
};
static const struct unit_test_item ftype_to_params[] = {
/* Smallest good drive. */
{2 * MEGABYTE_SIZE, 2 * MEGABYTE_SIZE, MEGABYTE_ORDER + 1, SECTOR_ORDER, -1, false},
/* Good, 4KB-block, 1GB drive. */
{GIGABYTE_SIZE, GIGABYTE_SIZE, GIGABYTE_ORDER, KILOBYTE_ORDER + 2, -1, false},
/* Bad drive. */
{0, GIGABYTE_SIZE, GIGABYTE_ORDER, SECTOR_ORDER, -1, false},
/* Geometry of a real limbo drive. */
{1777645568ULL, 32505331712ULL, GIGABYTE_ORDER + 5, SECTOR_ORDER, -1, false},
/* Wraparound drive. */
{2 * GIGABYTE_SIZE, 16 * GIGABYTE_SIZE, GIGABYTE_ORDER + 1, SECTOR_ORDER, -1, false},
/* Chain drive. */
{2 * GIGABYTE_SIZE, 16 * GIGABYTE_SIZE, GIGABYTE_ORDER + 2, SECTOR_ORDER, -1, false},
/* Extreme case for memory usage (limbo drive). */
{MEGABYTE_SIZE + SECTOR_SIZE, TERABYTE_SIZE, TERABYTE_ORDER, SECTOR_ORDER, -1, false},
/* Geometry of a real limbo drive with 256MB of strict cache. */
{7600799744ULL, 67108864000ULL, GIGABYTE_ORDER + 6, SECTOR_ORDER, 19, true},
/* The drive before with a non-strict cache. */
{7600799744ULL, 67108864000ULL, GIGABYTE_ORDER + 6, SECTOR_ORDER, 19, false},
/* The devil drive I. */
{0, TERABYTE_SIZE, TERABYTE_ORDER, SECTOR_ORDER, 21, true},
/* The devil drive II. */
{0, TERABYTE_SIZE, TERABYTE_ORDER, SECTOR_ORDER, 21, false},
};
static int unit_test(const char *filename)
{
const unsigned int n_cases = DIM(ftype_to_params);
unsigned int i, success = 0;
for (i = 0; i < 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);
struct probe_results results;
enum fake_type fake_type;
uint64_t max_written_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_written_blocks = probe_max_written_blocks(dev);
assert(!probe_device(dev, &results, dummy_cb, false, 0, 0));
free_device(dev);
fake_type = dev_param_to_type(results.real_size_byte,
results.announced_size_byte, results.wrap,
results.block_order);
/* Report */
printf("Test %i\t\ttype/real size/fake size/module/cache size/block size\n",
i + 1);
printf("\t\t%s/%.2f %s/%.2f %s/2^%i Byte%s/%.2f %s/2^%i Byte%s\n",
fake_type_to_name(origin_type),
f_real, unit_real, f_fake, unit_fake, item->wrap,
item->wrap != 0 ? "s" : "",
f_cache, unit_cache, item->block_order,
item->block_order != 0 ? "s" : "");
if (results.real_size_byte == item->real_size_byte &&
results.announced_size_byte == item->fake_size_byte &&
results.wrap == item->wrap &&
/* probe_device() returns an upper bound of
* the cache size.
*/
item_cache_byte <= (results.cache_size_block <<
results.block_order) &&
results.block_order == item->block_order) {
success++;
printf("\t\tPerfect!\tMax # of written block%s: %" PRIu64 "\n\n",
max_written_blocks != 1 ? "s" : "",
max_written_blocks);
} else {
double ret_f_real = results.real_size_byte;
double ret_f_fake = results.announced_size_byte;
double ret_f_cache = results.cache_size_block <<
results.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%s/%.2f %s/2^%i Byte%s\n\n",
fake_type_to_name(fake_type),
ret_f_real, ret_unit_real,
ret_f_fake, ret_unit_fake, results.wrap,
results.wrap != 0 ? "s" : "",
ret_f_cache, ret_unit_cache,
results.block_order,
results.block_order != 0 ? "s" : "");
}
}
printf("SUMMARY: ");
if (success == n_cases)
printf("Perfect!\n");
else
printf("Missed %u tests out of %u\n",
n_cases - success, n_cases);
return 0;
}
static inline void report_size(const char *prefix, uint64_t bytes,
unsigned int block_order)
{
report_probed_size(0, printf_cb, prefix, bytes, block_order);
}
static inline void report_order(const char *prefix, unsigned int order)
{
report_probed_order(0, printf_cb, prefix, order);
}
static inline void report_cache(const char *prefix, uint64_t cache_size_block,
unsigned int block_order)
{
report_probed_cache(0, printf_cb, prefix, cache_size_block,
block_order);
}
static inline void report_speed(const char *prefix, uint64_t blocks,
uint64_t time_ns, unsigned int block_order)
{
report_io_speed(0, printf_cb, prefix, blocks, "block", time_ns,
block_order);
}
static void report_probe_time(const char *prefix, uint64_t nsec)
{
char str[TIME_STR_SIZE];
nsec_to_str(nsec, str);
printf("%s %s\n", prefix, str);
}
static void report_ops(const char *op, uint64_t blocks, uint64_t time_ns)
{
char str1[TIME_STR_SIZE], str2[TIME_STR_SIZE];
nsec_to_str(time_ns, str1);
nsec_to_str(blocks > 0 ? time_ns / blocks : 0, str2);
printf("%10s: %s / %" PRIu64 " = %s\n", op, str1, blocks, str2);
}
static int test_device(struct args *args)
{
struct timespec t1, t2;
struct probe_results results;
struct device *dev, *pdev, *sdev;
enum fake_type fake_type;
uint64_t read_blocks, read_time_ns;
uint64_t write_blocks, write_time_ns;
uint64_t reset_count, reset_time_ns;
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, RT_NONE);
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_max_written_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(!clock_gettime(CLOCK_MONOTONIC, &t1));
/* XXX Have a better error handling to recover
* the state of the drive.
*/
assert(!probe_device(dev, &results,
args->verbose ? printf_flush_cb : dummy_cb,
args->show_progress,
args->max_read_rate, args->max_write_rate));
assert(!clock_gettime(CLOCK_MONOTONIC, &t2));
if (args->verbose) {
/* Isolate the verbose output. */
printf("\n");
}
/* 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_blocks, &read_time_ns,
&write_blocks, &write_time_ns,
&reset_count, &reset_time_ns);
if (sdev) {
uint64_t very_last_pos = results.real_size_byte >>
results.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);
}
free_device(dev);
if (args->save)
printf("\n");
fake_type = dev_param_to_type(results.real_size_byte,
results.announced_size_byte, results.wrap,
results.block_order);
switch (fake_type) {
case FKTY_GOOD:
printf("Good news: The device `%s' is the real thing\n",
args->filename);
break;
case FKTY_BAD:
printf("Bad news: The device `%s' is damaged\n",
args->filename);
break;
case FKTY_LIMBO:
case FKTY_WRAPAROUND:
case FKTY_CHAIN: {
const uint64_t last_good_block = (results.real_size_byte >>
results.block_order) - 1;
const uint64_t last_good_sector = (results.real_size_byte >>
SECTOR_ORDER) - 1;
assert(results.block_order >= SECTOR_ORDER);
printf("Bad news: The device `%s' is a counterfeit of type %s\n\n"
"Use the command below to check all blocks in the usable area:\n"
"f3brew --fix-cmd --end-at=%" PRIu64 " %s\n"
"If you prefer checking with f3write/f3read, use the following command:\n"
"f3fix --last-sec=%" PRIu64 " %s\n",
args->filename, fake_type_to_name(fake_type),
last_good_block, args->filename,
last_good_sector, args->filename);
break;
}
default:
assert(0);
break;
}
printf("\nDevice geometry:\n");
report_size("\t *Usable* size:", results.real_size_byte,
results.block_order);
report_size("\t Announced size:", results.announced_size_byte,
results.block_order);
report_order("\t Module:", results.wrap);
report_cache("\tApproximate cache size:", results.cache_size_block,
results.block_order);
report_order("\t Physical block size:", results.block_order);
if (!args->save) {
/* Only report I/O speeds when flag --destructive is used
* because the safe device disrupts the measurements.
*/
printf("\nI/O average speeds:\n");
report_speed("\tSequential write:",
results.seqw_blocks, results.seqw_time_ns,
results.block_order);
report_speed("\t Random write:",
results.randw_blocks, results.randw_time_ns,
results.block_order);
report_speed("\t Random read:",
results.randr_blocks, results.randr_time_ns,
results.block_order);
}
report_probe_time("\nProbe time:", diff_timespec_ns(&t1, &t2));
if (args->time_ops) {
printf(" Operation: total time / blocks = avg time\n");
report_ops("Read", read_blocks, read_time_ns);
report_ops("Write", write_blocks, write_time_ns);
assert(reset_count == 0);
}
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,
.time_ops = false,
.verbose = false,
/* If stdout isn't a terminal, suppress progress. */
.show_progress = isatty(STDOUT_FILENO),
.max_read_rate = FW_MAX_PROCESS_RATE_NONE,
.max_write_rate = FW_MAX_PROCESS_RATE_NONE,
.real_size_byte = 2 * GIGABYTE_SIZE,
.fake_size_byte = 16 * GIGABYTE_SIZE,
.wrap = 31,
.block_order = SECTOR_ORDER,
.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-10.0/src/f3read.c 0000664 0000000 0000000 00000026434 15175127362 0014063 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
#include "libutils.h"
#include "libfile.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 {
uint64_t start_at;
uint64_t end_at;
uint64_t 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 long ll;
switch (key) {
case 's':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"NUM must be greater than zero");
args->start_at = ll - 1;
break;
case 'e':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"NUM must be greater than zero");
args->end_at = ll - 1;
break;
case 'r':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_read_rate = ll;
break;
case 'p':
args->show_progress = !!arg_to_ll_bytes(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 {
struct block_stats secs;
uint64_t bytes_read;
int read_all;
};
static inline void zero_fstats(struct file_stats *stats)
{
memset(stats, 0, sizeof(*stats));
}
static inline void check_sector(char *sector, uint64_t expected_offset,
struct file_stats *stats)
{
uint64_t found_offset;
validate_block_update_stats(sector, SECTOR_ORDER, expected_offset,
&found_offset, 0, &stats->secs);
}
static void check_buffer(char *buf, uint64_t sectors,
uint64_t *pexpected_offset, struct file_stats *stats)
{
uint64_t i;
for (i = 0; i < sectors; i++) {
check_sector(buf, *pexpected_offset, stats);
buf += SECTOR_SIZE;
*pexpected_offset += SECTOR_SIZE;
}
}
static int read_all(int fd, char *buf, size_t *pbytes)
{
ssize_t rc;
size_t done = 0;
do {
rc = read(fd, buf + done, *pbytes - done);
if (rc < 0) {
if (errno == EINTR)
continue;
rc = errno;
goto out;
}
if (rc == 0)
goto out;
done += rc;
} while (done < *pbytes);
rc = 0;
out:
*pbytes = done;
return rc;
}
static int check_chunk(struct flow *fw, struct dynamic_buffer *dbuf,
int fd, uint64_t *pexpected_offset, struct file_stats *stats,
size_t *ptot_bytes_read)
{
uint64_t chunk_size = get_rem_chunk_blocks(fw) <<
fw_get_block_order(fw);
size_t len = chunk_size;
char * const buf = dbuf_get_buf(dbuf, 0, &len);
size_t tot_bytes_read = 0;
int rc = 0;
while (chunk_size > 0) {
size_t bytes_read = MIN(chunk_size, len);
rc = read_all(fd, buf, &bytes_read);
tot_bytes_read += bytes_read;
if (bytes_read == 0)
break;
chunk_size -= bytes_read;
assert((bytes_read & (SECTOR_SIZE - 1)) == 0);
check_buffer(buf, bytes_read >> SECTOR_ORDER,
pexpected_offset, stats);
if (rc != 0)
break;
}
stats->bytes_read += tot_bytes_read;
*ptot_bytes_read = tot_bytes_read;
return rc;
}
static inline void print_status(const struct file_stats *stats)
{
printf("%7" PRIu64 "/%9" PRIu64 "/%7" PRIu64 "/%7" PRIu64,
stats->secs.ok, stats->secs.bad, stats->secs.changed,
stats->secs.overwritten);
}
static void validate_file(struct flow *fw, struct dynamic_buffer *dbuf,
const char *path, uint64_t number, struct file_stats *stats)
{
const unsigned int block_size = fw_get_block_size(fw);
const unsigned int block_order = fw_get_block_order(fw);
double file_min_speed = INFINITY;
double file_max_speed = -INFINITY;
uint64_t file_tot_blocks = 0;
uint64_t file_tot_time_ns = 0;
uint64_t file_speed_samples = 0;
char *full_fn;
const char *filename;
int fd, saved_errno;
uint64_t expected_offset;
struct timespec file_t1, file_t2;
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));
saved_errno = 0;
expected_offset = number << GIGABYTE_ORDER;
assert(!clock_gettime(CLOCK_MONOTONIC, &file_t1));
start_measurement(fw);
while (true) {
size_t bytes_read;
struct fw_measurement m;
int rc = check_chunk(fw, dbuf, fd, &expected_offset, stats,
&bytes_read);
if (rc == 0 && bytes_read == 0) {
stats->read_all = true;
break;
}
assert((bytes_read & (block_size - 1)) == 0);
measure(fw, bytes_read >> block_order, &m);
if (m.valid) {
double inst_speed = calc_avg_speed(block_order,
m.blocks, m.time_ns);
file_speed_samples++;
if (inst_speed > file_max_speed)
file_max_speed = inst_speed;
if (inst_speed < file_min_speed)
file_min_speed = inst_speed;
file_tot_blocks += m.blocks;
file_tot_time_ns += m.time_ns;
}
if (rc != 0) {
saved_errno = rc;
break;
}
}
end_measurement(fw);
assert(!clock_gettime(CLOCK_MONOTONIC, &file_t2));
print_status(stats);
if (!stats->read_all) {
assert(saved_errno != 0);
printf(" - NOT fully read due to \"%s\"",
strerror(saved_errno));
} else if (saved_errno != 0) {
printf(" - %s", strerror(saved_errno));
} else if (stats->bytes_read > 0) {
uint64_t file_time_ns = diff_timespec_ns(&file_t1, &file_t2);
double file_avg_speed;
if (file_speed_samples >= 2) {
file_avg_speed = calc_avg_speed(block_order,
file_tot_blocks, file_tot_time_ns);
print_avg_min_max_samples(" ", "",
file_avg_speed, file_min_speed, file_max_speed,
file_speed_samples);
} else if (file_time_ns > 0) {
const uint64_t blocks_read =
stats->bytes_read >> block_order;
assert((stats->bytes_read & (block_size - 1)) == 0);
if (file_tot_blocks == blocks_read &&
file_tot_time_ns > 0) {
file_time_ns = file_tot_time_ns;
}
file_avg_speed = calc_avg_speed(block_order,
blocks_read, file_time_ns);
const char *unit = adjust_unit(&file_avg_speed);
printf(" Avg: %.2f %s/s", file_avg_speed, unit);
}
}
printf("\n");
close(fd);
free(full_fn);
}
static uint64_t get_total_blocks(const char *path, const uint64_t *files,
unsigned int block_order)
{
const unsigned int block_size = 1U << block_order;
uint64_t total_blocks = 0;
while (*files != (uint64_t)-1) {
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 & (block_size - 1)) == 0);
total_blocks += st.st_size >> block_order;
free(full_fn);
files++;
}
return total_blocks;
}
static void iterate_files(const char *path, const uint64_t *files,
uint64_t start_at, uint64_t end_at, uint64_t max_read_rate,
int progress)
{
const unsigned int block_order = get_block_order(path);
struct block_stats tot_stats = {0, 0, 0, 0};
uint64_t tot_size = 0;
int and_read_all = 1;
int or_missing_file = 0;
uint64_t number = start_at;
struct flow fw;
struct dynamic_buffer dbuf;
UNUSED(end_at);
init_flow(&fw, block_order, get_total_blocks(path, files, block_order),
max_read_rate, (GIGABYTE_SIZE >> block_order),
progress ? printf_flush_cb : dummy_cb, 0);
dbuf_init(&dbuf);
printf(" SECTORS ok/corrupted/changed/overwritten\n");
while (*files != (uint64_t)-1) {
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(&fw, &dbuf, path, *files, &stats);
tot_stats.ok += stats.secs.ok;
tot_stats.bad += stats.secs.bad;
tot_stats.changed += stats.secs.changed;
tot_stats.overwritten += stats.secs.overwritten;
tot_size += stats.bytes_read;
and_read_all = and_read_all && stats.read_all;
files++;
}
assert((tot_stats.ok + tot_stats.bad + tot_stats.changed +
tot_stats.overwritten) << SECTOR_ORDER == tot_size);
/* Notice that not reporting `missing' files after the last file
* in @files is important since @end_at could be very large.
*/
print_stats(&tot_stats, SECTOR_ORDER, "sector");
if (or_missing_file)
printf("WARNING: Not all F3 files in the range %" PRIu64 " to %" PRIu64 " 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. */
print_avg_seq_speed(&fw, "read", true);
dbuf_free(&dbuf);
}
int main(int argc, char **argv)
{
const uint64_t *files;
struct args args = {
/* Defaults. */
.start_at = 0,
.end_at = LONG_MAX - 1,
.max_read_rate = FW_MAX_PROCESS_RATE_NONE,
/* 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-10.0/src/f3write.c 0000664 0000000 0000000 00000024465 15175127362 0014304 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
#include
#include "libutils.h"
#include "libfile.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 {
uint64_t start_at;
uint64_t end_at;
uint64_t 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 long ll;
switch (key) {
case 's':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"NUM must be greater than zero");
args->start_at = ll - 1;
break;
case 'e':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"NUM must be greater than zero");
args->end_at = ll - 1;
break;
case 'w':
ll = arg_to_ll_bytes(state, arg);
if (ll <= 0)
argp_error(state,
"KB/s must be greater than zero");
args->max_write_rate = ll;
break;
case 'p':
args->show_progress = !!arg_to_ll_bytes(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 void fill_buffer(char *buf, uint64_t sectors, uint64_t *poffset)
{
uint64_t i;
for (i = 0; i < sectors; i++) {
fill_buffer_with_block(buf, SECTOR_ORDER, *poffset, 0);
buf += SECTOR_SIZE;
*poffset += SECTOR_SIZE;
}
}
static int write_all(int fd, const char *buf, size_t *pbytes)
{
ssize_t rc;
size_t done = 0;
do {
rc = write(fd, buf + done, *pbytes - done);
if (rc < 0) {
rc = errno;
goto out;
}
done += rc;
} while (done < *pbytes);
rc = 0;
out:
*pbytes = done;
return rc;
}
static int write_chunk(struct flow *fw, struct dynamic_buffer *dbuf,
int fd, uint64_t remaining_blocks, uint64_t *poffset,
size_t *ptot_bytes_written)
{
int rc = 0;
uint64_t chunk_size = MIN(get_rem_chunk_blocks(fw), remaining_blocks)
<< fw_get_block_order(fw);
size_t len = chunk_size;
char * const buf = dbuf_get_buf(dbuf, 0, &len);
size_t tot_bytes_written = 0;
while (chunk_size > 0) {
const size_t turn_size = MIN(chunk_size, len);
size_t bytes_written = turn_size;
assert((turn_size & (SECTOR_SIZE - 1)) == 0);
fill_buffer(buf, turn_size >> SECTOR_ORDER, poffset);
rc = write_all(fd, buf, &bytes_written);
tot_bytes_written += bytes_written;
if (rc != 0)
goto out;
assert(bytes_written == turn_size);
chunk_size -= turn_size;
}
out:
*ptot_bytes_written = tot_bytes_written;
return rc;
}
/* Return true when disk is full. */
static int create_and_fill_file(struct flow *fw, struct dynamic_buffer *dbuf,
const char *path, uint64_t number, int *phas_suggested_max_write_rate)
{
const unsigned int block_size = fw_get_block_size(fw);
const unsigned int block_order = fw_get_block_order(fw);
const uint64_t total_file_blocks =
1ULL << (GIGABYTE_ORDER - block_order);
uint64_t remaining_blocks = total_file_blocks;
double file_min_speed = INFINITY;
double file_max_speed = -INFINITY;
uint64_t file_tot_blocks = 0;
uint64_t file_tot_time_ns = 0;
uint64_t file_speed_samples = 0;
char *full_fn;
const char *filename;
int fd, saved_errno;
uint64_t offset;
struct timespec file_t1, file_t2;
assert(GIGABYTE_ORDER >= block_order);
/* 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. */
saved_errno = 0;
offset = number << GIGABYTE_ORDER;
assert(!clock_gettime(CLOCK_MONOTONIC, &file_t1));
start_measurement(fw);
while (remaining_blocks > 0) {
size_t bytes_written;
uint64_t written_blocks;
struct fw_measurement m;
saved_errno = write_chunk(fw, dbuf, fd, remaining_blocks,
&offset, &bytes_written);
if (bytes_written == 0)
break;
/* Push data to drive and tip the kernel. */
if (fdatasync(fd) < 0) {
/* Preserve the first error. */
if (saved_errno == 0)
saved_errno = errno;
}
if (saved_errno == 0) {
saved_errno = posix_fadvise(fd, 0, 0,
POSIX_FADV_DONTNEED);
}
assert((bytes_written & (block_size - 1)) == 0);
written_blocks = bytes_written >> block_order;
measure(fw, written_blocks, &m);
if (m.valid) {
double inst_speed = calc_avg_speed(block_order,
m.blocks, m.time_ns);
file_speed_samples++;
if (inst_speed > file_max_speed)
file_max_speed = inst_speed;
if (inst_speed < file_min_speed)
file_min_speed = inst_speed;
file_tot_blocks += m.blocks;
file_tot_time_ns += m.time_ns;
}
remaining_blocks -= written_blocks;
if (saved_errno != 0)
break;
}
end_measurement(fw);
assert(!clock_gettime(CLOCK_MONOTONIC, &file_t2));
close(fd);
free(full_fn);
if (saved_errno == 0 || saved_errno == ENOSPC) {
uint64_t file_time_ns = diff_timespec_ns(&file_t1, &file_t2);
double file_avg_speed;
if (saved_errno == 0)
assert(remaining_blocks == 0);
if (file_speed_samples >= 2) {
file_avg_speed = calc_avg_speed(block_order,
file_tot_blocks, file_tot_time_ns);
print_avg_min_max_samples("OK! ", "\n",
file_avg_speed, file_min_speed, file_max_speed,
file_speed_samples);
} else if (file_time_ns > 0) {
const uint64_t blocks_written =
total_file_blocks - remaining_blocks;
if (file_tot_blocks == blocks_written &&
file_tot_time_ns > 0) {
file_time_ns = file_tot_time_ns;
}
file_avg_speed = calc_avg_speed(block_order,
blocks_written, file_time_ns);
const char *unit = adjust_unit(&file_avg_speed);
printf("OK! Avg: %.2f %s/s\n",
file_avg_speed, unit);
} else {
printf("OK!\n");
}
return saved_errno == ENOSPC;
}
/* Something went wrong. */
assert(saved_errno != 0);
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 void pr_freespace(uint64_t fs)
{
double f = (double)fs;
const char *unit = adjust_unit(&f);
printf("Free space: %.2f %s\n", f, unit);
}
static int fill_fs(const char *path, uint64_t start_at, uint64_t end_at,
uint64_t max_write_rate, int progress)
{
const unsigned int block_order = get_block_order(path);
uint64_t free_blocks = get_free_blocks(path);
struct flow fw;
struct dynamic_buffer dbuf;
uint64_t i;
int has_suggested_max_write_rate = max_write_rate > 0;
pr_freespace(free_blocks << block_order);
if (free_blocks == 0) {
printf("No space!\n");
return 1;
}
assert(start_at <= end_at);
assert(GIGABYTE_ORDER >= block_order);
i = end_at - start_at + 1;
if (i <= (free_blocks >> (GIGABYTE_ORDER - block_order))) {
/* The amount of data to write is less than the space available,
* update free_blocks to improve estimate of time to finish.
*/
free_blocks = i << (GIGABYTE_ORDER - block_order);
} else {
/* There are more data to write than space available.
* Reduce end_at to reduce the number of error messages
* due to multiple write failures.
*/
end_at = start_at +
(free_blocks >> (GIGABYTE_ORDER - block_order));
}
init_flow(&fw, block_order, free_blocks, max_write_rate,
(GIGABYTE_SIZE >> block_order),
progress ? printf_flush_cb : dummy_cb, 0);
dbuf_init(&dbuf);
for (i = start_at; i <= end_at; i++) {
if (create_and_fill_file(&fw, &dbuf, path, i,
&has_suggested_max_write_rate))
break;
}
dbuf_free(&dbuf);
/* Final report. */
pr_freespace(get_free_blocks(path) << block_order);
print_avg_seq_speed(&fw, "write", true);
return 0;
}
static void unlink_old_files(const char *path,
uint64_t start_at, uint64_t end_at)
{
const uint64_t *files = ls_my_files(path, start_at, end_at);
const uint64_t *number = files;
while (*number != (uint64_t)-1) {
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 = FW_MAX_PROCESS_RATE_NONE,
/* 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-10.0/src/libdevs.c 0000664 0000000 0000000 00000101025 15175127362 0014335 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, unsigned int block_order)
{
unsigned int block_size;
/* Check general ranges. */
if (real_size_byte > announced_size_byte || wrap < 0 || wrap >= 64 ||
block_order < SECTOR_ORDER || block_order > MEGABYTE_ORDER)
return false;
/* Check alignment of the sizes. */
block_size = 1 << block_order;
if ((real_size_byte & (block_size - 1)) != 0 ||
(announced_size_byte & (block_size - 1)) != 0)
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, unsigned 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;
unsigned 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(const struct device *dev)
{
return dev->size_byte;
}
unsigned int dev_get_block_order(const struct device *dev)
{
return dev->block_order;
}
unsigned int dev_get_block_size(const struct device *dev)
{
return 1U << 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 unsigned int block_size = dev_get_block_size(dev);
const unsigned int block_order = dev_get_block_order(dev);
off_t off_ret, offset = block_pos << block_order;
unsigned 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 unsigned 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 unsigned int block_size = dev_get_block_size(dev);
const unsigned 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 unsigned 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,
unsigned 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;
assert(is_power_of_2(block_size));
block_order = ilog2(block_size);
}
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 unsigned 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 unsigned 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_sectors =
udev_device_get_sysattr_value(dev, "size");
char *end;
long long size_sectors;
if (str_size_sectors == NULL)
return 0;
size_sectors = strtoll(str_size_sectors, &end, 10);
assert(*end == '\0');
return size_sectors << SECTOR_ORDER;
}
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_blocks;
uint64_t read_time_ns;
uint64_t write_blocks;
uint64_t write_time_ns;
uint64_t reset_count;
uint64_t reset_time_ns;
};
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 timespec t1, t2;
int rc;
assert(!clock_gettime(CLOCK_MONOTONIC, &t1));
rc = pdev->shadow_dev->read_blocks(pdev->shadow_dev, buf,
first_pos, last_pos);
assert(!clock_gettime(CLOCK_MONOTONIC, &t2));
pdev->read_blocks += last_pos - first_pos + 1;
pdev->read_time_ns += diff_timespec_ns(&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 timespec t1, t2;
int rc;
assert(!clock_gettime(CLOCK_MONOTONIC, &t1));
rc = pdev->shadow_dev->write_blocks(pdev->shadow_dev, buf,
first_pos, last_pos);
assert(!clock_gettime(CLOCK_MONOTONIC, &t2));
pdev->write_blocks += last_pos - first_pos + 1;
pdev->write_time_ns += diff_timespec_ns(&t1, &t2);
return rc;
}
static int pdev_reset(struct device *dev)
{
struct perf_device *pdev = dev_pdev(dev);
struct timespec t1, t2;
int rc;
assert(!clock_gettime(CLOCK_MONOTONIC, &t1));
rc = dev_reset(pdev->shadow_dev);
assert(!clock_gettime(CLOCK_MONOTONIC, &t2));
pdev->reset_count++;
pdev->reset_time_ns += diff_timespec_ns(&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_blocks = 0;
pdev->read_time_ns = 0;
pdev->write_blocks = 0;
pdev->write_time_ns = 0;
pdev->reset_count = 0;
pdev->reset_time_ns = 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_blocks, uint64_t *pread_time_ns,
uint64_t *pwrite_blocks, uint64_t *pwrite_time_ns,
uint64_t *preset_count, uint64_t *preset_time_ns)
{
struct perf_device *pdev = dev_pdev(dev);
if (pread_blocks)
*pread_blocks = pdev->read_blocks;
if (pread_time_ns)
*pread_time_ns = pdev->read_time_ns;
if (pwrite_blocks)
*pwrite_blocks = pdev->write_blocks;
if (pwrite_time_ns)
*pwrite_time_ns = pdev->write_time_ns;
if (preset_count)
*preset_count = pdev->reset_count;
if (preset_time_ns)
*preset_time_ns = pdev->reset_time_ns;
}
#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 = sdev->saved_blocks + (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 = sdev->saved_blocks;
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_size = dev_get_block_size(dev);
const int block_order = dev_get_block_order(dev);
uint64_t length;
sdev = malloc(sizeof(*sdev));
if (!sdev)
goto error;
length = max_blocks << block_order;
sdev->saved_blocks = aligned_alloc(block_size, 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-10.0/src/libdevs.h 0000664 0000000 0000000 00000004551 15175127362 0014350 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, unsigned int block_order);
enum fake_type dev_param_to_type(uint64_t real_size_byte,
uint64_t announced_size_byte, int wrap, unsigned int block_order);
/*
* Abstract device
*/
struct device;
/*
* Properties
*/
uint64_t dev_get_size_byte(const struct device *dev);
unsigned int dev_get_block_order(const struct device *dev);
unsigned int dev_get_block_size(const 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
*/
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,
unsigned 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_blocks, uint64_t *pread_time_ns,
uint64_t *pwrite_blocks, uint64_t *pwrite_time_ns,
uint64_t *preset_count, uint64_t *preset_time_ns);
/* 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-10.0/src/libfile.c 0000664 0000000 0000000 00000010542 15175127362 0014316 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
#include
#include "libfile.h"
#include "libutils.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__);
}
}
unsigned int get_block_order(const char *path)
{
struct statvfs fs;
unsigned int block_size;
assert(!statvfs(path, &fs));
block_size = fs.f_frsize;
assert(is_power_of_2(block_size));
return ilog2(block_size);
}
uint64_t get_free_blocks(const char *path)
{
struct statvfs fs;
assert(!statvfs(path, &fs));
return fs.f_bfree;
}
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, uint64_t num)
{
char *str;
assert(asprintf(&str, "%s/%" PRIu64 ".h2w", path, num + 1) > 0);
*filename = str + strlen(path) + 1;
return str;
}
static uint64_t number_from_filename(const char *filename)
{
const char *p;
uint64_t 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,
uint64_t start_at, uint64_t end_at, uint64_t *number)
{
if (!is_my_file(filename))
return false;
*number = number_from_filename(filename);
return start_at <= *number && *number <= end_at;
}
static uint64_t count_files(const char *path,
uint64_t start_at, uint64_t end_at)
{
DIR *dir = opendir(path);
struct dirent *entry;
uint64_t 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 uint64_t *__ls_my_files(const char *path,
uint64_t start_at, uint64_t end_at, uint64_t *pcount)
{
uint64_t total_files = count_files(path, start_at, end_at);
DIR *dir;
struct dirent *entry;
uint64_t *ret, index;
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) {
uint64_t 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] = (uint64_t)-1;
*pcount = index;
return ret;
}
/* To be used with qsort(3). */
static int cmpintp(const void *p1, const void *p2)
{
if (*(const uint64_t *)p1 < *(const uint64_t *)p2)
return -1;
return *(const uint64_t *)p1 > *(const uint64_t *)p2;
}
const uint64_t *ls_my_files(const char *path,
uint64_t start_at, uint64_t end_at)
{
uint64_t *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;
}
#if __APPLE__ && __MACH__
/* This function is a _rough_ approximation of fdatasync(2). */
int fdatasync(int fd)
{
return fcntl(fd, F_FULLFSYNC);
}
#include "libutils.h" /* For UNUSED(). */
/* This function is a _rough_ approximation of posix_fadvise(2). */
int posix_fadvise(int fd, off_t offset, off_t len, int advice)
{
UNUSED(offset);
UNUSED(len);
switch (advice) {
case POSIX_FADV_SEQUENTIAL:
return fcntl(fd, F_RDAHEAD, 1);
case POSIX_FADV_DONTNEED:
return fcntl(fd, F_NOCACHE, 1);
default:
assert(0);
}
}
#endif /* Apple Macintosh */ f3-10.0/src/libfile.h 0000664 0000000 0000000 00000002635 15175127362 0014327 0 ustar 00root root 0000000 0000000 #ifndef HEADER_LIBFILE_H
#define HEADER_LIBFILE_H
#include /* For type uint64_t. */
void adjust_dev_path(const char **dev_path);
unsigned int get_block_order(const char *path);
uint64_t get_free_blocks(const char *path);
/* 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,
uint64_t num);
const uint64_t *ls_my_files(const char *path,
uint64_t start_at, uint64_t end_at);
#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_LIBFILE_H */
f3-10.0/src/libflow.c 0000664 0000000 0000000 00000033624 15175127362 0014354 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 "libflow.h"
#include "libutils.h"
/* Apple Macintosh / OpenBSD */
#if (__APPLE__ && __MACH__) || defined(__OpenBSD__)
static void nssleep(uint64_t wait_ns)
{
const lldiv_t div = lldiv(wait_ns, 1000000000);
const struct timespec req = {
.tv_sec = div.quot,
.tv_nsec = div.rem,
};
assert(!nanosleep(&req, NULL));
}
#else /* Everyone else */
static void nssleep(uint64_t wait_ns)
{
struct timespec req;
lldiv_t div;
int ret;
assert(!clock_gettime(CLOCK_MONOTONIC, &req));
/* Add @wait_ns to @req. */
div = lldiv(wait_ns, 1000000000);
req.tv_sec += div.quot;
req.tv_nsec += div.rem;
/* Round @req up. */
if (req.tv_nsec >= 1000000000) {
req.tv_sec++;
req.tv_nsec -= 1000000000;
}
do {
ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
&req, NULL);
} while (ret == EINTR);
assert(ret == 0);
}
#endif /* nssleep() */
static inline void move_to_inc_at_start(struct flow *fw)
{
fw->step_blocks = 1;
fw->state = FW_INC;
}
void init_flow(struct flow *fw, unsigned int block_order, uint64_t total_blocks,
uint64_t max_process_rate, uint64_t max_blocks_per_delay,
progress_cb cb, unsigned int indent)
{
fw->total_blocks = total_blocks;
fw->cb = cb;
fw->indent = indent;
fw->block_order = block_order;
fw->blocks_per_delay = 1;
fw->max_blocks_per_delay = max_blocks_per_delay == 0
? UINT64_MAX : max_blocks_per_delay;
fw->delay_ns = 1000000000ULL; /* 1s */
fw->max_process_rate = max_process_rate == 0
? DBL_MAX : max_process_rate << KILOBYTE_ORDER;
fw->measured_blocks = 0;
fw->measured_time_ns = 0;
fw->erase = 0;
fw->has_rem_chunk_blocks = false;
fw->rem_chunk_blocks = 0;
fw->rem_chunk_speed = 0;
fw->processed_blocks = 0;
fw->acc_delay_ns = 0;
assert(fw->block_order >= SECTOR_ORDER);
move_to_inc_at_start(fw);
}
uint64_t get_rem_chunk_blocks(const struct flow *fw)
{
const uint64_t rem_blocks = fw->blocks_per_delay - fw->processed_blocks;
assert(fw->blocks_per_delay > fw->processed_blocks);
return fw->has_rem_chunk_blocks && rem_blocks >= fw->rem_chunk_blocks
? fw->rem_chunk_blocks
: rem_blocks;
}
static inline unsigned int repeat_ch(char *buf, char ch, int count)
{
int i;
for (i = 0; i < count; i++)
buf[i] = ch;
return count;
}
void clear_progress(struct flow *fw)
{
char buf[512], *at_buf = buf;
if (fw->erase == 0) {
if (fw->indent > 0) {
/* Remove indented empty line. */
fw->cb(fw->indent, "\b");
}
goto out;
}
assert(fw->erase * 3 + 1 <= sizeof(buf));
at_buf += repeat_ch(at_buf, '\b', fw->erase);
at_buf += repeat_ch(at_buf, ' ', fw->erase);
at_buf += repeat_ch(at_buf, '\b', fw->erase);
at_buf[0] = '\0';
/* Pass buf as the format, so the implementation of cb can check that
* the intention is to clear the previously reported progress.
*/
fw->cb(fw->indent, buf);
out:
fw->erase = 0;
}
static inline bool has_enough_measurements(const struct flow *fw)
{
return fw->measured_time_ns > fw->delay_ns;
}
#define CHECK_AND_MOVE do { \
assert(c > 0); \
len += c; \
assert((size_t)c < rem_size); \
rem_size -= c; \
at_buf += c; \
} while (0)
static void report_progress(struct flow *fw, double inst_speed)
{
const uint64_t total_processed_blocks =
fw_get_total_processed_blocks(fw);
const char *unit = adjust_unit(&inst_speed);
double percent;
char buf[128 + TIME_STR_SIZE];
char *at_buf = buf;
size_t rem_size = sizeof(buf);
int c, len = 0;
/* 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_blocks < total_processed_blocks)
fw->total_blocks = total_processed_blocks;
percent = total_processed_blocks * 100.0 / fw->total_blocks;
c = snprintf(at_buf, rem_size, "%.2f%% -- %.2f %s/s",
percent, inst_speed, unit);
CHECK_AND_MOVE;
if (has_enough_measurements(fw)) {
const double rem_blocks =
fw->total_blocks - total_processed_blocks;
const double speed_blocks_per_ns =
(double)fw->measured_blocks / fw->measured_time_ns;
const uint64_t rem_time_ns =
round(rem_blocks / speed_blocks_per_ns);
c = snprintf(at_buf, rem_size, " -- ");
CHECK_AND_MOVE;
assert(rem_size >= TIME_STR_SIZE);
c = nsec_to_str(rem_time_ns, at_buf);
CHECK_AND_MOVE;
}
assert((size_t)len + 1 <= sizeof(buf));
clear_progress(fw);
fw->cb(fw->indent, "%s", buf);
fw->erase = len;
}
static inline void __start_measurement(struct flow *fw)
{
assert(!clock_gettime(CLOCK_MONOTONIC, &fw->t1));
}
void start_measurement(struct flow *fw)
{
uint64_t blocks, time_ns;
/*
* The report below is especially useful when a single measurement spans
* multiple files; this happens when a drive is faster than 1GB/s.
*/
fw_get_measurements(fw, &blocks, &time_ns);
if (time_ns > 0) {
report_progress(fw,
calc_avg_speed(fw->block_order, blocks, time_ns));
}
__start_measurement(fw);
}
static inline void move_to_steady(struct flow *fw)
{
fw->state = FW_STEADY;
}
static void move_to_search(struct flow *fw, uint64_t bpd1, uint64_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_blocks) {
fw->blocks_per_delay -= fw->step_blocks;
fw->step_blocks *= 2;
} else {
move_to_search(fw, 1,
fw->blocks_per_delay + fw->step_blocks / 2);
}
}
static void inc_step(struct flow *fw)
{
fw->blocks_per_delay += fw->step_blocks;
fw->step_blocks *= 2;
if (fw->blocks_per_delay > fw->max_blocks_per_delay) {
fw->blocks_per_delay = fw->max_blocks_per_delay;
move_to_steady(fw);
}
}
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_blocks = 1;
fw->state = FW_DEC;
dec_step(fw);
}
static inline int is_rate_above(const struct flow *fw,
uint64_t delay_ns, double inst_speed)
{
/* We use logical or here to enforce the lowest limit. */
return delay_ns > fw->delay_ns || inst_speed > fw->max_process_rate;
}
static inline int is_rate_below(const struct flow *fw,
uint64_t delay_ns, double inst_speed)
{
/* We use logical and here to enforce both limits. */
return delay_ns <= fw->delay_ns && inst_speed < fw->max_process_rate;
}
static void update_rem_chunk_blocks(struct flow *fw, double inst_speed)
{
if (fw->rem_chunk_blocks != 0 && inst_speed < fw->rem_chunk_speed)
return;
fw->rem_chunk_blocks = fw->blocks_per_delay;
fw->rem_chunk_speed = inst_speed;
}
void measure(struct flow *fw, uint64_t processed_blocks,
struct fw_measurement *m)
{
struct timespec t2;
uint64_t delay_ns;
double bytes_g, inst_speed;
fw->processed_blocks += processed_blocks;
if (fw->processed_blocks < fw->blocks_per_delay) {
if (m != NULL)
m->valid = false;
return;
}
assert(fw->processed_blocks == fw->blocks_per_delay);
assert(!clock_gettime(CLOCK_MONOTONIC, &t2));
delay_ns = diff_timespec_ns(&fw->t1, &t2) + fw->acc_delay_ns;
bytes_g = (fw->blocks_per_delay << fw->block_order) * 1000000000.0;
/* Instantaneous speed in bytes per second. */
inst_speed = bytes_g / delay_ns;
if (!fw->has_rem_chunk_blocks)
update_rem_chunk_blocks(fw, inst_speed);
if (delay_ns < fw->delay_ns && inst_speed > fw->max_process_rate) {
/* delay_ns should be such that
* inst_speed <= fw->max_process_rate.
* To accomplish this, the code below adds a wait.
*
* inst_speed <= fw->max_process_rate [=>]
* bytes_g / (delay_ns + wait_ns) <= fw->max_process_rate [=>]
* bytes_g / fw->max_process_rate <= delay_ns + wait_ns [=>]
* wait_ns >= bytes_g / fw->max_process_rate - delay_ns
*
* The step below minimizes rounding errors.
*
* wait_ns >= (bytes_g - delay_ns * fw->max_process_rate) /
* fw->max_process_rate
*
* Round wait_ns, so it operates as an integer when used in
* nanoseconds.
*/
uint64_t wait_ns = round(
(bytes_g - delay_ns * fw->max_process_rate) /
fw->max_process_rate);
/* From the if-test,
* inst_speed > fw->max_process_rate [=>]
* bytes_g / delay_ns > fw->max_process_rate [=>]
* bytes_g > delay_ns * fw->max_process_rate
*
* For wait_ns to be negative,
* wait_ns < 0 [=>]
* (bytes_g - delay_ns * fw->max_process_rate) /
* fw->max_process_rate < 0 [=>]
* bytes_g < delay_ns * fw->max_process_rate
*
* Therefore, wait_ns cannot be negative.
*/
if (delay_ns + wait_ns < fw->delay_ns) {
/* In this case, There is a factor f > 1 that
* satisfies the following equation:
*
* (delay_ns + wait_ns) * f = fw->delay_ns
*
* This means that both delay_ns and wait_ns should be
* increased to make f = 1. To signal that to the flow
* algorithm below, wait to fw->delay_ns.
*/
wait_ns = fw->delay_ns - delay_ns;
}
if (wait_ns > 0) {
/* Slow down. */
nssleep(wait_ns);
/* Adjust measurements. */
delay_ns += wait_ns;
inst_speed = bytes_g / delay_ns;
}
}
/* Update average. */
fw->measured_blocks += fw->processed_blocks;
fw->measured_time_ns += delay_ns;
if (m != NULL) {
m->valid = true;
m->blocks = fw->processed_blocks;
m->time_ns = delay_ns;
}
/* Reset accumulators. */
fw->processed_blocks = 0;
fw->acc_delay_ns = 0;
switch (fw->state) {
case FW_INC:
if (is_rate_above(fw, delay_ns, inst_speed)) {
if (!fw->has_rem_chunk_blocks) {
/* Recommend a chunk size to caller. */
assert(fw->rem_chunk_blocks != 0);
fw->has_rem_chunk_blocks = true;
}
move_to_search(fw,
fw->blocks_per_delay - fw->step_blocks / 2,
fw->blocks_per_delay);
} else if (is_rate_below(fw, delay_ns, inst_speed)) {
inc_step(fw);
} else
move_to_steady(fw);
break;
case FW_DEC:
if (is_rate_above(fw, delay_ns, inst_speed)) {
dec_step(fw);
} else if (is_rate_below(fw, delay_ns, inst_speed)) {
move_to_search(fw, fw->blocks_per_delay,
fw->blocks_per_delay + fw->step_blocks / 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_ns, inst_speed)) {
fw->bpd2 = fw->blocks_per_delay;
fw->blocks_per_delay = (fw->bpd1 + fw->bpd2) / 2;
} else if (is_rate_below(fw, delay_ns, 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 (!fw->has_rem_chunk_blocks) {
/* Recommend a chunk size to caller.
* Execution reaches here when fw->max_process_rate is
* throttling the flow.
*/
assert(fw->rem_chunk_blocks != 0);
fw->has_rem_chunk_blocks = true;
/* Since it's in steady state, go for another round
* before making any change.
*/
break;
}
if (delay_ns <= fw->delay_ns) {
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);
}
report_progress(fw, inst_speed);
__start_measurement(fw);
}
void end_measurement(struct flow *fw)
{
if (fw->processed_blocks > 0) {
/* Track progress in between measurement boundaries. */
struct timespec t2;
assert(!clock_gettime(CLOCK_MONOTONIC, &t2));
fw->acc_delay_ns += diff_timespec_ns(&fw->t1, &t2);
if (fw->max_blocks_per_delay < UINT64_MAX) {
/* Measurement boundary. */
fw->measured_blocks += fw->processed_blocks;
fw->measured_time_ns += fw->acc_delay_ns;
fw->processed_blocks = 0;
fw->acc_delay_ns = 0;
}
}
clear_progress(fw); /* Erase progress information. */
}
void print_avg_seq_speed(const struct flow *fw, const char *speed_type,
bool use_sectors)
{
unsigned int block_order = fw_get_block_order(fw);
uint64_t blocks, time_ns;
char prefix[128];
int ret = snprintf(prefix, sizeof(prefix), "Average sequential %s speed:",
speed_type);
assert(ret > 0 && (size_t)ret < sizeof(prefix));
fw_get_measurements(fw, &blocks, &time_ns);
if (use_sectors && block_order != SECTOR_ORDER) {
assert(block_order > SECTOR_ORDER);
blocks <<= block_order - SECTOR_ORDER;
block_order = SECTOR_ORDER;
}
report_io_speed(0, printf_cb, prefix, blocks,
use_sectors ? "sector" : "block",
time_ns, block_order);
}
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, unsigned int align_order,
size_t *psize)
{
const unsigned int max_align_order = ilog2(alignof(max_align_t));
const size_t original_size = *psize;
size_t size = original_size;
size_t alignment, threshold;
int shift;
char *ret;
if (align_order < max_align_order)
align_order = max_align_order;
alignment = 1ULL << align_order;
/* If enough buffer and aligned, return it. */
if (size <= dbuf->len && is_aligned(dbuf->buf, alignment)) {
assert(*psize == original_size);
ret = dbuf->buf;
goto out;
}
if (dbuf->max_buf) {
/* It's already the largest buffer. */
goto align;
}
/*
* Allocate a new buffer.
*/
__dbuf_free(dbuf);
threshold = sizeof(dbuf->backup_buf) - align_head(align_order);
do {
dbuf->buf = aligned_alloc(alignment, size);
if (dbuf->buf != NULL) {
dbuf->len = size;
*psize = size;
ret = dbuf->buf;
goto out;
} else {
dbuf->max_buf = true;
}
size /= 2;
} while (size > threshold);
/* A larger buffer is not available; failsafe. */
dbuf->buf = dbuf->backup_buf;
dbuf->len = sizeof(dbuf->backup_buf);
align:
ret = align_mem2(dbuf->buf, align_order, &shift);
*psize = MIN(*psize, dbuf->len - shift);
out:
assert(*psize <= original_size);
return ret;
}
f3-10.0/src/libflow.h 0000664 0000000 0000000 00000010756 15175127362 0014362 0 ustar 00root root 0000000 0000000 #ifndef HEADER_LIBFLOW_H
#define HEADER_LIBFLOW_H
#include
#include
#include
#include
#include
#include
#include "libutils.h"
#define FW_MAX_PROCESS_RATE_NONE (0)
#define FW_MAX_BLOCKS_PER_DELAY_NONE (0)
struct flow;
struct flow {
/* Total number of blocks to be processed. */
uint64_t total_blocks;
/* Callback to show progress. */
progress_cb cb;
/* Indentation level for callback. */
unsigned int indent;
/* Block order. */
unsigned int block_order;
/* Delay intended between measurements in nanoseconds. */
uint64_t delay_ns;
/* Increment to apply to blocks_per_delay. */
uint64_t step_blocks;
/* Blocks to process before measurement. */
uint64_t blocks_per_delay;
/* Maximum value that blocks_per_delay can take. */
uint64_t max_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_ns;
/* State. */
enum {FW_INC, FW_DEC, FW_SEARCH, FW_STEADY} state;
/* Number of characters to erase before printing out progress. */
unsigned int erase;
/*
* Initialized while measuring
*/
/* Has a recommended chunk size? */
bool has_rem_chunk_blocks;
/* Recommended chunk size in blocks. */
uint64_t rem_chunk_blocks;
/* Speed of the recommended chunk size in bytes per second. */
double rem_chunk_speed;
/* Number of blocks processed since last measurement. */
uint64_t processed_blocks;
/*
* Accumulated delay before processed_blocks reaches blocks_per_delay
* in nanoseconds.
*/
uint64_t acc_delay_ns;
/* Range of blocks_per_delay while in FW_SEARCH state. */
uint64_t bpd1, bpd2;
/* Time measurements. */
struct timespec t1;
};
/*
* If max_process_rate == FW_MAX_PROCESS_RATE_NONE,
* the maximum processing rate is infinity.
* The unit of max_process_rate is KB per second.
*
* If max_blocks_per_delay == FW_MAX_BLOCKS_PER_DELAY_NONE,
* there is no limit to blocks_per_delay.
* max_blocks_per_delay is meant to act as a measurement boundary when
* end_measurement() is called at a given limit (e.g. f3write and f3read
* call it at the end of each 1GB file). Thanks to this limit, f3write and
* f3read can make per-file measurements and libflow can still detect when
* the drive slows down.
*/
void init_flow(struct flow *fw, unsigned int block_order, uint64_t total_blocks,
uint64_t max_process_rate, uint64_t max_blocks_per_delay,
progress_cb cb, unsigned int indent);
/* Total number of blocks already processed. */
static inline uint64_t fw_get_total_processed_blocks(const struct flow *fw)
{
return fw->measured_blocks + fw->processed_blocks;
}
static inline unsigned int fw_get_block_size(const struct flow *fw)
{
return 1U << fw->block_order;
}
static inline unsigned int fw_get_block_order(const struct flow *fw)
{
return fw->block_order;
}
static inline void inc_total_blocks(struct flow *fw, uint64_t n_blocks)
{
fw->total_blocks = fw_get_total_processed_blocks(fw) + n_blocks;
}
static inline void fw_set_indent(struct flow *fw, unsigned int indent)
{
fw->indent = indent;
}
static inline void fw_get_measurements(const struct flow *fw,
uint64_t *blocks, uint64_t *time_ns)
{
*blocks = fw_get_total_processed_blocks(fw);
*time_ns = fw->measured_time_ns + fw->acc_delay_ns;
}
uint64_t get_rem_chunk_blocks(const struct flow *fw);
struct fw_measurement {
bool valid;
uint64_t blocks;
uint64_t time_ns;
};
void start_measurement(struct flow *fw);
void measure(struct flow *fw, uint64_t processed_blocks,
struct fw_measurement *m);
void clear_progress(struct flow *fw);
void end_measurement(struct flow *fw);
void print_avg_seq_speed(const struct flow *fw, const char *speed_type,
bool use_sectors);
struct dynamic_buffer {
char *buf;
size_t len;
bool max_buf;
/* Ensure that backup_buf has the same memory alignment as
* it would have, had it been returned by malloc().
*/
alignas(max_align_t) char backup_buf[2 * MEGABYTE_SIZE];
};
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
* the input value of *psize in bytes, this function never returns NULL.
* The input value of *psize is the maximum size of the returned buffer.
*/
char *dbuf_get_buf(struct dynamic_buffer *dbuf, unsigned int align_order,
size_t *psize);
#endif /* HEADER_LIBFLOW_H */
f3-10.0/src/libprobe.c 0000664 0000000 0000000 00000065535 15175127362 0014522 0 ustar 00root root 0000000 0000000 #define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 600
#include
#include
#include
#include
#include /* For time(). */
#include
#include "libutils.h"
#include "libflow.h"
#include "libprobe.h"
static int _write_blocks(struct device *dev, const char *buf,
uint64_t first_pos, uint64_t last_pos, struct flow *fw,
progress_cb cb, unsigned int indent)
{
if (dev_write_blocks(dev, buf, first_pos, last_pos) &&
dev_write_blocks(dev, buf, first_pos, last_pos)) {
clear_progress(fw);
cb(indent, "I/O ERROR: Write error at block%s [%" PRIu64 ", %\" PRIu64 \"]!\n",
first_pos != last_pos ? "s" : "", first_pos, last_pos);
return true;
}
return false;
}
/* Some fake drives have a "tiny" (e.g. 8KB) cache for random accesses and
* a "large" (e.g. 4MB) cache for sequential accesses. So, for these
* fake drives, a random read may return a bad block, while a sequential
* read that includes that block returns it as a good block.
* This situation has been verified with the donated drive from
* issue #50 (https://github.com/AltraMayor/f3/issues/50).
*
* The example cache sizes come from the following
* discussion among Linux kernel developers:
* https://linux-arm-kernel.infradead.narkive.com/h3crV0D3/mmc-quirks-relating-to-performance-lifetime
*
* To circunvent this problem, the probe must only issue random reads.
*/
struct rdwr_info {
uint64_t cache_pos;
uint64_t cache_size_block;
uint64_t salt;
struct dynamic_buffer seqw_dbuf;
struct flow seqw_fw;
struct flow randw_fw;
struct flow randr_fw;
};
static int write_random_blocks(struct device *dev, const uint64_t pos[],
uint32_t n_pos, struct rdwr_info *rwi, progress_cb cb,
unsigned int indent)
{
const unsigned int block_order = dev_get_block_order(dev);
const unsigned 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) + block_size];
char *buffer = align_mem(stack, block_order);
uint32_t i;
if (n_pos == 0)
return false;
inc_total_blocks(&rwi->randw_fw, n_pos);
fw_set_indent(&rwi->randw_fw, indent);
start_measurement(&rwi->randw_fw);
for (i = 0; i < n_pos; i++) {
fill_buffer_with_block(buffer, block_order,
pos[i] << block_order, rwi->salt);
if (_write_blocks(dev, buffer, pos[i], pos[i], &rwi->randw_fw,
cb, indent))
return true;
measure(&rwi->randw_fw, 1, NULL);
}
end_measurement(&rwi->randw_fw);
return false;
}
static int write_blocks(struct device *dev,
uint64_t first_block, uint64_t last_block,
struct rdwr_info *rwi, progress_cb cb, unsigned int indent)
{
const unsigned int block_order = dev_get_block_order(dev);
const unsigned int block_size = dev_get_block_size(dev);
uint64_t offset = first_block << block_order;
uint64_t first_pos = first_block;
if (first_block > last_block)
return false;
inc_total_blocks(&rwi->seqw_fw, last_block - first_block + 1);
fw_set_indent(&rwi->seqw_fw, indent);
start_measurement(&rwi->seqw_fw);
while (first_pos <= last_block) {
const uint64_t max_blocks_to_write = last_block - first_pos + 1;
uint64_t blocks_to_write = MIN(
get_rem_chunk_blocks(&rwi->seqw_fw),
max_blocks_to_write);
size_t buf_len = blocks_to_write << block_order;
char *buffer, *stamp_blk;
uint64_t pos, next_pos;
buffer = dbuf_get_buf(&rwi->seqw_dbuf, block_order, &buf_len);
blocks_to_write = buf_len >> block_order;
assert(blocks_to_write > 0);
next_pos = first_pos + blocks_to_write;
stamp_blk = buffer;
for (pos = first_pos; pos < next_pos; pos++) {
fill_buffer_with_block(stamp_blk, block_order, offset,
rwi->salt);
stamp_blk += block_size;
offset += block_size;
}
if (_write_blocks(dev, buffer, first_pos, next_pos - 1,
&rwi->seqw_fw, cb, indent))
return true;
measure(&rwi->seqw_fw, blocks_to_write, NULL);
first_pos = next_pos;
}
end_measurement(&rwi->seqw_fw);
return false;
}
static int overwhelm_cache(struct device *dev,
struct rdwr_info *rwi, progress_cb cb, unsigned int indent)
{
if (rwi->cache_size_block == 0)
return false;
cb(indent, "Overwhelming cache\n");
return write_blocks(dev, rwi->cache_pos,
rwi->cache_pos + rwi->cache_size_block - 1, rwi, cb, indent);
}
static int read_block(struct device *dev, char *buf, uint64_t pos,
struct flow *fw, progress_cb cb, unsigned int indent)
{
if (dev_read_blocks(dev, buf, pos, pos) &&
dev_read_blocks(dev, buf, pos, pos)) {
clear_progress(fw);
cb(indent, "I/O ERROR: Read error at block %" PRIu64 "!\n",
pos);
return true;
}
return false;
}
static uint64_t bs_to_set(enum block_state bs)
{
switch (bs) {
case bs_unknown:
case bs_good:
case bs_bad:
case bs_changed:
case bs_overwritten:
assert(bs < sizeof(uint64_t) * 8);
return 1ULL << bs;
default:
assert(0);
}
}
static uint64_t bss_to_set(const enum block_state bss[], uint32_t n_bs)
{
uint64_t bs_set = 0;
uint32_t i;
for (i = 0; i < n_bs; i++)
bs_set |= bs_to_set(bss[i]);
return bs_set;
}
static inline uint64_t neg_bs_set(uint64_t bs_set)
{
return ~bs_set;
}
static inline bool in_bs_set(uint64_t bs_set, enum block_state bs)
{
assert(bs < sizeof(bs_set) * 8);
return (bs_set >> bs) & 1;
}
struct def_x_block {
uint64_t pos;
uint64_t expected_offset;
};
static int find_first_x_block(struct device *dev,
const struct def_x_block x_blocks[], uint32_t n_blocks,
uint64_t bs_set, uint32_t *pfirst_x_block_idx,
enum block_state *pstate, struct rdwr_info *rwi,
progress_cb cb, unsigned int indent)
{
const unsigned int block_order = dev_get_block_order(dev);
const unsigned int block_size = dev_get_block_size(dev);
char stack[align_head(block_order) + block_size];
char *probe_blk = align_mem(stack, block_order);
uint32_t i;
if (n_blocks == 0)
goto not_found;
inc_total_blocks(&rwi->randr_fw, n_blocks);
fw_set_indent(&rwi->randr_fw, indent);
start_measurement(&rwi->randr_fw);
for (i = 0; i < n_blocks; i++) {
uint64_t found_offset;
enum block_state bs;
if (read_block(dev, probe_blk, x_blocks[i].pos, &rwi->randr_fw,
cb, indent))
return true;
bs = validate_buffer_with_block(probe_blk, block_order,
x_blocks[i].expected_offset, &found_offset, rwi->salt);
measure(&rwi->randr_fw, 1, NULL);
if (in_bs_set(bs_set, bs)) {
/* Found the first x_block. */
*pfirst_x_block_idx = i;
*pstate = bs;
end_measurement(&rwi->randr_fw);
return false;
}
}
end_measurement(&rwi->randr_fw);
not_found:
*pfirst_x_block_idx = n_blocks;
return false;
}
static int find_first_bad_block(struct device *dev, const uint64_t pos[],
uint32_t n_pos, bool *pany_bad, uint64_t *pbad_pos,
struct rdwr_info *rwi, progress_cb cb, unsigned int indent)
{
const unsigned int block_order = dev_get_block_order(dev);
struct def_x_block x_blocks[n_pos];
enum block_state bs;
uint32_t i;
for (i = 0; i < n_pos; i++) {
x_blocks[i].pos = pos[i];
x_blocks[i].expected_offset = pos[i] << block_order;
}
if (find_first_x_block(dev, x_blocks, n_pos,
neg_bs_set(bs_to_set(bs_good)),
&i, &bs, rwi, cb, indent))
return true;
*pany_bad = i < n_pos;
if (*pany_bad) {
*pbad_pos = x_blocks[i].pos;
cb(indent, "INFO: Block %" PRIu64 " is %s!\n",
*pbad_pos, block_state_to_str(bs));
}
return false;
}
static inline uint64_t uint64_rand(void)
{
/* Use exclusive OR to avoid correlation between the two random
* numbers. For the lower 32 bits, the zeros from the left shift make
* the exclusive OR equivalent to OR. For each bit pair in the higher
* 32 bits, there are 2 cases for which the exclusive OR produces 1
* (i.e., 0^1 and 1^0), and 2 cases to produce 0 (i.e., 0^0 and 1^1).
* If OR were used For each bit pair in the higher 32 bits, there
* would be 3 cases to produce 1 (i.e., 0^1, 1^0, and 1^1), and
* 1 case to produce 0 (i.e., 0^0). Therefore, the exclusive OR avoids
* a bias towards higher values.
*/
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));
}
/* Since the list size is small, at most SAMPLING_MAX blocks,
* the O(n_samples^2) complexity is not a problem.
*/
static void fill_with_unique_samples(uint64_t *samples, uint32_t n_samples,
uint64_t first_pos, uint64_t last_pos)
{
uint32_t i, j;
assert(n_samples < last_pos - first_pos + 1);
for (i = 0; i < n_samples; ) {
uint64_t r = uint64_rand_range(first_pos, last_pos);
bool unique = true;
for (j = 0; j < i; j++) {
if (samples[j] == r) {
unique = false;
break;
}
}
if (unique) {
samples[i] = r;
i++;
}
}
}
static int uint64_cmp(const void *pa, const void *pb)
{
const uint64_t *pia = pa;
const uint64_t *pib = pb;
return *pia - *pib;
}
/* Fill @samples with @n_samples unique random positions in the range
* [@first_pos, @last_pos]. If @sorted is true, sort the entries of
* @samples. If @is_linear is true, the entries of @samples are linear
* (i.e. @first_pos, @first_pos + 1, ...).
*/
static void fill_samples(uint64_t *samples, uint32_t *pn_samples,
uint64_t first_pos, uint64_t last_pos, bool sorted, bool *pis_linear)
{
const uint64_t gap = last_pos - first_pos + 1;
*pis_linear = gap <= *pn_samples;
if (*pis_linear) {
uint32_t i;
*pn_samples = gap;
for (i = 0; i < gap; i++)
samples[i] = first_pos + i;
/* Treat single blocks as random reads instead of
* sequential ones.
*/
*pis_linear = gap > 1;
} else {
fill_with_unique_samples(samples, *pn_samples, first_pos,
last_pos);
if (sorted) {
qsort(samples, *pn_samples, sizeof(uint64_t),
uint64_cmp);
}
}
}
/* 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).
*/
static int probabilistic_test(struct device *dev,
uint64_t first_pos, uint64_t last_pos, int *pfound_a_bad_block,
struct rdwr_info *rwi, progress_cb cb, unsigned int indent)
{
uint32_t n_samples = 64;
uint64_t samples[n_samples];
bool is_linear, any_bad;
uint64_t bad_pos;
if (first_pos > last_pos)
goto not_found;
fill_samples(samples, &n_samples, first_pos, last_pos, false,
&is_linear);
cb(indent, "Sampling %" PRIu32 " block%s from block%s [%" PRIu64 ", %" PRIu64 "]\n",
n_samples, n_samples != 1 ? "s" : "",
first_pos != last_pos ? "s" : "", first_pos, last_pos);
if (find_first_bad_block(dev, samples, n_samples, &any_bad, &bad_pos,
rwi, cb, indent))
return true;
if (any_bad) {
/* Found a bad block. */
*pfound_a_bad_block = true;
return false;
}
not_found:
*pfound_a_bad_block = false;
return false;
}
/* Find a bad block in the range (left_pos, right_pos) using up to
* n_samples random samples.
*
* If a bad block is found, set *pright_pos to the position of the
* leftmost bad block.
*
* The code relies on the same analytical result derived
* in probabilistic_test().
*/
static int find_a_bad_block(struct device *dev, uint32_t n_samples,
uint64_t left_pos, uint64_t *pright_pos, int *found_a_bad_block,
struct rdwr_info *rwi, progress_cb cb, unsigned int indent)
{
uint64_t samples[n_samples];
bool is_linear, any_bad;
uint64_t bad_pos;
if (n_samples == 0 || *pright_pos <= left_pos + 1) {
/* Nothing to sample. */
goto not_found;
}
/* Sort entries of samples to minimize reads.
* As soon as one finds a bad block, one can ignore the remaining
* samples because the found bad block is the leftmost bad block.
*/
fill_samples(samples, &n_samples, left_pos + 1, *pright_pos - 1, true,
&is_linear);
cb(indent, "### Sampling %" PRIu32 " block%s from block%s (%" PRIu64 ", %" PRIu64 ")\n",
n_samples, n_samples != 1 ? "s" : "",
*pright_pos != left_pos + 2 ? "s" : "", left_pos, *pright_pos);
cb(indent + 1, "Writing random blocks\n");
if (is_linear) {
if (write_blocks(dev, left_pos + 1, *pright_pos - 1, rwi,
cb, indent + 1))
return true;
} else {
if (write_random_blocks(dev, samples, n_samples, rwi,
cb, indent + 1))
return true;
}
if (overwhelm_cache(dev, rwi, cb, indent + 1))
return true;
/* Test samples. */
cb(indent + 1, "Reading written blocks\n");
if (find_first_bad_block(dev, samples, n_samples, &any_bad, &bad_pos,
rwi, cb, indent + 1))
return true;
if (any_bad) {
/* Found the leftmost bad block. */
*pright_pos = bad_pos;
*found_a_bad_block = true;
return false;
}
not_found:
*found_a_bad_block = false;
return false;
}
/* The following probabilities are caculated using the analytical result
* derived in probabilistic_test().
*
* min_n_samples: Pr_g <= 50% and k = 8 => Pr_1b >= 99.6%
* max_n_samples: Pr_g <= 99% and k = 1024 => Pr_1b >= 99.9966%
*
* These parameters must be powers of 2 to satisfy the bounds in
* probe_max_written_blocks().
*/
#define SAMPLING_MIN (8)
#define SAMPLING_MAX (1024)
/* This function assumes that the block at @left_pos is good, and
* that the block at @*pright_pos is bad.
*/
static int sampling_probe(struct device *dev,
uint64_t left_pos, uint64_t *pright_pos,
struct rdwr_info *rwi, progress_cb cb, unsigned int indent)
{
uint32_t n_samples = SAMPLING_MIN;
int found_a_bad_block;
bool phase1 = true;
assert(SAMPLING_MAX >= SAMPLING_MIN);
cb(indent, "## Sampling\n");
while (*pright_pos > left_pos + n_samples + 1) {
if (find_a_bad_block(dev, n_samples, left_pos, pright_pos,
&found_a_bad_block, rwi, cb, indent + 1))
return true;
if (found_a_bad_block)
continue;
if (phase1) {
n_samples <<= 1;
if (n_samples <= SAMPLING_MAX)
continue;
phase1 = false;
n_samples = SAMPLING_MIN;
}
/* Phase 2: Minimize the probability that
* the rightmost block is bad.
*/
left_pos = (*pright_pos + left_pos) / 2;
}
if (find_a_bad_block(dev, n_samples, left_pos, pright_pos,
&found_a_bad_block, rwi, cb, indent + 1))
return true;
return false;
}
static void report_cache_size_test(unsigned int indent, progress_cb cb,
const struct device *dev, uint64_t first_pos, uint64_t last_pos)
{
double f_size = (last_pos - first_pos + 1) << dev_get_block_order(dev);
const char *unit = adjust_unit(&f_size);
cb(indent, "### Testing cache size: %.2f %s; Block%s [%" PRIu64 ", %" PRIu64 "]\n",
f_size, unit, first_pos != last_pos ? "s" : "",
first_pos, last_pos);
}
/* This constant needs to be a power of 2 and larger than 2^block_order. */
#define MAX_CACHE_SIZE_BYTE GIGABYTE_SIZE
static int find_cache_size(struct device *dev, const uint64_t left_pos,
uint64_t *pright_pos, struct rdwr_info *rwi, progress_cb cb,
unsigned int indent)
{
const unsigned int block_order = dev_get_block_order(dev);
const uint64_t end_pos = *pright_pos - 1;
uint64_t write_target = 1;
uint64_t final_write_target = MAX_CACHE_SIZE_BYTE >> block_order;
uint64_t first_pos = *pright_pos;
cb(indent, "## Find cache size\n");
assert(write_target > 0);
assert(write_target < final_write_target);
do {
uint64_t last_pos = first_pos - 1;
int found_a_bad_block;
/* This convoluted test is needed because the variables are
* unsigned. In a simplified form, it tests the following:
* first_pos - write_target > left_pos
*/
if (first_pos > left_pos + write_target) {
first_pos -= write_target;
} else if (first_pos > left_pos + 1) {
/* There's no room to write @write_target blocks,
* so write what's possible.
*/
first_pos = left_pos + 1;
} else {
/* Cannot write any further. */
break;
}
report_cache_size_test(indent + 1, cb, dev, first_pos, end_pos);
/* Write @write_target blocks before
* the previously written blocks.
*/
cb(indent + 2, "Writing block%s [%" PRIu64 ", %" PRIu64 "]\n",
first_pos != last_pos ? "s" : "", first_pos, last_pos);
if (write_blocks(dev, first_pos, last_pos, rwi, cb, indent + 2))
goto bad;
if (probabilistic_test(dev, first_pos, end_pos,
&found_a_bad_block, rwi, cb, indent + 2))
goto bad;
if (found_a_bad_block) {
*pright_pos = first_pos;
rwi->cache_size_block = write_target == 1
? 0 /* There is no cache. */
: end_pos - first_pos + 1;
return false;
}
write_target <<= 1;
} while (write_target <= final_write_target);
/* Good drive. */
*pright_pos = end_pos + 1;
rwi->cache_size_block = 0;
return false;
bad:
/* *pright_pos does not change. */
rwi->cache_size_block = 0;
return true;
}
static int find_wrap(struct device *dev,
uint64_t left_pos, uint64_t *pright_pos,
struct rdwr_info *rwi, progress_cb cb, unsigned int indent)
{
const uint64_t good_block = left_pos + 1;
/* The smallest integer m such that 2^m > good_block. */
const uint32_t m = ceiling_log2(good_block + 1);
/* Let k be the *smallest* integer such that
* 2^(m+k) + good_block >= *pright_pos
*
* Since this function has to test the blocks
* 2^m + good_block, 2^(m+1) + good_block, ..., 2^(m+k-1) + good_block,
* k corresponds to the number of samples to test.
*
* 2^(m+k) + good_block >= *pright_pos [=>]
* 2^(m+k) >= *pright_pos - good_block [=>]
* m + k >= log2(*pright_pos - good_block) [=>]
* k >= log2(*pright_pos - good_block) - m [=>]
* k = ceiling_log2(*pright_pos - good_block) - m
*/
const uint32_t aux = *pright_pos > good_block
? ceiling_log2(*pright_pos - good_block)
: 0;
const uint32_t n_samples = aux > m ? aux - m : 0;
const enum block_state bss[] = {bs_good, bs_changed};
struct def_x_block x_blocks[n_samples];
bool any_bad;
uint64_t bad_pos;
unsigned int block_order;
uint64_t expected_offset, high_bit;
uint32_t i;
enum block_state bs;
cb(indent, "## Find module\n");
/*
* Basis
*/
/* Make sure that there is at least a good block at the beginning
* of the drive.
*/
if (good_block >= *pright_pos)
return false;
cb(indent + 1, "Writing reference block %" PRIu64 "\n", good_block);
if (write_random_blocks(dev, &good_block, 1, rwi, cb, indent + 1) ||
overwhelm_cache(dev, rwi, cb, indent + 1))
return true;
cb(indent + 1, "Reading reference block\n");
if (find_first_bad_block(dev, &good_block, 1, &any_bad, &bad_pos,
rwi, cb, indent + 1) || any_bad)
return true;
/*
* Inductive step
*/
cb(indent + 1, "Probing module (reading %" PRIu32 " block%s)\n",
n_samples, n_samples != 1 ? "s" : "");
block_order = dev_get_block_order(dev);
expected_offset = good_block << block_order;
/* high_bit starts as the smallest power of 2 greater than
* good_block.
*/
high_bit = 1ULL << m; /* 2^m */
assert(high_bit > good_block);
/* Fill x_blocks in. */
for (i = 0; i < n_samples; i++) {
uint64_t pos = high_bit + good_block;
assert(pos < *pright_pos);
x_blocks[i].pos = pos;
x_blocks[i].expected_offset = expected_offset;
high_bit <<= 1;
}
assert(high_bit + good_block >= *pright_pos);
if (find_first_x_block(dev, x_blocks, n_samples,
bss_to_set(bss, DIM(bss)), &i, &bs, rwi,
cb, indent + 1))
return true;
if (i < n_samples) {
*pright_pos = x_blocks[i].pos - good_block; /* = high_bit */
cb(indent + 1, "INFO: Block %" PRIu64 " overwrites %s block %" PRIu64 "\n",
x_blocks[i].pos, block_state_to_str(bs), good_block);
}
return false;
}
static uint64_t drive_mid_block(const struct device *dev)
{
const uint64_t dev_size_byte = dev_get_size_byte(dev);
const unsigned int block_order = dev_get_block_order(dev);
return clp2((dev_size_byte >> block_order) / 2);
}
uint64_t probe_max_written_blocks(const struct device *dev)
{
const int block_order = dev_get_block_order(dev);
const uint64_t num_blocks = dev_get_size_byte(dev) >> block_order;
const int n = ceiling_log2(num_blocks);
return
/* find_cache_size() */
MIN(
/* The maximum number of written blocks. */
(MAX_CACHE_SIZE_BYTE >> block_order) * 2 - 1,
/* High half of the drive. */
num_blocks - drive_mid_block(dev)
) +
/* find_wrap(): only one block is written.
*
* Note: Both find_wrap() and sampling_probe() call
* overwhelm_cache(), which writes rwi->cache_size_block blocks.
* However, these blocks are written over the exact same
* block range previously written and saved during
* find_cache_size(). Thus, the safe device (sdev) deduplicates
* these cache writes, and they contribute 0 to the maximum
* number of unique written blocks bounded here.
*/
1 +
/* sampling_probe():
*
* We assume that Phase 1 has at most n successes (finding a bad
* block). A success reduces the search space by moving the
* right boundary to the leftmost bad block found. Because the
* random samples are uniformly distributed, even if only one
* sample falls into the "bad" region (the portion of the interval
* containing bad blocks), the expected distance to that sample
* halves the size of the bad region. Since each success halves
* the bad region on average, and the initial bad region is at
* most N blocks, n (log2(N)) is a safe probabilistic upper bound
* for the number of successes. Each success writes at most
* SAMPLING_MAX blocks.
*
* Each failure (not finding a bad block) doubles the sample
* size, starting from SAMPLING_MIN up to SAMPLING_MAX. Since
* the sample size only doubles on failures, the number of
* blocks written during failures forms a geometric series:
*
* SAMPLING_MIN + 2*SAMPLING_MIN + 4*SAMPLING_MIN + ... +
* SAMPLING_MAX
* = 2 * SAMPLING_MAX - SAMPLING_MIN
*
* Therefore, the total number of blocks written in Phase 1 is
* bounded by:
*
* n * SAMPLING_MAX + 2 * SAMPLING_MAX - SAMPLING_MIN
* = (n + 2) * SAMPLING_MAX - SAMPLING_MIN
*
* Phase 2 is a binary search (halving the range or narrowing
* it) which takes at most n iterations. In Phase 2, the sample
* size is fixed at SAMPLING_MIN. The total number of blocks
* written in Phase 2 is bounded by:
*
* n * SAMPLING_MIN
*
* Finally, after the loop finishes, there is one last call to
* find_a_bad_block(). In the worst case, this call uses
* SAMPLING_MAX blocks.
*
* Summing Phase 1, Phase 2, and the last call yields:
*
* (n + 2) * SAMPLING_MAX - SAMPLING_MIN +
* n * SAMPLING_MIN + SAMPLING_MAX
* = (n + 3) * SAMPLING_MAX + (n - 1) * SAMPLING_MIN
*/
(n + 3) * SAMPLING_MAX + (n - 1) * SAMPLING_MIN;
}
void report_probed_size(unsigned int indent, progress_cb cb,
const char *prefix, uint64_t bytes, unsigned int block_order)
{
double f = bytes;
const char *unit = adjust_unit(&f);
uint64_t blocks = bytes >> block_order;
cb(indent, "%s %.2f %s (%" PRIu64 " block%s)\n",
prefix, f, unit, blocks, blocks != 1 ? "s" : "");
}
void report_probed_order(unsigned int indent, progress_cb cb,
const char *prefix, unsigned int order)
{
double f = (1ULL << order);
const char *unit = adjust_unit(&f);
cb(indent, "%s %.2f %s (2^%i Byte%s)\n", prefix, f, unit, order,
order != 0 ? "s" : "");
}
void report_probed_cache(unsigned int indent, progress_cb cb,
const char *prefix, uint64_t cache_size_block,
unsigned int block_order)
{
double f = (cache_size_block << block_order);
const char *unit = adjust_unit(&f);
cb(indent, "%s %.2f %s (%" PRIu64 " block%s)\n",
prefix, f, unit, cache_size_block,
cache_size_block != 1 ? "s" : "");
}
int probe_device(struct device *dev, struct probe_results *results,
progress_cb cb, int show_progress,
long max_read_rate, long max_write_rate)
{
const uint64_t dev_size_byte = dev_get_size_byte(dev);
const unsigned int block_order = dev_get_block_order(dev);
const progress_cb fw_cb = show_progress ? cb : dummy_cb;
uint64_t left_pos, right_pos, mid_drive_pos;
struct rdwr_info rwi;
int wrap;
dbuf_init(&rwi.seqw_dbuf);
/* We initialize total_blocks to 0 because inc_total_blocks() is called
* to update it when new blocks become available.
*/
init_flow(&rwi.seqw_fw, block_order, 0, max_write_rate,
FW_MAX_BLOCKS_PER_DELAY_NONE, fw_cb, 0);
init_flow(&rwi.randw_fw, block_order, 0, max_write_rate,
FW_MAX_BLOCKS_PER_DELAY_NONE, fw_cb, 0);
init_flow(&rwi.randr_fw, block_order, 0, max_read_rate,
FW_MAX_BLOCKS_PER_DELAY_NONE, fw_cb, 0);
/* @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.
*/
assert(block_order <= MEGABYTE_ORDER);
left_pos = (MEGABYTE_SIZE >> 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) {
rwi.cache_size_block = 0;
goto bad;
}
/* I, Michel Machado, define that any drive with less than
* this number of blocks is fake.
*/
mid_drive_pos = drive_mid_block(dev);
assert(left_pos < mid_drive_pos);
assert(mid_drive_pos < right_pos);
/* This call is needed due to rand(). */
srand(time(NULL));
rwi.salt = uint64_rand();
cb(0, "# Device geometry\n");
report_probed_size(0, cb, "=> Announced size:", dev_size_byte,
block_order);
report_probed_order(0, cb, "=> Physical block size:", block_order);
if (find_cache_size(dev, mid_drive_pos - 1, &right_pos, &rwi, cb, 0))
goto bad;
assert(mid_drive_pos <= right_pos);
rwi.cache_pos = right_pos;
report_probed_cache(0, cb, "=> Approximate cache size:",
rwi.cache_size_block, block_order);
if (find_wrap(dev, left_pos, &right_pos, &rwi, cb, 0))
goto bad;
wrap = ceiling_log2(right_pos << block_order);
report_probed_order(0, cb, "=> Module:", wrap);
if (sampling_probe(dev, left_pos, &right_pos, &rwi, cb, 0))
goto bad;
if (right_pos == left_pos + 1) {
/* Bad drive. */
right_pos = 0;
}
results->real_size_byte = right_pos << block_order;
results->wrap = wrap;
goto out;
bad:
results->real_size_byte = 0;
results->wrap = ceiling_log2(dev_size_byte);
out:
dbuf_free(&rwi.seqw_dbuf);
report_probed_size(0, cb, "=> Usable size:",
results->real_size_byte, block_order);
cb(0, "# I/O average speeds\n");
fw_get_measurements(&rwi.seqw_fw, &results->seqw_blocks,
&results->seqw_time_ns);
fw_get_measurements(&rwi.randw_fw, &results->randw_blocks,
&results->randw_time_ns);
fw_get_measurements(&rwi.randr_fw, &results->randr_blocks,
&results->randr_time_ns);
report_io_speed(0, cb, "=> Sequential write:",
results->seqw_blocks, "block", results->seqw_time_ns,
block_order);
report_io_speed(0, cb, "=> Random write:",
results->randw_blocks, "block", results->randw_time_ns,
block_order);
report_io_speed(0, cb, "=> Random read:",
results->randr_blocks, "block", results->randr_time_ns,
block_order);
results->announced_size_byte = dev_size_byte;
results->cache_size_block = rwi.cache_size_block;
results->block_order = block_order;
return false;
}
f3-10.0/src/libprobe.h 0000664 0000000 0000000 00000002725 15175127362 0014517 0 ustar 00root root 0000000 0000000 #ifndef HEADER_LIBPROBE_H
#define HEADER_LIBPROBE_H
#include
#include "libutils.h"
#include "libdevs.h"
#include "libflow.h" /* Enable usage of FW_MAX_PROCESS_RATE_NONE */
/* Provide an upper bound on the number of *unique* blocks that will be written
* when probe_device(dev) is called.
*
* Notice that probe_device() may read more blocks than it writes, and
* it may write the same block multiple times. For example, the helper function
* find_wrap() only writes 1 block, but reads multiple blocks. And the helper
* function overwhelm_cache() is called multiple times over the same blocks.
*/
uint64_t probe_max_written_blocks(const struct device *dev);
void report_probed_size(unsigned int indent, progress_cb cb,
const char *prefix, uint64_t bytes, unsigned int block_order);
void report_probed_order(unsigned int indent, progress_cb cb,
const char *prefix, unsigned int order);
void report_probed_cache(unsigned int indent, progress_cb cb,
const char *prefix, uint64_t cache_size_block,
unsigned int block_order);
struct probe_results {
uint64_t real_size_byte;
uint64_t announced_size_byte;
int wrap;
uint64_t cache_size_block;
unsigned int block_order;
uint64_t seqw_blocks, seqw_time_ns;
uint64_t randw_blocks, randw_time_ns;
uint64_t randr_blocks, randr_time_ns;
};
int probe_device(struct device *dev, struct probe_results *results,
progress_cb cb, int show_progress,
long max_read_rate, long max_write_rate);
#endif /* HEADER_LIBPROBE_H */
f3-10.0/src/libutils.c 0000664 0000000 0000000 00000023211 15175127362 0014534 0 ustar 00root root 0000000 0000000 #define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 600
#include /* For fprintf(). */
#include /* For strtoll(). */
#include
#include
#include
#include
#include "libutils.h"
#include "version.h"
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 __builtin_popcountll(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[] = {"Bytes", "KB", "MB", "GB", "TB", "PB", "EB"};
unsigned int i = 0;
double final = *ptr_bytes;
while (i < DIM(units) && final >= 1024) {
final /= 1024;
i++;
}
*ptr_bytes = final;
if (i > 0 || final != 1.0)
return units[i];
return "Byte";
}
int nsec_to_str(uint64_t nsec, char *str)
{
const uint64_t nsec_in_a_usec = 1000;
const uint64_t nsec_in_a_msec = 1000 * nsec_in_a_usec;
const uint64_t nsec_in_a_sec = 1000 * nsec_in_a_msec;
const uint64_t nsec_in_a_min = 60 * nsec_in_a_sec;
const uint64_t nsec_in_an_hour = 60 * nsec_in_a_min;
const uint64_t nsec_in_a_day = 24 * nsec_in_an_hour;
const uint64_t nsec_in_a_week = 7 * nsec_in_a_day;
bool has_w, has_d, has_h, has_m, has_s, has_prv = false;
lldiv_t div;
int c, tot = 0;
has_w = nsec >= nsec_in_a_week;
if (has_w) {
div = lldiv(nsec, nsec_in_a_week);
nsec = div.rem;
c = sprintf(str + tot, "%i week%s",
(int)div.quot, div.quot != 1 ? "s" : "");
assert(c > 0);
tot += c;
has_prv = true;
}
has_d = nsec >= nsec_in_a_day;
if (has_d) {
div = lldiv(nsec, nsec_in_a_day);
nsec = div.rem;
c = sprintf(str + tot, "%s%i day%s",
has_prv ? " " : "", (int)div.quot,
div.quot != 1 ? "s" : "");
assert(c > 0);
tot += c;
has_prv = true;
}
has_h = nsec >= nsec_in_an_hour;
if (has_h) {
div = lldiv(nsec, nsec_in_an_hour);
nsec = div.rem;
c = sprintf(str + tot, "%s%i:",
has_prv ? " " : "", (int)div.quot);
assert(c > 0);
tot += c;
has_prv = true;
}
has_m = has_h || nsec >= nsec_in_a_min;
if (has_m) {
div = lldiv(nsec, nsec_in_a_min);
nsec = div.rem;
if (has_h)
c = sprintf(str + tot, "%02i", (int)div.quot);
else
c = sprintf(str + tot, "%s%i'",
has_prv ? " " : "", (int)div.quot);
assert(c > 0);
tot += c;
has_prv = true;
}
has_s = nsec >= nsec_in_a_sec;
if (has_s) {
div = lldiv(nsec, nsec_in_a_sec);
nsec = 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_prv)
c = sprintf(str + tot, " %is", (int)div.quot);
else
c = sprintf(str + tot, "%i.%02is", (int)div.quot,
(int)(nsec / (10 * nsec_in_a_msec)));
assert(c > 0);
tot += c;
has_prv = true;
}
if (has_prv)
return tot;
if (nsec >= nsec_in_a_msec) {
div = lldiv(nsec, nsec_in_a_msec);
nsec = div.rem;
c = sprintf(str + tot, "%i.%ims", (int)div.quot,
(int)(nsec / (100 * nsec_in_a_usec)));
} else if (nsec >= nsec_in_a_usec) {
div = lldiv(nsec, nsec_in_a_usec);
nsec = div.rem;
c = sprintf(str + tot, "%i.%ius", (int)div.quot,
(int)(nsec / 100));
} else {
c = sprintf(str + tot, "%ins", (int)nsec);
}
assert(c > 0);
tot += c;
return tot;
}
void *align_mem2(void *p, unsigned int order, int *shift)
{
uintptr_t ip0 = (uintptr_t)p;
uintptr_t head = align_head(order);
uintptr_t ip1 = (ip0 + head) & ~head;
*shift = ip1 - ip0;
return (void *)ip1;
}
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 <<= SECTOR_ORDER;
end++;
break;
case 'k':
case 'K': /* KB */
ll <<= KILOBYTE_ORDER;
end++;
break;
case 'm':
case 'M': /* MB */
ll <<= MEGABYTE_ORDER;
end++;
break;
case 'g':
case 'G': /* GB */
ll <<= GIGABYTE_ORDER;
end++;
break;
case 't':
case 'T': /* TB */
ll <<= TERABYTE_ORDER;
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, unsigned int block_order,
uint64_t offset, uint64_t salt)
{
const unsigned int num_int64 = 1U << (block_order - 3);
uint64_t *int64_array = buf;
uint64_t random_number = offset ^ salt;
unsigned int i;
assert(block_order >= SECTOR_ORDER);
/* DO NOT add salt here!
* Drives know the offset, so applying salt to it leaks the salt.
*/
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);
}
}
const char *block_state_to_str(enum block_state state)
{
const char *conv_array[] = {
[bs_unknown] = "Unknown",
[bs_good] = "Good",
[bs_bad] = "Bad",
[bs_changed] = "Changed",
[bs_overwritten] = "Overwritten",
};
return conv_array[state];
}
enum block_state validate_buffer_with_block(const void *buf,
unsigned int block_order, uint64_t expected_offset,
uint64_t *pfound_offset, uint64_t salt)
{
const uint64_t *int64_array = buf;
const uint64_t found_offset = int64_array[0];
const unsigned int num_int64 = 1U << (block_order - 3);
uint64_t random_number = found_offset ^ salt;
const unsigned int bit_error_tolerance = 7;
unsigned int bit_error_count = 0;
unsigned int i;
assert(block_order >= SECTOR_ORDER);
for (i = 1; i < num_int64; i++) {
random_number = next_random_number(random_number);
if (int64_array[i] != random_number) {
bit_error_count += __builtin_popcountll(
int64_array[i] ^ random_number);
if (bit_error_count > bit_error_tolerance)
break;
}
}
*pfound_offset = found_offset;
if (expected_offset == found_offset) {
if (bit_error_count == 0)
return bs_good;
if (bit_error_count <= bit_error_tolerance)
return bs_changed;
return bs_bad;
}
if (bit_error_count <= bit_error_tolerance)
return bs_overwritten;
return bs_bad;
}
enum block_state validate_block_update_stats(const void *buf,
unsigned int block_order, uint64_t expected_offset,
uint64_t *pfound_offset, uint64_t salt, struct block_stats *stats)
{
enum block_state state = validate_buffer_with_block(buf, block_order,
expected_offset, pfound_offset, salt);
switch (state) {
case bs_good:
stats->ok++;
break;
case bs_changed:
stats->changed++;
break;
case bs_bad:
stats->bad++;
break;
case bs_overwritten:
stats->overwritten++;
break;
default:
assert(0);
}
return state;
}
static void print_stat(const char *prefix, uint64_t count,
unsigned int block_order, const char *unit_name)
{
double f = count << block_order;
const char *unit = adjust_unit(&f);
printf("%s %.2f %s (%" PRIu64 " %s%s)\n",
prefix, f, unit, count, unit_name, count != 1 ? "s" : "");
}
void print_stats(const struct block_stats *stats, unsigned int block_order,
const char *unit_name)
{
print_stat("\n Data OK:", stats->ok, block_order, unit_name);
print_stat("Data LOST:",
stats->bad + stats->changed + stats->overwritten,
block_order, unit_name);
print_stat("\t Corrupted:", stats->bad, block_order, unit_name);
print_stat("\tSlightly changed:", stats->changed, block_order, unit_name);
print_stat("\t Overwritten:", stats->overwritten, block_order, unit_name);
}
void print_avg_min_max_samples(const char *prefix, const char *suffix,
double avg_speed, double min_speed, double max_speed, uint64_t samples)
{
const char *avg_unit = adjust_unit(&avg_speed);
const char *min_unit = adjust_unit(&min_speed);
const char *max_unit = adjust_unit(&max_speed);
printf("%sAvg: %.2f %s/s\n\tMin: %.2f %s/s, Max: %.2f %s/s, %" PRIu64 " samples%s",
prefix, avg_speed, avg_unit, min_speed, min_unit,
max_speed, max_unit, samples, suffix);
}
void report_io_speed(unsigned int indent, progress_cb cb, const char *prefix,
uint64_t blocks, const char *block_unit, uint64_t time_ns,
unsigned int block_order)
{
double speed;
const char *unit;
char time_str[TIME_STR_SIZE];
if (time_ns == 0) {
cb(indent, "%s NO DATA\n", prefix);
return;
}
speed = calc_avg_speed(block_order, blocks, time_ns);
unit = adjust_unit(&speed);
nsec_to_str(time_ns, time_str);
cb(indent, "%s %.2f %s/s (%" PRIu64 " %s%s / %s)\n",
prefix, speed, unit, blocks, block_unit,
blocks != 1 ? "s" : "", time_str);
}
static void print_indent(unsigned int indent, const char *indent_str)
{
unsigned int i;
for (i = 0; i < indent; i++)
printf("%s", indent_str);
}
static void vprintf_cb(unsigned int indent, const char *format, va_list args)
{
const char *indent_str = " ";
const char *erase_str = "\b\b\b\b\b\b\b\b";
assert(format != NULL);
if (format[0] != '\b') {
print_indent(indent, indent_str);
vprintf(format, args);
return;
}
vprintf(format, args);
print_indent(indent, erase_str);
}
void printf_cb(unsigned int indent, const char *format, ...)
{
va_list args;
va_start(args, format);
vprintf_cb(indent, format, args);
va_end(args);
}
void printf_flush_cb(unsigned int indent, const char *format, ...)
{
va_list args;
va_start(args, format);
vprintf_cb(indent, format, args);
va_end(args);
fflush(stdout);
}
void dummy_cb(unsigned int indent, const char *format, ...)
{
/* Do nothing */
UNUSED(indent);
UNUSED(format);
}
f3-10.0/src/libutils.h 0000664 0000000 0000000 00000010176 15175127362 0014547 0 ustar 00root root 0000000 0000000 #ifndef HEADER_LIBUTILS_H
#define HEADER_LIBUTILS_H
#include
#include /* For struct argp_state. */
#include /* For struct timespec. */
#define SECTOR_ORDER (9)
#define KILOBYTE_ORDER (10)
#define MEGABYTE_ORDER (20)
#define GIGABYTE_ORDER (30)
#define TERABYTE_ORDER (40)
#define SECTOR_SIZE (1ULL << SECTOR_ORDER)
#define KILOBYTE_SIZE (1ULL << KILOBYTE_ORDER)
#define MEGABYTE_SIZE (1ULL << MEGABYTE_ORDER)
#define GIGABYTE_SIZE (1ULL << GIGABYTE_ORDER)
#define TERABYTE_SIZE (1ULL << TERABYTE_ORDER)
#define UNUSED(x) ((void)x)
#define DIM(x) (sizeof(x) / sizeof((x)[0]))
#define GEN_MIN(name, type) \
static inline type name##_min(type a, type b) \
{ \
return a < b ? a : b; \
}
GEN_MIN(ul, unsigned long)
GEN_MIN(ull, unsigned long long)
#define MIN(a, b) _Generic(1 ? (a) : (b), \
unsigned long: ul_min, \
unsigned long long: ull_min \
)(a, b)
typedef void (*progress_cb)(unsigned int indent, const char *format, ...);
void printf_cb(unsigned int indent, const char *format, ...);
void printf_flush_cb(unsigned int indent, const char *format, ...);
void dummy_cb(unsigned int indent, const char *format, ...);
static inline bool is_power_of_2(uint64_t x)
{
return x && !(x & (x - 1));
}
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 nsec_to_str(uint64_t nsec, 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 unsigned int align_head(unsigned int order)
{
return (1U << order) - 1;
}
void *align_mem2(void *p, unsigned int order, int *shift);
static inline void *align_mem(void *p, unsigned int order)
{
int shift;
return align_mem2(p, order, &shift);
}
/* Return true if @ptr is aligned to @alignment.
* @alignment must be a power of 2.
*/
static inline bool is_aligned(const void *ptr, size_t alignment)
{
return ((uintptr_t)ptr & (alignment - 1)) == 0;
}
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, unsigned int block_order,
uint64_t offset, uint64_t salt);
enum block_state {
bs_unknown,
bs_good,
bs_bad,
bs_changed,
bs_overwritten,
};
const char *block_state_to_str(enum block_state state);
struct block_stats {
uint64_t ok;
uint64_t bad;
uint64_t changed;
uint64_t overwritten;
};
/* Dependent on the byte order of the processor (i.e. endianness). */
enum block_state validate_buffer_with_block(const void *buf,
unsigned int block_order, uint64_t expected_offset,
uint64_t *pfound_offset, uint64_t salt);
enum block_state validate_block_update_stats(const void *buf,
unsigned int block_order, uint64_t expected_offset,
uint64_t *pfound_offset, uint64_t salt, struct block_stats *stats);
static inline uint64_t diff_timespec_ns(const struct timespec *t1,
const struct timespec *t2)
{
return (t2->tv_sec - t1->tv_sec) * 1000000000ULL +
t2->tv_nsec - t1->tv_nsec;
}
void print_stats(const struct block_stats *stats, unsigned int block_order,
const char *unit_name);
void print_avg_min_max_samples(const char *prefix, const char *suffix,
double avg_speed, double min_speed, double max_speed, uint64_t samples);
void report_io_speed(unsigned int indent, progress_cb cb, const char *prefix,
uint64_t blocks, const char *block_unit, uint64_t time_ns,
unsigned int block_order);
/* Return speed in bytes per second. */
static inline double calc_avg_speed(unsigned int block_order, uint64_t blocks,
uint64_t time_ns)
{
return (blocks << block_order) * 1000000000.0 / time_ns;
}
#endif /* HEADER_LIBUTILS_H */
f3-10.0/src/version.h 0000664 0000000 0000000 00000000160 15175127362 0014375 0 ustar 00root root 0000000 0000000 #ifndef HEADER_VERSION_H
#define HEADER_VERSION_H
#define F3_STR_VERSION "10.0"
#endif /* HEADER_VERSION_H */