[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[xen staging] tools: split libxenstat into new tools/libs/stat directory



commit 6d0ec0539077943af6d02be2adc79766c7950132
Author:     Juergen Gross <jgross@xxxxxxxx>
AuthorDate: Fri Aug 28 17:07:38 2020 +0200
Commit:     Wei Liu <wl@xxxxxxx>
CommitDate: Wed Sep 9 10:57:25 2020 +0000

    tools: split libxenstat into new tools/libs/stat directory
    
    There is no reason why libxenstat is not placed in the tools/libs
    directory.
    
    At the same time move xenstat.h to a dedicated include directory
    in tools/libs/stat in order to follow the same pattern as the other
    libraries in tools/libs.
    
    As now xentop is the only left directory in xenstat move it directly
    under tools and get rid of tools/xenstat.
    
    Fix some missing prototype errors (add one prototype and make two
    functions static).
    
    Signed-off-by: Juergen Gross <jgross@xxxxxxxx>
    Acked-by: Wei Liu <wl@xxxxxxx>
---
 .gitignore                                         |    8 +-
 tools/Makefile                                     |    2 +-
 tools/Rules.mk                                     |    6 -
 tools/libs/Makefile                                |    1 +
 tools/libs/stat/COPYING                            |  509 ++++++++
 tools/libs/stat/Makefile                           |  132 ++
 tools/libs/stat/bindings/swig/perl/.empty          |    1 +
 tools/libs/stat/bindings/swig/python/.empty        |    1 +
 tools/libs/stat/bindings/swig/xenstat.i            |    8 +
 tools/libs/stat/include/xenstat.h                  |  197 +++
 tools/libs/stat/xenstat.c                          |  735 +++++++++++
 tools/libs/stat/xenstat_freebsd.c                  |   47 +
 tools/libs/stat/xenstat_linux.c                    |  496 ++++++++
 tools/libs/stat/xenstat_netbsd.c                   |   97 ++
 tools/libs/stat/xenstat_priv.h                     |  108 ++
 tools/libs/stat/xenstat_qmp.c                      |  446 +++++++
 tools/libs/stat/xenstat_solaris.c                  |  405 ++++++
 tools/libs/uselibs.mk                              |    2 +
 tools/xenstat/Makefile                             |   10 -
 tools/xenstat/libxenstat/COPYING                   |  509 --------
 tools/xenstat/libxenstat/Makefile                  |  195 ---
 tools/xenstat/libxenstat/bindings/swig/perl/.empty |    1 -
 .../xenstat/libxenstat/bindings/swig/python/.empty |    1 -
 tools/xenstat/libxenstat/bindings/swig/xenstat.i   |    8 -
 tools/xenstat/libxenstat/src/xenstat.c             |  735 -----------
 tools/xenstat/libxenstat/src/xenstat.h             |  194 ---
 tools/xenstat/libxenstat/src/xenstat_freebsd.c     |   47 -
 tools/xenstat/libxenstat/src/xenstat_linux.c       |  496 --------
 tools/xenstat/libxenstat/src/xenstat_netbsd.c      |   97 --
 tools/xenstat/libxenstat/src/xenstat_priv.h        |  108 --
 tools/xenstat/libxenstat/src/xenstat_qmp.c         |  446 -------
 tools/xenstat/libxenstat/src/xenstat_solaris.c     |  405 ------
 tools/xenstat/xentop/Makefile                      |   50 -
 tools/xenstat/xentop/TODO                          |   34 -
 tools/xenstat/xentop/xentop.c                      | 1346 --------------------
 tools/xentop/Makefile                              |   50 +
 tools/xentop/TODO                                  |   34 +
 tools/xentop/xentop.c                              | 1346 ++++++++++++++++++++
 38 files changed, 4621 insertions(+), 4692 deletions(-)

diff --git a/.gitignore b/.gitignore
index 364b09506b..5e8c47e2db 100644
--- a/.gitignore
+++ b/.gitignore
@@ -128,6 +128,10 @@ tools/libs/guest/xc_core.h
 tools/libs/guest/xc_core_arm.h
 tools/libs/guest/xc_core_x86.h
 tools/libs/guest/xc_private.h
+tools/libs/stat/_paths.h
+tools/libs/stat/headers.chk
+tools/libs/stat/libxenstat.map
+tools/libs/stat/xenstat.pc
 tools/libs/store/headers.chk
 tools/libs/store/list.h
 tools/libs/store/utils.h
@@ -276,9 +280,6 @@ tools/xenmon/xentrace_setmask
 tools/xenmon/xenbaked
 tools/xenpaging/xenpaging
 tools/xenpmd/xenpmd
-tools/xenstat/libxenstat/src/_paths.h
-tools/xenstat/libxenstat/xenstat.pc
-tools/xenstat/xentop/xentop
 tools/xenstore/xenstore
 tools/xenstore/xenstore-chmod
 tools/xenstore/xenstore-exists
@@ -291,6 +292,7 @@ tools/xenstore/xenstore-ls
 tools/xenstore/xenstored
 tools/xenstore/xenstored_test
 tools/xenstore/xs_tdb_dump
+tools/xentop/xentop
 tools/xentrace/xentrace_setsize
 tools/xentrace/tbctl
 tools/xentrace/xenctx
diff --git a/tools/Makefile b/tools/Makefile
index 0db01707a4..ea69675cca 100644
--- a/tools/Makefile
+++ b/tools/Makefile
@@ -17,7 +17,7 @@ SUBDIRS-$(CONFIG_XCUTILS) += xcutils
 SUBDIRS-$(CONFIG_X86) += firmware
 SUBDIRS-y += console
 SUBDIRS-y += xenmon
-SUBDIRS-y += xenstat
+SUBDIRS-y += xentop
 SUBDIRS-$(CONFIG_NetBSD) += xenbackendd
 SUBDIRS-y += libfsimage
 SUBDIRS-$(CONFIG_Linux) += vchan
diff --git a/tools/Rules.mk b/tools/Rules.mk
index 5f17492a68..4fd91fa444 100644
--- a/tools/Rules.mk
+++ b/tools/Rules.mk
@@ -18,7 +18,6 @@ include $(XEN_ROOT)/tools/libs/uselibs.mk
 XEN_libxenlight    = $(XEN_ROOT)/tools/libxl
 # Currently libxlutil lives in the same directory as libxenlight
 XEN_libxlutil      = $(XEN_libxenlight)
-XEN_libxenstat     = $(XEN_ROOT)/tools/xenstat/libxenstat/src
 
 CFLAGS_xeninclude = -I$(XEN_INCLUDE)
 
@@ -108,11 +107,6 @@ ifeq ($(CONFIG_Linux),y)
 LDLIBS_libxenstore += -ldl
 endif
 
-CFLAGS_libxenstat  = -I$(XEN_libxenstat)
-SHDEPS_libxenstat  = $(SHLIB_libxenctrl) $(SHLIB_libxenstore)
-LDLIBS_libxenstat  = $(SHDEPS_libxenstat) 
$(XEN_libxenstat)/libxenstat$(libextension)
-SHLIB_libxenstat   = $(SHDEPS_libxenstat) -Wl,-rpath-link=$(XEN_libxenstat)
-
 ifeq ($(debug),y)
 # Disable optimizations
 CFLAGS += -O0 -fno-omit-frame-pointer
diff --git a/tools/libs/Makefile b/tools/libs/Makefile
index 756d059ee7..e8fcd59214 100644
--- a/tools/libs/Makefile
+++ b/tools/libs/Makefile
@@ -13,6 +13,7 @@ SUBDIRS-y += ctrl
 SUBDIRS-y += guest
 SUBDIRS-y += hypfs
 SUBDIRS-y += store
+SUBDIRS-y += stat
 SUBDIRS-$(CONFIG_Linux) += vchan
 
 ifeq ($(CONFIG_RUMP),y)
diff --git a/tools/libs/stat/COPYING b/tools/libs/stat/COPYING
new file mode 100644
index 0000000000..480e5f1876
--- /dev/null
+++ b/tools/libs/stat/COPYING
@@ -0,0 +1,509 @@
+
+                  GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+       51 Franklin St, 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.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations
+below.
+
+  When we speak of free software, we are referring to freedom of use,
+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 and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it
+becomes a de-facto standard.  To achieve this, non-free programs must
+be allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+                  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, 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 library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+  1. You may copy and distribute verbatim copies of the Library's
+complete 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 distribute a copy of this License along with the
+Library.
+
+  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 Library or any portion
+of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+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 Library, 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 Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you 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.
+
+  If distribution of 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 satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at least
+    three years, to give the same user the materials specified in
+    Subsection 6a, above, for a charge no more than the cost of
+    performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be 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.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library 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.
+
+  9. 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 Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+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 with
+this License.
+
+  11. 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 Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library 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 Library.
+
+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.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library 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.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+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 Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+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
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "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
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. 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 LIBRARY 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
+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms
+of the ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.
+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 library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; If not, see 
<http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or
+your school, if any, to sign a "copyright disclaimer" for the library,
+if necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James
+  Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/tools/libs/stat/Makefile b/tools/libs/stat/Makefile
new file mode 100644
index 0000000000..5463f5f7ca
--- /dev/null
+++ b/tools/libs/stat/Makefile
@@ -0,0 +1,132 @@
+# libxenstat: statistics-collection library for Xen
+# Copyright (C) International Business Machines Corp., 2005
+# Author: Josh Triplett <josh@xxxxxxxxxx>
+# 
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+# 
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+
+XEN_ROOT=$(CURDIR)/../../..
+include $(XEN_ROOT)/tools/Rules.mk
+
+CFLAGS += $(CFLAGS_libxenctrl) $(CFLAGS_libxenstore) $(CFLAGS_xeninclude) 
-include $(XEN_ROOT)/tools/config.h
+
+SRCS-y += xenstat.c
+SRCS-y += xenstat_qmp.c
+SRCS-$(CONFIG_Linux) += xenstat_linux.c
+SRCS-$(CONFIG_SunOS) += xenstat_solaris.c
+SRCS-$(CONFIG_NetBSD) += xenstat_netbsd.c
+SRCS-$(CONFIG_FreeBSD) += xenstat_freebsd.c
+
+LDLIBS-y += -lyajl
+LDLIBS-$(CONFIG_SunOS) += -lkstat
+APPEND_LDFLAGS += $(LDLIBS-y)
+
+include $(XEN_ROOT)/tools/libs/libs.mk
+
+$(PKG_CONFIG_LOCAL): PKG_CONFIG_INCDIR = $(XEN_libxenstat)/include
+
+$(LIB_OBJS): _paths.h
+
+PYLIB=bindings/swig/python/_xenstat.so
+PYMOD=bindings/swig/python/xenstat.py
+PYSRC=bindings/swig/python/_xenstat.c
+PERLLIB=bindings/swig/perl/xenstat.so
+PERLMOD=bindings/swig/perl/xenstat.pm
+PERLSRC=bindings/swig/perl/xenstat.c
+BINDINGS=$(PYLIB) $(PYMOD) $(PERLLIB) $(PERLMOD)
+BINDINGSRC=$(PYSRC) $(PERLSRC)
+
+# The all-bindings target builds all the language bindings
+.PHONY: all-bindings
+all-bindings: perl-bindings python-bindings
+
+# The install-bindings target installs all the language bindings
+install-bindings: install-perl-bindings install-python-bindings
+
+.PHONY: uninstall-bindings
+uninstall-bindings: uninstall-perl-bindings uninstall-python-bindings
+
+$(BINDINGS): $(SHLIB) $(SHLIB_LINKS) include/xenstat.h
+
+SWIG_FLAGS=-module xenstat -Iinclude -I.
+
+# Python bindings
+PYTHON_VERSION=$(PYTHON:python%=%)
+PYTHON_FLAGS=-I/usr/include/python$(PYTHON_VERSION) -lpython$(PYTHON_VERSION)
+$(PYMOD): $(PYSRC)
+$(PYSRC): bindings/swig/xenstat.i
+       swig -python $(SWIG_FLAGS) -outdir $(@D) -o $(PYSRC) $<
+
+$(PYLIB): $(PYSRC)
+       $(CC) $(CFLAGS) $(LDFLAGS) $(PYTHON_FLAGS) $(SHLIB_LDFLAGS) -lxenstat 
-o $@ $< $(APPEND_LDFLAGS)
+
+python-bindings: $(PYLIB) $(PYMOD)
+
+pythonlibdir=$(prefix)/lib/python$(PYTHON_VERSION)/site-packages
+install-python-bindings: $(PYLIB) $(PYMOD)
+       $(INSTALL_PROG) $(PYLIB) $(DESTDIR)$(pythonlibdir)/_xenstat.so
+       $(INSTALL_PROG) $(PYMOD) $(DESTDIR)$(pythonlibdir)/xenstat.py
+
+.PHONY: uninstall-python-bindings
+uninstall-python-bindings:
+       rm -f $(DESTDIR)$(pythonlibdir)/_xenstat.so
+       rm -f $(DESTDIR)$(pythonlibdir)/xenstat.py
+
+ifeq ($(XENSTAT_PYTHON_BINDINGS),y)
+.PHONY: all
+all: python-bindings
+install: install-python-bindings
+uninstall: uninstall-python-bindings
+endif
+
+# Perl bindings
+PERL_FLAGS=`perl -MConfig -e 'print "$$Config{ccflags} 
-I$$Config{archlib}/CORE";'`
+$(PERLMOD): $(PERLSRC)
+$(PERLSRC): bindings/swig/xenstat.i
+       swig -perl $(SWIG_FLAGS) -outdir $(@D) -o $(PERLSRC) $<
+
+$(PERLLIB): $(PERLSRC)
+       $(CC) $(CFLAGS) $(LDFLAGS) $(PERL_FLAGS) $(SHLIB_LDFLAGS) -lxenstat -o 
$@ $< $(APPEND_LDFLAGS)
+
+.PHONY: perl-bindings
+perl-bindings: $(PERLLIB) $(PERLMOD)
+
+.PHONY: install-perl-bindings
+perllibdir=$(prefix)/lib/perl5
+perlmoddir=$(prefix)/share/perl5
+install-perl-bindings: $(PERLLIB) $(PERLMOD)
+       $(INSTALL_PROG) $(PERLLIB) $(DESTDIR)$(perllibdir)/xenstat.so
+       $(INSTALL_PROG) $(PERLMOD) $(DESTDIR)$(perlmoddir)/xenstat.pm
+
+.PHONY: uninstall-perl-bindings
+uninstall-perl-bindings:
+       rm -f $(DESTDIR)$(perllibdir)/xenstat.so
+       rm -f $(DESTDIR)$(perlmoddir)/xenstat.pm
+
+ifeq ($(XENSTAT_PERL_BINDINGS),y)
+.PHONY: all
+all: perl-bindings
+
+.PHONY: install
+install: install-perl-bindings
+uninstall: uninstall-perl-bindings
+endif
+
+clean: cleanlocal
+
+.PHONY: cleanlocal
+cleanlocal:
+       rm -f $(BINDINGS) $(BINDINGSRC) $(DEPS_RM) _paths.h
+       rm -f libxenstat.map
+
+-include $(DEPS_INCLUDE)
+
+genpath-target = $(call buildmakevars2header,_paths.h)
+$(eval $(genpath-target))
diff --git a/tools/libs/stat/bindings/swig/perl/.empty 
b/tools/libs/stat/bindings/swig/perl/.empty
new file mode 100644
index 0000000000..2a8dd4274d
--- /dev/null
+++ b/tools/libs/stat/bindings/swig/perl/.empty
@@ -0,0 +1 @@
+This directory is empty; this file is included to prevent version control 
systems from removing the directory.
diff --git a/tools/libs/stat/bindings/swig/python/.empty 
b/tools/libs/stat/bindings/swig/python/.empty
new file mode 100644
index 0000000000..2a8dd4274d
--- /dev/null
+++ b/tools/libs/stat/bindings/swig/python/.empty
@@ -0,0 +1 @@
+This directory is empty; this file is included to prevent version control 
systems from removing the directory.
diff --git a/tools/libs/stat/bindings/swig/xenstat.i 
b/tools/libs/stat/bindings/swig/xenstat.i
new file mode 100644
index 0000000000..d18fe0b155
--- /dev/null
+++ b/tools/libs/stat/bindings/swig/xenstat.i
@@ -0,0 +1,8 @@
+%module xenstat_swig
+%{
+/* Includes the header in the wrapper code */
+#include "xenstat.h"
+%}
+
+/* Parse the header file to generate wrappers */
+%include "xenstat.h"
diff --git a/tools/libs/stat/include/xenstat.h 
b/tools/libs/stat/include/xenstat.h
new file mode 100644
index 0000000000..c3b98909dd
--- /dev/null
+++ b/tools/libs/stat/include/xenstat.h
@@ -0,0 +1,197 @@
+/* libxenstat: statistics-collection library for Xen
+ * Copyright (C) International Business Machines Corp., 2005
+ * Authors: Josh Triplett <josh@xxxxxxxxxx>
+ *          Judy Fischbach <jfisch@xxxxxxxxxx>
+ *          David Hendricks <cro_marmot@xxxxxxxxxxx>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ */
+
+/* libxenstat API */
+
+#ifndef XENSTAT_H
+#define XENSTAT_H
+
+#include <stdbool.h>
+
+/* Opaque handles */
+typedef struct xenstat_handle xenstat_handle;
+typedef struct xenstat_domain xenstat_domain;
+typedef struct xenstat_node xenstat_node;
+typedef struct xenstat_vcpu xenstat_vcpu;
+typedef struct xenstat_network xenstat_network;
+typedef struct xenstat_vbd xenstat_vbd;
+
+/* Initialize the xenstat library.  Returns a handle to be used with
+ * subsequent calls to the xenstat library, or NULL if an error occurs. */
+xenstat_handle *xenstat_init(void);
+
+/* Release the handle to libxc, free resources, etc. */
+void xenstat_uninit(xenstat_handle * handle);
+
+/* Flags for types of information to collect in xenstat_get_node */
+#define XENSTAT_VCPU 0x1
+#define XENSTAT_NETWORK 0x2
+#define XENSTAT_XEN_VERSION 0x4
+#define XENSTAT_VBD 0x8
+#define XENSTAT_ALL 
(XENSTAT_VCPU|XENSTAT_NETWORK|XENSTAT_XEN_VERSION|XENSTAT_VBD)
+
+/* Get all available information about a node */
+xenstat_node *xenstat_get_node(xenstat_handle * handle, unsigned int flags);
+
+/* Free the information */
+void xenstat_free_node(xenstat_node * node);
+
+/*
+ * Node functions - extract information from a xenstat_node
+ */
+
+/* Get information about the domain with the given domain ID */
+xenstat_domain *xenstat_node_domain(xenstat_node * node,
+                                   unsigned int domid);
+
+/* Get the domain with the given index; used to loop over all domains. */
+xenstat_domain *xenstat_node_domain_by_index(xenstat_node * node,
+                                            unsigned index);
+
+/* Get xen version of the node */
+const char *xenstat_node_xen_version(xenstat_node * node);
+
+/* Get amount of total memory on a node */
+unsigned long long xenstat_node_tot_mem(xenstat_node * node);
+
+/* Get amount of free memory on a node */
+unsigned long long xenstat_node_free_mem(xenstat_node * node);
+
+/* Get amount of freeable memory on a node */
+long xenstat_node_freeable_mb(xenstat_node * node);
+
+/* Find the number of domains existing on a node */
+unsigned int xenstat_node_num_domains(xenstat_node * node);
+
+/* Find the number of CPUs existing on a node */
+unsigned int xenstat_node_num_cpus(xenstat_node * node);
+
+/* Get information about the CPU speed */
+unsigned long long xenstat_node_cpu_hz(xenstat_node * node);
+
+/*
+ * Domain functions - extract information from a xenstat_domain
+ */
+
+/* Get the domain ID for this domain */
+unsigned xenstat_domain_id(xenstat_domain * domain);
+
+/* Set the domain name for the domain */
+char *xenstat_domain_name(xenstat_domain * domain);
+
+/* Get information about how much CPU time has been used */
+unsigned long long xenstat_domain_cpu_ns(xenstat_domain * domain);
+
+/* Find the number of VCPUs allocated to a domain */
+unsigned int xenstat_domain_num_vcpus(xenstat_domain * domain);
+
+/* Get the VCPU handle to obtain VCPU stats */
+xenstat_vcpu *xenstat_domain_vcpu(xenstat_domain * domain,
+                                 unsigned int vcpu);
+
+/* Find the current memory reservation for this domain */
+unsigned long long xenstat_domain_cur_mem(xenstat_domain * domain);
+
+/* Find the maximum memory reservation for this domain */
+unsigned long long xenstat_domain_max_mem(xenstat_domain * domain);
+
+/* Find the domain's SSID */
+unsigned int xenstat_domain_ssid(xenstat_domain * domain);
+
+/* Get domain states */
+unsigned int xenstat_domain_dying(xenstat_domain * domain);
+unsigned int xenstat_domain_crashed(xenstat_domain * domain);
+unsigned int xenstat_domain_shutdown(xenstat_domain * domain);
+unsigned int xenstat_domain_paused(xenstat_domain * domain);
+unsigned int xenstat_domain_blocked(xenstat_domain * domain);
+unsigned int xenstat_domain_running(xenstat_domain * domain);
+
+/* Get the number of networks for a given domain */
+unsigned int xenstat_domain_num_networks(xenstat_domain *);
+
+/* Get the network handle to obtain network stats */
+xenstat_network *xenstat_domain_network(xenstat_domain * domain,
+                                       unsigned int network);
+
+/* Get the number of VBDs for a given domain */
+unsigned int xenstat_domain_num_vbds(xenstat_domain *);
+
+/* Get the VBD handle to obtain VBD stats */
+xenstat_vbd *xenstat_domain_vbd(xenstat_domain * domain,
+                                   unsigned int vbd);
+
+/*
+ * VCPU functions - extract information from a xenstat_vcpu
+ */
+
+/* Get VCPU usage */
+unsigned int xenstat_vcpu_online(xenstat_vcpu * vcpu);
+unsigned long long xenstat_vcpu_ns(xenstat_vcpu * vcpu);
+
+
+/*
+ * Network functions - extract information from a xenstat_network
+ */
+
+/* Get the ID for this network */
+unsigned int xenstat_network_id(xenstat_network * network);
+
+/* Get the number of receive bytes for this network */
+unsigned long long xenstat_network_rbytes(xenstat_network * network);
+
+/* Get the number of receive packets for this network */
+unsigned long long xenstat_network_rpackets(xenstat_network * network);
+
+/* Get the number of receive errors for this network */
+unsigned long long xenstat_network_rerrs(xenstat_network * network);
+
+/* Get the number of receive drops for this network */
+unsigned long long xenstat_network_rdrop(xenstat_network * network);
+
+/* Get the number of transmit bytes for this network */
+unsigned long long xenstat_network_tbytes(xenstat_network * network);
+
+/* Get the number of transmit packets for this network */
+unsigned long long xenstat_network_tpackets(xenstat_network * network);
+
+/* Get the number of transmit errors for this network */
+unsigned long long xenstat_network_terrs(xenstat_network * network);
+
+/* Get the number of transmit drops for this network */
+unsigned long long xenstat_network_tdrop(xenstat_network * network);
+
+/*
+ * VBD functions - extract information from a xen_vbd
+ */
+
+/* Get the back driver type  for Virtual Block Device */
+unsigned int xenstat_vbd_type(xenstat_vbd * vbd);
+
+/* Get the device number for Virtual Block Device */
+unsigned int xenstat_vbd_dev(xenstat_vbd * vbd);
+
+/* Get the number of OO/RD/WR requests for vbd */
+unsigned long long xenstat_vbd_oo_reqs(xenstat_vbd * vbd);
+unsigned long long xenstat_vbd_rd_reqs(xenstat_vbd * vbd);
+unsigned long long xenstat_vbd_wr_reqs(xenstat_vbd * vbd);
+unsigned long long xenstat_vbd_rd_sects(xenstat_vbd * vbd);
+unsigned long long xenstat_vbd_wr_sects(xenstat_vbd * vbd);
+
+/* Returns error while getting stats (1 if error happened, 0 otherwise) */
+bool xenstat_vbd_error(xenstat_vbd * vbd);
+
+#endif /* XENSTAT_H */
diff --git a/tools/libs/stat/xenstat.c b/tools/libs/stat/xenstat.c
new file mode 100644
index 0000000000..6f93d4e982
--- /dev/null
+++ b/tools/libs/stat/xenstat.c
@@ -0,0 +1,735 @@
+/* libxenstat: statistics-collection library for Xen
+ * Copyright (C) International Business Machines Corp., 2005
+ * Authors: Josh Triplett <josh@xxxxxxxxxx>
+ *          Judy Fischbach <jfisch@xxxxxxxxxx>
+ *          David Hendricks <cro_marmot@xxxxxxxxxxx>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ */
+
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include "xenstat_priv.h"
+
+/*
+ * Data-collection types
+ */
+/* Called to collect the information for the node and all the domains on
+ * it. When called, the domain information has already been collected. 
+ * Return status is 0 if fatal error occurs, 1 for success. Collectors
+ * may prune a domain from the list if it has been deleted between the
+ * time the list was setup and the time the colector is called */
+typedef int (*xenstat_collect_func)(xenstat_node * node);
+/* Called to free the information collected by the collect function.  The free
+ * function will only be called on a xenstat_node if that node includes
+ * information collected by the corresponding collector. */
+typedef void (*xenstat_free_func)(xenstat_node * node);
+/* Called to free any information stored in the handle.  Note the lack of a
+ * matching init function; the collect functions should initialize on first
+ * use.  Also, the uninit function must handle the case that the collector has
+ * never been initialized. */
+typedef void (*xenstat_uninit_func)(xenstat_handle * handle);
+typedef struct xenstat_collector {
+       unsigned int flag;
+       xenstat_collect_func collect;
+       xenstat_free_func free;
+       xenstat_uninit_func uninit;
+} xenstat_collector;
+
+static int  xenstat_collect_vcpus(xenstat_node * node);
+static int  xenstat_collect_xen_version(xenstat_node * node);
+static void xenstat_free_vcpus(xenstat_node * node);
+static void xenstat_free_networks(xenstat_node * node);
+static void xenstat_free_xen_version(xenstat_node * node);
+static void xenstat_free_vbds(xenstat_node * node);
+static void xenstat_uninit_vcpus(xenstat_handle * handle);
+static void xenstat_uninit_xen_version(xenstat_handle * handle);
+static char *xenstat_get_domain_name(xenstat_handle * handle, unsigned int 
domain_id);
+static void xenstat_prune_domain(xenstat_node *node, unsigned int entry);
+
+static xenstat_collector collectors[] = {
+       { XENSTAT_VCPU, xenstat_collect_vcpus,
+         xenstat_free_vcpus, xenstat_uninit_vcpus },
+       { XENSTAT_NETWORK, xenstat_collect_networks,
+         xenstat_free_networks, xenstat_uninit_networks },
+       { XENSTAT_XEN_VERSION, xenstat_collect_xen_version,
+         xenstat_free_xen_version, xenstat_uninit_xen_version },
+       { XENSTAT_VBD, xenstat_collect_vbds,
+         xenstat_free_vbds, xenstat_uninit_vbds }
+};
+
+#define NUM_COLLECTORS (sizeof(collectors)/sizeof(xenstat_collector))
+
+/*
+ * libxenstat API
+ */
+xenstat_handle *xenstat_init(void)
+{
+       xenstat_handle *handle;
+
+       handle = (xenstat_handle *) calloc(1, sizeof(xenstat_handle));
+       if (handle == NULL)
+               return NULL;
+
+#if defined(PAGESIZE)
+       handle->page_size = PAGESIZE;
+#elif defined(PAGE_SIZE)
+       handle->page_size = PAGE_SIZE;
+#else
+       handle->page_size = sysconf(_SC_PAGE_SIZE);
+       if (handle->page_size < 0) {
+               perror("Failed to retrieve page size.");
+               free(handle);
+               return NULL;
+       }
+#endif
+
+       handle->xc_handle = xc_interface_open(0,0,0);
+       if (!handle->xc_handle) {
+               perror("xc_interface_open");
+               free(handle);
+               return NULL;
+       }
+
+       handle->xshandle = xs_daemon_open_readonly(); /* open handle to 
xenstore*/
+       if (handle->xshandle == NULL) {
+               perror("unable to open xenstore");
+               xc_interface_close(handle->xc_handle);
+               free(handle);
+               return NULL;
+       }
+
+       return handle;
+}
+
+void xenstat_uninit(xenstat_handle * handle)
+{
+       unsigned int i;
+       if (handle) {
+               for (i = 0; i < NUM_COLLECTORS; i++)
+                       collectors[i].uninit(handle);
+               xc_interface_close(handle->xc_handle);
+               xs_daemon_close(handle->xshandle);
+               free(handle->priv);
+               free(handle);
+       }
+}
+
+xenstat_node *xenstat_get_node(xenstat_handle * handle, unsigned int flags)
+{
+#define DOMAIN_CHUNK_SIZE 256
+       xenstat_node *node;
+       xc_physinfo_t physinfo = { 0 };
+       xc_domaininfo_t domaininfo[DOMAIN_CHUNK_SIZE];
+       int new_domains;
+       unsigned int i;
+
+       /* Create the node */
+       node = (xenstat_node *) calloc(1, sizeof(xenstat_node));
+       if (node == NULL)
+               return NULL;
+
+       /* Store the handle in the node for later access */
+       node->handle = handle;
+
+       /* Get information about the physical system */
+       if (xc_physinfo(handle->xc_handle, &physinfo) < 0) {
+               free(node);
+               return NULL;
+       }
+
+
+       node->cpu_hz = ((unsigned long long)physinfo.cpu_khz) * 1000ULL;
+        node->num_cpus = physinfo.nr_cpus;
+       node->tot_mem = ((unsigned long long)physinfo.total_pages)
+           * handle->page_size;
+       node->free_mem = ((unsigned long long)physinfo.free_pages)
+           * handle->page_size;
+
+       node->freeable_mb = 0;
+       /* malloc(0) is not portable, so allocate a single domain.  This will
+        * be resized below. */
+       node->domains = malloc(sizeof(xenstat_domain));
+       if (node->domains == NULL) {
+               free(node);
+               return NULL;
+       }
+
+       node->num_domains = 0;
+       do {
+               xenstat_domain *domain, *tmp;
+
+               new_domains = xc_domain_getinfolist(handle->xc_handle,
+                                                   node->num_domains, 
+                                                   DOMAIN_CHUNK_SIZE, 
+                                                   domaininfo);
+               if (new_domains < 0)
+                       goto err;
+
+               tmp = realloc(node->domains,
+                             (node->num_domains + new_domains)
+                             * sizeof(xenstat_domain));
+               if (tmp == NULL)
+                       goto err;
+
+               node->domains = tmp;
+
+               domain = node->domains + node->num_domains;
+
+               /* zero out newly allocated memory in case error occurs below */
+               memset(domain, 0, new_domains * sizeof(xenstat_domain));
+
+               for (i = 0; i < new_domains; i++) {
+                       /* Fill in domain using domaininfo[i] */
+                       domain->id = domaininfo[i].domain;
+                       domain->name = xenstat_get_domain_name(handle, 
+                                                              domain->id);
+                       if (domain->name == NULL) {
+                               if (errno == ENOMEM) {
+                                       /* fatal error */
+                                       xenstat_free_node(node);
+                                       return NULL;
+                               }
+                               else {
+                                       /* failed to get name -- this means the
+                                          domain is being destroyed so simply
+                                          ignore this entry */
+                                       continue;
+                               }
+                       }
+                       domain->state = domaininfo[i].flags;
+                       domain->cpu_ns = domaininfo[i].cpu_time;
+                       domain->num_vcpus = (domaininfo[i].max_vcpu_id+1);
+                       domain->vcpus = NULL;
+                       domain->cur_mem =
+                           ((unsigned long long)domaininfo[i].tot_pages)
+                           * handle->page_size;
+                       domain->max_mem =
+                           domaininfo[i].max_pages == UINT_MAX
+                           ? (unsigned long long)-1
+                           : (unsigned long long)(domaininfo[i].max_pages
+                                                  * handle->page_size);
+                       domain->ssid = domaininfo[i].ssidref;
+                       domain->num_networks = 0;
+                       domain->networks = NULL;
+                       domain->num_vbds = 0;
+                       domain->vbds = NULL;
+
+                       domain++;
+                       node->num_domains++;
+               }
+       } while (new_domains == DOMAIN_CHUNK_SIZE);
+
+
+       /* Run all the extra data collectors requested */
+       node->flags = 0;
+       for (i = 0; i < NUM_COLLECTORS; i++) {
+               if ((flags & collectors[i].flag) == collectors[i].flag) {
+                       node->flags |= collectors[i].flag;
+                       if(collectors[i].collect(node) == 0) {
+                               xenstat_free_node(node);
+                               return NULL;
+                       }
+               }
+       }
+
+       return node;
+err:
+       free(node->domains);
+       free(node);
+       return NULL;
+}
+
+void xenstat_free_node(xenstat_node * node)
+{
+       int i;
+
+       if (node) {
+               if (node->domains) {
+                       for (i = 0; i < node->num_domains; i++)
+                               free(node->domains[i].name);
+
+                       for (i = 0; i < NUM_COLLECTORS; i++)
+                               if((node->flags & collectors[i].flag)
+                                  == collectors[i].flag)
+                                       collectors[i].free(node);
+                       free(node->domains);
+               }
+               free(node);
+       }
+}
+
+xenstat_domain *xenstat_node_domain(xenstat_node * node, unsigned int domid)
+{
+       unsigned int i;
+
+       /* FIXME: binary search */
+       /* Find the appropriate domain entry in the node struct. */
+       for (i = 0; i < node->num_domains; i++) {
+               if (node->domains[i].id == domid)
+                       return &(node->domains[i]);
+       }
+       return NULL;
+}
+
+xenstat_domain *xenstat_node_domain_by_index(xenstat_node * node,
+                                            unsigned int index)
+{
+       if (index < node->num_domains)
+               return &(node->domains[index]);
+       return NULL;
+}
+
+const char *xenstat_node_xen_version(xenstat_node * node)
+{
+       return node->handle->xen_version;
+}
+
+unsigned long long xenstat_node_tot_mem(xenstat_node * node)
+{
+       return node->tot_mem;
+}
+
+unsigned long long xenstat_node_free_mem(xenstat_node * node)
+{
+       return node->free_mem;
+}
+
+long xenstat_node_freeable_mb(xenstat_node * node)
+{
+       return node->freeable_mb;
+}
+
+unsigned int xenstat_node_num_domains(xenstat_node * node)
+{
+       return node->num_domains;
+}
+
+unsigned int xenstat_node_num_cpus(xenstat_node * node)
+{
+       return node->num_cpus;
+}
+
+/* Get information about the CPU speed */
+unsigned long long xenstat_node_cpu_hz(xenstat_node * node)
+{
+       return node->cpu_hz;
+}
+
+/* Get the domain ID for this domain */
+unsigned xenstat_domain_id(xenstat_domain * domain)
+{
+       return domain->id;
+}
+
+/* Get the domain name for the domain */
+char *xenstat_domain_name(xenstat_domain * domain)
+{
+       return domain->name;
+}
+
+/* Get information about how much CPU time has been used */
+unsigned long long xenstat_domain_cpu_ns(xenstat_domain * domain)
+{
+       return domain->cpu_ns;
+}
+
+/* Find the number of VCPUs for a domain */
+unsigned int xenstat_domain_num_vcpus(xenstat_domain * domain)
+{
+       return domain->num_vcpus;
+}
+
+xenstat_vcpu *xenstat_domain_vcpu(xenstat_domain * domain, unsigned int vcpu)
+{
+       if (vcpu < domain->num_vcpus)
+               return &(domain->vcpus[vcpu]);
+       return NULL;
+}
+
+/* Find the current memory reservation for this domain */
+unsigned long long xenstat_domain_cur_mem(xenstat_domain * domain)
+{
+       return domain->cur_mem;
+}
+
+/* Find the maximum memory reservation for this domain */
+unsigned long long xenstat_domain_max_mem(xenstat_domain * domain)
+{
+       return domain->max_mem;
+}
+
+/* Find the domain's SSID */
+unsigned int xenstat_domain_ssid(xenstat_domain * domain)
+{
+       return domain->ssid;
+}
+
+/* Get domain states */
+unsigned int xenstat_domain_dying(xenstat_domain * domain)
+{
+       return (domain->state & XEN_DOMINF_dying) == XEN_DOMINF_dying;
+}
+
+unsigned int xenstat_domain_crashed(xenstat_domain * domain)
+{
+       return ((domain->state & XEN_DOMINF_shutdown) == XEN_DOMINF_shutdown)
+           && (((domain->state >> XEN_DOMINF_shutdownshift)
+                & XEN_DOMINF_shutdownmask) == SHUTDOWN_crash);
+}
+
+unsigned int xenstat_domain_shutdown(xenstat_domain * domain)
+{
+       return ((domain->state & XEN_DOMINF_shutdown) == XEN_DOMINF_shutdown)
+           && (((domain->state >> XEN_DOMINF_shutdownshift)
+                & XEN_DOMINF_shutdownmask) != SHUTDOWN_crash);
+}
+
+unsigned int xenstat_domain_paused(xenstat_domain * domain)
+{
+       return (domain->state & XEN_DOMINF_paused) == XEN_DOMINF_paused;
+}
+
+unsigned int xenstat_domain_blocked(xenstat_domain * domain)
+{
+       return (domain->state & XEN_DOMINF_blocked) == XEN_DOMINF_blocked;
+}
+
+unsigned int xenstat_domain_running(xenstat_domain * domain)
+{
+       return (domain->state & XEN_DOMINF_running) == XEN_DOMINF_running;
+}
+
+/* Get the number of networks for a given domain */
+unsigned int xenstat_domain_num_networks(xenstat_domain * domain)
+{
+       return domain->num_networks;
+}
+
+/* Get the network handle to obtain network stats */
+xenstat_network *xenstat_domain_network(xenstat_domain * domain,
+                                       unsigned int network)
+{
+       if (domain->networks && network < domain->num_networks)
+               return &(domain->networks[network]);
+       return NULL;
+}
+
+/* Get the number of VBDs for a given domain */
+unsigned int xenstat_domain_num_vbds(xenstat_domain * domain)
+{
+       return domain->num_vbds;
+}
+
+/* Get the VBD handle to obtain VBD stats */
+xenstat_vbd *xenstat_domain_vbd(xenstat_domain * domain,
+                               unsigned int vbd)
+{
+       if (domain->vbds && vbd < domain->num_vbds)
+               return &(domain->vbds[vbd]);
+       return NULL;
+}
+
+/*
+ * VCPU functions
+ */
+/* Collect information about VCPUs */
+static int xenstat_collect_vcpus(xenstat_node * node)
+{
+       unsigned int i, vcpu, inc_index;
+
+       /* Fill in VCPU information */
+       for (i = 0; i < node->num_domains; i+=inc_index) {
+               inc_index = 1; /* default is to increment to next domain */
+
+               node->domains[i].vcpus = malloc(node->domains[i].num_vcpus
+                                               * sizeof(xenstat_vcpu));
+               if (node->domains[i].vcpus == NULL)
+                       return 0;
+       
+               for (vcpu = 0; vcpu < node->domains[i].num_vcpus; vcpu++) {
+                       /* FIXME: need to be using a more efficient mechanism*/
+                       xc_vcpuinfo_t info;
+
+                       if (xc_vcpu_getinfo(node->handle->xc_handle,
+                                           node->domains[i].id, vcpu, &info) 
!= 0) {
+                               if (errno == ENOMEM) {
+                                       /* fatal error */ 
+                                       return 0;
+                               }
+                               else {
+                                       /* domain is in transition - remove
+                                          from list */
+                                       xenstat_prune_domain(node, i);
+
+                                       /* remember not to increment index! */
+                                       inc_index = 0;
+                                       break;
+                               }
+                       }
+                       else {
+                               node->domains[i].vcpus[vcpu].online = 
info.online;
+                               node->domains[i].vcpus[vcpu].ns = info.cpu_time;
+                       }
+               }
+       }
+       return 1;
+}
+
+/* Free VCPU information */
+static void xenstat_free_vcpus(xenstat_node * node)
+{
+       unsigned int i;
+       for (i = 0; i < node->num_domains; i++)
+               free(node->domains[i].vcpus);
+}
+
+/* Free VCPU information in handle - nothing to do */
+static void xenstat_uninit_vcpus(xenstat_handle * handle)
+{
+}
+
+/* Get VCPU online status */
+unsigned int xenstat_vcpu_online(xenstat_vcpu * vcpu)
+{
+       return vcpu->online;
+}
+
+/* Get VCPU usage */
+unsigned long long xenstat_vcpu_ns(xenstat_vcpu * vcpu)
+{
+       return vcpu->ns;
+}
+
+/*
+ * Network functions
+ */
+
+/* Free network information */
+static void xenstat_free_networks(xenstat_node * node)
+{
+       unsigned int i;
+       for (i = 0; i < node->num_domains; i++)
+               free(node->domains[i].networks);
+}
+
+/* Get the network ID */
+unsigned int xenstat_network_id(xenstat_network * network)
+{
+       return network->id;
+}
+
+/* Get the number of receive bytes */
+unsigned long long xenstat_network_rbytes(xenstat_network * network)
+{
+       return network->rbytes;
+}
+
+/* Get the number of receive packets */
+unsigned long long xenstat_network_rpackets(xenstat_network * network)
+{
+       return network->rpackets;
+}
+
+/* Get the number of receive errors */
+unsigned long long xenstat_network_rerrs(xenstat_network * network)
+{
+       return network->rerrs;
+}
+
+/* Get the number of receive drops */
+unsigned long long xenstat_network_rdrop(xenstat_network * network)
+{
+       return network->rdrop;
+}
+
+/* Get the number of transmit bytes */
+unsigned long long xenstat_network_tbytes(xenstat_network * network)
+{
+       return network->tbytes;
+}
+
+/* Get the number of transmit packets */
+unsigned long long xenstat_network_tpackets(xenstat_network * network)
+{
+       return network->tpackets;
+}
+
+/* Get the number of transmit errors */
+unsigned long long xenstat_network_terrs(xenstat_network * network)
+{
+       return network->terrs;
+}
+
+/* Get the number of transmit dropped packets */
+unsigned long long xenstat_network_tdrop(xenstat_network * network)
+{
+       return network->tdrop;
+}
+
+/*
+ * Xen version functions
+ */
+
+/* Collect Xen version information */
+static int xenstat_collect_xen_version(xenstat_node * node)
+{
+       long vnum = 0;
+       xen_extraversion_t version;
+
+       /* Collect Xen version information if not already collected */
+       if (node->handle->xen_version[0] == '\0') {
+               /* Get the Xen version number and extraversion string */
+               vnum = xc_version(node->handle->xc_handle,
+                       XENVER_version, NULL);
+
+               if (vnum < 0)
+                       return 0;
+
+               if (xc_version(node->handle->xc_handle, XENVER_extraversion,
+                       &version) < 0)
+                       return 0;
+               /* Format the version information as a string and store it */
+               snprintf(node->handle->xen_version, VERSION_SIZE, "%ld.%ld%s",
+                        ((vnum >> 16) & 0xFFFF), vnum & 0xFFFF, version);
+       }
+
+       return 1;
+}
+
+/* Free Xen version information in node - nothing to do */
+static void xenstat_free_xen_version(xenstat_node * node)
+{
+}
+
+/* Free Xen version information in handle - nothing to do */
+static void xenstat_uninit_xen_version(xenstat_handle * handle)
+{
+}
+
+/*
+ * VBD functions
+ */
+
+/* Save VBD information */
+xenstat_vbd *xenstat_save_vbd(xenstat_domain *domain, xenstat_vbd *vbd)
+{
+        xenstat_vbd *vbds = domain->vbds;
+
+        domain->num_vbds++;
+        domain->vbds = realloc(domain->vbds,
+                               domain->num_vbds *
+                               sizeof(xenstat_vbd));
+
+        if (domain->vbds == NULL) {
+                domain->num_vbds = 0;
+                free(vbds);
+        }
+        else {
+                domain->vbds[domain->num_vbds - 1] = *vbd;
+        }
+
+        return domain->vbds;
+}
+
+/* Free VBD information */
+static void xenstat_free_vbds(xenstat_node * node)
+{
+       unsigned int i;
+       for (i = 0; i < node->num_domains; i++)
+               free(node->domains[i].vbds);
+}
+
+/* Get the back driver type  for Virtual Block Device */
+unsigned int xenstat_vbd_type(xenstat_vbd * vbd)
+{
+       return vbd->back_type;
+}
+
+/* Get the major number of VBD device */
+unsigned int xenstat_vbd_dev(xenstat_vbd * vbd)
+{
+       return vbd->dev;
+}
+
+/* Get the number of OO(Out of) requests */
+unsigned long long xenstat_vbd_oo_reqs(xenstat_vbd * vbd)
+{
+       return vbd->oo_reqs;
+}
+
+/* Get the number of READ requests */
+unsigned long long xenstat_vbd_rd_reqs(xenstat_vbd * vbd)
+{
+       return vbd->rd_reqs;
+}
+
+/* Get the number of WRITE requests */
+unsigned long long xenstat_vbd_wr_reqs(xenstat_vbd * vbd)
+{
+       return vbd->wr_reqs;
+}
+
+/* Get the number of READ sectors */
+unsigned long long xenstat_vbd_rd_sects(xenstat_vbd * vbd)
+{
+       return vbd->rd_sects;
+}
+
+/* Get the number of WRITE sectors */
+unsigned long long xenstat_vbd_wr_sects(xenstat_vbd * vbd)
+{
+       return vbd->wr_sects;
+}
+
+/* Returns error while getting stats (1 if error happened, 0 otherwise) */
+bool xenstat_vbd_error(xenstat_vbd * vbd)
+{
+       return vbd->error;
+}
+
+static char *xenstat_get_domain_name(xenstat_handle *handle, unsigned int 
domain_id)
+{
+       char path[80];
+
+       snprintf(path, sizeof(path),"/local/domain/%i/name", domain_id);
+
+       return xs_read(handle->xshandle, XBT_NULL, path, NULL);
+}
+
+/* Remove specified entry from list of domains */
+static void xenstat_prune_domain(xenstat_node *node, unsigned int entry)
+{
+       /* nothing to do if array is empty or entry is beyond end */
+       if (node->num_domains == 0 || entry >= node->num_domains)
+               return;
+
+       /* decrement count of domains */
+       node->num_domains--;
+
+       /* shift entries following specified entry up by one */
+       if (entry < node->num_domains) {
+               xenstat_domain *domain = &node->domains[entry];
+               memmove(domain,domain+1,(node->num_domains - entry) * 
sizeof(xenstat_domain) );
+       }
+
+       /* zero out original last entry from node -- not
+          strictly necessary but safer! */
+       memset(&node->domains[node->num_domains], 0, sizeof(xenstat_domain)); 
+}
diff --git a/tools/libs/stat/xenstat_freebsd.c 
b/tools/libs/stat/xenstat_freebsd.c
new file mode 100644
index 0000000000..0c488dffac
--- /dev/null
+++ b/tools/libs/stat/xenstat_freebsd.c
@@ -0,0 +1,47 @@
+/* libxenstat: statistics-collection library for Xen
+ * Copyright (C) International Business Machines Corp., 2005
+ * Authors: Josh Triplett <josht@xxxxxxxxxx>
+ *          Judy Fischbach <jfisch@xxxxxxxxxx>
+ *          David Hendricks <dhendrix@xxxxxxxxxx>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ */
+
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#include "xenstat_priv.h"
+
+/* Collect information about networks */
+int xenstat_collect_networks(xenstat_node * node)
+{
+
+       return 1;
+}
+
+/* Free network information in handle */
+void xenstat_uninit_networks(xenstat_handle * handle)
+{
+}
+
+/* Collect information about VBDs */
+int xenstat_collect_vbds(xenstat_node * node)
+{
+
+       return 1;
+}
+
+/* Free VBD information in handle */
+void xenstat_uninit_vbds(xenstat_handle * handle)
+{
+}
diff --git a/tools/libs/stat/xenstat_linux.c b/tools/libs/stat/xenstat_linux.c
new file mode 100644
index 0000000000..793263f2b6
--- /dev/null
+++ b/tools/libs/stat/xenstat_linux.c
@@ -0,0 +1,496 @@
+/* libxenstat: statistics-collection library for Xen
+ * Copyright (C) International Business Machines Corp., 2005
+ * Authors: Josh Triplett <josh@xxxxxxxxxx>
+ *          Judy Fischbach <jfisch@xxxxxxxxxx>
+ *          David Hendricks <cro_marmot@xxxxxxxxxxx>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ */
+
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#include <fcntl.h>
+#include <dirent.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <regex.h>
+
+#include "xenstat_priv.h"
+
+#define SYSFS_VBD_PATH "/sys/bus/xen-backend/devices"
+
+struct priv_data {
+       FILE *procnetdev;
+       DIR *sysfsvbd;
+};
+
+static struct priv_data *
+get_priv_data(xenstat_handle *handle)
+{
+       if (handle->priv != NULL)
+               return handle->priv;
+
+       handle->priv = malloc(sizeof(struct priv_data));
+       if (handle->priv == NULL)
+               return (NULL);
+
+       ((struct priv_data *)handle->priv)->procnetdev = NULL;
+       ((struct priv_data *)handle->priv)->sysfsvbd = NULL;
+
+       return handle->priv;
+}
+
+/* Expected format of /proc/net/dev */
+static const char PROCNETDEV_HEADER[] =
+    "Inter-|   Receive                                                |"
+    "  Transmit\n"
+    " face |bytes    packets errs drop fifo frame compressed multicast|"
+    "bytes    packets errs drop fifo colls carrier compressed\n";
+
+/* We need to get the name of the bridge interface for use with bonding 
interfaces */
+/* Use excludeName parameter to avoid adding bridges we don't care about, eg. 
virbr0 */
+static void getBridge(char *excludeName, char *result, size_t resultLen)
+{
+       struct dirent *de;
+       DIR *d;
+
+       char tmp[512] = { 0 };
+
+       d = opendir("/sys/class/net");
+       while ((de = readdir(d)) != NULL) {
+               if ((strlen(de->d_name) > 0) && (de->d_name[0] != '.')
+                       && (strstr(de->d_name, excludeName) == NULL)) {
+                               sprintf(tmp, "/sys/class/net/%s/bridge", 
de->d_name);
+
+                               if (access(tmp, F_OK) == 0) {
+                                       strncpy(result, de->d_name, resultLen - 
1);
+                                       result[resultLen - 1] = 0;
+                               }
+               }
+       }
+
+       closedir(d);
+}
+
+/* parseNetLine provides regular expression based parsing for lines from 
/proc/net/dev, all the */
+/* information are parsed but not all are used in our case, ie. for xenstat */
+static int parseNetDevLine(char *line, char *iface, unsigned long long 
*rxBytes, unsigned long long *rxPackets,
+               unsigned long long *rxErrs, unsigned long long *rxDrops, 
unsigned long long *rxFifo,
+               unsigned long long *rxFrames, unsigned long long *rxComp, 
unsigned long long *rxMcast,
+               unsigned long long *txBytes, unsigned long long *txPackets, 
unsigned long long *txErrs,
+               unsigned long long *txDrops, unsigned long long *txFifo, 
unsigned long long *txColls,
+               unsigned long long *txCarrier, unsigned long long *txComp)
+{
+       /* Temporary/helper variables */
+       int ret;
+       char *tmp;
+       int i = 0, x = 0, col = 0;
+       regex_t r;
+       regmatch_t matches[19];
+       int num = 19;
+
+       /* Regular exception to parse all the information from /proc/net/dev 
line */
+       char *regex = "([^:]*):([^ ]*)[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ 
]*)[ ]*([^ ]*)"
+                       "[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ 
]*)[ ]*([^ ]*)[ ]*"
+                       "([^ ]*)[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ ]*)[ ]*([^ ]*)";
+
+       /* Initialize all variables called has passed as non-NULL to zeros */
+       if (iface != NULL)
+               memset(iface, 0, sizeof(*iface));
+       if (rxBytes != NULL)
+               *rxBytes = 0;
+       if (rxPackets != NULL)
+               *rxPackets = 0;
+       if (rxErrs != NULL)
+               *rxErrs = 0;
+       if (rxDrops != NULL)
+               *rxDrops = 0;
+       if (rxFifo != NULL)
+               *rxFifo = 0;
+       if (rxFrames != NULL)
+               *rxFrames = 0;
+       if (rxPackets != NULL)
+               *rxPackets = 0;
+       if (rxComp != NULL)
+               *rxComp = 0;
+       if (txBytes != NULL)
+               *txBytes = 0;
+       if (txPackets != NULL)
+               *txPackets = 0;
+       if (txErrs != NULL)
+               *txErrs = 0;
+       if (txDrops != NULL)
+               *txDrops = 0;
+       if (txFifo != NULL)
+               *txFifo = 0;
+       if (txColls != NULL)
+               *txColls = 0;
+       if (txCarrier != NULL)
+               *txCarrier = 0;
+       if (txComp != NULL)
+               *txComp = 0;
+
+       if ((ret = regcomp(&r, regex, REG_EXTENDED))) {
+               regfree(&r);
+               return ret;
+       }
+
+       tmp = (char *)malloc( sizeof(char) );
+       if (regexec (&r, line, num, matches, REG_EXTENDED) == 0){
+               for (i = 1; i < num; i++) {
+                       /* The expression matches are empty sometimes so we 
need to check it first */
+                       if (matches[i].rm_eo - matches[i].rm_so > 0) {
+                               /* Col variable contains current id of 
non-empty match */
+                               col++;
+                               tmp = (char *)realloc(tmp, (matches[i].rm_eo - 
+                                                       matches[i].rm_so + 1) * 
sizeof(char));
+                               for (x = matches[i].rm_so; x < 
matches[i].rm_eo; x++)
+                                       tmp[x - matches[i].rm_so] = line[x];
+
+                               /* We populate all the fields from 
/proc/net/dev line */
+                               if (i > 1) {
+                                       unsigned long long ullTmp = 
strtoull(tmp, NULL, 10);
+
+                                       switch (col) {
+                                               case 2: if (rxBytes != NULL)
+                                                               *rxBytes = 
ullTmp;
+                                                       break;
+                                               case 3: if (rxPackets != NULL)
+                                                               *rxPackets = 
ullTmp;
+                                                       break;
+                                               case 4: if (rxErrs != NULL)
+                                                               *rxErrs = 
ullTmp;
+                                                       break;
+                                               case 5: if (rxDrops != NULL)
+                                                               *rxDrops = 
ullTmp;
+                                                       break;
+                                               case 6: if (rxFifo != NULL)
+                                                               *rxFifo = 
ullTmp;
+                                                       break;
+                                               case 7: if (rxFrames != NULL)
+                                                               *rxFrames = 
ullTmp;
+                                                       break;
+                                               case 8: if (rxComp != NULL)
+                                                               *rxComp = 
ullTmp;
+                                                       break;
+                                               case 9: if (rxMcast != NULL)
+                                                               *rxMcast = 
ullTmp;
+                                                       break;
+                                               case 10: if (txBytes != NULL)
+                                                               *txBytes = 
ullTmp;
+                                                       break;
+                                               case 11: if (txPackets != NULL)
+                                                               *txPackets = 
ullTmp;
+                                                       break;
+                                               case 12: if (txErrs != NULL)
+                                                               *txErrs = 
ullTmp;
+                                                       break;
+                                               case 13: if (txDrops != NULL)
+                                                               *txDrops = 
ullTmp;
+                                                       break;
+                                               case 14: if (txFifo != NULL)
+                                                               *txFifo = 
ullTmp;
+                                                       break;
+                                               case 15: if (txColls != NULL)
+                                                               *txColls = 
ullTmp;
+                                                       break;
+                                               case 16: if (txCarrier != NULL)
+                                                               *txCarrier = 
ullTmp;
+                                                       break;
+                                               case 17: if (txComp != NULL)
+                                                               *txComp = 
ullTmp;
+                                                       break;
+                                       }
+                               }
+                               else
+                               /* There were errors when parsing this directly 
in RE. strpbrk() helps */
+                               if (iface != NULL) {
+                                       char *tmp2 = strpbrk(tmp, 
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
+                                       if (tmp2 != NULL)
+                                               strcpy(iface, tmp2);
+                               }
+
+                               memset(tmp, 0, matches[i].rm_eo - 
matches[i].rm_so);
+                       }
+               }
+       }
+
+       free(tmp);
+       regfree(&r);
+
+       return 0;
+}
+
+/* Find out the domid and network number given an interface name.
+ * Return 0 if the iface cannot be recognized as a Xen VIF. */
+static int get_iface_domid_network(const char *iface, unsigned int *domid_p, 
unsigned int *netid_p)
+{
+       char nodename_path[48];
+       FILE * nodename_file;
+       int ret;
+
+       snprintf(nodename_path, 48, "/sys/class/net/%s/device/nodename", iface);
+       nodename_file = fopen(nodename_path, "r");
+       if (nodename_file != NULL) {
+               ret = fscanf(nodename_file, "backend/vif/%u/%u", domid_p, 
netid_p);
+               fclose(nodename_file);
+               if (ret == 2)
+                       return 1;
+       }
+
+       if (sscanf(iface, "vif%u.%u", domid_p, netid_p) == 2)
+               return 1;
+
+       return 0;
+}
+
+/* Collect information about networks */
+int xenstat_collect_networks(xenstat_node * node)
+{
+       /* Helper variables for parseNetDevLine() function defined above */
+       int i;
+       char line[512] = { 0 }, iface[16] = { 0 }, devBridge[16] = { 0 }, 
devNoBridge[17] = { 0 };
+       unsigned long long rxBytes, rxPackets, rxErrs, rxDrops, txBytes, 
txPackets, txErrs, txDrops;
+
+       struct priv_data *priv = get_priv_data(node->handle);
+
+       if (priv == NULL) {
+               perror("Allocation error");
+               return 0;
+       }
+
+       /* Open and validate /proc/net/dev if we haven't already */
+       if (priv->procnetdev == NULL) {
+               char header[sizeof(PROCNETDEV_HEADER)];
+               priv->procnetdev = fopen("/proc/net/dev", "r");
+               if (priv->procnetdev == NULL) {
+                       perror("Error opening /proc/net/dev");
+                       return 0;
+               }
+
+               /* Validate the format of /proc/net/dev */
+               if (fread(header, sizeof(PROCNETDEV_HEADER) - 1, 1,
+                         priv->procnetdev) != 1) {
+                       perror("Error reading /proc/net/dev header");
+                       return 0;
+               }
+               header[sizeof(PROCNETDEV_HEADER) - 1] = '\0';
+               if (strcmp(header, PROCNETDEV_HEADER) != 0) {
+                       fprintf(stderr,
+                               "Unexpected /proc/net/dev format\n");
+                       return 0;
+               }
+       }
+
+       /* Fill in networks */
+       /* FIXME: optimize this */
+       fseek(priv->procnetdev, sizeof(PROCNETDEV_HEADER) - 1,
+             SEEK_SET);
+
+       /* We get the bridge devices for use with bonding interface to get 
bonding interface stats */
+       getBridge("vir", devBridge, sizeof(devBridge));
+       snprintf(devNoBridge, sizeof(devNoBridge), "p%s", devBridge);
+
+       while (fgets(line, 512, priv->procnetdev)) {
+               xenstat_domain *domain;
+               xenstat_network net;
+               unsigned int domid;
+
+               parseNetDevLine(line, iface, &rxBytes, &rxPackets, &rxErrs, 
&rxDrops, NULL, NULL, NULL,
+                               NULL, &txBytes, &txPackets, &txErrs, &txDrops, 
NULL, NULL, NULL, NULL);
+
+               /* If the device parsed is network bridge and both tx & rx 
packets are zero, we are most */
+               /* likely using bonding so we alter the configuration for dom0 
to have bridge stats */
+               if ((strstr(iface, devBridge) != NULL) &&
+                   (strstr(iface, devNoBridge) == NULL) &&
+                   ((domain = xenstat_node_domain(node, 0)) != NULL)) {
+                       for (i = 0; i < domain->num_networks; i++) {
+                               if ((domain->networks[i].id != 0) ||
+                                   (domain->networks[i].tbytes != 0) ||
+                                   (domain->networks[i].rbytes != 0))
+                                       continue;
+                               domain->networks[i].tbytes = txBytes;
+                               domain->networks[i].tpackets = txPackets;
+                               domain->networks[i].terrs = txErrs;
+                               domain->networks[i].tdrop = txDrops;
+                               domain->networks[i].rbytes = rxBytes;
+                               domain->networks[i].rpackets = rxPackets;
+                               domain->networks[i].rerrs = rxErrs;
+                               domain->networks[i].rdrop = rxDrops;
+                       }
+               }
+               else /* Otherwise we need to preserve old behaviour */
+               if (get_iface_domid_network(iface, &domid, &net.id)) {
+
+                       net.tbytes = txBytes;
+                       net.tpackets = txPackets;
+                       net.terrs = txErrs;
+                       net.tdrop = txDrops;
+                       net.rbytes = rxBytes;
+                       net.rpackets = rxPackets;
+                       net.rerrs = rxErrs;
+                       net.rdrop = rxDrops;
+
+               /* FIXME: this does a search for the domid */
+                 domain = xenstat_node_domain(node, domid);
+                 if (domain == NULL) {
+                       fprintf(stderr,
+                               "Found interface vif%u.%u but domain %u"
+                               " does not exist.\n", domid, net.id,
+                               domid);
+                       continue;
+                 }
+                 if (domain->networks == NULL) {
+                       domain->num_networks = 1;
+                       domain->networks = malloc(sizeof(xenstat_network));
+                 } else {
+                       struct xenstat_network *tmp;
+                       domain->num_networks++;
+                       tmp = realloc(domain->networks,
+                                     domain->num_networks *
+                                     sizeof(xenstat_network));
+                       if (tmp == NULL)
+                               free(domain->networks);
+                       domain->networks = tmp;
+                 }
+                 if (domain->networks == NULL)
+                       return 0;
+                 domain->networks[domain->num_networks - 1] = net;
+          }
+        }
+
+       return 1;
+}
+
+/* Free network information in handle */
+void xenstat_uninit_networks(xenstat_handle * handle)
+{
+       struct priv_data *priv = get_priv_data(handle);
+       if (priv != NULL && priv->procnetdev != NULL)
+               fclose(priv->procnetdev);
+}
+
+static int read_attributes_vbd(const char *vbd_directory, const char *what, 
char *ret, int cap)
+{
+       static char file_name[80];
+       int fd, num_read;
+
+       snprintf(file_name, sizeof(file_name), "%s/%s/%s",
+               SYSFS_VBD_PATH, vbd_directory, what);
+       fd = open(file_name, O_RDONLY, 0);
+       if (fd==-1) return -1;
+       num_read = read(fd, ret, cap - 1);
+       close(fd);
+       if (num_read<=0) return -1;
+       ret[num_read] = '\0';
+       return num_read;
+}
+
+/* Collect information about VBDs */
+int xenstat_collect_vbds(xenstat_node * node)
+{
+       struct dirent *dp;
+       struct priv_data *priv = get_priv_data(node->handle);
+
+       if (priv == NULL) {
+               perror("Allocation error");
+               return 0;
+       }
+
+       if (priv->sysfsvbd == NULL) {
+               priv->sysfsvbd = opendir(SYSFS_VBD_PATH);
+               if (priv->sysfsvbd == NULL) {
+                       perror("Error opening " SYSFS_VBD_PATH);
+                       return 0;
+               }
+       }
+
+       /* Get qdisk statistics */
+       read_attributes_qdisk(node);
+
+       rewinddir(priv->sysfsvbd);
+
+       for(dp = readdir(priv->sysfsvbd); dp != NULL ;
+           dp = readdir(priv->sysfsvbd)) {
+               xenstat_domain *domain;
+               xenstat_vbd vbd;
+               unsigned int domid;
+               int ret;
+               char buf[256];
+
+               ret = sscanf(dp->d_name, "%3s-%u-%u", buf, &domid, &vbd.dev);
+               if (ret != 3)
+                       continue;
+               if (!(strstr(buf, "vbd")) && !(strstr(buf, "tap")))
+                       continue;
+
+               if (strcmp(buf,"vbd") == 0)
+                       vbd.back_type = 1;
+               else if (strcmp(buf,"tap") == 0)
+                       vbd.back_type = 2;
+               else
+                       vbd.back_type = 0;
+
+               domain = xenstat_node_domain(node, domid);
+               if (domain == NULL) {
+                       fprintf(stderr,
+                               "Found interface %s-%u-%u but domain %u"
+                               " does not exist.\n",
+                               buf, domid, vbd.dev, domid);
+                       continue;
+               }
+
+               if (vbd.back_type == 1 || vbd.back_type == 2)
+               {
+
+                       vbd.error = 0;
+
+                       if ((read_attributes_vbd(dp->d_name, 
"statistics/oo_req", buf, 256)<=0) ||
+                               ((ret = sscanf(buf, "%llu", &vbd.oo_reqs)) != 
1) ||
+                               (read_attributes_vbd(dp->d_name, 
"statistics/rd_req", buf, 256)<=0) ||
+                               ((ret = sscanf(buf, "%llu", &vbd.rd_reqs)) != 
1) ||
+                               (read_attributes_vbd(dp->d_name, 
"statistics/wr_req", buf, 256)<=0) ||
+                               ((ret = sscanf(buf, "%llu", &vbd.wr_reqs)) != 
1) ||
+                               (read_attributes_vbd(dp->d_name, 
"statistics/rd_sect", buf, 256)<=0) ||
+                               ((ret = sscanf(buf, "%llu", &vbd.wr_sects)) != 
1) ||
+                               (read_attributes_vbd(dp->d_name, 
"statistics/wr_sect", buf, 256)<=0) ||
+                               ((ret = sscanf(buf, "%llu", &vbd.wr_sects)) != 
1))
+                       {
+                               vbd.error = 1;
+                       }
+               }
+               else
+               {
+                       vbd.error = 1;
+               }
+               if ((xenstat_save_vbd(domain, &vbd)) == NULL) {
+                       perror("Allocation error");
+                       return 0;
+               }
+       }
+
+       return 1;       
+}
+
+/* Free VBD information in handle */
+void xenstat_uninit_vbds(xenstat_handle * handle)
+{
+       struct priv_data *priv = get_priv_data(handle);
+       if (priv != NULL && priv->sysfsvbd != NULL)
+               closedir(priv->sysfsvbd);
+}
diff --git a/tools/libs/stat/xenstat_netbsd.c b/tools/libs/stat/xenstat_netbsd.c
new file mode 100644
index 0000000000..6e9d6aee10
--- /dev/null
+++ b/tools/libs/stat/xenstat_netbsd.c
@@ -0,0 +1,97 @@
+/* libxenstat: statistics-collection library for Xen
+ * Copyright (C) International Business Machines Corp., 2005
+ * Authors: Josh Triplett <josht@xxxxxxxxxx>
+ *          Judy Fischbach <jfisch@xxxxxxxxxx>
+ *          David Hendricks <dhendrix@xxxxxxxxxx>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ */
+
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#include <fcntl.h>
+#include <dirent.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "xenstat_priv.h"
+
+#define SYSFS_VBD_PATH "/sys/devices/xen-backend/"
+
+struct priv_data {
+       FILE *procnetdev;
+       DIR *sysfsvbd;
+};
+
+static struct priv_data *
+get_priv_data(xenstat_handle *handle)
+{
+       if (handle->priv != NULL)
+               return handle->priv;
+
+       handle->priv = malloc(sizeof(struct priv_data));
+       if (handle->priv == NULL)
+               return (NULL);
+
+       ((struct priv_data *)handle->priv)->procnetdev = NULL;
+       ((struct priv_data *)handle->priv)->sysfsvbd = NULL;
+
+       return handle->priv;
+}
+
+/* Expected format of /proc/net/dev */
+static const char PROCNETDEV_HEADER[] =
+    "Inter-|   Receive                                                |"
+    "  Transmit\n"
+    " face |bytes    packets errs drop fifo frame compressed multicast|"
+    "bytes    packets errs drop fifo colls carrier compressed\n";
+
+/* Collect information about networks */
+int xenstat_collect_networks(xenstat_node * node)
+{
+       /* XXX fixme: implement code to get stats from libkvm ! */
+       return 1;
+}
+
+/* Free network information in handle */
+void xenstat_uninit_networks(xenstat_handle * handle)
+{
+       struct priv_data *priv = get_priv_data(handle);
+       if (priv != NULL && priv->procnetdev != NULL)
+               fclose(priv->procnetdev);
+}
+
+static int read_attributes_vbd(const char *vbd_directory, const char *what, 
char *ret, int cap)
+{
+       /* XXX implement */
+       return 0;
+}
+
+/* Collect information about VBDs */
+int xenstat_collect_vbds(xenstat_node * node)
+{
+       return 1;       
+}
+
+/* Free VBD information in handle */
+void xenstat_uninit_vbds(xenstat_handle * handle)
+{
+       struct priv_data *priv = get_priv_data(handle);
+       if (priv != NULL && priv->sysfsvbd != NULL)
+               closedir(priv->sysfsvbd);
+}
diff --git a/tools/libs/stat/xenstat_priv.h b/tools/libs/stat/xenstat_priv.h
new file mode 100644
index 0000000000..4eb44a8ebb
--- /dev/null
+++ b/tools/libs/stat/xenstat_priv.h
@@ -0,0 +1,108 @@
+/* libxenstat: statistics-collection library for Xen
+ * Copyright (C) International Business Machines Corp., 2005
+ * Authors: Josh Triplett <josh@xxxxxxxxxx>
+ *          Judy Fischbach <jfisch@xxxxxxxxxx>
+ *          David Hendricks <cro_marmot@xxxxxxxxxxx>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ */
+
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#ifndef XENSTAT_PRIV_H
+#define XENSTAT_PRIV_H
+
+#include <sys/types.h>
+#include <xenstore.h>
+#include "xenstat.h"
+
+#include "xenctrl.h"
+
+#define SHORT_ASC_LEN 5                 /* length of 65535 */
+#define VERSION_SIZE (2 * SHORT_ASC_LEN + 1 + sizeof(xen_extraversion_t) + 1)
+
+struct xenstat_handle {
+       xc_interface *xc_handle;
+       struct xs_handle *xshandle; /* xenstore handle */
+       int page_size;
+       void *priv;
+       char xen_version[VERSION_SIZE]; /* xen version running on this node */
+};
+
+struct xenstat_node {
+       xenstat_handle *handle;
+       unsigned int flags;
+       unsigned long long cpu_hz;
+       unsigned int num_cpus;
+       unsigned long long tot_mem;
+       unsigned long long free_mem;
+       unsigned int num_domains;
+       xenstat_domain *domains;        /* Array of length num_domains */
+       long freeable_mb;
+};
+
+struct xenstat_domain {
+       unsigned int id;
+       char *name;
+       unsigned int state;
+       unsigned long long cpu_ns;
+       unsigned int num_vcpus;         /* No. vcpus configured for domain */
+       xenstat_vcpu *vcpus;            /* Array of length num_vcpus */
+       unsigned long long cur_mem;     /* Current memory reservation */
+       unsigned long long max_mem;     /* Total memory allowed */
+       unsigned int ssid;
+       unsigned int num_networks;
+       xenstat_network *networks;      /* Array of length num_networks */
+       unsigned int num_vbds;
+       xenstat_vbd *vbds;
+};
+
+struct xenstat_vcpu {
+       unsigned int online;
+       unsigned long long ns;
+};
+
+struct xenstat_network {
+       unsigned int id;
+       /* Received */
+       unsigned long long rbytes;
+       unsigned long long rpackets;
+       unsigned long long rerrs;
+       unsigned long long rdrop;
+       /* Transmitted */
+       unsigned long long tbytes;
+       unsigned long long tpackets;
+       unsigned long long terrs;
+       unsigned long long tdrop;
+};
+
+struct xenstat_vbd {
+       unsigned int back_type;
+       unsigned int dev;
+       unsigned int error;
+       unsigned long long oo_reqs;
+       unsigned long long rd_reqs;
+       unsigned long long wr_reqs;
+       unsigned long long rd_sects;
+       unsigned long long wr_sects;
+};
+
+extern int xenstat_collect_networks(xenstat_node * node);
+extern void xenstat_uninit_networks(xenstat_handle * handle);
+extern int xenstat_collect_vbds(xenstat_node * node);
+extern void xenstat_uninit_vbds(xenstat_handle * handle);
+extern void read_attributes_qdisk(xenstat_node * node);
+extern xenstat_vbd *xenstat_save_vbd(xenstat_domain * domain, xenstat_vbd * 
vbd);
+
+#endif /* XENSTAT_PRIV_H */
diff --git a/tools/libs/stat/xenstat_qmp.c b/tools/libs/stat/xenstat_qmp.c
new file mode 100644
index 0000000000..19b236e7b6
--- /dev/null
+++ b/tools/libs/stat/xenstat_qmp.c
@@ -0,0 +1,446 @@
+/* libxenstat: statistics-collection library for Xen
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ */
+
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <poll.h>
+#include <sys/un.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <xenctrl.h>
+
+#include "xenstat_priv.h"
+#include "_paths.h"
+
+#ifdef HAVE_YAJL_YAJL_VERSION_H
+#  include <yajl/yajl_version.h>
+#endif
+
+/* YAJL version check */
+#if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1)
+#  define HAVE_YAJL_V2 1
+#endif
+
+#ifdef HAVE_YAJL_V2
+
+#include <yajl/yajl_tree.h>
+
+static unsigned char *qmp_query(int, char *);
+
+enum query_blockstats {
+    QMP_STATS_RETURN  = 0,
+    QMP_STATS_DEVICE  = 1,
+    QMP_STATS         = 2,
+    QMP_RD_BYTES      = 3,
+    QMP_WR_BYTES      = 4,
+    QMP_RD_OPERATIONS = 5,
+    QMP_WR_OPERATIONS = 6,
+};
+
+enum query_block {
+    QMP_BLOCK_RETURN  = 0,
+    QMP_BLOCK_DEVICE  = 1,
+    QMP_INSERTED      = 2,
+    QMP_FILE          = 3,
+};
+
+
+/* Given the qmp device name, get the image filename associated with it
+   QMP Syntax for querying block information:
+     In: { "execute": "query-block" }
+     Out: {"return": [{
+            "device": 'str, "locked": 'bool', "removable": bool,
+            "inserted": {
+              "iops_rd": 'int',
+              "image": {
+                "virtual-size": 'int', "filename": 'str', "cluster-size": 
'int',
+                "format": 'str', "actual-size": 'int', "dirty-flag": 'bool'
+              },
+              "iops_wr": 'int', "ro": 'bool', "backing_file_depth": 'int',
+              "drv": 'str', "iops": 'int', "bps_wr": 'int', "encrypted": 
'bool',
+              "bps": 'int', "bps_rd": 'int',
+              "file": 'str', "encryption_key_missing": 'bool'
+            },
+            "type": 'str'
+          }]}
+*/
+static char *qmp_get_block_image(xenstat_node *node, char *qmp_devname, int 
qfd)
+{
+       char *tmp, *file = NULL;
+       char *query_block_cmd = "{ \"execute\": \"query-block\" }";
+       static const char *const qblock[] = {
+               [ QMP_BLOCK_RETURN  ] = "return",
+               [ QMP_BLOCK_DEVICE  ] = "device",
+               [ QMP_INSERTED      ] = "inserted",
+               [ QMP_FILE          ] = "file",
+       };
+       const char *ptr[] = {0, 0};
+       unsigned char *qmp_stats;
+       yajl_val info, ret_obj, dev_obj, n;
+       int i;
+
+       if ((qmp_stats = qmp_query(qfd, query_block_cmd)) == NULL)
+               return NULL;
+
+       /* Use libyajl version 2.0.3 or newer for the tree parser feature with 
bug fixes */
+       info = yajl_tree_parse((char *)qmp_stats, NULL, 0);
+       free(qmp_stats);
+       if (info == NULL)
+               return NULL;
+
+       ptr[0] = qblock[QMP_BLOCK_RETURN]; /* "return" */
+       if ((ret_obj = yajl_tree_get(info, ptr, yajl_t_array)) == NULL)
+               goto done;
+
+       for (i=0; i<YAJL_GET_ARRAY(ret_obj)->len; i++) {
+               n = YAJL_GET_ARRAY(ret_obj)->values[i];
+
+               ptr[0] = qblock[QMP_BLOCK_DEVICE]; /* "device" */
+               if ((dev_obj = yajl_tree_get(n, ptr, yajl_t_any)) != NULL) {
+                       tmp = YAJL_GET_STRING(dev_obj);
+                       if (!tmp || strcmp(qmp_devname, tmp))
+                               continue;
+               }
+               else
+                       continue;
+
+               ptr[0] = qblock[QMP_INSERTED]; /* "inserted" */
+               n = yajl_tree_get(n, ptr, yajl_t_any);
+               if (n) {
+                       ptr[0] = qblock[QMP_FILE]; /* "file" */
+                       n = yajl_tree_get(n, ptr, yajl_t_any);
+                       if (n && YAJL_IS_STRING(n)) {
+                               tmp = YAJL_GET_STRING(n);
+                               file = malloc(strlen(tmp)+1);
+                               if (file != NULL)
+                                       strcpy(file, tmp);
+                               goto done;
+                       }
+               }
+       }
+done:
+       yajl_tree_free(info);
+       return file;
+}
+
+
+/* Given a QMP device name, lookup the associated xenstore qdisk device id */
+static void lookup_xenstore_devid(xenstat_node * node, unsigned int domid, 
char *qmp_devname,
+       int qfd, unsigned int *dev, unsigned int *sector_size)
+{
+       char **dev_ids, *tmp, *ptr, *image, path[80];
+       unsigned int num_dev_ids;
+       int i, devid;
+
+       /* Get all the qdisk dev IDs associated with the this VM */
+       snprintf(path, sizeof(path),"/local/domain/0/backend/qdisk/%i", domid);
+       dev_ids = xs_directory(node->handle->xshandle, XBT_NULL, path, 
&num_dev_ids);
+       if (dev_ids == NULL) {
+               return;
+       }
+
+       /* Get the filename of the image associated with this QMP device */
+       image = qmp_get_block_image(node, qmp_devname, qfd);
+       if (image == NULL) {
+               free(dev_ids);
+               return;
+       }
+
+       /* Look for a matching image in xenstore */
+       for (i=0; i<num_dev_ids; i++) {
+               devid = atoi(dev_ids[i]);
+               /* Get the xenstore name of the image */
+               snprintf(path, 
sizeof(path),"/local/domain/0/backend/qdisk/%i/%i/params", domid, devid);
+               if ((ptr = xs_read(node->handle->xshandle, XBT_NULL, path, 
NULL)) == NULL)
+                       continue;
+
+               /* Get to actual path in string */
+               if ((tmp = strchr(ptr, '/')) == NULL)
+                       tmp = ptr;
+               if (!strcmp(tmp,image)) {
+                       *dev = devid;
+                       free(ptr);
+
+                       /* Get the xenstore sector size of the image while 
we're here */
+                       snprintf(path, 
sizeof(path),"/local/domain/0/backend/qdisk/%i/%i/sector-size", domid, devid);
+                       if ((ptr = xs_read(node->handle->xshandle, XBT_NULL, 
path, NULL)) != NULL) {
+                               *sector_size = atoi((char *)ptr);
+                               free(ptr);
+                       }
+                       break;
+               }
+               free(ptr);
+       }
+
+       free(image);
+       free(dev_ids);
+}
+
+/* Parse the stats buffer which contains I/O data for all the disks belonging 
to domid */
+static void qmp_parse_stats(xenstat_node *node, unsigned int domid, unsigned 
char *stats_buf, int qfd)
+{
+       char *qmp_devname;
+       static const char *const qstats[] = {
+               [ QMP_STATS_RETURN  ] = "return",
+               [ QMP_STATS_DEVICE  ] = "device",
+               [ QMP_STATS         ] = "stats",
+               [ QMP_RD_BYTES      ] = "rd_bytes",
+               [ QMP_WR_BYTES      ] = "wr_bytes",
+               [ QMP_RD_OPERATIONS ] = "rd_operations",
+               [ QMP_WR_OPERATIONS ] = "wr_operations",
+       };
+       const char *ptr[] = {0, 0};
+       yajl_val info, ret_obj, stats_obj, n;
+       xenstat_vbd vbd;
+       xenstat_domain *domain;
+       unsigned int sector_size = 512;
+       int i, j;
+
+       /* Use libyajl version 2.0.3 or newer for the tree parser feature */
+       if ((info = yajl_tree_parse((char *)stats_buf, NULL, 0)) == NULL)
+               return;
+
+       ptr[0] = qstats[QMP_STATS_RETURN]; /* "return" */
+       if ((ret_obj = yajl_tree_get(info, ptr, yajl_t_array)) == NULL)
+               goto done;
+
+       /* Array of devices */
+       for (i=0; i<YAJL_GET_ARRAY(ret_obj)->len; i++) {
+               memset(&vbd, 0, sizeof(xenstat_vbd));
+               qmp_devname = NULL;
+               stats_obj = YAJL_GET_ARRAY(ret_obj)->values[i];
+
+               ptr[0] = qstats[QMP_STATS_DEVICE]; /* "device" */
+               if ((n = yajl_tree_get(stats_obj, ptr, yajl_t_any)) != NULL)
+                       qmp_devname = YAJL_GET_STRING(n);
+
+               ptr[0] = qstats[QMP_STATS]; /* "stats" */
+               stats_obj = yajl_tree_get(stats_obj, ptr, yajl_t_object);
+               if (stats_obj && YAJL_IS_OBJECT(stats_obj)) {
+                       for (j=3; j<7; j++) {
+                               ptr[0] = qstats[j];
+                               n = yajl_tree_get(stats_obj, ptr, 
yajl_t_number);
+                               if (n && YAJL_IS_NUMBER(n)) {
+                                       switch(j) {
+                                       case QMP_RD_BYTES: /* "rd_bytes" */
+                                               vbd.rd_sects = 
YAJL_GET_INTEGER(n) / sector_size;
+                                               break;
+                                       case QMP_WR_BYTES: /* "wr_bytes" */
+                                               vbd.wr_sects = 
YAJL_GET_INTEGER(n) / sector_size;
+                                               break;
+                                       case QMP_RD_OPERATIONS: /* 
"rd_operations" */
+                                               vbd.rd_reqs = 
YAJL_GET_INTEGER(n);
+                                               break;
+                                       case QMP_WR_OPERATIONS: /* 
"wr_operations" */
+                                               vbd.wr_reqs = 
YAJL_GET_INTEGER(n);
+                                               break;
+                                       }
+                               }
+                       }
+                       /* With the QMP device name, lookup the xenstore qdisk 
device ID and set vdb.dev */
+                       if (qmp_devname)
+                               lookup_xenstore_devid(node, domid, qmp_devname, 
qfd, &vbd.dev, &sector_size);
+                       if ((domain = xenstat_node_domain(node, domid)) == NULL)
+                               continue;
+                       if ((xenstat_save_vbd(domain, &vbd)) == NULL)
+                               goto done;
+               }
+       }
+done:
+       yajl_tree_free(info);
+}
+
+/* Write a command via the QMP. Returns number of bytes written */
+static size_t qmp_write(int qfd, char *cmd, size_t cmd_len)
+{
+       size_t pos = 0;
+       ssize_t res;
+
+       while (cmd_len > pos) {
+               res = write(qfd, cmd + pos, cmd_len - pos);
+               switch (res) {
+               case -1:
+                       if (errno == EINTR || errno == EAGAIN)
+                               continue;
+                       return 0;
+               case 0:
+                       errno = EPIPE;
+                       return pos;
+               default:
+                       pos += (size_t)res;
+               }
+       }
+       return pos;
+}
+
+/* Read the data sent in response to a QMP execute query. Returns 1 for 
success */
+static int qmp_read(int qfd, unsigned char **qstats)
+{
+       unsigned char buf[1024], *ptr;
+       struct pollfd pfd[1];
+       int n, qsize = 0;
+
+       *qstats = NULL;
+       pfd[0].fd = qfd;
+       pfd[0].events = POLLIN;
+       while ((n = poll(pfd, 1, 10)) > 0) {
+               if (pfd[0].revents & POLLIN) {
+                       if ((n = read(qfd, buf, sizeof(buf))) < 0) {
+                               free(*qstats);
+                               return 0;
+                       }
+                       ptr = realloc(*qstats, qsize+n+1);
+                       if (ptr == NULL) {
+                               free(*qstats);
+                               return 0;
+                       }
+                       memcpy(&ptr[qsize], buf, n);
+                       qsize += n;
+                       ptr[qsize] = 0;
+                       *qstats = ptr;
+               }
+       }
+       return 1;
+}
+
+/* With the given cmd, query QMP for requested data. Returns allocated buffer 
containing data or NULL */
+static unsigned char *qmp_query(int qfd, char *cmd)
+{
+       unsigned char *qstats = NULL;
+       int n;
+
+       n = strlen(cmd);
+       if (qmp_write(qfd, cmd, n) != n)
+               return NULL;
+       if (!qmp_read(qfd, &qstats))
+               return NULL;
+       return qstats;
+}
+
+/* Returns a socket connected to the QMP socket. Returns -1 on failure. */
+static int qmp_connect(char *path)
+{
+       struct sockaddr_un sun;
+       int s;
+
+       if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
+               return -1;
+       (void)fcntl(s, F_SETFD, 1);
+
+       memset(&sun, 0, sizeof(struct sockaddr_un));
+       sun.sun_family = AF_UNIX;
+
+       if (strlen(path) >= sizeof(sun.sun_path)) {
+               close(s);
+               return -1;
+       }
+
+       strcpy(sun.sun_path, path);
+       if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
+               close(s);
+               return -1;
+       }
+
+       return s;
+}
+
+/* Gather the qdisk statistics by querying QMP
+   Resources: http://wiki.qemu.org/QMP and qmp-commands.hx from the qemu code
+   QMP Syntax for entering command mode. This command must be issued before
+   issuing any other command:
+     In: {"execute": "qmp_capabilities"}
+     Out: {"return": {}}
+   QMP Syntax for querying block statistics:
+     In: { "execute": "query-blockstats" }
+     Out: {"return": [{
+            "device": 'str',
+            "parent": {
+              "stats": {
+                "flush_total_time_ns": 'int', "wr_highest_offset": 'int',
+                "wr_total_time_ns": 'int', "wr_bytes": 'int',
+                "rd_total_time_ns": 'int', "flush_operations": 'int',
+                "wr_operations": 'int', "rd_bytes": 'int', "rd_operations": 
'int'
+              }
+            },
+            "stats": {
+              "flush_total_time_ns": 'int', "wr_highest_offset": 'int',
+              "wr_total_time_ns": 'int', "wr_bytes": 'int',
+              "rd_total_time_ns": 'int', "flush_operations": 'int',
+              "wr_operations": 'int', "rd_bytes": 'int', "rd_operations": 'int'
+            }
+          }]}
+*/
+static void read_attributes_qdisk_dom(xenstat_node *node, domid_t domain)
+{
+       char *cmd_mode = "{ \"execute\": \"qmp_capabilities\" }";
+       char *query_blockstats_cmd = "{ \"execute\": \"query-blockstats\" }";
+       unsigned char *qmp_stats, *val;
+       char path[80];
+       int qfd;
+
+       /* Verify that qdisk disks are used with this VM */
+       snprintf(path, sizeof(path),"/local/domain/0/backend/qdisk/%i", domain);
+       val = xs_read(node->handle->xshandle, XBT_NULL, path, NULL);
+       if (val == NULL)
+               return;
+       free(val);
+
+       /* Connect to this VMs QMP socket */
+       snprintf(path, sizeof(path), XEN_RUN_DIR "/qmp-libxenstat-%i", domain);
+       if ((qfd = qmp_connect(path)) < 0)
+               return;
+
+       /* First enable QMP capabilities so that we can query for data */
+       if ((qmp_stats = qmp_query(qfd, cmd_mode)) != NULL) {
+               free(qmp_stats);
+               /* Query QMP for this VMs blockstats */
+               qmp_stats = qmp_query(qfd, query_blockstats_cmd);
+               if (qmp_stats != NULL) {
+                       qmp_parse_stats(node, domain, qmp_stats, qfd);
+                       free(qmp_stats);
+               }
+       }
+       close(qfd);
+}
+
+void read_attributes_qdisk(xenstat_node * node)
+{
+       xc_domaininfo_t dominfo[1024];
+       int i, num_doms;
+       domid_t next_domid = 0;
+
+       for (;;) {
+               num_doms = xc_domain_getinfolist(node->handle->xc_handle,
+                                                next_domid, 1024, dominfo);
+               if (num_doms <= 0)
+                       return;
+
+               for (i = 0; i < num_doms; i++)
+                       if (dominfo[i].domain > 0)
+                               read_attributes_qdisk_dom(node, 
dominfo[i].domain);
+
+               next_domid = dominfo[num_doms - 1].domain + 1;
+       }
+}
+
+#else /* !HAVE_YAJL_V2 */
+
+/* Statistics gathering for qdisks requires at least yajl v2 */
+void read_attributes_qdisk(xenstat_node * node)
+{
+}
+
+#endif /* !HAVE_YAJL_V2 */



 


Rackspace

Lists.xenproject.org is hosted with RackSpace, monitoring our
servers 24x7x365 and backed by RackSpace's Fanatical Support®.