Commit a0329e62 authored by Alessandro Rubini's avatar Alessandro Rubini

Merge branch 'sdbfs-gitorious'

This is a merge of all previous work done on sdbfs using a different
repository (which I used to push to gitorious).

Besides the kernel stuff, which is still in flush, userspace and lib
are actually useful to sdb users in general, so this is a better place
to host it.
parents b99c61e4 4da49f56
*~
*.o
*.a
*.mod.c
*.ko
.*.cmd
modules.order
.tmp_versions
Module.symvers
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
DIRS = lib userspace kernel doc
all clean modules install modules_install:
for d in $(DIRS); do $(MAKE) -C $$d $@ || exit 1; done
This is an implementation of the SDB filesystem. Such thing is a
flash-based filesystem meant to be accessed both by a soft-core
running on the FPGA and the host computer (but not at the same time).
The structure of the filesystem is read-only, but each individual file
may be read-write, based on alignment restrictions of the hosting
device.
The thing is split in three parts
kernel/
includes the kernel driver (filesystem and sample hw support).
lib/
includes the library that the soft-core can use to access its
own flash memory.
userspace/
includes the gensdbfs tool and other user-space stuff that uses
the library above.
Since SDB is used to self-describe a bus, you can even mount sdbfs
over a real bus. In this case however only mmap is allowed on the
individual files (no read or write method is there).
*~
*.aux
*.cp
*.cps
*.fn
*.html
*.info
*.ky
*.log
*.pdf
*.pg
*.texi
*.toc
*.tp
/*.txt
*.vr
#
# Makefile for the documentation directory
#
# Copyright 1994,2000,2010,2011 Alessandro Rubini <rubini@linux.it>
#
#################
# There is not basenames here, all *.in are considered input
INPUT = $(wildcard *.in)
TEXI = $(INPUT:.in=.texi)
INFO = $(INPUT:.in=.info)
HTML = $(INPUT:.in=.html)
TXT = $(INPUT:.in=.txt)
PDF = $(INPUT:.in=.pdf)
ALL = $(INFO) $(HTML) $(TXT) $(PDF)
MAKEINFO ?= makeinfo
%.texi: %.in
@rm -f $@
sed -f ./infofilter $< > $@
emacs -batch --no-site-file -l fixinfo $@
chmod -w $@
%.pdf: %.texi
texi2pdf --batch $<
%.info: %.texi
$(MAKEINFO) $< -o $@
%.html: %.texi
$(MAKEINFO) --html --no-split -o $@ $<
%.txt: %.texi
$(MAKEINFO) --no-headers $< > $@
##############################################
.PHONY: all images check terse clean install
.INTERMEDIATE: $(TEXI)
all: images $(ALL)
$(MAKE) terse
images::
if [ -d images ]; then $(MAKE) -C images || exit 1; fi
check: _err.ps
gs -sDEVICE=linux -r320x200x16 $<
terse:
for n in cp fn ky pg toc tp vr aux log; do rm -f *.$$n; done
rm -f *~
clean: terse
rm -f $(ALL) $(TEXI)
# add the other unused targets, so the rule in ../Makefile works
modules install modules_install:
;; use:
;; emacs -batch -l ./fixinfo.el <file>
;; or, better:
;; emacs -batch --no-site-file -l ./fixinfo.el <file>
(defun fixinfo (file)
(find-file-other-window file)
(message (concat "Maxing texinfo tree in " file))
(texinfo-all-menus-update)
(texinfo-every-node-update)
(save-buffer)
(kill-buffer (current-buffer))
)
;; loop over command line arguments
(mapcar 'fixinfo command-line-args-left)
(kill-emacs)
#! /usr/bin/sed -f
# allow "%" as a comment char, but only at the beginning of the line
s/^%/@c /
#s/[^\\]%.*$//
s/^\\%/%/
#preserve blanks and braces in @example blocks
/^@example/,/^@end example/ s/{/@{/g
/^@example/,/^@end example/ s/}/@}/g
/^@example/,/^@end example/ p
/^@example/,/^@end example/ d
/^@smallexample/,/^@end smallexample/ s/{/@{/g
/^@smallexample/,/^@end smallexample/ s/}/@}/g
/^@smallexample/,/^@end smallexample/ p
/^@smallexample/,/^@end smallexample/ d
# remove leading blanks
s/^[ ]*//
\input texinfo @c -*-texinfo-*-
%
% sdbfs.in - main file for the documentation
%
%%%%
%------------------------------------------------------------------------------
%
% NOTE FOR THE UNAWARE USER
% =========================
%
% This file is a texinfo source. It isn't the binary file of some strange
% editor of mine. If you want ASCII, you should "make sdbfs.txt".
%
%------------------------------------------------------------------------------
%
% This is not a conventional info file...
% I use three extra features:
% - The '%' as a comment marker, if at beginning of line ("\%" -> "%")
% - leading blanks are allowed (this is something I can't live without)
% - braces are automatically escaped when they appear in example blocks
%
@comment %**start of header
@documentlanguage en
@setfilename sdbfs.info
@settitle sdbfs
@iftex
@afourpaper
@end iftex
@paragraphindent none
@comment %**end of header
@setchapternewpage off
@set update-month September 2012
@finalout
@titlepage
@title SDBFS
@subtitle @value{update-month}
@subtitle A Flash File-system based on SDB data structures
@author Alessandro Rubini for CERN (BE-CO-HT)
@end titlepage
@headings single
@c ##########################################################################
@iftex
@contents
@end iftex
@c ##########################################################################
@node Top
@top Introduction
This package implements and describes a file-system based on the SDB
data structures defined by the Open Hardware Repository project called
@i{FPGA Configuration Space}. The official SDB specification at the time
of this writing is @url{http://www.ohwr.org/attachments/1487/sdb-1.0.pdf}.
The SDB data structures are designed to describe the address space
covered by a bus, which is split in memory regions belonging to
different devices. This project reuses the same structures to describe
a storage address space, exploiting the simple design. While the structures
are not simple to generate, they are very simple to parse, which allows
an embedded processor (like a soft-core running on an FPGA) to access
this filesystem with a minimal amount of code.
@i{sdbfs} is read-only as far as the structure is concerned, but
individual files may be modified if so configured to. The filesystem
is aware of the concept of block size, so it can be placed on flash
memory, but doesn't do wear-leveling or any other fancy thing to
preserver simplicity.
Currently, the repository is hosted at Gitorious:
@code{git://gitorious.org/rubi/sdbfs.git} but it will likely be merged
into the OHWR project (thus:
@code{git://ohwr.org/hdl-core-lib/fpga-config-space.git}. If you are reading
this document and look for the latest version, if the Gitorious repository
doesn't exist, please try the @i{fpga-config-space} in the OHWR project.
@c ##########################################################################
@node Library Support
@chapter Library Support
This package offers a library of functions to access the filesystem,
but not to create it -- creation is performed by @file{gensdbfs} which
has no code to be shared with actual access to the filesystem.
The library is designed to be used in three different environments:
Posix user space, Linux kernel space and freestanding environments.
The last environment is going to be verified with the LM32 processor,
because we need to access @i{sdbfs} from that very soft-core in our
FPGA devices.
In order to be suitable to constrained freestanding environments, the
library is designed not to use external functions that may weight over
the final footprint:
@itemize @bullet
@item No @i{malloc} is ever called by the library;
@item The library keeps internal status to avoid too much token passing;
@item Every function is compiled to its own ELF section;
@item Endian conversion is left out of the library as far as possible.
@end itemize
The user space programs that use this library can be used to better
understand how the library is meant to be used.
@c ==========================================================================
@node The Filesystem Structure
@section The Filesystem Structure
Users of the library must have @code{-I} to find @file{libsdbfs.h}
(which includes other files from the same directory where it lives).
Similarly, they must link @file{libsdbfs.a} from the same
directory.
Everything in the library refers to @code{struct sdbfs} and library
users can register more than one such filesystems. A freestanding
application will most likely have a static structure in its data
section, initialized at compile time. Some of the fields
in the structure are library-private; this is the list of
the public fields:
@table @code
@item char *name;
The device name is optional; it is only used by @i{sdbfs_dev_find()}.
@item void *drvdata;
The field is there for library users to store their data, if they
register more than one filesystem and implement the methods
listed here below.
@item int blocksize;
The erase block size for the device.
@item unsigned long entrypoint;
The offset of the first @i{sdb} record in the device. For example,
for FMC EEPROM devices we'll have an entry point of 256 because
the FMC standard mandates the content of the leading part of the
flash device.
@item void *data;
If the filesystem is directly mapped, the user may fill this
pointer and avoid declaring the @i{read} method described next.
@item unsigned long datalen;
The length of the mapped area.
@item int (*read)(struct sdbfs *fs, int offset, void *buf, int count);
The method is used to read raw data from the storage device.
It is called by the library if the @i{data} field is NULL.
@item int (*write)(struct sdbfs *fs, int offset, void *buf, int count);
@itemx int (*erase)(struct sdbfs *fs, int offset, int count);
These methods are defined but not yet used as of this version.
@end table
@c ==========================================================================
@node Library functions
@section Library functions
The library defines the following functions to act on a @i{sdb} storage
device. All functions returning integer will return a negative
number in case of error, within the @i{errno} range (e.g. @code{-ENOENT}).
@table @code
@item int sdbfs_dev_create(struct sdbfs *fs, int verbose);
@itemx int sdbfs_dev_destroy(struct sdbfs *fs);
Register and unregister a device. Each library user can register
more than one device if needed. Please note that the device must
be preallocated by the caller, as the library doesn't use
@i{malloc} internally, as a design choice. The @i{create} function
fails with @code{ENOTDIR} if no @i{sdb} magic number is found
at the specified entry point (field @code{entrypoint}). All
fields that are not used by the caller must be zeroed before
calling the @i{create} function.
@item struct sdbfs *sdbfs_dev_find(const char *name);
If the user registered more than one device, this function
can be used to scan the list of devices and return one according
to its own @code{name} field.
@item int sdbfs_open_name(struct sdbfs *fs, const char *name);
@itemx int sdbfs_open_id(struct sdbfs *fs, uint64_t vid, uint32_t did);
@itemx int sdbfs_close(struct sdbfs *fs);
The library has the concept of @i{currently-open} file for each
@i{sdb} device. The user can open a file according to its
name or its vendor/device identifiers. Please note that if
several files feature tha same identifiers (or name) the library
will return the first it finds. Keeping the @i{open} file
within the data structure is clearly limiting over more modern
approaches, but it allows keeping down the footprint of both the
library and user code.
@item struct sdb_device *sdbfs_scan(struct sdbfs *fs, int newscan);
The function can be used to get a listing of the @i{sdb}
device. If @code{newscan} is not-zero the library starts a
fresh new scan; otherwise it continues the ongoing scan.
The return value is the pointer to an @i{sdb} structure
representing the file, which is only valid up to the next
library call. After the last valid file the function returns
@code{NULL}. The function uses internal storage, so it
can only be called when no file is currently open.
@item int sdbfs_fstat(struct sdbfs *fs, struct sdb_device *record_return);
The function copies the @i{sdb} record for the currently-open
file to a user-provided data area. The user will then be able
to collect information about the file.
@item int sdbfs_fread(struct sdbfs *fs, int offset, char *buf, int count);
Read from the currently-open file. If the @code{offset} argument
is less than zero the file is read sequentially; if it is zero or
positive it represents the offset from the beginning of the file.
@item int sdbfs_fwrite(struct sdbfs *fs, int offset, char *buf, int count);
This is not yet implemented.
@item uint64_t htonll(uint64_t ll);
@itemx uint64_t ntohll(uint64_t ll);
The functions are provided by library headers to convert 64-bit
values between host byte order and @i{sdb} byte order -- which is
the same as network byte order. For 32-bit and 16-bit please use
the standard functions for network byte order.
@end table
@c ##########################################################################
@node User-Space Tools
@chapter User-Space Tools
The @file{userspace} subdirectory of this package includes a few
user-space tools to create @i{sdbfs} images and access them. All tools
but @i{gensdbfs} are base on the @i{sdbfs} library and their source
can be used as an example and best practice of library use.
@c ==========================================================================
@node gensdbfs
@section gensdbfs
The tool receives two arguments: the directory to copy into an @i{sdbfs}
image and the name of the image file to be generated.
It accepts the following command line arguments:
@table @code
@item -b <blocksize>
The block size to be used in generating the file. All files
and directories are currently aligned to the block size, but
later versions will not aligned read-only files, to save storage
space. The default block size is 64 bytes.
@item -s <devicesize>
The device size by default is unlimited, internally
represented by 0. If you specify a device size, @i{gensdbfs} will
verify that data fits the requested size, and will return an error
if it doesn't.
@end table
The tool creates an image file that includes the following SDB structures:
@table @i
@item sdb_interconnect
The structure is used as the first SDB structure of each directory,
so to include the magic number and the size of the directory. The
bus type is defined as @i{sdb_data}, with identifier 1. This
type is not yet part of the official SDB specification.
@item sdb_device
Every file is instantiated as a device. By being hosted in a
bus of type @i{sdb_data}, the device is known to be a storage area.
@item sdb_bridge (not yet implemented)
The @i{bridge} structure is used to represent a subdirectory.
@end table
@c --------------------------------------------------------------------------
@node Use of SDB fields in sdbfs
@subsection Use of SDB fields in sdbfs
The individual fields of the SDB structure are filled in the following way:
@table @code
@item sdb_magic
In interconnect records, the magic is the standard SDB magic number.
@item sdb_version
1, because this is the SDB version used here.
@item sdb_bus_type
@code{sdb_data} (added to SDB specification after version 1.0
of the spec itself).
@item vendor_id
0x46696c6544617461LL (i.e. @code{"FileData"}). It may be changed
by the configuration file.
@item device_id
The first 4 bytes of the file name. It may be changed
by the configuration file.
@item version
Currently 1. Should be the @i{sdbfs} version (git commit).
@item date
Currently not set. Should be the date when @i{gensdbfs} generated
the image, in the SDB suggested format.
@item name
The name is the first 19 character of the original file name,
padded with blanks (0x20) as per SDB specification. You can't change
the name using the configuration file.
@item record_type
@code{sdb_type_interconnect}, for the current directory,
@code{sdb_type_device} for files and in
the future @code{sdb_type_bridge} for subdirectories.
@item addr_first
For a file this is the first byte address where data is found.
This is currently an absolute address, which makes sense since
we have no subdirectories yet. However, some use cases require
the directory information not to live at offset 0, while referring
to a file that is at the beginning of the storage. SDB mandates
relative addresses because it's designed for gateware crossbars,
so we'll have to understand how to deal with this when we have
subdirectories. For the directory itself, addr_first is the
address of the directory -- again, data-before-dir is not cleanly
handled.
@itemx addr_last
This is the last allocated byte for files. If the configuration
file requested extra size for the file, it is accounted here.
The trailing space is filled with zeroes by @file{gensdbfs} but
later the configuration file will be able to specify a filler value.
For directories, this is the last byte written by any files
within the directory itself.
@item
@end table
@c --------------------------------------------------------------------------
@node Customizing gensdbfs
@subsection Customizing gensdbfs
If @file{gensdbfs} finds a @code{--SDB-CONFIG--} file in
the toplevel directory, it opens it as a configuration file. Subdirectories
can't have configuration files, as configuration is filesystem-wide.
The file is a text file, line-oriented. Empty lines and comment lines
are ignored. All lines that begin with the hash (@code{#}) are
considered comments (this means that you can't configure a filename
that begins with the hash, but I think this is not a problem.
Configuration values are specified per-file. Lines that begin with
non-space characters refer to file names. Later indented lines
specify parameters for the current file name.
The following options are supported
@table @code
@item vendor = <number>
Change the default vendor value. The value is a 64-bit number and
can be specified as decimal, hexadecimal or octal.
@item device = <number>
Change the default device value (the default device is the first
4 bytes of the file name). The value is a 32-bit number and
can be specified as decimal, hexadecimal or octal.
@item write = 1
By default, only world-writable files are generated as writable
in the filesystem image. This option allows to create a modifiable
file in the sdb filesystem image without giving over permissions on
the host filesystem. (You can also use @code{write = 0} to turn
off write permission).
@item maxsize = <number>
Specifies the maximum file size. This allows a writeable file to
be extended in the filesystem image, for later overwriting with
different data. The program doesn't
check whether @i{maxsize} is smaller than the current size.
@c FIXME: the maxsize/size issue
@item position = <number>
Force the data to be placed at a specific address in the
filesystem image. For directories, this is the address where
you'll find the SDB records, whose first 4 bytes are the magic
number. For files this is the placement of the associated data.
For all files where @i{position} is not specified, @file{gensdbfs}
will allocate storage sequentially after the directory itself,
respecting block alignment. It's not possible, currently, to
request all files to be stored sequentially at a specific address
@end table
This package includes a working example in the @file{userspace} directory.
You can thus test the configuration file by running @file{gensdbfs} over
its own source directory.
This is the current content of the file:
@example
.
vendor = 0x123456789abcdef
device = 257
position = 0x1000
Makefile
position = 0
gensdbfs.c
write = 1
maxsize = 0x10000
@end example
The resulting @i{sdbfs} image will have @code{Makefile} at offset 0,
the directory itself at offset 0x1000 and an area of 64kB of storage
reserved for @code{gensdbfs.c}. The leading part of such are is filled
with the current contents of the file (which is shorter than 64kB).
@c ==========================================================================
@node sdb-read
@section sdb-read
The @i{sdb-read} program can be used to access an @i{sdbfs} image
stored in a disk file. It works both as @i{ls} (to list the files
included in the image) and as @i{cat} (to print to its own @i{stdout}
one of the files that live in the binary image).
The program can be used in three ways:
@table @code
@item sdb-read [options] <image-file>
This invocation lists the contents of the image. With @code{-l}
the listing is @i{long}, including more information than the
file name.
@item sdb-read [options] <image-file> <filename>
When called with two arguments, the program prints to @i{stdout}
the content of the named file, extracted from the image. Please
note that if the file has been over-sized at creation time,
the whole allocated data area is printed to standard output.
@item sdb-read [options] <image-file> <hex-vendor>:<hex-device>
If the second argument is built as two hex numbers separated
by a colon, then the program uses them as vendor-id and device-id
to find the file. If more than one file have the same identifiers,
the @i{first} of them is printed.
@end table
The following option flags are supported:
@table @code
@item -l
For listing, use @i{long} format. A @i{verbose} format will
be added later.
@item -e <entrypoint>
Specify the offset of the magic number in the image file.
@item -r
Register the device with a @i{read} method instead of the @i{data}
pointer (@ref{The Filesystem Structure}). In this way the
tool can be used to test the library with either access method.
@end table
The following examples are based on the @i{sdb} image of the
@i{userspace} directory of this package, using the
@code{--SDB-CONFIG--} file part of the package, described and included
for reference in @ref{Customizing gensdbfs}. You can see how the
entry point is at 0x1000, the @i{Makefile} is stored at offset 0
and @i{gensdbfs.c} has been over-allocated as a 64kB area.
@smallexample
morgana% ./gensdbfs . /tmp/userspace.sdb
morgana% ./sdb-read /tmp/userspace.sdb
./sdb-read: sdbfs_dev_create(): Not a directory
(wrong entry point 0x00000000?)
morgana% ./sdb-read -e 0x1000 /tmp/userspace.sdb
.
gensdbfs.c
gensdbfs
.gitignore
sdb-read
sdb-read.c
gensdbfs.h
Makefile
morgana% ./sdb-read -e 0x1000 -l /tmp/userspace.sdb
./sdb-read: listing format is to be defined
0123456789abcdef:00000101 @@ 00001000-0001de55 .
46696c6544617461:67656e73 @@ 00001200-000111ff gensdbfs.c
46696c6544617461:67656e73 @@ 00011200-00016e21 gensdbfs
46696c6544617461:2e676974 @@ 00016e40-00016e51 .gitignore
46696c6544617461:7364622d @@ 00016e80-0001c90f sdb-read
46696c6544617461:7364622d @@ 0001c940-0001db29 sdb-read.c
46696c6544617461:67656e73 @@ 0001db40-0001de55 gensdbfs.h
46696c6544617461:4d616b65 @@ 00000000-0000024b Makefile
morgana% ./sdb-read -e 0x1000 /tmp/userspace.sdb gensdbfs.c | wc -c
65536
morgana% md5sum Makefile
e38de09fe2bd0dab3ff7ebcab300977e Makefile
morgana% ./sdb-read -e 0x1000 /tmp/userspace.sdb Makefile | md5sum
e38de09fe2bd0dab3ff7ebcab300977e -
morgana% ./sdb-read -e 0x1000 /tmp/userspace.sdb 46696c6544617461:4d616b65 | md5sum
e38de09fe2bd0dab3ff7ebcab300977e -
@end smallexample
@c ##########################################################################
@node Kernel Support
@chapter Kernel Support
Kernel support is in the form of a module, which allows drivers to
register (and unregister) storage devices. Each storage device
declares a set of operations to it, so the filesystem can read, erase,
write data independently of the actual storage. See @i{sdbfs.h} about
data structures and methods.
To test without real hardware at hand, the module called
@i{sdb-fakedev.ko} can load to kernel space one or more image files,
and offer their data for mounting.
If your host can access an SDB-described FPGA device in I/O memory,
the module called @i{sdb-iomem.ko} can register those areas to the
@i{sdbfs} module, so you can mount the FPGA and perform register
access from user space using named files.
@c ==========================================================================
@node Supported kernel versions
@section Supported kernel versions
The current version is a development version only, and as such it has
only been built and run under Linux-3.4. In the future I'll check
backward portability -- but I'm sure something changed at 3.2 times,
so backward portability will need some work.
@c ==========================================================================
@node sdbfs.ko
@section sdbfs.ko
The filesystem currently only works in read-only mode, and there is no
support for subdirectories. The @i{name} argument you pass to the
@code{mount} command must match one of the device names that have already
been registered to the filesystem using @code{sdbfs_register_device}.
The available names should appear in @i{sysfs} but this is not yet implemented.
@c ==========================================================================
@node sdb-fakedev.ko
@section sdb-fakedev.ko
The module receives an array of strings as a parameter called @code{fsimg}.
It supports up to 8 strings: for each of them it calls @code{request_firmware}
and in case of success it registers an @i{sdb} device with the name of
the firmware file.
Such images are expected to be the output of @i{gensdbfs}, but currently
the entry point must be at offset zero (we'd need another module argument
to specify where the entry point is).
After mount, you'll see the files hosted in the image. See
@ref{Example use of sdbfs and sdb-fakedev}
@c ==========================================================================
@node Example use of sdbfs and sdb-fakedev
@section Example use of sdbfs and sdb-fakedev
This is an example session that creates, mounts and reads
an @i{sdbfs} image:
@smallexample
# ls -l userspace
total 44
-rw-rw-r-- 1 rubini staff 458 Aug 17 11:33 Makefile
-rwxrwxr-x 1 rubini staff 20630 Aug 30 13:55 gensdbfs
-rw-rw-r-- 1 rubini staff 9259 Aug 30 13:55 gensdbfs.c
-rw-rw-r-- 1 rubini staff 776 Aug 18 06:54 gensdbfs.h
# userspace/gensdbfs -b 1024 userspace /lib/firmware/stuff.sdb
# insmod kernel/sdbfs.ko
# insmod kernel/sdb-fakedev.ko fsimg=stuff.sdb
# mount -t sdbfs stuff.sdb /mnt
# ls -l /mnt
total 0
-r--r--r-- 1 root root 458 Jan 1 1970 Makefile
-r--r--r-- 1 root root 20630 Jan 1 1970 gensdbfs
-r--r--r-- 1 root root 9259 Jan 1 1970 gensdbfs.c
-r--r--r-- 1 root root 776 Jan 1 1970 gensdbfs.h
# md5sum /mnt/Makefile userspace/Makefile
e87991b1c4ac1664327ef388aac4bd71 /mnt/Makefile
e87991b1c4ac1664327ef388aac4bd71 userspace/Makefile
@end smallexample
@c ==========================================================================
@node sdb-iomem.ko
@section sdb-iomem.ko
This module can access a region of I/O registers and show it as an
@i{sdbfs} object. The user can specify the memory regions to be
accessed with a module argument.
The expected use of this type of filesystem is for driver developers:
if you are working on an SDB-aware FPGA project, you can mount the
internal bus of the FPGA and see the internal registers. Once you know
register offsets, you can ignore the base address of each device
by accessing it by pathname.
This module is currently only a trivial example, and a number of
features are missing. For example, the file-operations for register
access are not yet defined, and the lack of support for subdirectories
is a serious problem to be solved soon. Nonetheless, this approach
may prove very useful over time.
I envision the following steps for development of I/O acess in @i{sdbfs}:
@itemize @bullet
@item FPGA projects should be able to register their internal bus.
@item The names of available @i{sdbfs} devices should appear in @i{sysfs}.
@item A user-space program should know register names for all devices.
@item A web service should publish such register layout files.
@end itemize
Each of these steps is pretty simple in itself, it just takes time to
implement. As for the last step, the central @i{sdb} registry may
offer a DNS service, in order for each vendor to be autonomous in
publishing its own register maps from a vendor-specific host name.
The current implementation does very little, but it is able to
scan a read SDB device and see the internal devices. The specification
of each memory area (at most 8 of them are supported) is:
@example
<name>@@<hex-address>{-<hex-end>|+<hex-size>}[=<hex-entry>]
@end example
All numbers are hexadecimal: the area is specified either as
a range (@code{<addr>-<end>}) or as start-plus-size (@code{<addr>+<size>}).
If the entry point for SDB information is not zero, it must be passed
after an equal (@code{=}) sign.
The following example shows what the current @code{sdb-iomem.ko} can
do, accessing an FPGA driven but the @i{wr-nic} driver (package @i{spec-sw},
version 2.0):
@smallexample
spusa.root# insmod sdb-iomem.ko area=spec0@@0xfd300000+100000=63000
spusa.root# mount -t sdbfs spec0 /mnt
spusa.root# ls -l /mnt
total 0
-r--r--r-- 1 root root 256 Jan 1 1970 WB-VIC-Int.Control
?--------- 1 root root 262144 Jan 1 1970 WR-CORE
?--------- 1 root root 4096 Jan 1 1970 WR-DIO-Core
-r--r--r-- 1 root root 131072 Jan 1 1970 WR-NIC
-r--r--r-- 1 root root 256 Jan 1 1970 WR-TXTSU
spusa.root# rmmod sdb-iomem
spusa.root# insmod sdb-iomem.ko area=spec0@@0xfd300000+100000=62400
spusa.root# mount -t sdbfs spec0 /mnt
spusa.root# ls -l /mnt
total 0
-r--r--r-- 1 root root 256 Jan 1 1970 WB-GPIO-Port
-r--r--r-- 1 root root 256 Jan 1 1970 WB-I2C-Master
-r--r--r-- 1 root root 256 Jan 1 1970 WR-1Wire-master
-r--r--r-- 1 root root 256 Jan 1 1970 WR-DIO-Registers
@end smallexample
The first listing above shows the overall @i{WishBone} bus of
the FPGA. The bridge @code{WR-DIO-Core} should be shown as a
subdirectory. The second listing shows the content of such
subdirectory, by telling @i{sdb-iomem} to access the SDB records
for the @i{dio-core} rather than the top-level one.
@c ##########################################################################
@node Bugs and Missing Features
@chapter Bugs and Missing Features
While the general idea is flying, there are a lot of details that are
still missing. This is just a quick list of things, just off the top
of my head (while looking at the code), sorted by field rather than
priority or complexity:
@itemize
@item gensdbfs: more config file options: class and so on.
@item kernel and gensdbfs: support subdirectories. This is not
trivial in gensdbfs because of the relative placement of files
within the subdir.
@item kernel: add . and .. entries to readdir
@item kernel: support writing to files
@item kernel: complete support for device access
@item kernel: read and write bits are not propagated
@item core sdbfs: show available images in /sys
@item lib: kernel space and freestanding is not tested
@item lib: write support is missing
@item read-sdb: implement verbose mode and @code{rwxrwxrwx} in long mode
@item general: factorize some common procedures
@item general: the various FIXME for details in the code itself
@item general: too many printk still in the code
@end itemize
@bye
@c LocalWords: Alessandro Rubini CERN iftex texinfo sdbfs gensdbfs devicesize
@c LocalWords: blocksize fsimg userspace insmod filesystem gateware http ohwr
@c LocalWords: gitorious EEPROM malloc struct
/*
* This is a modified version 1.0 of sdb.h, not the official spec version
*/
#ifndef __SDB_H__
#define __SDB_H__
#ifdef __KERNEL__
#include <linux/types.h>
#else
#include <stdint.h>
#endif
/*
* All structures are 64 bytes long and are expected
* to live in an array, one for each interconnect.
* Most fields of the structures are shared among the
* various types, and most-specific fields are at the
* beginning (for alignment reasons, and to keep the
* magic number at the head of the interconnect record
*/
/* Product, 40 bytes at offset 24, 8-byte alignmed
*
* device_id is vendor-assigned; version is device-specific,
* date is hex (e.g 0x20120501), name is UTF-8, blank-filled
* and not terminated with a 0 byte.
*/
struct sdb_product {
uint64_t vendor_id; /* 0x18..0x1f */
uint32_t device_id; /* 0x20..0x23 */
uint32_t version; /* 0x24..0x27 */
uint32_t date; /* 0x28..0x2b */
uint8_t name[19]; /* 0x2c..0x3e */
uint8_t record_type; /* 0x3f */
};
/*
* Component, 56 bytes at offset 8, 8-byte aligned
*
* The address range is first to last, inclusive
* (for example 0x100000 - 0x10ffff)
*/
struct sdb_component {
uint64_t addr_first; /* 0x08..0x0f */
uint64_t addr_last; /* 0x10..0x17 */
struct sdb_product product; /* 0x18..0x3f */
};
/* Type of the SDB record */
enum sdb_record_type {
sdb_type_interconnect = 0x00,
sdb_type_device = 0x01,
sdb_type_bridge = 0x02,
sdb_type_integration = 0x80,
sdb_type_empty = 0xFF,
};
/* Type 0: interconnect (first of the array)
*
* sdb_records is the length of the table including this first
* record, version is 1. The bus type is enumerated later.
*/
#define SDB_MAGIC 0x5344422d /* "SDB-" */
struct sdb_interconnect {
uint32_t sdb_magic; /* 0x00-0x03 */
uint16_t sdb_records; /* 0x04-0x05 */
uint8_t sdb_version; /* 0x06 */
uint8_t sdb_bus_type; /* 0x07 */
struct sdb_component sdb_component; /* 0x08-0x3f */
};
/* Type 1: device
*
* class is 0 for "custom device", other values are
* to be standardized; ABI version is for the driver,
* bus-specific bits are defined by each bus (see below)
*/
struct sdb_device {
uint16_t abi_class; /* 0x00-0x01 */
uint8_t abi_ver_major; /* 0x02 */
uint8_t abi_ver_minor; /* 0x03 */
uint32_t bus_specific; /* 0x04-0x07 */
struct sdb_component sdb_component; /* 0x08-0x3f */
};
/* Type 2: bridge
*
* child is the address of the nested SDB table
*/
struct sdb_bridge {
uint64_t sdb_child; /* 0x00-0x07 */
struct sdb_component sdb_component; /* 0x08-0x3f */
};
/* Type 0x80: integration
*
* all types with bit 7 set are meta-information, so
* software can ignore the types it doesn't know. Here we
* just provide product information for an aggregate device
*/
struct sdb_integration {
uint8_t reserved[24]; /* 0x00-0x17 */
struct sdb_product product; /* 0x08-0x3f */
};
/* Type 0xff: empty
*
* this allows keeping empty slots during development,
* so they can be filled later with miminal efforts and
* no misleading description is ever shipped -- hopefully.
* It can also be used to pad a table to a desired length.
*/
struct sdb_empty {
uint8_t reserved[63]; /* 0x00-0x3e */
uint8_t record_type; /* 0x3f */
};
/* The type of bus, for bus-specific flags */
enum sdb_bus_type {
sdb_wishbone = 0x00,
sdb_data = 0x01,
};
#define SDB_WB_WIDTH_MASK 0x0f
#define SDB_WB_ACCESS8 0x01
#define SDB_WB_ACCESS16 0x02
#define SDB_WB_ACCESS32 0x04
#define SDB_WB_ACCESS64 0x08
#define SDB_WB_LITTLE_ENDIAN 0x80
#define SDB_DATA_READ 0x04
#define SDB_DATA_WRITE 0x02
#define SDB_DATA_EXEC 0x01
#endif /* __SDB_H__ */
LINUX ?= /lib/modules/$(shell uname -r)/build
# get sdb.h from ../include/linux/
ccflags-y = -I$M/../include
obj-m = sdbfs.o
obj-m += sdb-fakedev.o
obj-m += sdb-iomem.o
sdbfs-y = sdbfs-core.o
sdbfs-y += sdbfs-file.o
sdbfs-y += sdbfs-inode.o
sdbfs-y += sdbfs-client.o
all: modules
install: modules_install
modules clean modules_install:
$(MAKE) -C $(LINUX) M=$(shell /bin/pwd) $@
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include "sdbfs.h"
/* We register up to 8 filesystems getting the names as module parameters */
static int fakedev_nimg;
static char *fakedev_fsimg[8];
module_param_array_named(fsimg, fakedev_fsimg, charp, &fakedev_nimg, 0444);
struct fakedev {
struct sdbfs_dev sd;
const struct firmware *fw;
};
static struct fakedev fakedev_devs[8];
static struct device fakedev_device;
static ssize_t fakedev_read(struct sdbfs_dev *sd, uint32_t begin, void *buf,
size_t count)
{
struct fakedev *fd;
int len;
printk("%s: %08x - %i\n", __func__, (int)begin, count);
fd = container_of(sd, struct fakedev, sd);
len = fd->fw->size;
if (begin > len)
return -EINVAL;
if (begin + count > len)
count = len - begin;
memcpy(buf, fd->fw->data + begin, count);
return count;
}
static struct sdbfs_dev_ops fakedev_ops = {
.owner = THIS_MODULE,
.erase = NULL,
.read = fakedev_read,
.write = NULL,
};
static int fakedev_init(void)
{
struct fakedev *d;
int i;
/* we need a device to request a firmware image */
dev_set_name(&fakedev_device, KBUILD_MODNAME);
device_initialize(&fakedev_device);
i = device_add(&fakedev_device);
if (i < 0) {
printk("%s: failed to init device (error %i)\n",
KBUILD_MODNAME, i);
return i;
}
for (i = 0; i < fakedev_nimg; i++) {
d = fakedev_devs + i;
if (request_firmware(&d->fw, fakedev_fsimg[i],
&fakedev_device) < 0) {
dev_err(&fakedev_device, "can't load %s\n",
fakedev_fsimg[i]);
continue;
}
d->sd.name = fakedev_fsimg[i];
d->sd.blocksize = 64; /* bah! */
d->sd.size = d->fw->size;
d->sd.ops = &fakedev_ops;
if (sdbfs_register_device(&d->sd) < 0) {
dev_err(&fakedev_device, "can't register %s\n",
fakedev_fsimg[i]);
release_firmware(d->fw);
d->fw = NULL;
}
}
return 0;
}
static void fakedev_exit(void)
{
struct fakedev *d;
int i;
for (i = 0; i < fakedev_nimg; i++) {
d = fakedev_devs + i;
if (!d->fw)
continue;
sdbfs_unregister_device(&d->sd);
release_firmware(d->fw);
}
device_del(&fakedev_device);
}
module_init(fakedev_init);
module_exit(fakedev_exit);
MODULE_LICENSE("GPL");
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/sdb.h>
#include "sdbfs.h"
struct sdbmem {
struct sdbfs_dev sd;
void __iomem *address;
size_t datalen;
int ready;
};
/* We register up to 8 filesystems getting the description at insmod */
static int sdbmem_narea;
static char *sdbmem_area[8];
module_param_array_named(area, sdbmem_area, charp, &sdbmem_narea, 0444);
/*
* area=<name>@<address>-<address>[=<entrypoint>]
* area=<name>@<address>+<lenght>[=<entrypoint>]
*/
static int sdbmem_parse(char *desc, struct sdbmem *d)
{
unsigned long addr, size;
char *at;
int i;
char c;
memset(d, 0, sizeof(*d));
at = strchr(desc, '@');
if (!at)
return -EINVAL;
i = sscanf(at,"@%lx+%lx=%lx%c", &addr, &size,
&d->sd.entrypoint, &c);
if (i == 1) {
i = sscanf(at,"@%lx-%lx=%lx%c", &addr, &size,
&d->sd.entrypoint, &c);
size -= addr;
}
if (i < 2 || i > 3) {
pr_err("%s: wrong argument \"%s\"\n", KBUILD_MODNAME,
desc);
pr_err("Use \"<name>@<addr>[-+]<addr>[=<entrypoint>\"\n");
return -EINVAL;
}
/* So, the name is the first one and there is the '@' sign */
*at = '\0';
d->sd.name = desc;
d->address = ioremap(addr, size);
if (!d->address)
return -ENOMEM;
d->sd.size = d->datalen = size;
return 0;
}
static struct sdbmem sdbmem_devs[8];
static ssize_t sdbmem_read(struct sdbfs_dev *sd, uint32_t begin, void *buf,
size_t count)
{
struct sdbmem *fd;
size_t len;
printk("%s: %08x - %i\n", __func__, (int)begin, count);
fd = container_of(sd, struct sdbmem, sd);
len = fd->datalen;
if (begin > len)
return -EINVAL;
if (begin + count > len)
count = len - begin;
memcpy_fromio(buf, fd->address + begin, count);
return count;
}
static struct sdbfs_dev_ops sdbmem_ops = {
.owner = THIS_MODULE,
.erase = NULL,
.read = sdbmem_read,
.write = NULL,
};
/* FIXME: export the register and unregister functions for external users */
static int sdbmem_init(void)
{
struct sdbmem *d;
int i, done = 0;
uint32_t magic;
for (i = 0; i < sdbmem_narea; i++) {
d = sdbmem_devs + i;
if (sdbmem_parse(sdbmem_area[i], d) < 0)
continue;
/* Check the magic number, so we fail ASAP */
magic = readl(d->address + d->sd.entrypoint);
if (magic != SDB_MAGIC && magic != ntohl(SDB_MAGIC)) {
iounmap(d->address);
pr_err("%s: wrong magic 0x%08x at 0x%lx\n", __func__,
magic, d->sd.entrypoint);
continue;
}
d->sd.blocksize = 4; /* bah! */
d->sd.ops = &sdbmem_ops;
if (sdbfs_register_device(&d->sd) < 0) {
pr_err("%s: can't register area %s\n", KBUILD_MODNAME,
d->sd.name);
continue;
}
done++;
d->ready = 1;
}
if (done)
return 0;
return -ENODEV;
}
static void sdbmem_exit(void)
{
struct sdbmem *d;
int i;
for (i = 0; i < sdbmem_narea; i++) {
d = sdbmem_devs + i;
if (!d->ready)
continue;
sdbfs_unregister_device(&d->sd);
iounmap(d->address);
}
}
module_init(sdbmem_init);
module_exit(sdbmem_exit);
MODULE_LICENSE("GPL");
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/sdb.h> /* in ../include, by now */
#include "sdbfs.h"
#include "sdbfs-int.h"
static LIST_HEAD(sdbfs_devlist);
struct sdbfs_dev *sdbfs_get_by_name(char *name)
{
struct sdbfs_dev *sd;
list_for_each_entry(sd, &sdbfs_devlist, list)
if (!strcmp(sd->name, name))
goto found;
return ERR_PTR(-ENOENT);
found:
if (try_module_get(sd->ops->owner)) {
printk("%s: %p\n", __func__, sd);
return sd;
}
return ERR_PTR(-ENOENT);
}
void sdbfs_put(struct sdbfs_dev *sd)
{
printk("%s: %p\n", __func__, sd);
module_put(sd->ops->owner);
}
/* Exported functions */
int sdbfs_register_device(struct sdbfs_dev *sd)
{
struct sdbfs_dev *osd;
list_for_each_entry(osd, &sdbfs_devlist, list)
if (!strcmp(osd->name, sd->name))
return -EBUSY;
list_add(&sd->list, &sdbfs_devlist);
list_for_each_entry(osd, &sdbfs_devlist, list)
printk("list entry %p\n", osd);
return 0;
}
EXPORT_SYMBOL(sdbfs_register_device);
void sdbfs_unregister_device(struct sdbfs_dev *sd)
{
struct sdbfs_dev *osd;
list_for_each_entry(osd, &sdbfs_devlist, list)
printk("list entry %p\n", osd);
printk("removing %p\n", sd);
list_for_each_entry(osd, &sdbfs_devlist, list)
if (osd == sd)
break;
if (osd == sd)
list_del(&sd->list);
}
EXPORT_SYMBOL(sdbfs_unregister_device);
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/sdb.h> /* in ../include, by now */
#include "sdbfs-int.h"
static const struct super_operations sdbfs_super_ops = {
.alloc_inode = sdbfs_alloc_inode,
.destroy_inode = sdbfs_destroy_inode,
};
static int sdbfs_fill_super(struct super_block *sb, void *data, int silent)
{
struct inode *inode;
struct dentry *root;
struct sdbfs_dev *sd;
uint32_t magic;
printk("%s\n", __func__);
/* HACK: this data is really a name */
sd = sdbfs_get_by_name(data);
if (IS_ERR(sd))
return PTR_ERR(sd);
sb->s_fs_info = sd;
/* Check magic number first */
sd->ops->read(sd, sd->entrypoint, &magic, 4);
if (magic == ntohl(SDB_MAGIC)) {
/* all right: we are big endian or byte-level connected */
} else if (magic == SDB_MAGIC) {
/* looks like we are little-endian on a 32-bit-only bus */
sd->flags |= SDBFS_F_FIXENDIAN;
} else {
printk("%s: wrong magic at 0x%lx (%08x is not %08x)\n",
__func__, sd->entrypoint, magic, SDB_MAGIC);
return -EINVAL;
}
/* All of our data is organized as 64-byte blocks */
sb->s_blocksize = 64;
sb->s_blocksize_bits = 6;
sb->s_magic = SDB_MAGIC;
sb->s_op = &sdbfs_super_ops;
/* The root inode is 1. It is a fake bridge and has no parent. */
inode = sdbfs_iget(NULL, sb, SDBFS_ROOT);
if (IS_ERR(inode)) {
sdbfs_put(sd);
return PTR_ERR(inode);
}
/*
* Instantiate and link root dentry. d_make_root only exists
* after 3.2, but d_alloc_root was killed soon after 3.3
*/
root = d_make_root(inode);
if (!root) {
sdbfs_put(sd);
/* FIXME: release inode? */
return -ENOMEM;
}
root->d_fsdata = NULL; /* FIXME: d_fsdata */
sb->s_root = root;
return 0;
}
static struct dentry *sdbfs_mount(struct file_system_type *type, int flags,
const char *name, void *data)
{
struct dentry *ret;
char *fakedata = (char *)name;
/* HACK: use "name" as data, to use the mount_single helper */
ret = mount_single(type, flags, fakedata, sdbfs_fill_super);
printk("%s: %p\n", __func__, ret);
return ret;
}
static void sdbfs_kill_sb(struct super_block *sb)
{
struct sdbfs_dev *sd = sb->s_fs_info;
printk("%s\n", __func__);
kill_anon_super(sb);
if (sd)
sdbfs_put(sd);
}
static struct file_system_type sdbfs_fs_type = {
.owner = THIS_MODULE,
.name = "sdbfs",
.mount = sdbfs_mount, /* 2.6.37 and later only */
.kill_sb = sdbfs_kill_sb,
};
struct kmem_cache *sdbfs_inode_cache;
static int __init sdbfs_init(void)
{
sdbfs_inode_cache = KMEM_CACHE(sdbfs_inode, 0);
if (!sdbfs_inode_cache)
return -ENOMEM;
return register_filesystem(&sdbfs_fs_type);
return 0;
}
static void __exit sdbfs_exit(void)
{
unregister_filesystem(&sdbfs_fs_type);
kmem_cache_destroy(sdbfs_inode_cache);
}
module_init(sdbfs_init);
module_exit(sdbfs_exit);
MODULE_LICENSE("GPL");
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include "sdbfs-int.h"
static ssize_t sdbfs_read(struct file *f, char __user *buf, size_t count,
loff_t *offp)
{
struct inode *ino = f->f_dentry->d_inode;
struct super_block *sb = ino->i_sb;
struct sdbfs_dev *sd = sb->s_fs_info;
struct sdbfs_inode *inode;
char kbuf[16];
unsigned long start, size;
ssize_t i, done;
inode = container_of(ino, struct sdbfs_inode, ino);
start = be64_to_cpu(inode->info.s_d.sdb_component.addr_first);
size = be64_to_cpu(inode->info.s_d.sdb_component.addr_last) + 1 - start;
if (*offp > size)
return 0;
if (*offp + count > size)
count = size - *offp;
done = 0;
while (done < count) {
/* Horribly inefficient, just copy a few bytes at a time */
int n = sizeof(kbuf) > count ? count : sizeof(kbuf);
/* FIXME: error checking */
i = sd->ops->read(sd, start + *offp, kbuf, n);
if (i < 0) {
if (done)
return done;
return i;
}
if (copy_to_user(buf, kbuf, i))
return -EFAULT;
buf += i;
done += i;
if (i != n) {
/* Partial read: done for this time */
break;
}
}
*offp += done;
return done;
}
const struct file_operations sdbfs_fops = {
.read = sdbfs_read,
};
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/sdb.h> /* in ../include, by now */
#include "sdbfs-int.h"
static void sdbfs_fix_endian(struct sdbfs_dev *sd, void *ptr, int len)
{
uint32_t *p = ptr;
int i;
if (!(sd->flags & SDBFS_F_FIXENDIAN))
return;
if (len & 3)
return; /* Hmmm... */
for (i = 0; i < len / 4; i++)
p[i] = htonl(p[i]);
}
/* This is called by readdir and by lookup, when needed */
static int sdbfs_read_whole_dir(struct sdbfs_inode *inode)
{
struct sdbfs_info *info;
struct super_block *sb = inode->ino.i_sb;
struct sdbfs_dev *sd = sb->s_fs_info;
unsigned long offset;
int i, j, n;
if (inode->nfiles)
return 0;
printk("%s\n", __func__);
/* Get the interconnect and see how many */
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
n = sd->ops->read(sd, inode->base_sdb, &info->s_i, SDB_SIZE);
if (n != SDB_SIZE) {
kfree(info);
return -EIO;
}
sdbfs_fix_endian(sd, &info->s_i, SDB_SIZE);
if (info->s_i.sdb_magic != htonl(SDB_MAGIC)) {
pr_err("%s: wrong magic (%08x) at offset 0x%lx\n", __func__,
info->s_i.sdb_magic, inode->base_sdb);
kfree(info);
return -EINVAL;
}
inode->nfiles = be16_to_cpu(info->s_i.sdb_records);
kfree(info);
printk("nfiles %i\n", inode->nfiles);
info = kmalloc(sizeof(*info) * inode->nfiles, GFP_KERNEL);
if (!info) {
inode->nfiles = 0;
return -ENOMEM;
}
offset = inode->base_sdb;
printk("reading at 0x%lx\n", offset);
inode->files = info;
for (i = 0; i < inode->nfiles; i++) {
info = inode->files + i;
n = sd->ops->read(sd, offset, &info->s_d, SDB_SIZE);
if (n != SDB_SIZE) {
/* FIXME: iput? */
kfree(inode->files);
inode->nfiles = 0;
return -EIO;
}
sdbfs_fix_endian(sd, &info->s_d, SDB_SIZE);
strncpy(info->name,
info->s_d.sdb_component.product.name, 19);
for (j = 19; j; j--) {
info->name[j] = '\0';
if (info->name[j-1] != ' ')
break;
}
info->namelen = j;
offset += SDB_SIZE;
}
return 0;
}
static int sdbfs_readdir(struct file * filp,
void * dirent, filldir_t filldir)
{
struct inode *ino = filp->f_dentry->d_inode;
struct sdbfs_inode *inode;
struct sdbfs_info *info;
unsigned long offset;
int i, type, done = 0;
printk("%s\n", __func__);
/* dot and dotdot are special */
if (filp->f_pos == 0) {
if (filldir(dirent, ".", 1, 0, ino->i_ino, DT_DIR) < 0)
return done;
done++;
filp->f_pos++;
}
if (filp->f_pos == 1) {
if (filldir(dirent, "..", 2, 1,
parent_ino(filp->f_dentry), DT_DIR) < 0)
return done;
done++;
filp->f_pos++;
}
/* Then our stuff */
inode = container_of(ino, struct sdbfs_inode, ino);
sdbfs_read_whole_dir(inode);
offset = inode->base_sdb;
for (i = filp->f_pos - 2; i < inode->nfiles; i++) {
info = inode->files + i;
if (info->s_e.record_type == sdb_type_bridge)
type = DT_DIR;
else
type = DT_REG;
if (filldir(dirent, info->name, info->namelen,
SDBFS_INO(offset), i + 2 /* ? */, type) < 0)
return done;
filp->f_pos++;
done++;
}
return done;
}
static const struct file_operations sdbfs_dir_fops = {
.read = generic_read_dir,
.readdir = sdbfs_readdir,
.llseek = default_llseek,
};
static struct dentry *sdbfs_lookup(struct inode *dir,
struct dentry *dentry, struct nameidata *nd)
{
struct inode *ino = NULL;
struct sdbfs_inode *inode = container_of(dir, struct sdbfs_inode, ino);
struct sdbfs_info *info;
unsigned long offset = inode->base_sdb;
int i, n, len;
printk("%s\n", __func__);
sdbfs_read_whole_dir(inode);
n = inode->nfiles;
len = dentry->d_name.len;
for (i = 0; i < n; i++) {
info = inode->files + i;
if (info->namelen != len)
continue;
if (!strncmp(info->name, dentry->d_name.name, len))
break;
}
if (i != n) {
offset = offset + SDB_SIZE * i;
ino = sdbfs_iget(inode, dir->i_sb, SDBFS_INO(offset));
}
d_add(dentry, ino);
return 0;
}
static const struct inode_operations sdbfs_dir_iops = {
.lookup = sdbfs_lookup,
};
struct inode *sdbfs_alloc_inode(struct super_block *sb)
{
struct sdbfs_inode *inode;
printk("%s\n", __func__);
inode = kmem_cache_alloc(sdbfs_inode_cache, GFP_KERNEL);
if (!inode)
return NULL;
inode_init_once(&inode->ino);
printk("%s: return %p\n", __func__, &inode->ino);
return &inode->ino;
}
void sdbfs_destroy_inode(struct inode *ino)
{
struct sdbfs_inode *inode;
inode = container_of(ino, struct sdbfs_inode, ino);
kfree(inode->files);
kmem_cache_free(sdbfs_inode_cache, inode);
}
static struct inode *sdbfs_iget_root(struct super_block *sb,
struct inode *ino)
{
struct sdbfs_dev *sd = sb->s_fs_info;
struct sdbfs_inode *inode = container_of(ino, struct sdbfs_inode, ino);
struct sdb_bridge *b = &inode->info.s_b;
/* The root directory is a fake "bridge" structure */
memset(b, 0, sizeof(*b));
b->sdb_child = cpu_to_be64(sd->entrypoint);
b->sdb_component.addr_first = 0;
b->sdb_component.addr_last = cpu_to_be64(sd->size);
b->sdb_component.product.record_type = sdb_type_bridge;
/* So, this is a directory, and it links to the first interconnect */
inode->base_data = 0;
inode->base_sdb = sd->entrypoint;
ino->i_size = sd->size;
ino->i_mode = S_IFDIR | 0555;
ino->i_op = &sdbfs_dir_iops;
ino->i_fop = &sdbfs_dir_fops;
return ino;
}
struct inode *sdbfs_iget(struct sdbfs_inode *parent,
struct super_block *sb, unsigned long inum)
{
struct inode *ino;
struct sdbfs_dev *sd = sb->s_fs_info;
struct sdbfs_inode *inode;
uint32_t offset;
unsigned long size, base_data; /* target offset */
int n;
int type;
printk("%s: inum 0x%lx\n", __func__, inum);
ino = iget_locked(sb, inum);
if (!ino)
return ERR_PTR(-ENOMEM);
if (!(ino->i_state & I_NEW))
return ino;
/* general setup; no link concept: the structure is immutable */
set_nlink(ino, 1);
ino->i_mtime.tv_sec = ino->i_atime.tv_sec = ino->i_ctime.tv_sec = 0;
ino->i_mtime.tv_nsec = ino->i_atime.tv_nsec = ino->i_ctime.tv_nsec = 0;
if (unlikely(!parent)) { /* inum == SDBFS_ROOT */
sdbfs_iget_root(sb, ino);
unlock_new_inode(ino);
return ino;
}
inode = container_of(ino, struct sdbfs_inode, ino);
offset = SDBFS_OFFSET(inum);
n = sd->ops->read(sd, offset, &inode->info.s_d, SDB_SIZE);
if (n != SDB_SIZE)
return ERR_PTR(-EIO);
sdbfs_fix_endian(sd, &inode->info.s_d, SDB_SIZE);
base_data = be64_to_cpu(inode->info.s_d.sdb_component.addr_first);
size = be64_to_cpu(inode->info.s_d.sdb_component.addr_last)
- base_data + 1;
type = inode->info.s_e.record_type;
switch (type) {
case sdb_type_interconnect:
case sdb_type_device:
/* You can access internal registers/data */
ino->i_fop = &sdbfs_fops; /* FIXME: Which bus type? */
ino->i_mode = S_IFREG | 0444;
ino->i_size = size;
inode->base_data = parent->base_data + base_data;
break;
case sdb_type_bridge:
/* A bridge is a subdirectory */
ino->i_mode = S_IFDIR | 0555;
ino->i_op = &sdbfs_dir_iops;
ino->i_fop = &sdbfs_dir_fops;
inode->base_data = parent->base_data + base_data;
inode->base_sdb = parent->base_data
+ be64_to_cpu(inode->info.s_b.sdb_child);
break;
default:
if (type & 0x80) /* informative only */
pr_info("%s: ignoring unknown record 0x%02x\n",
__func__, type);
else
pr_err("%s: unsupported record 0x%02x\n",
__func__, type);
break;
}
unlock_new_inode(ino);
return ino;
}
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#ifndef __SDBFS_INT_H__
#define __SDBFS_INT_H__
#include <linux/fs.h>
#include <linux/sdb.h>
#include "sdbfs.h"
/* This is our mapping of inode numbers */
#define SDBFS_ROOT 1
#define SDBFS_INO(offset) ((offset) + 2)
#define SDBFS_OFFSET(ino) ((ino) & ~15)
#define SDB_SIZE (sizeof(struct sdb_device))
struct sdbfs_info {
/* unnamed union to save typing */
union {
struct sdb_device s_d;
struct sdb_interconnect s_i;
struct sdb_bridge s_b;
struct sdb_empty s_e;
};
char name[20]; /* 19 + terminator */
int namelen;
};
struct sdbfs_inode {
struct sdbfs_info info;
int nfiles;
struct sdbfs_info *files; /* for directories */
struct inode ino;
/* below, the former is the base for relative addresses */
unsigned long base_data;
unsigned long base_sdb;
};
/* This is needed to convert endianness. Hoping it is not defined elsewhere */
static inline uint64_t htonll(uint64_t ll)
{
uint64_t res;
if (htonl(1) == 1)
return ll;
res = htonl(ll >> 32);
res |= (uint64_t)(htonl((uint32_t)ll)) << 32;
return res;
}
static inline uint64_t ntohll(uint64_t ll)
{
return htonll(ll);
}
/* Material in sdbfs-file.c */
extern const struct file_operations sdbfs_fops;
/* Material in sdbfs-inode.c */
struct inode *sdbfs_alloc_inode(struct super_block *sb);
void sdbfs_destroy_inode(struct inode *ino);
struct inode *sdbfs_iget(struct sdbfs_inode *parent,
struct super_block *sb, unsigned long inum);
extern struct kmem_cache *sdbfs_inode_cache;
#endif /* __SDBFS_INT_H__ */
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#ifndef __SDBFS_H__
#define __SDBFS_H__
struct sdbfs_dev;
/*
* Client modules register sdbfs-capable devices, and several of them
* may use the same hardware abstraction, so separate it. We use 32-bit
* addresses, being aware of potential issues, but our target is small
* devices accessed by a soft-core. If the need arises, we'll add erase64
* and similar methods.
*/
struct sdbfs_dev_ops {
struct module *owner;
int (*erase)(struct sdbfs_dev *sd, uint32_t begin, uint32_t end);
ssize_t (*read)(struct sdbfs_dev *sd, uint32_t begin, void *buf,
size_t count);
ssize_t (*write)(struct sdbfs_dev *sd, uint32_t begin, void *buf,
size_t count);
};
struct sdbfs_dev {
char *name;
unsigned long flags;
int blocksize;
unsigned long entrypoint;
struct sdbfs_dev_ops *ops;
struct list_head list;
unsigned long size;
/* Following is private to the FS code */
unsigned long ino_base;
};
/* flags */
#define SDBFS_F_FIXENDIAN 0x0001
/* Internal inter-file calls */
struct sdbfs_dev *sdbfs_get_by_name(char *name);
void sdbfs_put(struct sdbfs_dev *sd);
/* Exported to other modules */
int sdbfs_register_device(struct sdbfs_dev *sd);
void sdbfs_unregister_device(struct sdbfs_dev *sd);
#endif /* __SDBFS_H__ */
LINUX ?= /lib/modules/$(shell uname -r)/build
# If we compile for the kernel, we need to include real kernel headers.
# The thing is enough a mess that I moved it to a different file
include Makefile.arch
AS = $(CROSS_COMPILE)as
LD = $(CROSS_COMPILE)ld
CC = $(CROSS_COMPILE)gcc
CPP = $(CC) -E
AR = $(CROSS_COMPILE)ar
NM = $(CROSS_COMPILE)nm
STRIP = $(CROSS_COMPILE)strip
OBJCOPY = $(CROSS_COMPILE)objcopy
OBJDUMP = $(CROSS_COMPILE)objdump
# calculate endianness at compile time
ENDIAN := $(shell ./check-endian $(CC))
CFLAGS = -Wall -ggdb -O2
CFLAGS += -I../include/linux # for <sdb.h>
CFLAGS += -ffunction-sections -fdata-sections
CFLAGS += -Wno-pointer-sign
CFLAGS += $(ENDIAN) $(LINUXINCLUDE)
LIB = libsdbfs.a
OBJS = glue.o access.o
all: $(LIB)
$(OBJS): $(wildcard *.h)
$(LIB): $(OBJS)
$(AR) r $@ $(OBJS)
clean:
rm -f $(OBJS) $(LIB) *~ core
# add the other unused targets, so the rule in ../Makefile works
modules install modules_install:
srctree = $(LINUX)
#
# This set of contortions comes from the kernel Makefile. We need this
# in order to properly compile libsdbfs for the kernel without being
# in a kernel build environment (for example, to check for compile errors).
#
ARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ \
-e s/arm.*/arm/ -e s/sa110/arm/ \
-e s/s390x/s390/ -e s/parisc64/parisc/ \
-e s/ppc.*/powerpc/ -e s/mips.*/mips/ \
-e s/sh[234].*/sh/ )
SRCARCH := $(ARCH)
# Additional ARCH settings for x86
ifeq ($(ARCH),i386)
SRCARCH := x86
endif
ifeq ($(ARCH),x86_64)
SRCARCH := x86
endif
# Additional ARCH settings for sparc
ifeq ($(ARCH),sparc32)
SRCARCH := sparc
endif
ifeq ($(ARCH),sparc64)
SRCARCH := sparc
endif
# Additional ARCH settings for sh
ifeq ($(ARCH),sh64)
SRCARCH := sh
endif
# Additional ARCH settings for tile
ifeq ($(ARCH),tilepro)
SRCARCH := tile
endif
ifeq ($(ARCH),tilegx)
SRCARCH := tile
endif
# Where to locate arch specific headers
hdr-arch := $(SRCARCH)
ifeq ($(ARCH),m68knommu)
hdr-arch := m68k
endif
# Use LINUXINCLUDE when you must reference the include/ directory.
# Needed to be compatible with the O= option
LINUXINCLUDE := -I$(srctree)/arch/$(hdr-arch)/include \
-Iarch/$(hdr-arch)/include/generated \
-I$(srctree)/include
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
/* To avoid many #ifdef and associated mess, all headers are included there */
#include "libsdbfs.h"
int sdbfs_fstat(struct sdbfs *fs, struct sdb_device *record_return)
{
if (!fs->currentp)
return -ENOENT;
memcpy(record_return, fs->currentp, sizeof(*record_return));
return 0;
}
int sdbfs_fread(struct sdbfs *fs, int offset, char *buf, int count)
{
if (!fs->currentp)
return -ENOENT;
if (offset < 0)
offset = fs->read_offset;
if (offset + count > fs->f_len)
count = fs->f_len - offset;
if (fs->data)
memcpy(buf, fs->data + fs->f_offset + offset, count);
else
fs->read(fs, fs->f_offset + offset, buf, count);
fs->read_offset = offset + count;
return count;
}
int sdbfs_fwrite(struct sdbfs *fs, int offset, char *buf, int count)
{
return -ENOSYS;
}
#!/bin/bash
# Check endianness at compile time, so we can pass the -D to CFLAGS
CC=$1
if [ "x$CC" == "x" ]; then
echo "$0: pass the compiler path (\$CC) as argument" >& 2
exit 1
fi
# Check endianness, by making an object file
TMPC=$(mktemp /tmp/endian-c-XXXXXX)
TMPO=$(mktemp /tmp/endian-o-XXXXXX)
echo "int i = 0xbbee;" > $TMPC
$CC -x c -c $TMPC -o $TMPO
OBJCOPY=$(echo $CC | sed 's/gcc$/objcopy/')
if $OBJCOPY -O binary $TMPO /dev/stdout | od -t x1 -An | \
grep -q 'bb ee'; then
echo " -DSDBFS_BIG_ENDIAN"
else
echo " -DSDBFS_LITTLE_ENDIAN"
fi
rm -f $TMPC $TMPO
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
/* To avoid many #ifdef and associated mess, all headers are included there */
#include "libsdbfs.h"
static struct sdbfs *sdbfs_list;
/* All fields unused by the caller are expected to be zeroed */
int sdbfs_dev_create(struct sdbfs *fs, int verbose)
{
unsigned int magic;
/* First, check we have the magic */
if (fs->data)
magic = *(unsigned int *)(fs->data + fs->entrypoint);
else
fs->read(fs, fs->entrypoint, &magic, sizeof(magic));
if (htonl(magic) != SDB_MAGIC)
return -ENOTDIR;
if (verbose)
fs->flags |= SDBFS_F_VERBOSE;
fs->next = sdbfs_list;
sdbfs_list = fs;
return 0;
}
int sdbfs_dev_destroy(struct sdbfs *fs)
{
struct sdbfs **p;
for (p = &sdbfs_list; *p && *p != fs; p = &(*p)->next)
;
if (!*p)
return -ENOENT;
*p = fs->next;
return 0;
}
struct sdbfs *sdbfs_dev_find(const char *name)
{
struct sdbfs *l;
for (l = sdbfs_list; l && strcmp(l->name, name); l = l->next)
;
if (!l)
return NULL;
return l;
}
/*
* To open by name or by ID we need to scan the tree. The scan
* function is also exported in order for "sdb-ls" to use it
*/
static struct sdb_device *sdbfs_readentry(struct sdbfs *fs,
unsigned long offset)
{
/*
* This function reads an entry from a known good offset. It
* returns the pointer to the entry, which may be stored in
* the fs structure itself. Only touches fs->current_record
*/
if (fs->data)
return (struct sdb_device *)(fs->data + offset);
fs->read(fs, offset, &fs->current_record, sizeof(fs->current_record));
return &fs->current_record;
}
struct sdb_device *sdbfs_scan(struct sdbfs *fs, int newscan)
{
/*
* This returns a pointer to the next sdb record, or a new one.
* Subdirectories are not supported. Uses all internal fields
*/
struct sdb_device *ret;
struct sdb_interconnect *i;
if (newscan) {
fs->f_offset = fs->entrypoint;
} else {
fs->f_offset += sizeof(struct sdb_device);
if (!fs->nleft)
return NULL;
}
ret = sdbfs_readentry(fs, fs->f_offset);
if (newscan) {
i = (typeof(i))ret;
fs->nleft = ntohs(i->sdb_records) - 1;
} else {
fs->nleft--;
}
return ret;
}
static void __open(struct sdbfs *fs)
{
fs->f_offset = htonll(fs->currentp->sdb_component.addr_first);
fs->f_len = htonll(fs->currentp->sdb_component.addr_last)
+ 1 - fs->f_offset;
fs->read_offset = 0;
}
int sdbfs_open_name(struct sdbfs *fs, const char *name)
{
struct sdb_device *d;
int len = strlen(name);
if (len > 19)
return -ENOENT;
sdbfs_scan(fs, 1); /* new scan: get the interconnect and igore it */
while ( (d = sdbfs_scan(fs, 0)) != NULL) {
if (strncmp(name, d->sdb_component.product.name, len))
continue;
if (len < 19 && d->sdb_component.product.name[len] != ' ')
continue;
fs->currentp = d;
__open(fs);
return 0;
}
return -ENOENT;
}
int sdbfs_open_id(struct sdbfs *fs, uint64_t vid, uint32_t did)
{
struct sdb_device *d;
sdbfs_scan(fs, 1); /* new scan: get the interconnect and igore it */
while ( (d = sdbfs_scan(fs, 0)) != NULL) {
if (vid != d->sdb_component.product.vendor_id)
continue;
if (did != d->sdb_component.product.device_id)
continue;
fs->currentp = d;
__open(fs);
return 0;
}
return -ENOENT;
}
int sdbfs_close(struct sdbfs *fs)
{
fs->currentp = NULL;
return 0;
}
/* Though freestanding, some minimal headers are expected to exist */
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#define SDB_KERNEL 0
#define SDB_USER 0
#define SDB_FREESTAND 1
#ifdef SDBFS_BIG_ENDIAN
# define ntohs(x) (x)
# define htons(x) (x)
# define ntohl(x) (x)
# define htonl(x) (x)
#else
# error "No support, yet, for little-endian freestanding library"
#endif
#include <linux/types.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <asm/byteorder.h>
/*
* The default installed /usr/include/linux stuff misses the __KERNEL__ parts.
* For libsdbfs it means we won't get uint32_t and similar types.
*
* So, check if we got the information we need before strange errors happen.
* The DECLARE_BITMAP macro is in <linux/types.h> since the epoch, but it
* is not installed in /usr/include/linux/types.h, so use it to check.
*/
#ifndef DECLARE_BITMAP
# error "Please point LINUX to a source tree if you define __KERNEL__"
#endif
#define SDB_KERNEL 1
#define SDB_USER 0
#define SDB_FREESTAND 0
#define sdb_print(format, ...) printk(format, __VA_ARGS__)
#ifndef __LIBSDBFS_USER_H__
#define __LIBSDBFS_USER_H__
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h> /* htonl */
#define SDB_KERNEL 0
#define SDB_USER 1
#define SDB_FREESTAND 0
#define sdb_print(format, ...) fprintf(stderr, format, __VA_ARGS__)
#endif /* __LIBSDBFS_USER_H__ */
#ifndef __LIBSDBFS_H__
#define __LIBSDBFS_H__
/* The library can work in three different environments */
#ifdef __KERNEL__
# include "libsdbfs-kernel.h"
#elif defined(__unix__)
# include "libsdbfs-user.h"
#else
# include "libsdbfs-freestanding.h"
#endif
#include <sdb.h> /* Please point your "-I" to some sensible place */
/*
* Data structures: please not that the library intself doesn't use
* malloc, so it's the caller who must deal withallocation/removal.
* For this reason we can have no opaque structures, but some fields
* are private
*/
struct sdbfs {
/* Some fields are informative */
char *name; /* may be null */
void *drvdata; /* driver may need some detail.. */
int blocksize;
unsigned long entrypoint;
/* The "driver" must offer some methods */
void *data; /* Use this if directly mapped */
unsigned long datalen; /* Length of the above array */
int (*read)(struct sdbfs *fs, int offset, void *buf, int count);
int (*write)(struct sdbfs *fs, int offset, void *buf, int count);
int (*erase)(struct sdbfs *fs, int offset, int count);
/* The following fields are library-private */
struct sdb_device current_record;
struct sdb_device *currentp;
int nleft;
unsigned long f_offset;
unsigned long f_len;
unsigned long read_offset;
unsigned long flags;
struct sdbfs *next;
};
#define SDBFS_F_VERBOSE 0x0001
/* Defined in glue.c */
int sdbfs_dev_create(struct sdbfs *fs, int verbose);
int sdbfs_dev_destroy(struct sdbfs *fs);
struct sdbfs *sdbfs_dev_find(const char *name);
int sdbfs_open_name(struct sdbfs *fs, const char *name);
int sdbfs_open_id(struct sdbfs *fs, uint64_t vid, uint32_t did);
int sdbfs_close(struct sdbfs *fs);
struct sdb_device *sdbfs_scan(struct sdbfs *fs, int newscan);
/* Defined in access.c */
int sdbfs_fstat(struct sdbfs *fs, struct sdb_device *record_return);
int sdbfs_fread(struct sdbfs *fs, int offset, char *buf, int count);
int sdbfs_fwrite(struct sdbfs *fs, int offset, char *buf, int count);
/* This is needed to convert endianness. Hoping it is not defined elsewhere */
static inline uint64_t htonll(uint64_t ll)
{
uint64_t res;
if (htonl(1) == 1)
return ll;
res = htonl(ll >> 32);
res |= (uint64_t)(htonl((uint32_t)ll)) << 32;
return res;
}
static inline uint64_t ntohll(uint64_t ll)
{
return htonll(ll);
}
#endif /* __LIBSDBFS_H__ */
# This is an example config file, that can be used to build a filesystem
# from this very directory. Please note that gensdbfs doesn't look for
# config files in subdirectories but only in the tol-level one.
.
vendor = 0x123456789abcdef
device = 257
position = 0x1000
Makefile
position = 0
gensdbfs.c
write = 1
maxsize = 0x10000
AS = $(CROSS_COMPILE)as
LD = $(CROSS_COMPILE)ld
CC = $(CROSS_COMPILE)gcc
CPP = $(CC) -E
AR = $(CROSS_COMPILE)ar
NM = $(CROSS_COMPILE)nm
STRIP = $(CROSS_COMPILE)strip
OBJCOPY = $(CROSS_COMPILE)objcopy
OBJDUMP = $(CROSS_COMPILE)objdump
CFLAGS = -Wall -ggdb
CFLAGS += -I../lib -I../include -I../include/linux
LDFLAGS = -L../lib -lsdbfs
PROG = gensdbfs sdb-read
all: $(PROG)
%: %.c
$(CC) $(CFLAGS) -o $@ $*.c $(LDFLAGS)
$(PROG): ../lib/libsdbfs.a
clean:
rm -f $(PROG) *.o *~ core
# add the other unused targets, so the rule in ../Makefile works
modules install modules_install:
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <dirent.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sdb.h>
#include "gensdbfs.h"
/*
* This takes a directory and turns it into an sdb image. An optional
* config file (called --SDB-CONFIG--) states more about the entries.
* Information about the storage, on the other hand, is received on
* the command line.
*/
/* Lazily, these are globals, pity me */
static unsigned blocksize = 64;
static unsigned long devsize = 0; /* unspecified */
static unsigned long lastwritten = 0;
static char *prgname;
static inline unsigned long SDB_ALIGN(unsigned long x)
{
return (x + (blocksize - 1)) & ~(blocksize - 1);
}
/* Helpers for scan_input(), which is below */
static void __fill_dot(struct sdbf *dot, char *dir)
{
struct sdb_interconnect *i = &dot->s_i;
struct sdb_component *c = &i->sdb_component;
struct sdb_product *p = &c->product;
char fn[PATH_MAX];
strcpy(fn, dir);
strcat(fn, "/.");
dot->fullname = strdup(fn);
dot->basename = strdup(".");
i->sdb_magic = htonl(SDB_MAGIC);
i->sdb_version = 1;
i->sdb_bus_type = sdb_data;
/* c->addr_first/last to be filled later */
p->vendor_id = htonll(0x46696c6544617461LL); /* "FileData" */
p->version = htonl(1); /* FIXME: version of gensdbfs */
/* FIXME: date */
memset(p->name, ' ', sizeof(p->name));
p->name[0] = '.';
memcpy(&p->device_id, p->name, 4);
p->record_type = sdb_type_interconnect;
}
static int __fill_file(struct sdbf *f, char *dir, char *fname)
{
char fn[PATH_MAX];
struct sdb_device *d = &f->s_d;
struct sdb_component *c = &d->sdb_component;
struct sdb_product *p = &c->product;
int flags, len;
strcpy(fn, dir);
strcat(fn, "/");
strcat(fn, fname);
f->fullname = strdup(fn);
f->basename = strdup(fname);
if (stat(fn, &f->stbuf) < 0) {
fprintf(stderr, "%s: stat(%s): %s\n", prgname, fn,
strerror(errno));
return -1;
}
if (!S_ISREG(f->stbuf.st_mode)) {
/* FIXME: support subdirs */
fprintf(stderr, "%s: ignoring non-regular \"%s\"\n",
prgname, fn);
return 0;
}
/*
* size can be enlarged by config file, but in any case if the
* file can be written to, align to the block size
*/
f->size = f->stbuf.st_size;
if (f->stbuf.st_mode & S_IWOTH) f->size = SDB_ALIGN(f->size);
/* abi fields remain 0 */
flags = 0;
if (f->stbuf.st_mode & S_IROTH) flags |= SDB_DATA_READ;
if (f->stbuf.st_mode & S_IWOTH) flags |= SDB_DATA_WRITE;
if (f->stbuf.st_mode & S_IXOTH) flags |= SDB_DATA_EXEC;
d->bus_specific = htonl(flags);
/* c->addr_first/last to be filled later */
p->vendor_id = htonll(0x46696c6544617461LL); /* "FileData" */
p->version = htonl(1); /* FIXME: version of gensdbfs */
/* FIXME: date */
memset(p->name, ' ', sizeof(p->name));
len = strlen(fname);
if (len > sizeof(p->name)) {
fprintf(stderr, "%s: truncating filename \"%s\"\n",
prgname, fname);
len = sizeof(p->name);
}
memcpy(p->name, fname, len);
memcpy(&p->device_id, p->name, 4);
p->record_type = sdb_type_device;
return 1;
}
/* Helpers for scan_config(), which is below */
static struct sdbf *find_filename(struct sdbf *tree, char *s)
{
int i, n = ntohs(tree->s_i.sdb_records);
struct sdbf *f;
for (i = 0; i < n; i++) {
f = tree + i;
if (!strcmp(s, f->basename))
return f;
}
return NULL;
}
static int parse_config_line(struct sdbf *tree, struct sdbf *current, int line,
char *t)
{
struct sdb_device *d = &current->s_d;
struct sdb_component *c = &d->sdb_component;
struct sdb_product *p = &c->product;
unsigned long int32; /* may be 64 bits on some machines */
unsigned long long int64;
int i;
if (getenv("VERBOSE"))
fprintf(stderr, "parse line %i for %s: %s\n", line,
current->fullname, t);
if (sscanf(t, "vendor = %lli", &int64) == 1) {
p->vendor_id = htonll(int64);
return 0;
}
if (sscanf(t, "device = %li", &int32) == 1) {
p->device_id = htonl(int32);
return 0;
}
if (sscanf(t, "write = %i", &i) == 1) {
if (i)
d->bus_specific |= htonl(SDB_DATA_WRITE);
else
d->bus_specific &= htonl(~SDB_DATA_WRITE);
return 0;
}
if (sscanf(t, "maxsize = %li", &int32) == 1) {
current->size = int32;
return 0;
}
if (sscanf(t, "position = %li", &int32) == 1) {
current->userpos = 1;
current->astart = int32;
return 0;
}
fprintf(stderr, "%s: %s:%i: Unknown directive \"%s\" for file \"%s\"\n",
prgname, CFG_NAME, line, t, current->fullname);
return -1;
}
/* step 0: read the directory and build the tree. Returns NULL on error */
static struct sdbf *scan_input(char *name, struct sdbf *parent, FILE **cfgf)
{
DIR *d;
struct dirent *de;
struct sdbf *tree;
int n, ret;
/* first loop: count the entries */
d = opendir(name);
if (!d) {
fprintf(stderr, "%s: %s: %s\n", prgname, name,
strerror(errno));
return NULL;
}
for (n = 0; (de = readdir(d)); )
n++;
closedir(d);
tree = calloc(n, sizeof(*tree));
if (!tree) {
fprintf(stderr, "%s: out of memory\n", prgname);
return NULL;
}
tree->nfiles = n;
/* second loop: fill it */
d = opendir(name);
if (!d) {
fprintf(stderr, "%s: %s: %s\n", prgname, name,
strerror(errno));
return NULL;
}
for (n = 1 /* 0 resvd for interconnect */; (de = readdir(d)); ) {
tree[n].de = *de;
if (!strcmp(de->d_name, ".")) {
tree[0].de = *de;
__fill_dot(tree, name);
continue;
}
if (!strcmp(de->d_name, ".."))
continue; /* no dot-dot */
if (!strcmp(de->d_name, CFG_NAME)) {
char s[PATH_MAX];
strcpy(s, name);
strcat(s, "/");
strcat(s, de->d_name);
*cfgf = fopen(s, "r");
if (!*cfgf)
fprintf(stderr, "%s: open(%s): %s\n",
prgname, CFG_NAME, strerror(errno));
/* don't exit on this error: proceed without cfg */
continue;
}
ret = __fill_file(tree + n, name, de->d_name);
if (ret < 0)
return NULL;
n += ret;
}
/* number or records in the interconnect */
tree->s_i.sdb_records = htons(n);
return tree;
}
static int dumpstruct(FILE *dest, char *name, void *ptr, int size)
{
int ret, i;
unsigned char *p = ptr;
ret = fprintf(dest, "%s (size 0x%x)\n", name, size);
for (i = 0; i < size; ) {
ret += fprintf(dest, "%02x", p[i]);
i++;
ret += fprintf(dest, i & 3 ? " " : i & 0xf ? " " : "\n");
}
if (i & 0xf)
ret += fprintf(dest, "\n");
return ret;
}
static void dump_tree(struct sdbf *tree)
{
int i, n = ntohs(tree->s_i.sdb_records);
for (i = 0; i < n; i++, tree++) {
printf("%s: \"%s\" ino %li\n", tree->fullname, tree->de.d_name,
(long)tree->de.d_ino);
printf("astart %lx, rstart %lx, size %lx (%lx)\n",
tree->astart, tree->rstart, tree->size,
tree->stbuf.st_size);
dumpstruct(stdout, "sdb record", &tree->s_d,
sizeof(tree->s_d));
printf("\n");
}
}
/* step 1: change the in-memory tree according to config file */
static struct sdbf *scan_config(struct sdbf *tree, FILE *f)
{
struct sdbf *current = NULL;
char s[256];
char *t;
int i, lineno = 0;
while (fgets(s, sizeof(s), f)) {
lineno++;
for (i = strlen(s) - 1; i >= 0 && isspace(s[i]); i--)
s[i] = '\0';
t = s;
while (*t && isblank(*t))
t++;
if (*t == '#' || !*t) /* empty or comment */
continue;
if (t == s) {
/* line starts in column 0: new file name */
current = find_filename(tree, s);
if (!current) {
fprintf(stderr, "%s: Warning: %s:%i: "
"\"%s\" not found\n",
prgname, CFG_NAME, lineno, s);
}
continue;
}
if (!current) {
/* ignore directives for non-existent files */
continue;
}
parse_config_line(tree, current, lineno, t);
}
return tree;
}
/* step 2: place the files in the storage area */
static struct sdbf *alloc_storage(struct sdbf *tree)
{
int i, n;
unsigned long rpos; /* the next expected relative position */
unsigned long l, last; /* keep track of last, for directory record */
struct sdbf *f;
tree->s_i.sdb_component.addr_first = htonll(tree->astart);
/* The "suggested" output place is after the directory itself */
n = ntohs(tree->s_i.sdb_records);
rpos = SDB_ALIGN(n * sizeof(struct sdb_device));
last = tree->astart + rpos;
for (i = 1; i < n; i++) {
f = tree + i;
if (f->userpos) { /* user-specified position */
f->s_d.sdb_component.addr_first = htonll(f->astart);
l = f->astart + f->size - 1;
f->s_d.sdb_component.addr_last = htonll(l);
if (l > last) last = l;
continue;
}
/* position not mandated: go sequential from previous one */
f->rstart = rpos;
f->s_d.sdb_component.addr_first = htonll(tree->astart + rpos);
l = tree->astart + rpos + f->size - 1;
f->s_d.sdb_component.addr_last = htonll(l);
if (l > last) last = l;
rpos = SDB_ALIGN(rpos + f->size);
}
/* finally, save the last used byte for the whole directory */
tree->s_i.sdb_component.addr_last = htonll(last);
return tree;
}
/* step 3: output the image file */
static struct sdbf *write_sdb(struct sdbf *tree, FILE *out)
{
int i, j, n, copied;
unsigned long pos;
struct sdbf *sdbf;
FILE *f;
char *buf;
buf = malloc(blocksize);
if (!buf) {
fprintf(stderr, "%s: out of memory\n", prgname);
return NULL;
}
n = ntohs(tree->s_i.sdb_records);
/* First, write the directory, from its starting position */
fseek(out, tree->astart, SEEK_SET);
for (i = 0; i < n; i++)
fwrite(&tree[i].s_d, sizeof(tree[i].s_d), 1, out);
/* then each file */
for (i = 1; i < n; i++) {
sdbf = tree + i;
f = fopen(sdbf->fullname, "r");
if (!f) {
fprintf(stderr, "%s: %s: %s -- ignoring\n", prgname,
sdbf->fullname, strerror(errno));
continue;
}
/*
* This astart and rstart stuff must be cleaned up, especially
* when we add subdirectories. Currently, user-placed files
* use astart, while auto-allocated use rstart from dir head
*/
if (sdbf->userpos)
fseek(out, sdbf->astart, SEEK_SET);
else
fseek(out, tree->astart + sdbf->rstart, SEEK_SET);
for (copied = 0; copied < sdbf->stbuf.st_size; ) {
j = fread(buf, 1, blocksize, f);
if (j <= 0)
break; /* unlikely */
fwrite(buf, 1, j, out);
copied += j;
pos = ftell(out);
if (pos > lastwritten)
lastwritten = pos;
}
fclose(f);
}
return tree;
}
static int usage(char *prgname)
{
fprintf(stderr, "%s: Use \"%s [<options>] <inputdir> <output>\"\n",
prgname, prgname);
fprintf(stderr, " -b <number> : block size (default 64)\n");
fprintf(stderr, " -s <number> : device size (default: as needed)\n");
fprintf(stderr, " a file called \"" CFG_NAME "\", in the root of\n"
" <inputdir> is used as configuration file\n");
exit(1);
}
int main(int argc, char **argv)
{
int c;
struct stat stbuf;
FILE *fcfg = NULL, *fout;
char *rest;
struct sdbf *tree;
prgname = argv[0];
while ( (c = getopt(argc, argv, "b:s:")) != -1) {
switch (c) {
case 'b':
blocksize = strtol(optarg, &rest, 0);
if (rest && *rest) {
fprintf(stderr, "%s: not a number \"%s\"\n",
prgname, optarg);
exit(1);
}
break;
case 's':
devsize = strtol(optarg, &rest, 0);
if (rest && *rest) {
fprintf(stderr, "%s: not a number \"%s\"\n",
prgname, optarg);
exit(1);
}
break;
}
}
if (optind != argc - 2)
usage(prgname);
/* check input and output */
if (stat(argv[optind], &stbuf) < 0) {
fprintf(stderr, "%s: %s: %s\n", prgname, argv[optind],
strerror(errno));
exit(1);
}
if (!S_ISDIR(stbuf.st_mode)) {
fprintf(stderr, "%s: %s: not a directory\n", prgname,
argv[optind]);
exit(1);
}
fout = fopen(argv[optind+1], "w");
if (!fout) {
fprintf(stderr, "%s: %s: %s\n", prgname, argv[optind+1],
strerror(errno));
exit(1);
}
/* scan the whole input tree and save the information */
tree = scan_input(argv[optind], NULL /* parent */, &fcfg);
if (!tree)
exit(1);
/* read configuration file and save its info for each file */
if (fcfg)
tree = scan_config(tree, fcfg);
if (!tree)
exit(1);
/* allocate space in the storage */
tree = alloc_storage(tree);
if (!tree)
exit(1);
if (getenv("VERBOSE"))
dump_tree(tree);
/* write out the whole tree */
tree = write_sdb(tree, fout);
if (!tree)
exit(1);
if (lastwritten < devsize) {
fseek(fout, devsize - 1, SEEK_SET);
fwrite("\0", 1, 1, fout);
}
fclose(fout);
if (devsize && (lastwritten > devsize)) {
fprintf(stderr, "%s: data storage (0x%lx) exceeds device size"
" (0x%lx)\n", prgname, lastwritten, devsize);
exit(1);
}
exit(0);
}
#ifndef __GENSDBFS_H__
#define __GENSDBFS_H__
#include <stdint.h>
#define CFG_NAME "--SDB-CONFIG--"
/* We need to keep track of each file as both unix and sdb entity*/
struct sdbf {
struct stat stbuf;
struct dirent de;
union {
struct sdb_device s_d;
struct sdb_interconnect s_i;
struct sdb_bridge s_b;
};
char *fullname;
char *basename;
unsigned long astart, rstart; /* absolute, relative */
unsigned long size;
int nfiles, totsize; /* for dirs */
struct sdbf *dot; /* for files, pointer to owning dir */
struct sdbf *parent; /* for dirs, current dir in ../ */
int userpos;
};
static inline uint64_t htonll(uint64_t ll)
{
uint64_t res;
if (htonl(1) == 1)
return ll;
res = htonl(ll >> 32);
res |= (uint64_t)(htonl((uint32_t)ll)) << 32;
return res;
}
#endif /* __GENSDBFS_H__ */
/*
* Copyright (C) 2012 CERN (www.cern.ch)
* Author: Alessandro Rubini <rubini@gnudd.com>
*
* Released according to the GNU GPL, version 2 or any later version.
*
* This work is part of the White Rabbit project, a research effort led
* by CERN, the European Institute for Nuclear Research.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include "libsdbfs.h"
char *prgname;
int opt_long, opt_verbose, opt_read, opt_entry;
/*
* This read method is not really needed, but it's there
* to exercise the library procedures
*/
static int do_read(struct sdbfs *fs, int offset, void *buf, int count)
{
if (opt_verbose)
fprintf(stderr, "%s @ 0x%08x - size 0x%x (%i)\n", __func__,
offset, count, count);
memcpy(buf, fs->drvdata + offset, count);
return count;
}
/* Boring ascii representation of a device */
static void list_device(struct sdb_device *d)
{
struct sdb_product *p;
struct sdb_component *c;
c = &d->sdb_component;
p = &c->product;
static int warned;
if (!opt_long) {
printf("%.19s\n", p->name);
return;
}
if (!warned) {
fprintf(stderr, "%s: listing format is to be defined\n",
prgname);
warned = 1;
}
printf("%016llx:%08x @ %08llx-%08llx %.19s\n",
ntohll(p->vendor_id), ntohl(p->device_id),
ntohll(c->addr_first), ntohll(c->addr_last),
p->name);
}
/* The following three function perform the real work, main() is just glue */
static void do_list(struct sdbfs *fs)
{
struct sdb_device *d;
int new = 1;
while ( (d = sdbfs_scan(fs, new)) != NULL) {
list_device(d);
new = 0;
}
}
static void do_cat_name(struct sdbfs *fs, char *name)
{
char buf[4096];
int i;
i = sdbfs_open_name(fs, name);
if (i < 0) {
fprintf(stderr, "%s: %s: %s\n", prgname, name, strerror(-i));
exit(1);
}
while ( (i = sdbfs_fread(fs, -1, buf, sizeof(buf))) > 0)
fwrite(buf, 1, i, stdout);
sdbfs_close(fs);
}
static void do_cat_id(struct sdbfs *fs, uint64_t vendor, uint32_t dev)
{
char buf[4096];
int i;
i = sdbfs_open_id(fs, htonll(vendor), htonl(dev));
if (i < 0) {
fprintf(stderr, "%s: %016llx-%08x: %s\n", prgname, vendor,
dev, strerror(-i));
exit(1);
}
while ( (i = sdbfs_fread(fs, -1, buf, sizeof(buf))) > 0)
fwrite(buf, 1, i, stdout);
sdbfs_close(fs);
}
/* As promised, here's the user-interface glue (and initialization, I admit) */
int main(int argc, char **argv)
{
int c, err;
FILE *f;
struct sdbfs _fs;
struct sdbfs *fs = &_fs; /* I like to type "fs->" */
struct stat stbuf;
void *mapaddr;
char *fsname;
char *filearg = NULL;
unsigned long int32;
unsigned long long int64;
int pagesize = getpagesize();
prgname = argv[0];
while ( (c = getopt(argc, argv, "lvre:")) != -1) {
switch (c) {
case 'l':
opt_long = 1;
break;
case 'v':
opt_verbose = 1;
break;
case 'r':
opt_read = 1;
break;
case 'e':
if (sscanf(optarg, "%i", &opt_entry) != 1) {
fprintf(stderr, "%s: not a number \"%s\"\n",
prgname, optarg);
exit(1);
}
break;
}
}
if (optind < argc - 2 || optind > argc - 1) {
fprintf(stderr, "%s: Use: \"%s [-l|-v] <image-file> [<file>]\n",
prgname, prgname);
exit(1);
}
fsname = argv[optind];
if (optind + 1 < argc)
filearg = argv[optind + 1];
if ( !(f = fopen(fsname, "r")) || fstat(fileno(f), &stbuf) < 0) {
fprintf(stderr, "%s: %s: %s\n", prgname, fsname,
strerror(errno));
exit(1);
}
stbuf.st_size += pagesize - 1;
stbuf.st_size &= ~(pagesize - 1);
mapaddr = mmap(0, stbuf.st_size, PROT_READ, MAP_PRIVATE, fileno(f), 0);
if (mapaddr == MAP_FAILED) {
fprintf(stderr, "%s: mmap(%s): %s\n", prgname, fsname,
strerror(errno));
exit(1);
}
/* So, describe the filesystem instance and give it to the library */
memset(fs, 0, sizeof(*fs));
fs->name = fsname; /* not mandatory */
fs->blocksize = 256; /* only used for writing, actually */
fs->entrypoint = opt_entry;
if (opt_read) {
fs->drvdata = mapaddr;
fs->read = do_read;
} else {
fs->data = mapaddr;
}
err = sdbfs_dev_create(fs, opt_verbose);
if (err) {
fprintf(stderr, "%s: sdbfs_dev_create(): %s\n", prgname,
strerror(-err));
fprintf(stderr, "\t(wrong entry point 0x%08lx?)\n",
fs->entrypoint);
exit(1);
}
/* Now use the thing: either scan, or look for name, or look for id */
if (!filearg)
do_list(fs);
else if (sscanf(filearg, "%llx:%lx", &int64, &int32) != 2)
do_cat_name(fs, filearg);
else
do_cat_id(fs, int64, int32);
sdbfs_dev_destroy(fs);
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment