Project import generated by Copybara. GitOrigin-RevId: 3752d22df69d0aa28abd56be39b45e5148adea60
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a890cee --- /dev/null +++ b/.gitignore
@@ -0,0 +1,32 @@ +*.5 +*.7 +*.8 +*.a +*.d +*.o +*.orig +*.pc +*.pot +*.pyc +*.pyo +*.rej +*.so +*.so.* +*.sw* +*~ + +.export.sym +.exported_symbols_generated +.gdb_history + +Makefile +make.tmpl + +/autom4te.cache/ +/autoscan.log +/config.log +/config.status +/configure.scan +/cscope.out +/tags +/tmp/
diff --git a/Android.mk b/Android.mk new file mode 100644 index 0000000..6e3a5b5 --- /dev/null +++ b/Android.mk
@@ -0,0 +1,56 @@ +# Copyright 2016 Google Inc. All Rights Reserved. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := libdm +LOCAL_MODULE_TAGS := optional + +LOCAL_SRC_FILES:= \ + libdm/datastruct/bitset.c \ + libdm/datastruct/hash.c \ + libdm/datastruct/list.c \ + libdm/libdm-common.c \ + libdm/libdm-config.c \ + libdm/libdm-deptree.c \ + libdm/libdm-file.c \ + libdm/libdm-report.c \ + libdm/libdm-stats.c \ + libdm/libdm-string.c \ + libdm/libdm-targets.c \ + libdm/libdm-timestamp.c \ + libdm/mm/dbg_malloc.c \ + libdm/mm/pool.c \ + libdm/regex/matcher.c \ + libdm/regex/parse_rx.c \ + libdm/regex/ttree.c \ + libdm/ioctl/libdm-iface.c + +LOCAL_C_INCLUDES += \ + $(LOCAL_PATH)/lib/misc \ + $(LOCAL_PATH)/lib/log \ + $(LOCAL_PATH)/libdm \ + $(LOCAL_PATH)/libdm/ioctl \ + $(LOCAL_PATH)/libdm/misc + +include $(BUILD_STATIC_LIBRARY) + + +include $(CLEAR_VARS) +LOCAL_MODULE := dmsetup +LOCAL_MODULE_TAGS := optional +LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT_SBIN) + +LOCAL_SRC_FILES := \ + tools/dmsetup.c + +LOCAL_C_INCLUDES += \ + $(LOCAL_PATH)/lib/misc \ + $(LOCAL_PATH)/lib/log \ + $(LOCAL_PATH)/libdm \ + $(LOCAL_PATH)/libdm/misc + +LOCAL_CFLAGS += -Wno-unused-parameter +LOCAL_STATIC_LIBRARIES := libdm + +include $(BUILD_EXECUTABLE)
diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..e54f9f4 --- /dev/null +++ b/COPYING
@@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License.
diff --git a/COPYING.LIB b/COPYING.LIB new file mode 100644 index 0000000..5ab7695 --- /dev/null +++ b/COPYING.LIB
@@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[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, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +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/INSTALL b/INSTALL new file mode 100644 index 0000000..8d0d54d --- /dev/null +++ b/INSTALL
@@ -0,0 +1,31 @@ +Installation +============ + +1) Generate custom makefiles. + + Run the 'configure' script from the top directory. + + If you don't want to include the LVM1 backwards-compatibility code use: + ./configure --with-lvm1=none + + To separate the LVM1 support into a shared library loaded by lvm.conf use: + ./configure --with-lvm1=shared + + Use ./configure --help to see other options. + +2) Build and install. + + Run 'make' from the top directory to build everything you configured. + Run 'make install' to build and install everything you configured. + + If you only want the device-mapper libraries and tools use + 'make device-mapper' or 'make install_device-mapper'. + +3) If using LVM2, create a configuration file. + + The tools will work fine without a configuration file being + present, but you ought to review the example file in doc/example.conf. + +Please also refer to the WHATS_NEW file and the manual pages for the +individual commands. +
diff --git a/MODULE_LICENSE_GPL b/MODULE_LICENSE_GPL new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/MODULE_LICENSE_GPL
diff --git a/Makefile.in b/Makefile.in new file mode 100644 index 0000000..52441f1 --- /dev/null +++ b/Makefile.in
@@ -0,0 +1,243 @@ +# +# Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. +# Copyright (C) 2004-2015 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ + +SUBDIRS = conf daemons include lib libdaemon libdm man scripts tools + +ifeq ("@UDEV_RULES@", "yes") + SUBDIRS += udev +endif + +ifeq ("@INTL@", "yes") + SUBDIRS += po +endif + +ifeq ("@APPLIB@", "yes") + SUBDIRS += liblvm +endif + +ifeq ("@PYTHON_BINDINGS@", "yes") + SUBDIRS += python +endif + +ifeq ($(MAKECMDGOALS),clean) + SUBDIRS += test +endif +# FIXME Should use intermediate Makefiles here! +ifeq ($(MAKECMDGOALS),distclean) + SUBDIRS = conf include man test scripts \ + libdaemon lib tools daemons libdm \ + udev po liblvm python \ + unit-tests/datastruct unit-tests/mm unit-tests/regex +tools.distclean: test.distclean +endif +DISTCLEAN_DIRS += lcov_reports* +DISTCLEAN_TARGETS += config.cache config.log config.status make.tmpl + +include make.tmpl + +libdm: include +libdaemon: include +lib: libdm libdaemon +liblvm: lib +daemons: lib libdaemon tools +tools: lib libdaemon device-mapper +po: tools daemons +scripts: liblvm libdm + +lib.device-mapper: include.device-mapper +libdm.device-mapper: include.device-mapper +liblvm.device-mapper: include.device-mapper +daemons.device-mapper: libdm.device-mapper +tools.device-mapper: libdm.device-mapper +scripts.device-mapper: include.device-mapper +device-mapper: tools.device-mapper daemons.device-mapper man.device-mapper + +ifeq ("@INTL@", "yes") +lib.pofile: include.pofile +tools.pofile: lib.pofile +daemons.pofile: lib.pofile +po.pofile: tools.pofile daemons.pofile +pofile: po.pofile +endif + +ifeq ("@PYTHON_BINDINGS@", "yes") +python: liblvm +endif + +ifneq ("$(CFLOW_CMD)", "") +tools.cflow: libdm.cflow lib.cflow +daemons.cflow: tools.cflow +cflow: include.cflow +endif + +ifneq ("@CSCOPE_CMD@", "") +cscope.out: + @CSCOPE_CMD@ -b -R -s$(top_srcdir) +all: cscope.out +endif +DISTCLEAN_TARGETS += cscope.out +CLEAN_DIRS += autom4te.cache + +check check_system check_cluster check_local check_lvmetad check_lvmpolld check_lvmlockd_test check_lvmlockd_dlm check_lvmlockd_sanlock unit: all + $(MAKE) -C test $(@) + +conf.generate: tools + +# how to use parenthesis in makefiles +leftparen:=( +LVM_VER := $(firstword $(subst $(leftparen), ,$(LVM_VERSION))) +VER := LVM2.$(LVM_VER) +# release file name +FILE_VER := $(VER).tgz +CLEAN_TARGETS += $(FILE_VER) +CLEAN_DIRS += $(rpmbuilddir) + +dist: + @echo "Generating $(FILE_VER)";\ + (cd $(top_srcdir); git ls-tree -r HEAD --name-only | xargs tar --transform "s,^,$(VER)/," -c) | gzip >$(FILE_VER) + +rpm: dist + $(RM) -r $(rpmbuilddir)/SOURCES + $(MKDIR_P) $(rpmbuilddir)/SOURCES + $(LN_S) -f $(abs_top_builddir)/$(FILE_VER) $(rpmbuilddir)/SOURCES + $(LN_S) -f $(abs_top_srcdir)/spec/build.inc $(rpmbuilddir)/SOURCES + $(LN_S) -f $(abs_top_srcdir)/spec/macros.inc $(rpmbuilddir)/SOURCES + $(LN_S) -f $(abs_top_srcdir)/spec/packages.inc $(rpmbuilddir)/SOURCES + DM_VER=$$(cut -d- -f1 $(top_srcdir)/VERSION_DM);\ + GIT_VER=$$(cd $(top_srcdir); git describe | cut -d- --output-delimiter=. -f2,3 || echo 0);\ + sed -e "s,\(device_mapper_version\) [0-9.]*$$,\1 $$DM_VER," \ + -e "s,^\(Version:[^0-9%]*\)[0-9.]*$$,\1 $(LVM_VER)," \ + -e "s,^\(Release:[^0-9%]*\)[0-9.]\+,\1 $$GIT_VER," \ + $(top_srcdir)/spec/source.inc >$(rpmbuilddir)/SOURCES/source.inc + rpmbuild -v --define "_topdir $(rpmbuilddir)" -ba $(top_srcdir)/spec/lvm2.spec + +generate: conf.generate + $(MAKE) -C conf generate + +all_man: + $(MAKE) -C man all_man + +install_system_dirs: + $(INSTALL_DIR) $(DESTDIR)$(DEFAULT_SYS_DIR) + $(INSTALL_ROOT_DIR) $(DESTDIR)$(DEFAULT_ARCHIVE_DIR) + $(INSTALL_ROOT_DIR) $(DESTDIR)$(DEFAULT_BACKUP_DIR) + $(INSTALL_ROOT_DIR) $(DESTDIR)$(DEFAULT_CACHE_DIR) + $(INSTALL_ROOT_DIR) $(DESTDIR)$(DEFAULT_LOCK_DIR) + $(INSTALL_ROOT_DIR) $(DESTDIR)$(DEFAULT_RUN_DIR) + $(INSTALL_ROOT_DATA) /dev/null $(DESTDIR)$(DEFAULT_CACHE_DIR)/.cache + +install_initscripts: + $(MAKE) -C scripts install_initscripts + +install_systemd_generators: + $(MAKE) -C scripts install_systemd_generators + $(MAKE) -C man install_systemd_generators + +install_systemd_units: + $(MAKE) -C scripts install_systemd_units + +install_all_man: + $(MAKE) -C man install_all_man + +ifeq ("@PYTHON_BINDINGS@", "yes") +install_python_bindings: + $(MAKE) -C liblvm/python install_python_bindings +endif + +install_tmpfiles_configuration: + $(MAKE) -C scripts install_tmpfiles_configuration + +LCOV_TRACES = libdm.info lib.info liblvm.info tools.info \ + libdaemon/client.info libdaemon/server.info \ + daemons/clvmd.info \ + daemons/dmeventd.info \ + daemons/lvmetad.info \ + daemons/lvmlockd.info \ + daemons/lvmpolld.info + +CLEAN_TARGETS += $(LCOV_TRACES) + +ifneq ("$(LCOV)", "") +.PHONY: lcov-reset lcov lcov-dated $(LCOV_TRACES) + +ifeq ($(MAKECMDGOALS),lcov-dated) +LCOV_REPORTS_DIR := lcov_reports-$(shell date +%Y%m%d%k%M%S) +lcov-dated: lcov +else +LCOV_REPORTS_DIR := lcov_reports +endif + +lcov-reset: + $(LCOV) --zerocounters $(addprefix -d , $(basename $(LCOV_TRACES))) + +# maybe use subdirs processing to create tracefiles... +$(LCOV_TRACES): + $(LCOV) -b $(basename $@) -d $(basename $@) \ + --ignore-errors source -c -o - | $(SED) \ + -e "s/\(dmeventd_lvm.[ch]\)/plugins\/lvm2\/\1/" \ + -e "s/dmeventd_\(mirror\|snapshot\|thin\|raid\)\.c/plugins\/\1\/dmeventd_\1\.c/" \ + >$@ + +ifneq ("$(GENHTML)", "") +lcov: $(LCOV_TRACES) + $(RM) -r $(LCOV_REPORTS_DIR) + $(MKDIR_P) $(LCOV_REPORTS_DIR) + for i in $(LCOV_TRACES); do \ + test -s $$i -a $$(wc -w <$$i) -ge 100 && lc="$$lc $$i"; \ + done; \ + test -z "$$lc" || $(GENHTML) -p @abs_top_builddir@ \ + -o $(LCOV_REPORTS_DIR) $$lc +endif + +endif + +ifeq ("$(TESTING)", "yes") +# testing and report generation +RUBY=ruby1.9 -Ireport-generators/lib -Ireport-generators/test + +.PHONY: unit-test ruby-test test-programs + +# FIXME: put dependencies on libdm and liblvm +# FIXME: Should be handled by Makefiles in subdirs, not here at top level. +test-programs: + cd unit-tests/regex && $(MAKE) + cd unit-tests/datastruct && $(MAKE) + cd unit-tests/mm && $(MAKE) + +unit-test: test-programs + $(RUBY) report-generators/unit_test.rb $(shell find . -name TESTS) + $(RUBY) report-generators/title_page.rb + +memcheck: test-programs + $(RUBY) report-generators/memcheck.rb $(shell find . -name TESTS) + $(RUBY) report-generators/title_page.rb + +ruby-test: + $(RUBY) report-generators/test/ts.rb +endif + +ifneq ($(shell which ctags),) +.PHONY: tags +tags: + test -z "$(shell find $(top_srcdir) -type f -name '*.[ch]' -newer tags 2>/dev/null | head -1)" || $(RM) tags + test -f tags || find $(top_srcdir) -maxdepth 5 -type f -name '*.[ch]' -exec ctags -a '{}' + + +CLEAN_TARGETS += tags +endif
diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..e54f9f4 --- /dev/null +++ b/NOTICE
@@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License.
diff --git a/README b/README new file mode 100644 index 0000000..a0e3c9e --- /dev/null +++ b/README
@@ -0,0 +1,33 @@ +This tree contains the LVM2 and device-mapper tools and libraries. + +For more information about LVM2 read the changelog in the WHATS_NEW file. +Installation instructions are in INSTALL. + +There is no warranty - see COPYING and COPYING.LIB. + +Tarballs are available from: + ftp://sources.redhat.com/pub/lvm2/ + +The source code is stored in git: + http://git.fedorahosted.org/git/lvm2.git + git clone git://git.fedorahosted.org/git/lvm2.git + +Mailing list for general discussion related to LVM2: + linux-lvm@redhat.com + Subscribe from https://www.redhat.com/mailman/listinfo/linux-lvm + +Mailing lists for LVM2 development, patches and commits: + lvm-devel@redhat.com + Subscribe from https://www.redhat.com/mailman/listinfo/lvm-devel + + lvm2-commits@lists.fedorahosted.org (Read-only archive of commits) + Subscribe from https://fedorahosted.org/mailman/listinfo/lvm2-commits + +Mailing list for device-mapper development, including kernel patches +and multipath-tools: + dm-devel@redhat.com + Subscribe from https://www.redhat.com/mailman/listinfo/dm-devel + +The source code repository used until 7th June 2012 is accessible here: + http://sources.redhat.com/cgi-bin/cvsweb.cgi/LVM2/?cvsroot=lvm2. +
diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..32cef62 --- /dev/null +++ b/VERSION
@@ -0,0 +1 @@ +2.02.163(2)-git (2016-07-28)
diff --git a/VERSION_DM b/VERSION_DM new file mode 100644 index 0000000..41ac4ce --- /dev/null +++ b/VERSION_DM
@@ -0,0 +1 @@ +1.02.133-git (2016-07-28)
diff --git a/WHATS_NEW b/WHATS_NEW new file mode 100644 index 0000000..2ef2e09 --- /dev/null +++ b/WHATS_NEW
@@ -0,0 +1,4567 @@ +Version 2.02.163 - +================================= + +Version 2.02.162 - 28th July 2016 +================================= + Extend vg_validate also to check raid configurations thoroughly. + Support lvconvert -Zn also when doing full cache pool conversion. + Suppress not zeroing warn when converting to thin LV for non-zeroing tpool. + Fix automatic updates of PV extension headers to newest version. + Improve lvconvert --trackchanges validation to require --splitmirrors 1. + Add note about lastlog built-in command to lvm man page. + Fix unrecognised segtype flag message. + lvconvert not clears cache pool metadata ONLY with -Zn. + Add allocation/raid_stripe_all_devices to reinstate previous behaviour. + Create raid stripes across fixed small numbers of PVs instead of all PVs. + Enabled lvconvert --uncache to work with partial VG. + Disallow lvconvert --replace with raid0* LVs. + Fix some lvmetad changed VG metadata notifications that sent uncommitted data. + +Version 2.02.161 - 15th July 2016 +================================= + Prohibit some lvchange/lvresize that were failing on raid0 volumes. + Fix segfaults in complex vgsplits. (2.02.159) + Reformat unwieldy lvconvert man page. + Allow --force to be passed through to pvcreate from vgcreate. (2.02.144) + Fix lvresize of filesystem when LV has already right size (2.02.141) + New LVM_LOG_FILE_MAX_LINES env var to limit max size of created logs. + +Version 2.02.160 - 6th July 2016 +================================ + Minor fixes from coverity. + +Version 2.02.159 - 6th July 2016 +================================ + Add raid0_meta segment type that provides metadata space for raid conversions. + Fix created link for a used pool for vgmknode. + Introduce and use is_power_of_2 macro. + Support conversions between striped and raid0 segment types. + Add infrastructure for raid takeover lvconvert options. + +Version 2.02.158 - 25th June 2016 +================================= + Add a more efficient native vgimportclone command to replace the script. + Make lvmlockd always attempt to connect to lvmetad if no connection exists. + Let lvmetad handle new connections after shutdown signal. + Disable lvmetad when vgcfgrestore begins and enable it again after. + Make pvscan do activation if lvmetad is configured but not running. + Fix rescanning the PVs for a single VG when using lvmetad. + Pool metadata lvresize uses now same code as resize of normal volume. + Preserve monitoring status when updating thin-pool metadata. + Return 0 (inactive) when status cannot be queried in _lv_active(). + Switch to log_warn() for failing activation status query. + Replace vgimportclone script with binary. + While lvmetad is shutting down, continue handling all connections cleanly. + Refactor lvconvert argument handling code. + Notify lvmetad when vgcfgrestore changes VG metadata. + Add --logonly option to report only cmd log for a command, not other reports. + Add log/command_log_selection to configure default selection used on cmd log. + Use 'orphan' object type in cmd log for groups to collect PVs not yet in VGs. + Add lvm lastlog command for query and display of last cmd's log in lvm shell. + Report per-object return codes via cmd log while processing multiple objects. + Annotate processing code with log report hooks for per-object command log. + Also pass common printed messages (besides warnings and errors) to log report. + Log warnings and errors via report during cmd processing if this is enabled. + Make it possible to iterate over internal 'orphan' VGs in process_each_vg fn. + Make -S|--select option groupable that allows this option to be repeated. + Make -O|--sort option groupable that allows this option to be repeated. + Add --configreport option to select report for which next options are applied. + Add support for priorities on grouping command arguments. + Add report/{pvs,vgs,lvs,pvsegs,segs}_{cols,sort}_full to lvm.conf. + Add lvm fullreport command for joined PV, VG, LV and segment report per VG. + Integrate report group handling and cmd log report into cmd processing code. + Add log/report_command_log to lvm.conf to enable or disable cmd log report. + Add log/report_output_format to lvm.conf for default report output format. + Recognize --reportformat {basic|json} option to select report output format. + Add log/command_log_{sort,cols} to lvm.conf to configure command log report. + Add log_object_{type,name,id,group,group_id} fields to cmd log. + Add log_{seq_num,type,context,message,errno,ret_code} fields to cmd log. + Add CMDLOG report type - a separate report type for command logging. + +Version 2.02.157 - 17th June 2016 +================================= + Change pvscan --cache -aay to scan locally if lvmetad fails. + +Version 2.02.156 - 11th June 2016 +================================= + Don't allow duplicate orphan PVs to be used with vgcreate/vgextend/pvcreate. + Improve handling of lvmetad update failures. + Yes/No prompt accepts '^[ ^t]*([Yy]([Ee]([Ss]|)|)|[Nn]([Oo]|))[ ^t]*$'. + If available, also collect output from lsblk command when running lvmdump -s. + +Version 2.02.155 - 3rd June 2016 +================================ + Reject PV tags on pvmove cmdline because only 1 PV is supported. (2.02.141) + Fix compilation error when building with configure --disable-devmapper. + Fix lvmconfig --type diff to display complete diff if config cascade used. + Automatically filter out partitioned loop devices with partscan (losetup -P). + Fix lvm devtypes internal error if -S used with field name from pvs/vgs/lvs. + When reporting Data%,Snap%,Meta%,Cpy%Sync use single ioctl per LV. + Add lvseg_percent_with_info_and_seg_status() for percent retrieval. + Enhance internal seg_status handling to understand snapshots better. + When refresh failed in suspend, call resume upon error path. + Support passthrough cache mode when waiting for clean cache. + Check cache status only for 'in-use' cache pools. + Extend setup_task() to preset flushing for dm_task object. + When checking LV is a merging COW, validate its a COW LV first. + Correcting value in copy_percent() for 100%. + Update vgreduce to use process_each_vg. + Update lvconvert to use process_each_lv. + Update pvscan to use process_each_vg for autoactivation. + Add basic support for --type raid0 using md. + Add support for lvchange --cachemode for cached LV. + Fix liblvm2app error handling when setting up context. + Delay liblvm2app init in python code until it is needed. + Simplify thread locking in lvmetad to fix locking problems. + Allow pvremove -ff to remove a duplicate PV. + Fix lvm2-activation-generator to read lvm.conf without full command setup. + Allow a minimal context to be used in lvm2app for reading lvm.conf. + +Version 2.02.154 - 14th May 2016 +================================ + Fix liblvm segfault after failure initialising lvmetad connection. + Retry open without O_NOATIME if it fails (not file owner/CAP_FOWNER). + Split _report into one fn for options and arguments and one for processing. + +Version 2.02.153 - 7th May 2016 +=============================== + Change warning messages related to duplicate PVs. + A named device is always processed itself, not switched for a duplicate. + Add PV attr "d" and report field "duplicate" for duplicate PVs. + Add config setting to disallow VG changes when duplicate PVs exist. + Use device size and active LVs to choose the preferred duplicate PV. + Disable lvmetad when duplicate PVs are seen. + Support --chunksize option also when caching LV when possible. + Add function to check for target presence and version via 1 ioctl. + +Version 2.02.152 - 30th April 2016 +================================== + Use any inherited tags when wiping metadata sub LVs to ensure activation. + Add str_list_wipe. + Improve support for interrupting procesing of volumes during lvchange. + Use failed command return code when lvchanging read-only volume. + Show creation transaction_id and zeroing state of pool with thin volume. + Stop checking for dm_cache_mq policy with cache target 1.9 (alias to smq). + Check first /sys/module/dm_* dir existance before using modprobe. + Remove mpath from 10-dm.rules, superseded by 11-dm-mpath.rules (mpath>=0.6.0). + +Version 2.02.151 - 23rd April 2016 +================================== + Fix error path after reusing of _setup_task (2.02.150). + Fix memory access for empty sysfs values (2.02.149). + Disable lvmetad when lvm1 metadata is seen, so commands revert to scanning. + Suppress errors when snapshot merge gets delayed because volume is in use. + Avoid internal snapshot LV names in messages. + Autodetect and use /run/lock dir when available instead of /var/lock. + lvchange --refresh for merging thin origin will retry to deactivate snapshot. + Recognize in-progress snapshot merge for thin volumes from dm table. + Avoid deciding to initiate a pending snapshot merge during resume. + Improve retrying lvmetad requests while lvmetad is being updated. + Read devices instead of using the lvmetad cache if rescan fails. + Move lvmetad token/filter check and device rescan to the start of commands. + Don't try deactivating fictional internal LV before snapshot merge. (2.02.105) + When not obtaining devs from udev, check they exist before caching them. + Detect device mismatch also when compiling without udev support. + +Version 2.02.150 - 9th April 2016 +================================= + Avoid using flushing dm status ioctl when checking for usable DM device. + Check for devices without LVM- uuid prefix only with kernels < 3.X. + Reuse %FREE size aproximation with lvcreate -l%PVS thin-pool. + Allow the lvmdump directory to exist already provided it is empty. + Show lvconverted percentage with 2 decimal digits. + Fix regression in suspend when repairing --type mirror (2.02.133). + +Version 2.02.149 - 1st April 2016 +================================= + Do not flush thin-pool when checking metadata fullness. + Remove spurious error about no value in /sys/dev/block/major:minor/dm/uuid. + Fix device mismatch detection for LV if persistent .cache file is used. + Fix holder device not being found in /dev while sysfs has it during dev scan. + +Version 2.02.148 - 26th March 2016 +================================== + Introduce TARGET_NAME and MODULE NAME macros. + Replace hard-coded module and target names with macros. + Add pv_major and pv_minor report fields. + Detect and warn about mismatch between devices used and assumed for an LV. + +Version 2.02.147 - 19th March 2016 +================================== + If available, use /proc/self/mountinfo to detect mounted volume in fsadm. + Fix resize of stacked raid thin data volume (2.02.141). + Fix test for lvremove failure in lvconvert --uncache (2.02.146). + +Version 2.02.146 - 11th March 2016 +================================== + More man page cleanups in lvconvert. + Fix makefile vpath in /udev when generating udev rules files. + Another attempt to improve VG name parsing for lvconvert (2.02.144). + Use new cache status info and skip flushing for failed cache. + Support --uncache with missing PVs. + Tidy report field names, headings and widths. + Add vgscan --notifydbus to send a dbus notification. + Add dbus notification from commands after a PV/VG/LV changes state. + +Version 2.02.145 - 4th March 2016 +================================= + Make it possible to use lvremove and lvrename on historical LVs. + For historical LVs, report 'none' for lv_layout and 'history' for lv_role. + Add full_{ancestors,descendants} fields to report LV ancestry with history. + Report (h)istorical state within 5th bit (State) of the lv_attr field. + Add lv_historical reporting field to report if LV is historical or not. + Add lv_time_removed reporting field to display removal time for hist. LVs. + Report lv_name, lv_uuid, vg_name, lv_time for historical LVs. + Add --nohistory switch to lvremove to disable history recording on demand. + Add -H|--history switch to lvs and lvdisplay to include historical LVs. + Create historical LVs out of removed thin snapshot LVs and record in history. + Add metadata/lvs_history_retention_time for automatic removal of hist. LVs. + Add metadata/record_lvs_history config for switching LV history recording. + Add support and infrastructure for tracking historical LVs. + Improve lvconvert man page. + Add kernel_cache_policy lvs field. + Display [unknown] instead of 'unknown device' in pvs output. + Fix error path when pvcreate allocation fails (2.02.144). + Display [unknown] instead of blank for unknown VG names in pvs output. + +Version 2.02.144 - 26th February 2016 +===================================== + Use new PV processing code in pvcreate/vgcreate/vgextend/pvremove. + Add new PV processing code that prompts user without locks held. + Prevent lvmlockd blocking with new flag requiring sanlock 3.3.0. + Only show (u)sed pv_attr char when PV is not (a)llocatable. (2.02.143) + Update makefile to generate lcov output also for lvmpolld and lvmlockd. + Fix SystemdService lvm2-lvmdbusd.service name. + Improve support for env LVM_VG_NAME for reference VG name in lvconvert. + Fix regression when lvresize accepted zero sizes. (2.02.141) + Always warn user about PV in use even when pvremove uses --force --force. + Use uninitialized pool header detection in all cases. + Fix read error detection when checking for uninitialized thin-pool header. + Fix error path for internal error in lvmetad VG lookup code. + +Version 2.02.143 - 21st February 2016 +===================================== + Fix error path when sending thin-pool message fails in update_pool_lv(). + Support reporting CheckNeeded and Fail state for thin-pool and thin LV. + For failing thin-pool and thin volume correctly report percentage as INVALID. + Report -1, not 'unkown' for lv_{snapshot_invalid,merge_failed} with --binary. + Add configure --enable-dbus-service for an LVM D-Bus service. + Replace configure --enable-python_bindings with python2 and python3 versions. + If PV belongs to some VG and metadata missing, skip it if system ID is used. + Automatically change PV header extension to latest version if writing PV/VG. + Identify used PVs in pv_attr field by new 'u' character. + Add pv_in_use reporting field to report if PV is used or not. + Add pv_ext_vsn reporting field to report PV header extension version. + Add protective flag marking PVs as used even if no metadata available. + +Version 2.02.142 - 15th February 2016 +===================================== + Fix memory pool corruption in pvmove (2.02.141). + Support control of spare metadata creation when repairing thin-pool. + Fix config type of 'log/verbose' from bool to int (2.02.99). + Fix inverted data LV thinp watermark calc for dmeventd response (2.02.133). + Use use_blkid_wiping=0 if not defined in lvm.conf and support not compiled in. + Do not check for suspended devices if scanning for lvmetad update. + Clear cached bootloader areas when PV format changed. + Fix partn table filter with external_device_info_source="udev" and blkid<2.20. + +Version 2.02.141 - 25th January 2016 +==================================== + Add metadata/check_pv_device_sizes switch to lvm.conf for device size checks. + Warn if device size is less than corresponding PV size in metadata. + Cache device sizes internally. + Restore support for command breaking in process_each_lv_in_vg() (2.02.118). + Use correct mempool when process_each_lv_in_vg() (2.02.118). + Fix lvm.8 man to show again prohibited suffixes. + Fix configure to set proper use_blkid_wiping if autodetected as disabled. + Initialise udev in clvmd for use in device scanning. (2.02.116) + Add seg_le_ranges report field for common format when displaying seg devices. + Honour report/list_item_separator for seg_metadata_le_ranges report field. + Don't mark hidden devs in -o devices,metadata_devices,seg_pe_ranges.(2.02.140) + Change LV sizes in seg_pe_ranges report field to match underlying devices. + Add kernel_cache_settings report field for cache LV settings used in kernel. + +Version 2.02.140 - 16th January 2016 +==================================== + Fix lvm2app to return either 0 or 1 for lvm_vg_is_{clustered,exported}. + Add kernel_discards report field to display thin pool discard used in kernel. + Correct checking of target presence when driver access is disabled. + Eval poolmetadatasize arg earlier in lvresize. + Fix vgcfgrestore to respect allocatable attribute of PVs. + Add report/mark_hidden_devices to lvm.conf. + Use brackets consistently in report fields to mark hidden devices. + Restore background polling processing during auto-activation (2.02.119). + Fix invalid memory read when reporting cache LV policy_name (2.02.126). + +Version 2.02.139 - 8th January 2016 +=================================== + Update lvmlockd with the new VG seqno before devices are suspended. + Rework vgrename to use the common processing code in toollib. + Make pvs show new devices on the system since the last .cache update. + Document F,D and M thin pool health status chars for lv_attr in lvs man page. + Also add lvm2-activation{-early,-net}.service systemd status for lvmdump -s. + +Version 2.02.138 - 14th December 2015 +===================================== + Support lvrename for hidden (used) cache pools. + Fix lvrename for stacked cache pools. + +Version 2.02.137 - 5th December 2015 +==================================== + Restore archiving before changing metadata in vgextend (2.02.117). + Dropped internal usage of log_suppress(2). + Cleaned logging code for buffer size usage. + Added internal id_read_format_try() function to check and read valid UUID. + Change lvcreate, lvrename, lvresize to use process_each_vg. + Change process_each_vg to handle single VG as separate arg. + Issue error if ambiguous VG name is supplied in most commands. + Make process_each fns always work through full list of known VG names. + Use dm_get_status_mirror() instead of individual parsers. + Add mem pool arg for check_transient_status() target function. + Avoid misleading error with -m is omitted with lvconvert to raid types. + Add system_id to vginfo cache. + +Version 2.02.136 - 28th November 2015 +===================================== + Add new --sinceversion option for lvmconfig --type new. + Fix inactive table loaded for wrapping thin-pool when resizing it. + Extend the list of ignored libraries when locking memory. + +Version 2.02.135 - 23rd November 2015 +===================================== + Add a model file for Coverity. + Show correct error message for unsupported yet cache pool repair. + Allow lvconvert cache pools' data and metadata LV to raid. + Fix reading of old metadata with missing cache policy or mode settings. + Issue error if external_device_info_source=udev and udev db record incomplete. + Update lvmetad duplicate VG name handling to use hash function extensions. + Detect invalid vgrenames by vgid where the name is unchanged. + Fix passing of 32bit values through daemons (mostly lvmlockd). + Use local memory pool for whole alloc_handle manipulation. + Add missing pointer validation after dm_get_next_target(). + Do not deref NULL pointer in debug message for _match_pv_tags(). + Drop unneeded stat() call when checking for sysfs file. + Fix memory leak on error path of failing thin-pool percentage check. + Add missing test for failing node allocation in lvmetad. + Correct configure messages when enabling/disabling lvmlockd. + +Version 2.02.134 - 9th November 2015 +==================================== + Refactor some lvmetad code and adjust some duplicate PV messages. + No longer repair/wipe VG/PVs if inaccessible because foreign or shared. + Pass correct data size to mirror log calc so log can be bigger than 1 extent. + +Version 2.02.133 - 30th October 2015 +==================================== + Support repeated -o|--options for reporting commands. + Support -o- and -o# for reporting commands to remove and compact fields. + Fix missing PVs from pvs output if vgremove is run concurrently. + Remove unwanted error message when running pvs/vgs/lvs and vgremove at once. + Check newly created VG's metadata do not overlap in metadata ring buffer. + Check metadata area size is at least the minimum size defined for the format. + Thin pool targets uses low_water_mark from profile. + Dropping 'yet' from error of unsupported thick snapshot of snapshots. + Do not support unpartitioned DASD devices with CDL formatted with pvcreate. + For thins use flush for suspend only when volume size is reduced. + Enable code which detects the need of flush during suspend. + Ensure --use-policy will resize volume to fit below threshold. + Correct percentage evaluation when checking thin-pool over threshold. + Fix lvmcache to move PV from VG to orphans if VG is removed and lvmetad used. + Fix lvmcache to not cache even invalid info about PV which got removed. + Support checking of memlock daemon counter. + Allow all log levels to be used with the lvmetad -l option. + Add optional shutdown when idle support for lvmetad. + Fix missing in-sync progress info while lvconvert used with lvmpolld. + Add report/compact_output_cols to lvm.conf to define report cols to compact. + Do not change logging in lvm2 library when it's already set. + Check for enough space in thin-pool in command before creating new thin. + Make libblkid detect all copies of the same signature if use_blkid_wiping=1. + Fix vgimportclone with -n to not add number unnecessarily to base VG name. + Cleanup vgimportclone script and remove dependency on awk, grep, cut and tr. + Add vg_missing_pv_count report field to report number of missing PVs in a VG. + Properly identify internal LV holding sanlock locks within lv_role field. + Add metadata_devices and seg_metadata_le_ranges report fields for raid vols. + Fix lvm2-{activation,clvmd,cmirrord,monitor} service to exec before mounting. + +Version 2.02.132 - 22nd September 2015 +====================================== + Fix lvmconf to set locking_type=2 if external locking library is requested. + Remove verbose message when rescanning an unchanged device. (2.02.119) + Add origin_uuid, mirror_log_uuid, move_pv_uuid, convert_lv_uuid report fields. + Add pool_lv_uuid, metadata_lv_uuid, data_lv_uuid reporting fields. + Fix PV label processing failure after pvcreate in lvm shell with lvmetad. + +Version 2.02.131 - 15th September 2015 +====================================== + Rename 'make install_full_man' to install_all_man and add all_man target. + Fix vgimportclone cache_dir path name (2.02.115). + Swapping of LV identifiers handles more complex LVs. + Use passed list of PVS when allocating space in lvconvert --thinpool. + Disallow usage of --stripe and --stripesize when creating cache pool. + Warn user when caching raid or thin pool data LV. + When layering LV, move LV flags with segments. + Ignore persistent cache if configuration changed. (2.02.127) + Fix devices/filter to be applied before disk-accessing filters. (2.02.112) + Make tags only when requested via 'make tags'. + Configure supports --disable-dependency-tracking for one-time builds. + Fix usage of configure.h when building in srcdir != builddir. + +Version 2.02.130 - 5th September 2015 +===================================== + Fix use of uninitialized device status if reading outdated .cache record. + Restore support for --monitor option in lvcreate (2.02.112). + Read thin-pool data and metadata percent without flush. + Detect blocked thin-pool and avoid scanning their thin volumes. + Check if dm device is usable before checking its size (2.02.116). + Extend parsing of cache_check version in configure. + Make lvpoll error messages visible in lvmpolld's stderr and in syslog. + Add 'make install_full_man' to install all man pages regardless of config. + +Version 2.02.129 - 26th August 2015 +=================================== + Drop error message when vgdisplay encounters an exported VG. (2.02.27) + Fix shared library generation to stop exporting internal functions.(2.02.120) + Accept --cachemode with lvconvert. + Fix and improve reporting properties of cache-pool. + Enable usage of --cachepolicy and --cachesetting with lvconvert. + Don't allow to reduce size of thin-pool metadata. + Fix debug buffer overflows in cmirrord logging. + Add --foreground and --help to cmirrord. + +Version 2.02.128 - 17th August 2015 +=================================== + Allocation setting cache_pool_cachemode is replaced by cache_mode. + Don't attempt to close config file that couldn't be opened. + Check for valid cache mode in validation of cache segment. + Change internal interface handling cache mode and policy. + When no cache policy specified, prefer smq (if available) over mq. + Add demo cache-mq and cache-smq profiles. + Add cmd profilable allocation/cache_policy,cache_settings,cache_mode. + Require cache_check 0.5.4 for use of --clear-needs-check-flag. + Fix lvmetad udev rules to not override SYSTEMD_WANTS, add the service instead. + +Version 2.02.127 - 10th August 2015 +=================================== + Do not init filters, locking, lvmetad, lvmpolld if command doesn't use it. + Order fields in struct cmd_context more logically. + Add lock_type to lvmcache VG summary and info structs. + Fix regression in cache causing some PVs to bypass filters (2.02.105). + Make configure --enable-realtime the default now. + Update .gitignore and configure.in files to reflect usage of current tree. + +Version 2.02.126 - 24th July 2015 +================================= + Fix long option hyphen removal. (2.02.122) + Fix clvmd freeze if client disappears without first releasing its locks. + Fix lvconvert segfaults while performing snapshots merge. + Ignore errors during detection if use_blkid_wiping=1 and --force is used. + Recognise DM_ABORT_ON_INTERNAL_ERRORS env var override in lvm logging fn. + Fix alloc segfault when extending LV with fewer stripes than in first seg. + Fix handling of cache policy name. + Set cache policy before with the first lvm2 cache pool metadata commit. + Fix detection of thin-pool overprovisioning (2.02.124). + Fix lvmpolld segfaults on 32 bit architectures. + Add lvmlockd lock_args validation to vg_validate. + Fix ignored --startstopservices option if running lvmconf with systemd. + Hide sanlock LVs when processing LVs in VG unless named or --all used. + +Version 2.02.125 - 7th July 2015 +================================ + Fix getline memory usage in lvmpolld. + Add support --clear-needs-check-flag for cache_check of cache pool metadata. + Add lvmetactl for developer use only. + Rename global/lock_retries to lvmlockd_retries. + Replace --enable-lvmlockd by --enable-lockd-sanlock and --enable-lockd-dlm. + +Version 2.02.124 - 3rd July 2015 +================================ + Move sending thin pool messages from resume to suspend phase. + Report warning when pool is overprovisioned and not auto resized. + Recognize free-form date/time values for lv_time field in selection criteria. + Added experimental lvmlockd with configure --enable-lvmlockd. + Fix regression in select to match string fields if using synonyms (2.02.123). + Fix regression when printing more lv names via display_lvname (2.02.122). + Add missing error logging to unlock_vg and sync_local_dev_names callers. + +Version 2.02.123 - 30th June 2015 +================================= + Add report/time_format lvm.conf option to define time format for report. + Fix makefile shell compare == when building lvmetad lvmpolld (2.02.120). + Add --type full to lvmconfig for full configuration tree view. + Add undocumented environment variables to lvm man page. (2.02.119) + Add device synchronization point before activating a new snapshot. + Add --withspaces to lvmconfig to add spaces in output for better readability. + Add custom main function to libdaemon. + Use lvmetad to track out-of-date metadata discovered. + +Version 2.02.122 - 20th June 2015 +================================= + Flush stdout before printing to stderr. + Use pre-allocated buffer for printed LV names in display_lvname. + Support thins with size of external origin unaligned with thin pool chunk. + Allow extension of reduced thin volumes with external origins. + Consider snapshot and origin LV as unusable if component devices suspended. + Fix lvmconfig segfault on settings with undefined default value (2.02.120). + Add explicit 's' (shared) LV activation mode. + Ignore hyphens in long options names (i.e. --long-option == --longoption). + +Version 2.02.121 - 12th June 2015 +================================= + Distinguish between on-disk and lvmetad versions of text metadata. + Remove DL_LIBS from Makefiles for daemons that don't need them. + Zero errno in before strtoul call in dmsetup if tested after the call. + Zero errno in before strtoul call in lvmpolld. + Fix a segfault in pvscan --cache --background command. + Fix test for AREA_PV when checking for failed mirrors. + Do not use --sysinit in lvm2-activation{-early,-net}.service if lvmpolld used. + Maintain outdated PV info in lvmetad till all old metadata is gone from disk. + Do not fail polling when poll LV not found (already finished or removed). + Replace poll_get_copy_vg/lv fns with vg_read() and find_lv() in polldaemon. + Close all device fds only in before sleep call in polldaemon. + Simplify Makefile targets that generate exported symbols. + Move various -D settings from Makefiles to configure.h. + +Version 2.02.120 - 15th May 2015 +================================ + Make various adjustments to Makefile compilation flags. + Add lvmpolld debug message class. + Add lvmpolld client mode for querying running server instance for status info. + Fix some libdaemon socket creation and reuse error paths. + Daemons (libdaemon) support exit on idle also in non-systemd environment. + Provide make dist and make rpm targets + Configure lvm.conf for use_lvmetad and use_lvmpolld. + Add lvpoll for cmdline communication with lvmpolld. + Add lvmpolld acting as a free-standing version of polldaemon. + Avoid repeated identical lvmetad VG lookups in commands processing all VGs. + Handle switches to alternative duplicate PVs efficiently with lvmetad. + Properly validate PV size for pvcreate --restorefile. + Fix check if pvcreate wiped device (2.02.117). + Fix storing of vgid when caching metadata (2.02.118). + Fix recursive lvm-config man page. (2.02.119) + Refactor polldaemon interfaces to poll every operation by VG/LV couple + Skip wait after testing in _wait_for_single_lv when polling finished + Return 'None' in python for empty string properties instead of crashing. + Distinguish signed numerical property type in reports for lvm2app library. + Reread raid completion status immediately when progress appears to be zero. + lvm2app closes locking on lvm_quit(). + Configure detects /run or /var/run. + Add missing newline in clvmd --help output. + +Version 2.02.119 - 2nd May 2015 +=============================== + New LVM_LOG_FILE_EPOCH, LVM_EXPECTED_EXIT_STATUS env vars. Man page to follow. + Remove detailed content from lvm.conf man page: use lvmconfig instead. + Generate complete config files with lvmconfig or 'make generate'. + Also display info on deprecated config with lvmconfig --withcomments. + Display version since which config is deprecated in lvmconfig --withversions. + Add --showdeprecated to lvmconfig to also display deprecated settings. + Hide deprecated settings in lvmconfig output for all types but current,diff. + Introduce support for exit on idle feature in libdaemon + Add --showunsupported to lvmconfig to also display unsupported settings. + Display unsupported settings for lvmconfig --type current,diff only by default + Honour lvmconfig --ignoreunsupported and --ignoreadvanced for all --type. + Make python bindings usable with python3 (and compatible with 2.6 & 2.7). + Add lvmconfig -l|--list as shortcut for lvmconfig --type list --withsummary. + Add lvmconfig --type list to display plain list of configuration settings. + Introduce lvmconfig as the preferred form of 'lvm dumpconfig'. + Add lv_ancestors and lv_descendants reporting fields. + Add --ignorelocal option to dumpconfig to ignore the local section. + Close connection to lvmetad after fork. + Make lvchange able to resume background pvmove polling again. + Split pvmove update metadata fn in an initial one and a subsequent one. + Refactor shared pvmove and lvconvert code into new _poll files. + Add --unconfigured option to dumpconfig to print strings unconfigured. + Add --withsummary option to dumpconfig to print first line - summary comment. + Use number of device holders to help choose between duplicate PVs. + Try to make lvmetad and non-lvmetad duplicate PV handling as similar as poss. + Issue warnings about duplicate PVs discovered by lvmetad. + Track alternative devices with matching PVIDs in lvmetad. + Check for lvm binary in blkdeactivate and skip LVM processing if not present. + Add --enable-halvm and --disable-halvm options to lvmconf script. + Add --services, --mirrorservice and --startstopservices option to lvmconf. + Use proper default value of global/use_lvmetad when processing lvmconf script. + Respect allocation/cling_tag_list during intial contiguous allocation. + Add A_PARTITION_BY_TAGS set when allocated areas should not share tags. + Make changes persist with python addTag/removeTag. + Set correct vgid when updating cache when writing PV metadata. + More efficient clvmd singlenode locking emulation. + Reject lvcreate -m with raid4/5/6 to avoid unexpected layout. + Don't skip invalidation of cached orphans if vg write lck is held (2.02.118). + Log relevant PV tags when using cling allocation. + Add str_list_add_list() to combine two lists. + Fix LV processing with selection to always do the selection on initial state. + Add internal LV_REMOVED LV status flag. + +Version 2.02.118 - 23rd March 2015 +================================== + Store metadata size + checksum in lvmcache and add struct lvmcache_vgsummary. + Remove inaccessible clustered PVs from 'pvs -a'. + Don't invalidate cached orphan information while global lock is held. + Avoid rescan of all devices when requested pvscan for removed device. + Measure configuration timestamps with nanoseconds when available. + Disable lvchange of major and minor of pool LVs. + Fix pvscan --cache to not scan and read ignored metadata areas on PVs. + Add After=iscsi-shutdown.service to blk-availability.service systemd unit. + Disallow vgconvert from changing metadata format when lvmetad is used. + Don't do a full read of VG when creating a new VG with an existing name. + Reduce amount of VG metadata parsing when looking for vgname on a PV. + Avoid reparsing same metadata when reading same metadata from multiple PVs. + Save extra device open/close when scanning device for size. + Fix seg_monitor field to report status also for mirrors and thick snapshots. + Replace LVM_WRITE with LVM_WRITE_LOCKED flags in metadata if system ID is set. + Remove ACCESS_NEEDS_SYSTEM_ID VG status flag. (2.02.117) + Enable system ID features. + +Version 2.02.117 - 4th March 2015 +================================= + Add CFG_DISABLED for new system ID config settings that must not yet be used. + Preserve original format type field when processing backup files. + Implement status action for lvm2-monitor initscript to display monitored LVs. + Allow lvchange -p to change kernel state only if metadata state differs. + Fix incorrect persistent .cache after report with label fields only (2.02.106). + Reinstate PV tag recognition for pvs if reporting label fields only (2.02.105). + Rescan devices before vgimport with lvmetad so exported VG is seen. + Fix hang by adjusting cluster mirror regionsize, avoiding CPG msg limit. + Do not crash when --cachepolicy is given without --cachesettings. + Add NEEDS_FOREIGN_VGS flag to vgimport so --foreign is always supplied. + Add --foreign to the 6 display and reporting tools and vgcfgbackup. + Install /etc/lvm/lvmlocal.conf template with local section for systemid. + Record creation_host_system_id in lvm2 metadata (never set yet). + Reinstate recursive config file tag section processing. (2.02.99) + Add 'lvm systemid' to display the current system ID (never set yet). + Fix configure to properly recognize --with-default-raid10-segtype option. + Do not refresh filters/rescan if no signature is wiped during pvcreate. + Enforce none external dev info for wiping during pvcreate to avoid races. + Add global/system_id_source and system_id_file to lvm.conf (disabled). + Add support for VG system_id to control host access to VGs. + Update vgextend to use process_each_vg. + Add --ignoreskippedcluster to pvchange. + Allow pvchange to modify several properties at once. + Update pvchange to use process_each_pv. + Fix pvs -a used with lvmetad to filter out devices unsuitable for PVs. + Fix selection to recognize units for ba_start, vg_free and seg_start fields. + Add support for -S/--select to vgexport and vgimport. + Add support for -S/--select to vgdisplay, lvdisplay and pvdisplay without -C. + Add support for -S/--select to vgremove and lvremove. + Add support for -S/--select to vgchange,lvchange and pvchange. + Add infrastructure to support selection for non-reporting tools. + Add LVM_COMMAND_PROFILE env var to set default command profile name to use. + Set CLOEXEC flag on file descriptors originating in libdaemon. + +Version 2.02.116 - 30th January 2015 +==================================== + Deactivate unused thin pools activated with lvm2 pre-2.02.112 versions. + Check lock holding LV when lvconverting stacked raid LV in cluster. + Support udev external dev info for filters: PV min size, mpath, md, partition. + Add fw_raid_component_detection lvm.conf option to enable FW raid detection. + Add devices/external_device_info_source lvm.conf option ("none" by default). + Scan pools in for_each_sub_lv() and add for_each_sub_lv_except_pools(). + Fix lvm2app lvm_lv_get_property return value for fields with info/status ioctl. + Fix lvm2app regression in lvm_lv_get_attr causing unknown values (2.02.115). + Set default cache_mode to writehrough when missing in metadata. + Preserve chunk size with repair and metadata swap of a thin pool. + Fix raid --splitmirror 1 functionality (2.02.112). + Fix tree preload to handle splitting raid images. + Do not support unpartitioned DASD devices. + Improve config validation to check if setting with string value can be empty. + +Version 2.02.115 - 21st January 2015 +==================================== + Report segment types without monitoring support as undefined. + Support lvchange --errorwhenfull for thin pools. + Improve the processing and reporting of duplicate PVs. + Report lv_health_status and health attribute also for thin pool. + Add lv_when_full reporting field. + Add support for lvcreate --errorwhenfull y|n for thin pools. + Fix lvconvert --repair to honour resilience requirement for segmented RAID LV. + Filter out partitioned device-mapper devices as unsuitable for use as PVs. + Also notify lvmetad about filtered device if using pvscan --cache DevicePath. + Use LVM's own selection instead of awk expressions in clvmd startup scripts. + Do not filter out snapshot origin LVs as unusable devices for an LVM stack. + Fix incorrect rimage names when converting from mirror to raid1 LV (2.02.112). + Introduce pvremove_many to avoid excessive metadata re-reading and messages. + Check for cmirror availability during cluster mirror creation and activation. + Add cache_policy and cache_settings reporting fields. + Add missing recognition for --binary option with {pv,vg,lv}display -C. + Fix vgimportclone to notify lvmetad about changes done if lvmetad is used. + Fix vgimportclone to properly override config if it is missing in lvm.conf. + Fix automatic use of configure --enable-udev-systemd-background-jobs. + Correctly rename active split LV with -splitmirrors for raid1. + Add report/compact_output to lvm.conf to enable/disable compact report output. + Still restrict mirror region size to power of 2 when VG extent size is not. + +Version 2.02.114 - 28th November 2014 +===================================== + Release socket in daemon_close and protocol string in daemon_open error path. + Add --cachepolicy and --cachesettings to lvcreate. + Fix regression when parsing /dev/mapper dir (2.02.112). + Fix missing rounding to 64KB when estimating optimal thin pool chunk size. + Fix typo in clvmd initscript causing CLVMD_STOP_TIMEOUT var to be ignored. + Fix size in pvresize "Resizing to ..." verbose msg to show proper result size. + +Version 2.02.113 - 24th November 2014 +===================================== + Add --cachepolicy and --cachesettings options to lvchange. + Validate that converted volume and specified pool volume differ in lvconvert. + Fix regression in vgscan --mknodes usage (2.02.112). + Respect --prefix when setting CLMVD_PATH configure (2.02.89). + Default to configure --enable-udev-systemd-background-jobs for systemd>=205. + Fix ignore_vg() to properly react on various vg_read errors (2.02.112). + Failed recovery returns FAILED_RECOVERY status flag for vg_read(). + Exit with non-zero status code when pvck encounters a problem. + Fix clean_tree after activation/resume for cache target (2.02.112). + +Version 2.02.112 - 11th November 2014 +===================================== + Add cache_{read,write}_{hits,misses} reporting fields. + Add cache_{total,used,dirty}_blocks reporting fields. + Add _corig as reserved suffix. + Reduce number of VG writes and commits when creating spare volumes. + When remove_layer_from_lv() removes layer, restore subLV names. + Cache-pool in use becomes invisible LV. + Don't prompt for removal of _pmspare in VG without pool metadata LV. + Deactivation of snapshot origin detects and deactivates left-over snapshots. + Properly report error when taking snapshot of any cache type LV. + Add basic thread debugging messages to dmeventd. + Include threads being shutdown in dmeventd device registration responses. + Inital support for external users of thin pools based on transaction_id. + Report some basic percentage info for cache pools. + Introduce size_mb_arg_with_percent() for advanced size arg reading. + Add extra support for '.' as decimal point in size args. + Add configure parameters for default segment type choices. + Add global/sparse_segtype_default setting to use thin for --type sparse. + Update and correct lvcreate and lvcovert man pages. + Mark pools and snapshots as unzeroable volumes. + Check for zeroing of volume after segment type is fully detected. + Better support for persistent major and minor options with lvcreate. + Refactor lvcreate towards more complete validation of all supported options. + Support lvcreate --type linear. + Improve _should_wipe_lv() to warn with message. + Inform about temporarily created volumes only in verbose mode. + Better support for --test mode with pool creation. + Query lock holding LV when replacing and converting raid volumes. + Add extra validate for locked lv within validate_lv_cache_create(). + Add internal lvseg_name() function. + Skip use of lock files for virtual internal VG names. + Fix selection on {vg,lv}_permissions fields to properly match selection criteria. + Fix lv_permissions reporting to display read-only{-override} instead of blank. + Fix liblvm2cmd and lvm shell to respect quotes around args in cmd line string. + Permit extent sizes > 128KB that are not power of 2 with lvm2 format. + Remove workaround for lvm2-monitor.service hang on stop if lvmetad stopped. + Change vgremove to use process_each_lv_in_vg. + Allow lvconvert --repair and --splitmirrors on internal LVs. + Introduce WARN_ flags to control some metadata warning messages. + Use process_each_pv in vgreduce. + Refactor process_each_pv in toollib. + Introduce single validation routine for pool chunk size. + Support --yes like --force in vg/lvremove to skip y|n prompt. + Support --yes with lvconvert --splitsnapshot. + Fix detection of unsupported thin external lvconversions. + Fix detection of unsupported cache and thin pool lvconversions. + Fix detection of unsupported lvconversion of cache to snapshot. + Improve code for creation of cache and cache pool volumes. + Check cluster-wide (not local) active status before removing LV. + Properly check if activation of removed cached LV really activated. + lvremove cached LV removes cachepool (keep with lvconvert --splitcache). + Always remove spare LV with last removed pool volume. + Support lvconvert --splitcache and --uncache of cached LV. + Option --cache has also shortcut -H (i.e. lvcreate -H). + Refactor lvcreate code and better preserve --type argument. + Refactor filter processing around lvmetad. + Refactor process_each_lv in toollib. + Refactor process_each_vg in toollib. + Pools cannot be used as external origin. + Use lv_update_and_reload() for snapshot reload. + Don't print message in adjusted_mirror_region_size() in activation. + Improve lv_update_and_reload() to find out proper lock holding LV. + Improve search of LV in lv_ondisk(). + Do not scan sysfs in lv_check_not_in_use() when device is closed. + Backup final metadata after resync of mirror/raid. + Unify handling of --persistent option for lvcreate and lvchange. + Validate major and minor numbers stored in metadata. + Use -fPIE when linking -pie executables. + Support DEBUG_MEMLOCK to trap unsupported mmap usage. + Enable cache segment type by default. + Ensure only supported volume types are used with cache segments. + Fix inablility to specify cachemode when 'lvconvert'ing to cache-pool. + Grab cluster lock for active LVs when setting clustered attribute. + Use va_copy to properly pass va_list through functions. + Add function to detect rotational devices. + Review internal checks for mirror/raid/pvmove volumes. + Track mirror segment type with separate MIRROR flag. + Fix cmirror endian conversions. + Introduce lv_is_pvmove/locked/converting/merging macros. + Avoid leaving linear logical volume when thin pool creation fails. + Don't leak alloc_handle on raid target error path. + Properly validate raid leg names. + Archive metadata before starting their modification in raid target. + Add missing vg_revert() in suspend_lv() raid and snapshot error path. + Add missing backup of lvm2 metadata after some raid modifications. + Use vg memory pool for extent allocation. + Add allocation/physical_extent_size config option for default PE size of VGs. + Demote an error to a warning when devices known to lvmetad are filtered out. + Re-order filter evaluation, making component filters global. + Fix logic that checks for full scan before iterating through devices. + Introduce common code to modify metadata and reload updated LV. + Fix rename of active snapshot volume in cluster. + Make sure shared libraries are built with RELRO option. + +Version 2.02.111 - 1st September 2014 +===================================== + Pass properly sized char buffers for sscanf when initializing clvmd. + Reinstate nosync logic when extending mirror. (2.02.110) + Fix total area extent calculation when allocating cache pool. (2.02.110) + +Version 2.02.110 - 26th August 2014 +=================================== + Fix manipulation with thin-pools which are excluded via volume_list. + Support lv/vgremove -ff to remove thin vols from broken/inactive thin pools. + Fix typo breaking configure --with-lvm1=shared. + Modify lvresize code to handle raid/mirrors and physical extents. + Don't allow pvcreate to proceed if scanning or filtering fails. + Cleanly error when creating RAID with stripe size < PAGE_SIZE. + Print name of LV which on activation triggers delayed snapshot merge. + Add lv_layout and lv_role LV reporting fields. + Properly display lvs lv_attr volume type and target type bit for cache origin. + Fix pvcreate_check() to update cache correctly after signature wiping. + Fix primary device lookup failure for partition when processing mpath filter. + If LV inactive and non-clustered, do not issue "Cannot deactivate" on -aln. + Remove spurious "Skipping mirror LV" message on pvmove of clustered mirror. + +Version 2.02.109 - 5th August 2014 +================================== + Remove lv_volume_type field from reports. (2.02.108) + Fix a segfault in lvscan --cache when devices were already missing. (2.02.108) + Fix incorrect persistent .cache after vgcreate with PV creation. (2.02.108) + Display actual size changed when resizing LV. + Allow approximate allocation with +%FREE in lvextend. + Remove possible spurious "not found" message on PV create before wiping. + Handle upgrade from 2.02.105 when an LV now gaining a uuid suffix is active. + +Version 2.02.108 - 23rd July 2014 +================================= + Add lvscan --cache which re-scans constituents of a particular LV. + Make dmeventd's RAID plugin re-scan failed PVs when lvmetad is in use. + Improve code sharing for lvconvert and lvcreate and pools (cache & thin). + Improve lvconvert --merge validation. + Improve lvconvert --splitsnapshot validation. + Add report/list_item_separator lvm.conf option. + Add lv_active_{locally,remotely,exclusively} LV reporting fields. + Comment out devices/{preferred_names,filter} in default lvm.conf file. + Enhance lvconvert thin, thinpool, cache and cachepool command line support. + Display 'C' only for cache and cache-pool target types in lvs. + Prompt for confirmation before change LV into a snapshot exception store. + Return proper error codes for some failing lvconvert funtions. + Add initial code to use cache tools (cache_check|dump|repair|restore). + Support lvdisplay --maps for raid. + Add --activationmode degraded to activate degraded raid volumes by default. + Add separate lv_active_{locally,remotely,exclusively} LV reporting fields. + Recognize "auto"/"unmanaged" values in selection for appropriate fields only. + Add report/binary_values_as_numeric lvm.conf option for binary values as 0/1. + Add --binary arg to pvs,vgs,lvs and {pv,vg,lv}display -C for 0/1 on reports. + Add separate reporting fields for each each {pv,vg,lv}_attr bit. + Separate LV device status reporting fields out of LV fields. + Fix regression causing PVs not in VGs to be marked as allocatable (2.02.59). + Fix VG component of lvid in vgsplit/vgmerge and check in vg_validate. + Add lv_full_name, lv_parent and lv_dm_path fields to reports. + Change lv_path field to suppress devices that never appear in /dev/vg. + Postpone thin pool lvconvert prompts (2.02.107). + Require --yes option to skip prompt to lvconvert thin pool chunksize. + Support lvremove -ff to remove thin volumes from broken thin pools. + Require --yes to skip raid repair prompt. + Change makefile %.d generation to handle filename changes without make clean. + Fix use of buildir in make pofile. + Enhance private volumes UUIDs with suffixed for easier detection. + Do not use reserved _[tc]meta volumes for temporary LVs. + Leave backup pool metadata with _meta%d suffix instead of reserved _tmeta%d. + Allow RAID repair to reuse PVs from same image that suffered a failure. + New RAID images now avoid allocation on any PVs in the same parent RAID LV. + Always reevaluate filters just before creating PV. + +Version 2.02.107 - 23rd June 2014 +================================= + Introduce LCK_ACTIVATION to avoid concurrent activation of basic LV types. + Fix open_count test for lvchange --refresh or mirrors and raids. + Update pvs,vgs,lvs and lvm man page for selection support. + Add -S/--select to lvm devtypes for report selection. + Add -S/--select to pvs,vgs,lvs and {pv,vg,lv}display -C for report selection. + Use dm_report_init_with_selection now, implicit "selected" field appears. + Make use of libdm's DM_REPORT_FIELD_TYPE{SIZE,PERCENT,STRING_LIST} for fields. + Support all-or-nothing pvmove --atomic. + Automatically add snapshot metadata size for -l %ORIGIN calculation. + When converting RAID origin to cache LV, properly rename sub-LVs. + Use RemoveOnStop for lvm2-lvmetad.socket systemd unit. + Add thin-generic configuration profile for generic thin settings. + Fix crash when reporting empty labels on pvs. + Use retry_deactivation also when cleaning orphan devices. + Wait for client threads when shutting down lvmetad. + Remove PV from cache on pvremove. + Avoid repeatedly reporting of failure to connect to lvmetad. + Introduce MDA_FAILED to permit metadata updates even if some mdas are missing. + Prompt when setting the VG cluster attr if the cluster is not setup. + Allow --yes to skip prompt in vgextend (worked only with -f). + Don't use name mangling for LVM - it never uses dm names with wrong char set. + Remove default.profile and add {command,metadata}_profile_template.profile. + Use proper umask for systemd units generated by lvm2-activation-generator. + Check for failing mirror_remove_missing() function. + Prompt before converting volumes to thin pool and thin pool metadata. + Add dumpconfig --type profilable-{metadata,command} to select profile type. + Exit immediately with error if command profile is found invalid. + Separate --profile cmd line arg into --commandprofile and --metadataprofile. + Strictly separate command profiles and per-VG/LV profiles referenced in mda. + Fix dumpconfig --type diff when run as second and later cmd in lvm shell. + Fix wrong profile reuse from previous run if another cmd is run in lvm shell. + Move cache description from lvm(8) to new lvmcache(7) man page. + Display skipped prompt in silent mode. + Make reporting commands show help about possible sort keys on '-O help'. + Add metadata_percent to lvs_cols. + Take account of parity areas with alloc anywhere in _calc_required_extents. + Use proper uint64 casting for calculation of cache metadata size. + Better support for nesting of blocking signals. + Use only sigaction handler and drop duplicate signal handler. + Separate signal handling and flock code out into lib/misc. + Don't start dmeventd checking seg_monitor and monitoring is disabled. + Catch CTRL-c during pvremove prompts. + Show correct availability status for snapshot origin in lvscan. + Move segment thin pool/volume info into segment display 'lvdisplay --maps'. + Display thin pool usage even when just thin volume is available. + Display monitoring status for monitorable segments in 'lvdisplay --maps'. + Display virtual extents for virtual LVs in 'lvdisplay --maps'. + Make vgsplit fail cleanly when not all PVs are specified for RAID 4/5/6. + Make vgsplit work on mirrors with logs that share PVs with images. + Use devices/ignore_suspended_devices=0 by default if not defined in lvm.conf. + Use proper libmem mempool for allocation of unknown segment name. + Add --readonly to reporting and display tools for lock-free metadata access. + Add locking_type 5 for dummy locking for tools that do not need any locks. + Fix _recover_vg() error path when lock conversion fails. + Use X for LV attributes that are unknown when activation disabled. + Only output lvdisplay 'LV Status' field when activation is enabled. + Use lvmetad_used() in pvscan instead of config_tree. + Configure --enable-udev-systemd-background-jobs if not disabled explicitly. + Add lvmdump -s to collect system info and context (currently systemd only). + Refactor allocation code to make A_POSITIONAL_FILL explicit. + Use thread-safe ctime_r() for clvmd debug logging. + Skip adding replies to already finished reply thread. + Use mutex to check number of replies in request_timed_out() in clvmd. + Drop usage of extra reply_mutex for localsock in clvmd. + Protect manipulation with finished flag with mutex in clvmd. + Shift mutex creation and destroy for localsock in clvmd to correct place. + Fix usage of --test option in clvmd. + Skip more libraries to be mlocked in memory. + Remove LOCKED flag for pvmove replaced with error target. + Return invalid command when specifying negative polling interval. + +Version 2.02.106 - 10th April 2014 +================================== + Fix ignored --dataalignment/dataalignment offset for pvcreate --restorefile. + Fix lost information about bootloader area when using lvmetad. + Don't require --major to be specified when using -My option on kernels > 2.4. + Add configure --disable-thin_check_needs_check to support old thin_check. + Use thin_check --clear-needs-check-flag by default. + Export lvm_even_rand() for controlled provision of random numbers. + Add lvmthin man page to section 7. + Ensure mapped device names are not too long in vg_validate and lvrename. + Ensure resume failure in lvrename results in command failure. + Add explicit error message when using lvdisplay -c -m. + Report error if superfluous argument (e.g. PV name) supplied to pvscan. + Fix error message for pvdisplay -c -m and add one for pvdisplay -c -s. + Use EINVALID_CMD_LINE correctly instead of ECMD_FAILED in vgimport/export. + Obtain list of known VGs from lvmetad for pvchange --all. + Add man page for lvm-dumpconfig to section 8. + Drop unused cmd pointer for internal function for_each_sub_lv(). + Validate name for renamed sub LVs. + When lvrename fails on argument parsing return EINVALID_CMD_LINE. + Fix exit code regression in failing pvchange command (2.02.66). + Include 'lvm dumpconfig --type missing' and '--type diff' output to lvmdump. + Return failure when specifying negative size for pvresize. + Fix memory corruption in cmd context refresh if clvmd leaks opened device. + Reinitialise lvmcache properly on fork to fix premature polldaemon exit. + Add 'lvm dumpconfig --type diff' to show differences from defaults. + Fix swap signature detection for devices smaller then 2MB. + Use dm_malloc function in clvmd.c. + Resolve memory release order for clvmd shutdown. + Report error when lvm2 activation is released in critical_section. + Fix memory corruption when pvscan reports long pv names. + Do not report internal orphan VG names when reporting pvdisplay/pvscan. + Fix pvdisplay -c man page referencing KB instead of sectors. + Skip redundant synchronization calls on local clvmd. + Use correct PATH_MAX for locking dir path. + Do not check for backups when when its creation is disabled. + Don't allow --mergedconfig without --type current in dumpconfig. Fix memleak. + Make global/lvdisplay_shows_full_device_path lvm.conf setting profilable. + Make global/{units|si_unit_consistency|suffix} lvm.conf setting profilable. + Validate minimal chunk size for snapshot COW volume in lvconvert. + Disallow lvconvert of origin to snapshot COW volume. + Make report lvm.conf settings profilable. + Add existing report settings to lvm.conf. + Use VG read lock during 'pvscan --cache -aay' autoactivation. + Issue a VG refresh before autoactivation only if the PV has changed/is new. + Add flag to lvmetad protocol to indicate the PV scanned has changed/is new. + Also add vgname to lvmetad protocol when referencing VGs for PVs scanned. + Add man page for lvm2-activation-generator. + Don't print an error and accept empty value for global/thin_disabled_features. + Update API for internal function build_dm_uuid(). + Do not try to check empty pool with scheduled messages. + Fix return value in pool_has_message() when quering for any message. + Cleanup all client resources on clvmd exit. + Use dm_zalloc to clear members of clvmd client struct. + Use BLKID_CFLAGS when compiling with blkid support. + Use correct rl_completion_func_t typedef for new readline. + Make lvm 'dumpconfig --type default' complete for it to be consumed by lvm. + Run pvscan --cache via systemd-run in udev if the PV label is detected lost. + Fix memleak when lvmetad discovers PV to appear on another device. + Fix calculation of maximum size of COW device for snapshot (2.02.99). + Do not allow stripe size to be bigger then extent size for lvresize. + Zero snapshot COW header when creating read-only snapshot. + Comment out config lines in dumpconfig output without default values defined. + Improve detection of clustered mirror support. + Enhance raid code with feature flags, for now checks for raid10. + Move parsing of VG metadata from vg_commit() back to vg_write() (2.02.99) + Avoid a PV label scan while in a critical section. + Remove (always 0) skip argument from lv_activation_skip(). + Create /dev/disk/by-id/lvm-pv-uuid-<PV_UUID> symlink for each PV via udev. + lvcreate computes RAID4/5/6 stripes if not given from # of allocatable PVs. + Fix merging of old snapshot into thin volume origin. + Use --ignoreskippedcluster in lvm2-monitor initscript/systemd unit. + Do not use VG read/write state for LV read/write state. + Use --ignoreskippedcluster in activation systemd units if use_lvmetad=0. + Allow approximate allocation when specifying size in percentage terms. + Add basic LVM support for cache[pool] segment types. + Use local exclusive activation for creation of raid in cluster. + Use correctly signed 64b constant when selecting raid volumes. + Add systemd native service for clvmd, cmirrord and clustered LV activation. + Remove ExecReload from lvmetad systemd unit: lvmetad -R undefined. (2.02.98) + Do not fork lvmetad if running under systemd. + Wipe DM_snapshot_cow signature without prompt in new LVs with blkid wiping. + Avoid exposing temporary devices when initializing raid metadata volumes. + Add internal tags command to display any tags defined on the host. + Prohibit use of external origin with size incompatible with thin pool. + Avoid trying to convert single to thin pool and volume at the same time. + Add support for partitions on ZFS zvol. + Fix unwanted drop of hold flocks on forked children. + Respect LVM_LVMETAD_PIDFILE env var for lvm command. + Avoid exposing temporary devices when initializing thin pool volume. + Fix test when checking target version for available thin features. + Detect thin feature external_origin_extend and limit extend when missing. + Rename internal pool_can_resize_metadata() to thin_pool_feature_supported(). + Issue error if libbblkid detects signature and fails to return offset/length. + Update autoconf config.guess/sub to 2014-01-01. + Online thin pool metadata resize requires 1.10 kernel thin pool target. + +Version 2.02.105 - 20th January 2014 +==================================== + Fix thin LV flagging for udev to skip scanning only if the LV is wiped. + Replace use of xfs_check with xfs_repair in fsadm. + Mark lvm1 format metadata as FMT_OBSOLETE. Do not use it with lvmetad. + Invalidate cached VG struct after a PV in it gets orphaned. (2.02.87) + Mark pool format metadata as FMT_OBSOLETE. + Use major:minor in lvm2-pvscan@.service for proper global_filter application. + Syntax and spelling fixes in some man pages. + Dependency scan counts with snapshots and external origins. + Make sure VG extent size is always greater or equal to PV phys. block size. + Optimize double call of stat() for cached devices. + Enable support for thin provisioning for default configuration. + Improve process_each_lv_in_vg() tag processing. + Reordered and simplified logging code. + Fix SYSTEMD_READY assignment for foreign devices in lvmetad udev rules. + Disable online thin pool metadata resize for 1.9 kernel thin target. + Shortened code for initialization of raid segment types. + Cache global library dir in command context. + Return success when inserting dirs and links into device cache. + Test for remote exclusive activation after activation fails. + Support lvconvert --merge for thin snapshots. + Add support to read thin device id from table line entry. + Drop extra test for origin when testing merging origin in lv_refresh(). + Extend lv_remove_single() to not print info about removed LV. + Replace open_count check with lv_check_not_in_use() for snapshot open test. + Add error messages with LV names for failing lv refresh. + Compile/link executables with new RELRO and PIE options (non-static builds). + Support per-object compilation cflags via CFLAGS_object.o. + Automatically detect support for compiler/linker options to use RELRO and PIE. + Add --splitsnapshot to lvconvert to separate out cow LV. + Reinstate origin reload to complete lvconvert -s with active LVs. (2.02.98) + Select only active volume groups if vgdisplay -A is used. + Add -p and LVM_LVMETAD_PIDFILE env var to lvmetad to change pid file. + Allow lvmetad to reuse stale socket. + Only unlink lvmetad socket on error if created by the same process. + Append missing newline to lvmetad missing socket path error message. + Check for non-zero aligment in _text_pv_add_metadata_area() to not div by 0. + Add allocation/use_blkid_wiping to lvm.conf to enable blkid wiping. + Enable blkid_wiping by default if the blkid library is present. + Add configure --disable-blkid_wiping to disable libblkid signature detection. + Add -W/--wipesignatures lvcreate option to support wiping on new LVs. + Add allocation/wipe_signatures_when_zeroing_new_lvs to lvm.conf. + Do not fail the whole autoactivation if the VG refresh done before fails. + Do not connect to lvmetad on vg/lvchange --sysinit -aay and socket absent. + Use lv_check_not_in_use() when testing device in use before merging. + Move test for target present from init_snapshot_merge() to lvconvert. + Check for failure of lvmcache_add_mda() when writing pv. + Check for failure of dev_get_size() when reporting device size. + Drop extra unneeded '/' when scanning sysfs directory. + Fix undef value if skipped clustered VG ignored for toollib PV seg. (2.02.103) + Support validation of VG/LV names in liblvm/python. + Allow creation of PVs with arguments to liblvm/python. + Ensure sufficient metadata copies retained in liblvm/python vgreduce. + Fix installation of profiles from conf subdir when not building in srcdir. + Show UUIDs for missing PVs in reports. + Change dev_size/name, pv_fmt/mda_free/mda_size/uuid fields from pv to label. + Add struct device *dev to struct label. + Introduce process_each_label. + Change void *private to struct format_type *fmt in struct labeller. + Remove pv_read. + Add reporting of thin_id device id for thin volumes. + Fix reporting of empty numerical values for recently-added fields. + Use _field_set_percent/value in reporting code. + +Version 2.02.104 - 13th November 2013 +===================================== + Workaround VG refresh race during autoactivation by retrying the refresh. + Handle failures in temporary mirror used when adding images to mirrors. + Fix and improve logic for implicitely exclusive activations. + Return success when LV cannot be activated because of volume_list filter. + Return proper error state for remote exclusive activation. + Fix missing lvmetad scan for PVs found on MD partitions. + Respect DM_UDEV_DISABLE_OTHER_RULES_FLAG in lvmetad udev rules. + Fix clvmd message verification to not reject REMOTE flag. (2.02.100) + Compare equality of double values with DBL_EPSILON predefined constant. + Use additional gcc warning flags by default. + Add ignore_lvm_mirrors to config file to read/ignore labels on mirrors. + Add internal flag for temporary LVs to properly direct udev to not interfere. + Fix endless loop in blkdeactivate <device>... if unable to umount/deactivate. + Add dev-block-<major>:<minor>.device systemd alias for complete PV tracking. + Use major:minor as short form of --major and --minor arg for pvscan --cache. + Remove 2>/dev/null from three lvm commands executed by vgimportclone. + Add configure --enable-udev-systemd-background-jobs. + Add lvm2-pvscan@.service to run pvscan as a service for lvmetad/autoactivation. + Use #ifdef __linux__ instead of linux throughout. + Fix lvconvert swap of poolmetadata volume for active thin pool. + Check for open count with a timeout before removal/deactivation of an LV. + Report RAID images split with tracking as out-of-sync ("I"). + Improve parsing of snapshot lv segment. + Add workaround for deactivation problem of opened virtual snapshot. + Disable unsupported merge for virtual snapshot. + Move code to remove virtual snapshot from tools to lib for lvm2app. + Fix possible race during daemon worker thread creation (lvmetad). + Fix possible deadlock while clearing lvmetad cache for full rescan. + Recognise NVM Express devices in filter. + Fix failing metadata repair when lvmetad is used. + Fix incorrect memory handling when reading messages from lvmetad. + Fix locking in lvmetad when handling the PV which is gone. + Recognize new flag to skip udev scanning in udev rules and act appropriately. + Add support for flagging an LV to skip udev scanning during activation. + Improve message when unable to change discards setting on active thin pool. + Run full scan before vgrename operation to avoid any cache name collision. + Fix lvconvert when converting to a thin pool and thin LV at once. (2.02.99) + +Version 2.02.103 - 4th October 2013 +=================================== + Ensure vgid matches before removing vgname entry from lvmetad cache. + Add --ignoreskippedcluster for exit status success when clustered VGs skipped. + Fix 3 minute udev timeout so that it is applied for all LVM volumes. + Fix thin/raid & activation config defaults with configure --disable-devmapper. + Fix RAID calculation for sufficient allocatable space. + lvconvert from linear to mirror or RAID1 now honors mirror_segtype_default. + Add thin-performance configuration profile. + Add lvm.conf allocation/thin_pool_chunk_size_policy option. + Fix contiguous & cling allocation policies for parity RAID. (2.02.100) + Have lvmconf --enable/disable-cluster reset/set use_lvmetad. + Don't install separate command symlink for 'lvm devtypes'. (2.02.101) + Add seg_size_pe field to reports. + Support start+length notation with command line PE ranges. + Exit cleanly with message when pvmove cannot restart because LV is inactive. + +Version 2.02.102 - 23rd September 2013 +====================================== + Fix missing build dependency for scripts subdir in Makefile. + Extend lv_info() for more efficient lv_is_active_locally() check. + Fix node up/down handling in clvmd corosync module. + +Version 2.02.101 - 20th September 2013 +====================================== + Fix 3-thread clvmd deadlock triggered by cleanup on EOF from client. + Remove VG from lvmetad before restoring it with vgcfgrestore. + Use strtoull instead of strtol in _get_int_arg. + Add devtypes report command to display built-in recognised block device types. + Fix CC Makefile override which had reverted to using built-in value. (2.02.75) + Recognise bcache block devices in filter (experimental). + Run lvm2-activation-net after lvm2-activation service to prevent parallel run. + Add man page entries for lvmdump's -u and -l options. + Fix lvm2app segfault while using lvm_list_pvs_free fn if there are no PVs. + Improve of clvmd singlenode locking simulation. + lvconvert no longer converts LVs of "mirror" segment type to thinpool. + lvconvert no longer converts thinpool sub-LVs to "mirror" segment type. + Direct udev to use 3min timeout for LVM devices. Recent udev has default 30s. + Do not scan multipath or RAID components and avoid incorrect autoactivation. + Fix MD/loop udev handling to fire autoactivation after setup or coldplug only. + Make RAID capable of single-machine exclusive operations in a cluster. + Drop calculation of read ahead for deactivated volume. + Check for exactly one lv segment in validation of thin pools and volumes. + Fix dmeventd unmonitoring of thin pools. + Fix lvresize for stacked thin pool volumes (i.e. mirrors). + Write Completed debug message before reinstating log defaults after command. + Refresh existing VG before autoactivation (event retrigger/device reappeared). + Use pvscan -b in udev rules to avoid a deadlock on udev process count limit. + Add pvscan -b/--background for the command to be processed in the background. + Don't assume stdin file descriptor is readable. + Avoid unlimited recursion when creating dtree containing inactive pvmove LV. + Require exactly 3 arguments for lvm2-activation-generator. Remove defaults. + Inform lvmetad about any lost PV label to make it in sync with system state. + Support most of lvchange operations on stacked thin pool meta/data LVs. + Enable non-clustered pvmove of snapshots and snapshot origins. + Add ability to pvmove non-clustered RAID, mirror, and thin volumes. + Make lvm2-activation-generator silent unless it's in error state. + Remove "mpath major is not dm major" msg for mpath component scan (2.02.94). + Prevent cluster mirror logs from being corrupted by redundant checkpoints. + Fix ignored lvmetad update on loop device configuration (2.02.99). + Use LVM_PATH instead of hardcoded value in lvm2 activation systemd generator. + Fix vgck to notice on-disk corruption even if lvmetad is used. + Move mpath device filter before partitioned filter (which opens devices). + Split partitioned filter out of lvm_type filter. + Merge filter*.h into a single filter.h. + Require confirmation for vgchange -c when no VGs listed explicitly. + Also skip /var and /var/log by default in blkdeactivate when unmounting. + Add support for bind mounts in blkdeactivate. + Add blkdeactivate -v/--verbose for debug output from external tools used. + Add blkdeactivate -e/--errors for error messages from external tools used. + Suppress messages from external tools called in blkdeactivate by default. + +Version 2.02.100 - 13th August 2013 +=================================== + Fix inability to remove a VG's cluster flag if it contains a mirror. + Suppress arg: prefix in log_sys_error macro when arg is empty string. + Fix bug making lvchange unable to change recovery rate for RAID. + Prohibit conversion of thin pool to external origin. + Workaround gcc v4.8 -O2 bug causing failures if config/checks=1 (32bit arch). + Verify clvmd message validity before processing and log error if incorrect. + When creating PV on existing LV don't forbid reserved LV names on LVs below. + Split out device_is_suspended_or_blocking from device_is_usable. + When converting mirrors, default segtype should be the same unless specified. + Make "raid1" the default mirror segment type. + Fix clogd descriptor leak when daemonizing. + Fix clvmd descriptor leak on restart. + Add pipe_open/close() to use instead of less efficient/secure popen(). + Fix metadata area offset/size overflow if it's >= 4g and while using lvmetad. + Inherit and apply any profile attached to a VG if creating new thin pool. + Add initial support thin pool lvconvert --repair. + Add --with-thin-repair and --with-thin-dump configure options. + Add lvm.conf thin_repair/dump_executable and thin_repair_options. + Require 1.9 thin pool target version for online thin pool metadata resize. + Ignore previous LV seg with alloc contiguous & cling when num stripes varies. + Fix segfault if devices/global_filter is not specified correctly. + +Version 2.02.99 - 24th July 2013 +================================ + Do not zero init 4KB of thin snapshot for non-zeroing thin pool (2.02.94). + Issue an error msg if lvconvert --type used incorrectly with other options. + Use LOG_DEBUG/ERR msg severity instead default for lvm2-activation-generator. + Support ARG_GROUPABLE with merge_synonym (for --raidwritemostly). + Fix segfault when reporting raid_syncaction for older kernels. + Add LV report fields: raid_mismatch_count/raid_sync_action/raid_write_behind. + Add LV reporting fields raid_min_recovery_rate, raid_max_recovery_rate. + Add sync_percent as alias for copy_percent LV reporting field. + Add lv_ prefix to modules reporting field. + Use units B or b (never E) with no decimal places when displaying sizes < 1k. + Add support for poolmetadataspare LV, that will be used for pool recovery. + Improve activation order when creating thin pools in non-clustered VG. + List thin-pool and thin modules for thin volumes. + Correct thin creation error paths. + Use local activation for clearing snapshot COW device. + Add lvm2-activation-net systemd unit to activate LVs on net-attached storage. + Release memory allocated with _cached_info(). + Add whole log_lv and metadata_lv sub volumes when creating partial tree. + Properly use snapshot layer for origin which is also thin volume. + Avoid generating metadata backup when calling update_pool_lv(). + Send thin messages also for active thin pool and inactive thin volume. + Add activation/auto_set_activation_skip to control activation skip flagging. + Add 's(k)ip activation' bit to lvs -o lv_attr to indicate skip flag attached. + Add --ignoreactivationskip to lvcreate/vgchange/lvchange to ignore skip flag. + Add --setactivationskip to lvcreate/lvchange to set activation skip flag. + Automatically flag thin snapshots to be skipped during activation. + Add support for persistent flagging of LVs to be skipped during activation. + Add --type profilable to lvm dumpconfig to show profilable config settings. + Add --mergedconfig to lvm dumpconfig for merged --config/--profile/lvm.conf. + Relase memory and unblock signals in lock_vol error path. + Define LVM2_* command errors in lvm2cmd.h and use in dmeventd plugins. + Move errors.h to tools dir. + Add man page entries for profile configuration and related options. + Improve error loging when user tries to interrupt commands. + Rename _swap_lv to _swap_lv_identifiers and move to allow an additional user. + Rename snapshot segment returning methods from find_*_cow to find_*_snapshot. + liblvm/python API: Additions: PV create/removal/resize/listing + liblvm/python API: Additions: LV attr/origin/Thin pool/Thin LV creation + Add vgs/lvs -o vg_profile/lv_profile to report profiles attached to VG/LV. + Add default.profile configuration profile and install it on make install. + Create a new 'conf' subdir for configuration files including profiles. + Make selected thinp settings customizable by a profile. + Support changing VG/LV profiles: vgchange/lvchange --profile/--detachprofile. + Support storing profile name in metadata for both VGs and LVs. + Add new --profile command line arg to select a configuration profile for use. + Add config/profile_dir to set working directory to load profiles from. + Add configure --with-default-profile-subdir to select dir to keep profiles in. + Add support for configuration profiles. + Introduce config_source wrapper for identification of configuration sources. + Avoid creation of multiple archives for one command. + Use mirror_segtype_default if type not specified for linear->mirror upconvert. + Fix use of too big chunks of memory when communication with lvmetad. + Fix vgcfgrestore crash when specified incorrect vg name. + Refine lvm.conf and man page documentation for autoactivation feature. + Add support for thin volumes in vgsplit. + Also filter partitions on mpath components if multipath_component_detection=1. + Add lvresize support for online thin pool metadata volume resize. + Add helper functions find_pool_lv() and pool_can_resize_metadata(). + Add detection for thin pool metadata resize kernel support. + Report lvs volume type 'e' with higher priority. + Report lvs volume type 'o' also for external origin volumes. + Report lvs target type 't' only for thin pools and thin volumes. + Fix test for active snapshot in cluster before resizing it. + Allow local activation to receive a locally-supplied LV struct. + Add vg->vg_ondisk / lv_ondisk() holding committed metadata. + Report backtrace from dump filter error path. + Do not use persistent filter with lvmetad. + Composable persistent filter functionality for global filter. + Override system's global_filter settings for vgimportclone. + Detect maximum usable size for snapshot for lvresize. + Creation of snapshot takes at most 100% origin coverage. + Add cow_max_extents() to calc extents for 100% origin coverage. + For creation of snapshot require size for at least 3 chunks. + Fix lvresize --use-policies of VALID but 100% full snapshot. + Do not accept size parameters bigger then 16EiB. + Fix release of PV's fid in free_pv_fid(). + Skip monitoring of snapshots that are already bigger then origin. + Add lv_is_cow_covering_origin() to check if cow covers origin size. + Use libdm dm_get_status_snapshot() to parse snapshot status. + Add detection of mounted fs also for vgchange deactivation. + Replace 'lv_is_active' with more correct/specific variants (e.g. *_locally). + Refuse to init a snapshot merge in lvconvert if there's no kernel support. + Fix exported symbols regex for non-GNU busybox sed. + Accept --yes in all commands so test scripts can be simpler. + Fix alignment of PV data area if detected alignment less than 1 MB (2.02.74). + Fix memory resource leak in memlocking error path. + Fix premature DM version checking which caused useless mapper/control access. + Add "active" LV reporting field to show activation state. + Add "monitor" segment reporting field to show dmevent monitoring status. + Document lvextend --use-policies option in man. + Fix creation and removal of clustered snapshot. + Fix clvmd caching of metadata when suspending inactive volumes. + Find newest timestamp of merged config files. + Fix assignment order for vg fid for lvm1 and pool format. + Fix memleak in dmeventd thin plugin in device list obtaining err path. + Add explicit message about unsupported pvmove for thin/thinpool volumes. + Fix lvmetad error path in lvmetad_vg_lookup() for null vgname. + Fix clvmd _cluster_request() return code in memory fail path. + Add lvcreate/lvchange --[raid]{min|max}recoveryrate for raid LVs. + Add lvchange --[raid]writemostly/writebehind support for RAID1 + Add lv_change_activate() for common activation code in vg/lvchange. + Add lvchange --[raid]syncaction for scrubbing of RAID LVs. + Improve RAID kernel status retrieval to include sync_action/mismatch_cnt. + Add external origin support for lvcreate. + Improve lvcreate, lvconvert and lvm man pages. + Clean up format1 PV write to remove a need for an orphan VG for it to pass. + Fix vgextend to not allow a PV with 0 MDAs to be used while already in a VG. + Move update_pool_params() from /tools to /lib for better reuse. + Give precedence to EMC power2 devices with duplicate PVIDs. + Add --validate option to lvm dumpconfig to validate current config on demand. + Add --ignoreadvanced and --ignoreunsupported switch to lvm dumpconfig. + Add --withcomments and --withversions switch to lvm dumpconfig. + Add --type {current|default|missing|new} and --atversion to lvm dumpconfig. + Support automatic config validation and add 'config' section to lvm.conf. + Add pvs -o pv_ba_start,pv_ba_size to report bootloader area start and size. + Add --bootloaderareasize to pvcreate and vgconvert to create bootloader area. + Add PV header extension: extension version, flags and bootloader areas. + Initial support for lvconvert of thin external origin. + Add _lv_remove_segs_using_this_lv() for removal of dependent lvs. + Improve activation code for better support of stacked devices. + Add _add_layer_target_to_dtree() for adding linear layer into dtree. + Extend _cached_info() to accept layer string. + vgimport '--force' now allows import of VGs with missing PVs. + Fix PV alignment to incorporate alignment offset if the PV has zero MDAs. + Add global/raid10_segtype_default to lvm.conf. + Allow removal or replacement of RAID LV components that are error segments. + Make 'vgreduce --removemissing' able to handle RAID LVs with missing PVs. + Accept activation/raid_region_size in preference to mirror_region_size config. + Fix pvs -o pv_free reporting for PVs with zero PE count. + Fix missing cleanup of flags when the LV is detached from pool. + Fix check for some forbidden discards conversion of thin pools. + Add pool_is_active() to check for any pool related active LV. + Report blank origin_size field if the LV doesn't have an origin instead of 0. + Do not take a free lv name argument for lvconvert --thinpool option. + Avoid flushing thin pool when just requesting transaction_id. + Add internal function lv_layer() to obtain layer name for LV. + Report partial and in-sync RAID attribute based on kernel status + Fix blkdeactivate to handle nested mountpoints and mangled mount paths. + Use LC_ALL to set locale in daemons and fsadm instead of lower priority LANG. + Avoid crash-inducing race in lvmetad when VG disappears during rename. + Add log/debug_classes to lvm.conf to control debug log messages. + Synchronize with udev in pvscan --cache and fix dangling udev_sync cookies. + Fix autoactivation to not autoactivate VG/LV on each change of the PVs used. + Limit RAID device replacement to repair only if LV is not in-sync. + Disallow RAID device replacement or repair on inactive LVs. + Fix possible race while removing metadata from lvmetad. + Fix possible deadlock when querying and updating lvmetad at the same time. + Check lvmcache_info_from_pvid and recall only when needed in _pv_read. + Check for memory failure of dm_config_write_node() in lvmetad. + Fix socket leak on error path in lvmetad's handle_connect. + Check for failing id_read_format() in _pv_populate_lvmcache. + Fix memleak on error path for lvmetad's pv_found. + Unlock vg mutex in error path when lvmetad tries to lock_vg. + Detect key string duplication failure in config_make_nodes_v in libdaemon. + Detect fid creation failure in _scan_file in format_text. + Log output also to syslog when abort_on_internal_error is set. + Add LV snapshot support to liblvm and python-lvm. + Avoid a global lock in pvs when lvmetad is in use. + Fix crash in pvscan --cache -aay triggered by non-mda PV. + Allow lvconvert --stripes/stripesize only with --mirrors/--repair/--thinpool. + Fix memleak in device_is_usable mirror testing function. + Do not ignore -f in lvconvert --repair -y -f for mirror and raid volumes. + Disallow pvmove on RAID LVs until they are addressed properly + Allow empty activation/{auto_activation|read_only|}_volume_list config option. + Add lvm.conf option global/thin_disabled_features. + Add lvconvert support to swap thin pool metadata volume. + Implement internal function detach_pool_metadata_lv(). + Fix lvm2app to return all property sizes in bytes (not sectors). + Recognize DM_DISABLE_UDEV environment variable for a complete fallback. + Do not verify udev operations if --noudevsync command option is used. + Fix lvm2app and return lvseg discards property as string. + Allow vgcfgrestore of lvm2 metadata with thin volumes if --force is used. + Recognise Storage Class Memory (IBM S/390) devices in filter. + Recognise STEC skd devices in filter. + Recognise Violin Memory vtms devices in filter. + Add lvm.conf thin pool allocation settings thin_pool_{chunk_size|discards|zero}. + Support discards for non-power-of-2 thin pool chunks. + Automatically restore MISSING PVs with no MDAs. + When no --stripes argument is given when creating a RAID10 volume, default to 2 stripes. + Do not allow lvconvert --splitmirrors on RAID10 logical volumes. + Skip mlocking [vectors] on arm architecture. + Support allocation of pool metadata with lvconvert command. + Move common functionality for thin lvcreate and lvconvert to toollib. + Repair a mirrored log before the mirror itself when both fail. + Add python-lvm unit test case + Exit pvscan --cache immediately if cluster locking used or lvmetad not used. + Don't use lvmetad in lvm2-monitor.service ExecStop to avoid a systemd issue. + Remove dependency on fedora-storage-init.service in lvm2 systemd units. + Depend on lvm2-lvmetad.socket in lvm2-monitor.service systemd unit. + Hardcode use_lvmetad=0 if cluster locking used and issue a warning msg. + Avoid trying to read a mirror that has a failed device in its mirrored log. + Relax ignore_suspended_devices to read from mirrors that don't have a device marked failed. + Change lvs heading Copy% to Cpy%Sync and print RAID4/5/6 sync% there too. + Fix clvmd support for option -d and properly use its argument. + Support use of option --yes for lvchange --persistent. + Fix memory leak on error path for pvcreate with invalid uuid. + Implement ref-counting for parents in python lib. + Add lv_is_active_locally and use instead of most local lv_info calls. + Reduce some log_error messages to log_warn where we don't fail. + Remove python liblvm object. systemdir can only be changed using env var now. + +Version 2.02.98 - 15th October 2012 +=================================== + Switch from DEBUG() to DEBUGLOG() in lvmetad as -DDEBUG is already used. + Prohibit not yet supported change of thin-pool to read-only. + Support creation of read-only thin volumes (lvcreate -p r). + Using autoextend percent 0 for thin pool fails 'lvextend --use-policies'. + Introduce blkdeactivate script to deactivate block devs with dependencies. + Implement devices/global_filter to hide devices from lvmetad. + Make vgscan --cache an alias for pvscan --cache. + Clear lvmetad metadata/PV cache before a rescan. + Fix a segmentation fault upon receiving a corrupt lvmetad response. + Give inconsistent metadata warnings in pvscan --cache. + Make lvremove ask before discarding data areas. + Avoid overlapping locks that could cause a deadlock in lvmetad. + Fix memory leaks in libdaemon and lvmetad. + Optimize libdaemon logging for a fast no-output path. + Only create lvmetad pidfile when running as a daemon (no -f). + Warn if lvmetad is running but disabled. + Warn about running lvmetad with use_lvmetad = 0 in example.conf. + Update lvmetad help output (flags and their meaning). + Make pvscan --cache read metadata from LVM1 PVs. + Make libdaemon buffer handling asymptotically more efficient. + Add lvmdump -l, to collect a state dump from lvmetad. + Make --sysinit suppress lvmetad connection failure warnings. + Prohibit usage of lvcreate --thinpool with --mirrors. + Fix lvm2api origin reporting for thin snapshot volume. + Add configure --enable-python_bindings for liblvm2app to new python subdir. + Add implementation of lvm2api function lvm_percent_to_float. + Allow non power of 2 thin chunk sizes if thin pool driver supports that. + Allow limited metadata changes when PVs are missing via [vg|lv]change. + Do not start dmeventd for lvchange --resync when monitoring is off. + Remove pvscan --cache from lvm2-lvmetad init script. + Remove ExecStartPost with pvscan --cache from lvm2-lvmetad.service. + Report invalid percentage for property snap_percent of non-snaphot LVs. + Disallow conversion of thin LVs to mirrors. + Fix lvm2api data_percent reporting for thin volumes. + Do not allow RAID LVs in a clustered volume group. + Add --discards to lvconvert. + Add --poolmetadata to lvconvert and support thin meta/data dev stacking. + Support changes of permissions for thin snapshot volumes. + Enhance insert_layer_for_lv() with recursive rename for _tdata LVs. + Skip building dm tree for thin pool when called with origin_only flag. + Add internal lv_rename_update() to rename LV without updating mda. + Ensure descriptors 0,1,2 are always available, using /dev/null if necessary. + Use /proc/self/fd when available for closing opened descriptors efficiently. + Add missing pkg init with --enable-testing in configure.in (2.02.71). + Fix inability to create, extend or convert to a large (> 1TiB) RAID LV. + Split out daemon-io from daemon-shared and always build libdaemonclient. + Update lvmetad communications to cope with clients using different filters. + Add (p)artial attribute to lvs. + Don't try to issue discards to a missing PV to avoid segfault. + Clear LV_NOSYNCED flag when a RAID1 LV is converted to a linear LV. + Disallow RAID1 upconvert if the LV was created with --nosync. + Depend on systemd-udev-settle in units generated by activation generator. + Fix vgchange -aay not to activate non-matching LVs that follow a matching LV. + Fix lvchange --resync for RAID LVs which had no effect. + Restructure mirror resync code. + Disallow addition of RAID images until the array is in-sync. + Fix RAID LV creation with '--test' so valid commands do not fail. + Add lvm_lv_rename() to lvm2api. + Fix setvbuf code by closing and reopening stream before changing buffer. + Disable private buffering when using liblvm. + When private stdin/stdout buffering is not used always use silent mode. + Add log/silent to lvm.conf equivalent to -qq. + Suppress non-essential stdout with -qq. + Switch non-essential log_print messages to log_print_unless_silent. + Use -q as short form of --quiet. + Add RAID10 support (--type raid10). + Reuse _reload_lv() in more lvconvert functions. + Fix 32-bit device size arithmetic needing 64-bit casting throughout tree. + Remove numerous unnecessary #includes and the empty util.c. + Fix dereference of NULL in lvmetad error path logging. + Fix buffer memory leak in lvmetad logging. + Add support for lvcreate --discards. + Correct the discards field in the lvs manpage (2.02.97). + Use proper condition to check for discards settings unsupported by kernel. + Reinstate correct default to ignore discards for thin metadata from old tools. + Issue error message when -i and -m args do not match specified RAID type. + Change lvmetad logging syntax from -ddd to -l {all|wire|debug}. + Add new libdaemon logging infrastructure. + +Version 2.02.97 - 7th August 2012 +================================= + Improve documention of allocation policies in lvm.8. + Increase limit for major:minor to 4095:1048575 when using -My option. + Add make install_systemd_generators. + Add generator for lvm2 activation systemd units. + Add lvm_config_find_bool lvm2app fn to retrieve bool value from config tree. + Respect --test when using lvmetad. + No longer capitalise first LV attribute char for invalid snapshots. + Allow vgextend to add PVs to a VG that is missing PVs. + Recognise Micron PCIe SSDs in filter and move array out to device-types.h. + Fix dumpconfig <node> to print only <node> without its siblings. (2.02.89) + Do not issue "Failed to handle a client connection" error if lvmetad killed. + Support lvchange --discards and -Z with thin pools. + Add discard LV segment field to reports. + Add --discards to lvcreate --thin. + Set discard and external snapshot features if thin pool target is vsn 1.1+. + Count percentage of completeness upwards not downwards when merging snapshot. + Skip activation when using vg/lvchange --sysinit -a ay and lvmetad is active. + Fix extending RAID 4/5/6 logical volumes + Fix test for PV with unknown VG in process_each_pv to ignore ignored mdas. + Update man pages with --activate ay option and auto_activation_volume_list. + Fix _alloc_parallel_area to avoid picking already-full areas for raid devices. + Use vgchange -aay instead of vgchange -ay in clmvd init script. + Add activation/auto_activation_volume_list to lvm.conf. + Add --activate ay to lvcreate, lvchange, pvscan and vgchange. + Add support for volume autoactivation using lvmetad. + Add --activate synonym for --available arg and prefer --activate. + Never issue discards when LV extents are being reconfigured, not deleted. + Allow release_lv_segment_area to fail as functions it calls can fail. + Open device read-only instead of read-write when obtaining readahead value. + Fix lvconvert thin pool error path NULL pointer dereference. + Detect create_instance() failure in pvscan_lvmetad_single(). + Use 64-bit calculations for reserved memory and stack. + Fix missing sync of filesystem when creating thin volume snapshot. + +Version 2.02.96 - 8th June 2012 +=============================== + Upstream source repo now fedorahosted.org git not sources.redhat.com CVS. + Fix error paths for regex filter initialization. + Re-enable partial activation of non-thin LVs until it can be fixed. (2.02.90) + Fix alloc cling to cling to PVs already found with contiguous policy. + Fix cling policy not to behave like normal policy if no previous LV seg. + Fix allocation loop not to use later policies when --alloc cling without tags. + Append _TO_LVSEG to names of internal A_CONTIGUOUS and A_CLING flags. + Add missing pkg init --with-systemdsystemunitdir in configure.in (2.02.92). + Fix division by zero if PV with zero PE count is used during vgcfgrestore. + Add initial support for thin pool lvconvert. + Fix lvrename for thin volumes (regression in for_each_sub_lv). (2.02.89) + Fix up-convert when mirror activation is controlled by volume_list and tags. + Warn of deadlock risk when using snapshots of mirror segment type. + Fix bug in cmirror that caused incorrect status info to print on some nodes. + Remove statement that snapshots cannot be tagged from lvm man page. + Disallow changing cluster attribute of VG while RAID LVs are active. + Fix lvconvert error message for non-mergeable volumes. + Allow subset of failed devices to be replaced in RAID LVs. + Prevent resume from creating error devices that already exist from suspend. + Improve clmvd singlenode locking for better testing. + Update and correct lvs man page with supported column names. + Handle replacement of an active device that goes missing with an error device. + Change change raid1 segtype always to request a flush when suspending. + Add udev info and context to lvmdump. + Add lvmetad man page. + Fix RAID device replacement code so that it works under snapshot. + Fix inability to split RAID1 image while specifying a particular PV. + Update man pages to give them all the same look&feel. + Fix lvresize of thin pool for striped devices. + For lvresize round upward when specifying number of extents. + For lvcreate with %FREE support rounding downward stripe alignment. + Change message severity to log_very_verbose for missing dev info in udev db. + Fix lvconvert when specifying removal of a RAID device other than last one. + Fix ability to handle failures in mirrored log in dmeventd plugin. (2.02.89) + Fix unlocking volume group in vgreduce in error path. + Cope when VG name is part of the supplied name in lvconvert --splitmirrors -n. + Fix exclusive lvchange running from other node. (2.02.89) + Add 'vgscan --cache' functionality for consistency with 'pvscan --cache'. + Keep exclusive activation in pvmove if LV is already active. + Disallow exclusive pvmove if some affected LVs are not exclusively activated. + Remove unused and wrongly set cluster VG flag from clvmd lock query command. + Fix pvmove for exclusively activated LV pvmove in clustered VG. (2.02.86) + Always free hash table on update_pvid_to_vgid() in lvmetad. + Update and fix monitoring of thin pool devices. + Check hash insert success in lock_vg in clvmd. + Check for buffer overwrite in get_cluster_type() in clvmd. + Fix global/detect_internal_vg_cache_corruption config check. + Update lcov Makefile target to support all dmeventd plugins. + Fix initializiation of thin monitoring. (2.02.92) + Cope with improperly formatted device numbers in /proc/devices. (2.02.91) + Exit if LISTEN_PID environment variable incorrect in lvmetad systemd handover. + Use pvscan --cache instead of vgscan in lvmetad scripts. + Fix fsadm propagation of -e option. + Fix fsadm parsing of /proc/mounts files (don't check for substrings). + Fix fsadm usage of arguments with space. + Fix arg_int_value alongside ARG_GROUPABLE --major/--minor for lvcreate/change. + Fix name conflicts that prevent down-converting RAID1 when specifying a device + Improve thin_check option passing and use configured path. + Add --with-thin-check configure option for path to thin_check. + Fix error message when pvmove LV activation fails with name already in use. + Better structure layout for device_info in dev_subsystem_name(). + Change message severity for creation of VG over uninitialised devices. + Fix error path for failed toolcontext creation. + Detect lvm binary path in lvmetad udev rules. + Don't unlink socket on lvmetad shutdown if instantiated from systemd. + Restart lvmetad automatically from systemd if it exits from uncaught signal. + Fix warn msg for thin pool chunk size and update man for chunksize. (2.02.89) + +Version 2.02.95 - 6th March 2012 +================================ + If unspecified, adjust thin pool metadata and chunk size to fit into 128MB. + Print just warning on thin pool check callback path for failing check. + Always use 64bit arithmetic with VG extent_size expression. + Validate udev structures in _insert_udev_dir(). + Take repeatable --major --minor with pvscan --cache instead of major:minor. + Scan all devices for lvmetad if 'pvscan --cache' used without device list. + Populate lvmcache from lvmetad before displaying PVs in pvscan. (2.02.94) + Suppress incorrect -n pvscan warning now always displayed. (2.02.94) + +Version 2.02.94 - 3rd March 2012 +================================ + Add support to execute thin_check with each de/active of thin pool. + Fix automatic estimation of metadata device size for thin pool. + Test for alloc fail from _alloc_pv_segment() in _extend_pv(). + Check for alloc fail from get_segtype_from_string() in _lvcreate_params(). + Add _rimage as reserved suffix to lvm.8 man page. + Improve error logging from mpath filter. + Check for allocation failure in hold_lock() in clvmd. + Use set_lv() (wipe initial 4KiB) for non zeroed thin volume. + Allow cluster mirrors to handle the absence of the checkpoint lib (libSaCkpt). + Revert free of allocated segtype in init segment error path (2.02.89). + Test dm_hash_insert() failures in filter-persistent.c and fid_add_mda(). + Ensure clvmd message is always NUL-terminated after read. + Add some close() and dev_close() error path backtraces. + Set stdin/stdout/stderr to /dev/null for polldaemon. + Limit the max size of processed clvmd message to ~8KB. + Do not send uninitialised bytes in cluster error reply messages. + Use unsigned type for bitmask instead of enum type for lvm properties. + Add missing cleanup of excl_uuid hash on some exit paths of clvmd. + Check for existence of vg_name in _format1/_pool_vg_read(). + Fix missing break in _format_pvsegs (2.02.92). + Test seg pointer for non-null it in raid_target_percent error path. + Check for errors in _init_tags() during config loading. + Always check result of _set_vg_name() in lvcreate. + Drop unused call to uname() during clvmd initialization. + Test allocation result in sysfs filter creation. + Limit sscanf parameters with buffer size in clvmd get_initial_state(). + Use const lv pointer for lv_is_active...() functions. + Use same signed numbers in _mirrored_transient_status(). + Support 'pvscan --cache' to update lvmetad state from specific PVs. + Provide new metadata daemon for testing with configure --enable-lvmetad . + Integrate client-side lvmetad into build. + +Version 2.02.93 - 23rd February 2012 +==================================== + Require number of stripes to be greater than parity devices in higher RAID. + Fix allocation code to allow replacement of single RAID 4/5/6 device. + Check all tags and LV names are in a valid form in vg_validate. + Add tmpfiles.d style configuration for lvm2 lock and run directory. + Add configure --with-tmpfilesdir for dir holding volatile-file configuration. + Allow 'lvconvert --repair' to operate on RAID 4/5/6. + Fix build_parallel_areas_from_lv to account correctly for raid parity devices. + Print message when faulty raid devices have been replaced. + +Version 2.02.92 - 20th February 2012 +==================================== + Read dmeventd monitoring config settings for every lvm command. + For thin devices, initialize monitoring only for thin pools not thin volumes. + Make conversion from a synced 'mirror' to 'raid1' not cause a full resync. + Properly test buffer for unit check in units_to_bytes(). + Add configure --with-systemdsystemunitdir. + Add check for allocation failure in _build_matcher(). + Add check for rimage name allocation failure in _raid_add_images(). + Add check for mda_copy failure in _text_pv_setup(). + Add check for _mirrored_init_target failure. + Add free_orphan_vg. + Skip pv/vg_set_fid processing if the fid is same. + Check for foreach loop errors in _vg_read_orphans() (2.02.91). + Clean error paths for format instance creation (2.02.91). + Release vg in error path of _format1_vg_read() instead of just free(). + Report allocation failure for allocation of PV structure. + Add clvmd init dependency on dlm service when running with new corosync. + +Version 2.02.91 - 12th February 2012 +==================================== + Remove PV-based format instances (which are no longer needed). + Link all orphan PVs directly to a per-format global orphan VG. + Refactor lvmcache around an internal API. + Stop processing lvextend if trying to extend a mirror that is being recovered. + Add pool_below_threshold() function to check thin pool percent status. + Fix test for snap percent for failing merge when removing LV. + Switch int to void return for str_list_del(). + Fix error path handling in _build_desc(). + Add range test for device number in _scan_proc_dev(). + Use signed long for sysconf() call in cmirrord. + Do not write in front of log buffer in print_log(). + Add boundary test for number of mirror devs and logs. + Check that whole locking_dir fits _lock_dir buffer in init_file_locking(). + Use list functions for label_exit(). + Ensure strncpy() function always ends with '\0'. + Set status in _fsadm_cmd() for error path. + Add missing deps for lvm2api for rebuild when lvm-internal is changed. + Fix resource leaks for failing allocation of formats (lvm1/2,pool). + Release allocated resources in error path for composite_filter_create(). + Do not use lstat() results when failed in _rm_link(). + Remove a "waiting for another thread" log message from dmeventd plugins. + +Version 2.02.90 - 1st February 2012 +=================================== + sync_local_dev_names before (re)activating mirror log for initialisation. + Disable partial activation for thin LVs and LVs with all missing segments. + Do not print warning for pv_min_size between 512KB and 2MB. + Clean up systemd unit ordering and requirements. + Fix lcov reports when srcdir != builddir. + Allow ALLOC_NORMAL to track reserved extents for log and data on same PV. + Automatically detect whether corosync clvmd needs to use confdb or cmap. + Fix data% report for thin volume used as origin for non-thin snapshot. + +Version 2.02.89 - 26th January 2012 +=================================== + Add missing check for uname result in clvmd TEST processing. + Fix memleak in target_version() error path (unsupported LIST_VERSIONS). + Limit data_alignment and data_alignment_offset to 32bit values. + Check for correctness of uint64 dev_size value in format_text. + Thin pools have segment fields thin_count, zero, transaction_id. + Add data_percent and metadata_percent for thin pools to lvs -v. + Add data_lv & metadata_lv fields to lvs for thin pools. + Add data_percent & pool_lv fields to lvs for thin volumes. + Rename origin_only parm to use_layer for lv_info and use with thin LVs. + Add lv_thin_pool_transaction_id to read the transaction_id value. + Use {suspend,resume}_origin_only when up-converting RAID, as mirrors do. + Always add RAID metadata LVs to deptree (even when origin_only is set). + Change exclusive LV activation logic to try local node before remote nodes. + Add CLVMD_FLAG_REMOTE to skip processing on local node. + Prompt if request is made to remove a snapshot whose "Merge failed". + Allow removal of an invalid snapshot that was to be merged on next activation. + Don't allow a user to merge an invalid snapshot. + Use m and M lv_attr to indicate that a snapshot merge failed in lvs. + Differentiate between snapshot status of "Invalid" and "Merge failed". + Report snapshot usage percent of origin volume when a snapshot is merging. + Require global/lvdisplay_shows_full_device_path for (bogus) lvm1-style paths. + Do not report linear segtype for non-striped targets. + Record creation host & time for each LV and report as lv_time & lv_host. + Make error message hit when preallocated memlock memory exceeded clearer. + Use R lv_attr to indicate read-only activation of non-read-only device in lvs. + Show read-only activation override in lvdisplay & add 4 to perms in -c. + Add activation/read_only_volume_list to override LV permission in metadata. + Give priority to emcpower devices with duplicate PVIDs. + Add check for error in _adjust_policy_params() (lvextend --use-policies). + Round specified percentages upwards (%LV, %VG...) when resizing LVs. + Use dmeventd_lvm2_command in dmeventd plugins snapshot, raid, mirror. + Add helper dmeventd_lvm2_command() to libdevmapper-event-lvm2 library. + Update documentation for dmeventd. + Remove unnecessary stat before opening device in dev_open_flags. + Reduce number of lstat calls when selecting device alias. + Add _dev_init to initialize common struct device members. + Always zalloc struct device during initialization. + Fix missing thread list manipulation protection in dmeventd. + Do not derefence lv pointer in _percent_run() function before NULL check. + Allow empty strings for description and creation_host config fields. + Issue deprecation warning when removing last lvm1-format snapshot. + Reinstate support for snapshot removal with lvm1 format. (2.02.86) + Add policy-based automated repair of RAID logical volumes. + Don't allow two images to be split and tracked from a RAID LV at one time. + Don't allow size change of RAID LV that is tracking changes for a split image. + Don't allow size change of RAID sub-LVs independently. + Don't allow name change of RAID LV that is tracking changes for a split image. + Do not allow users to change the name of RAID sub-LVs independently. + Do not allow users to change permissions on RAID sub-LVs. + Allow lvconvert to replace specified devices in a RAID array. + Add activation/use_linear_target enabled by default. + Use gcc warning options only with .c to .o compilation. + Move y/n prompts to stderr and repeat if response has both 'n' and 'y'. + Replace the unit testing framework with CUnit (--enable-testing). + Fix dmeventd snapshot monitoring when multiple extensions were involved. + Don't ignore configure --mandir and --infodir. + Drop pool memory allocated within lv_has_target_type(). + Reduce stack allocation of some PATH_MAX sized char buffers. + Unlock memory before writing metadata. + Add query before removing snapshots when inactive snapshot origin is removed. + Allow changing availability state of snapshots. + Skip non-virtual snapshots for availability change for lvchange with vg name. + Skip adjusting mirror region size unless mirror or raid. + Reorder prompt conditions for removal of active volumes. + Avoid 'mda inconsistency' by properly registering UNLABELLED_PV flag.(2.02.86) + Fix --enable-static_link unless using --enable-dmeventd / --enable-udev_sync. + Move gentoo MAKEDEV to /sbin in lvm2create_initrd. + Add filter to avoid scan of device if it is part of active multipath. + Add missing default $LVM_VG_NAME usage for snapshots. + Avoid extent_count overflow with lvextend. + Add missing lvrename mirrored log recursion in for_each_sub_lv. + Improve lv_extend stack reporting. + Increase virtual segment size instead of creating multiple segment list. + Add last_seg(lv) internal function. + Support empty string for log/prefix. + Disallow mirrored logs for cluster mirrors. (2.02.72) + Don't print char type[8] as a plain string in pvck PV type. + Use vg memory pool implicitly for vg read. + Always use vg memory pool for allocated lv segment. + Remove extra 4kB buffer allocated on stack in print_log(). + Make move_lv_segment non-static function and use dm_list function. + Pass exclusive LV locks to all nodes in the cluster. + Improve lvcreate chunksize man page description. + Improve man page style for lvcreate & lvs. + Avoid recursive calls to dmeventd in its LVM plugins. + Log dev name now returned to kernel for registering during cmirror CTR. + Fix lv_info open_count test for disabled verify_udev_operations. (2.02.86) + Simplify code for lvm worker thread in clvmd. + Use pthread_barrier to synchronize clvmd threads at startup. + Limit clvmd's thread size to 128KiB and ignore activation/reserved_stack. + Reduce default preallocated stack size to 64KiB. + Add check for access through NULL pointer when refresh_filter() fails. + Use pthread condition for SINGLENODE lock implementation. + Improve backtrace reporting for some dev_manager_ functions. + Change message severity to log_warn when symlink creation fails. + Add ability to convert mirror segtype to RAID1 segtype. + Add ability to convert from linear to RAID1. + Add ability to extend mirrors with '--nosync' option. + Fix splitmirror LV names to maintain consistent state in a cluster. + Apply appropriate udev flags when suspending/resuming mirror sub-LVs. + Fix vgsplit to handle mirrored logs. + Clarify multi-name device filter pattern matching explanation in lvm.conf. + Introduce revert_lv for better pvmove cleanup. + Replace incomplete pvmove activation failure recovery code with a message. + Abort if _finish_pvmove suspend_lvs fails instead of cleaning up incompletely. + Change suspend_lvs to call vg_revert internally. + Change vg_revert to void and remove superfluous calls after failed vg_commit. + Use execvp for CLVMD restart to preserve environment settings. + Restart CLVMD with same cluster manager. + Fix log_error() usage in raid and unknown segtype initialisation. + Improve testing Makefile. + Fix install_ocf make target when srcdir != builddir. (2.02.80) + Support env vars LVM_CLVMD_BINARY and LVM_BINARY in clvmd. + Fix restart of clvmd (preserve exlusive locks). (2.02.64) + Add 'Volume Type' lv_attr characters for RAID and RAID_IMAGE. + Add activation/retry_deactivation to lvm.conf to retry deactivation of an LV. + Replace open_count check with holders/mounted_fs check on lvremove path. + Disallow the creation of mirrors (mirror or raid1 segtype) with only one leg. + Cleanup restart clvmd code (no memory allocation, debug print passed args). + Add all exclusive locks to clvmd restart option args. + Always send the whole clvmd packet header in refresh commands. + Add missing error checks for some system calls in cmirrord. + Add missing log_error() to lvresize command when fsadm tool fails. + Add support for DM_DEV_DIR device path into fsadm script. + Support different PATH setting for fsadm script testing. + Surround all executed commands with quotes in fsadm script. + Fix missing '$' in test for content of "$LVM" in fsadm script. + Move debug message in exec_cmd after sync_local_dev_names. + Fix clvmd processing of invalid request on local socket. + Fix command line option decoding. + Reset LV status when unlinking LV from VG. + Fix overly-strict extent-count divisibility requirements for striped mirrors. + Fix rounding direction in lvresize when reducing volume size. + Fix possible overflow of size if %FREE or %VG is used. + Fix vgchange activation of snapshot with virtual origin. + Activate virtual snapshot origin exclusively (only on local node in cluster). + Fix lv_mirror_count to handle mirrored stripes properly. + Fix failure to down-convert a mirror to linear due to udev "dev open" conflict + Fix mirrored log creation when PE size is small: use log_size >= region_size. + Fix log size calculation when only a log is being added to a mirror. + Add 7th lv_attr char to show the related kernel target. + Terminate pv_attr field correctly. (2.02.86) + Fix 'not not' typo in pvcreate man page. + Improve man page style for fsadm, lvreduce, lvremove, lvrename & lvresize. + Support break for vgchange and vgrefresh operation. + Switch int to unsigned type for pvmetadatacopies for pv_create(). + Replace :space: with [\t ] for awk in vgimportclone (not widely supported). + Begin using 64-bit status field flags. + Detect sscanf recovering_region input error in cmirrord pull_state(). + Fix error path bitmap leak in cmirrord import_checkpoint(). + Log unlink() error in cmirrord remove_lockfile(). + Remove incorrect requirement for -j or -m from lvchange error message. + Fix unsafe table load when splitting off smaller mirror from a larger one. + Use size_t return type for text_vg_export_raw() and export_vg_to_buffer(). + Add configure --enable-lvmetad for building the (experimental) LVMetaD. + Fix resource leak when strdup fails in _get_device_status() (2.02.85). + Directly allocate buffer memory in a pvck scan instead of using a mempool. + Add configure --with-thin for segtypes "thin" and "thin_pool". + Fix raid shared lib segtype registration (2.02.87). + +Version 2.02.88 - 19th August 2011 +================================== + Remove incorrect 'Breaking' error message from allocation code. (2.02.87) + Add lvconvert --merge support for raid1 devices split with --trackchanges. + Support lvconvert of -m1 raid1 devices to a higher number. + Add --trackchanges support to lvconvert --splitmirrors option for raid1. + Support splitting off a single raid1 rimage in lvconvert --splitmirrors. + Use sync_local_dev_names when reducing number of raid rimages in lvconvert. + Add -V as short form of --virtualsize in lvcreate. + Fix make clean not to remove Makefile. (2.02.87) + +Version 2.02.87 - 12th August 2011 +================================== + Fix make distclean to remove stray dmeventd and exported symbols files. + Add global/detect_internal_vg_cache_corruption to lvm.conf. + Use memory pool locking to check for corruption of internal VG structs. + Cache and share generated VG structs. + Fix possible format instance memory leaks and premature releases in _vg_read. + Suppress locking error messages in monitoring init scripts. + If pipe in clvmd fails return busy instead of using uninitialised descriptors. + Add ability to reduce the number of mirrors in raid1 arrays to lvconvert. + Add dmeventd plugin for raid. + Replace free_vg with release_vg and move it to vg.c. + Remove INCONSISTENT_VG flag from the code. + Remove lock from cache in _lock_vol even if unlock fails. + Initialise clvmd locks before lvm context to avoid open descriptor leaks. + Remove obsolete gulm clvmd cluster locking support. + Suppress low-level locking errors and warnings while using --sysinit. + Remove unused inconsistent_seqno variable in _vg_read(). + Remove meaningless const type qualifiers on cast type. + Add test for fcntl error in singlenode client code. + Remove --force option from lvrename manpage. + Add global/mirror_segtype_default to pick md raid or dm mirror as default. + Add configure --with-raid for new segtype 'raid' for MD RAID 1/4/5/6 support. + Change DEFAULT_UDEV_SYNC to 1 so udev_sync is used if there is no config file. + Add systemd unit file to provide lvm2 monitoring. + Compare file size (as well as timestamp) to detect changed config file. + +Version 2.02.86 - 8th July 2011 +=============================== + Remove unnecessary warning in pvcreate for MD linear devices. + Move snapshot removal activation logic into lib/activate. + Cope with a PV only discovered missing when creating deptree. + Abort operation if dm_tree_node_add_target_area fails. + Add activation/checks to lvm.conf to perform additional ioctl validation. + Always preload on suspend, even if no metadata changed (lvchange --refresh). + When suspending, automatically preload newly-visible existing LVs. + Teardown any stray devices with $COMMON_PREFIX during test runs. + Reinstate correct permissions when creating mirrors. [2.02.85] + Append 'm' attribute to pv_attr for missing PVs. + Annotate CLVMD_CMD_SYNC_NAMES in decode_cmd. + Remove enforcement of udev verification when using non-standard /dev location. + Keep an exclusive mirror non-clustered if reloaded e.g. during conversion. + Reject allocation if number of extents is not divisible by area count. + Fix cluster mirror creation to work with new mirror allocation algorithm. + Ignore activation/verify_udev_operations if dm kernel driver vsn < 4.18. + Add activation/verify_udev_operations to lvm.conf, disabled by default. + Call vg_mark_partial_lvs() before VG structure is returned from the cache. + Remove unused internal flag ACTIVATE_EXCL from the code. + Remove useless test of ACTIVATE_EXCL in lv_add_mirrors() clustered code path. + Add lv_activate_opts structure for activation (replacing activation flags). + Ignore inconsistent pre-commit metadata on MISSING_PV devs while activating. + Add proper udev library context initialization and finalization to liblvm. + Fix last snapshot removal to avoid table reload while a device is suspended. + Use dm_get_suspended_counter in replacement critical_section logic. + Downgrade critical_section errors to debug level until it is moved to libdm. + Fix ignored background polling default in vgchange -ay. + Fix pvmove activation sequences to avoid trapped I/O with multiple LVs. + Annotate critical section debug messages. + Fix reduction of mirrors with striped segments to always align to stripe size. + Validate mirror segments size. + Include lvmetad development code in tree. + Fix extent rounding for striped volumes never to reduce more than requested. + Fix create_temp_name to replace any '/' found in the hostname with '?'. + Always use append to file in lvmdump. selinux policy may ban file truncation. + Propagate test mode to clvmd to skip activation and changes to held locks. + Defer writing PV labels until vg_write. + Store label_sector only in struct physical_volume. + Permit --available with lvcreate so non-snapshot LVs need not be activated. + Report sector containing label in verbose message. + Clarify error message when unable to convert an LV into a snapshot of an LV. + Add and use dev_open_readonly and variations. + Do not log a superfluous stack message when the lv is properly processed. + Do not issue an error message when unable to remove .cache on read-only fs. + Avoid memlock size mismatch by preallocating stdio line buffers. + Rewrite vgreduce --removemissing --force to share lvconvert code. + Reorganize lvconvert --repair code to allow reuse. + +Version 2.02.85 - 29th April 2011 +================================= + Add new obtain_device_list_from_udev setting to lvm.conf. + Obtain device list from udev by default if LVM2 is compiled with udev support. + Add test for vgimportclone and querying of vgnames with duplicate pvs. + Avoid use of released memory when duplicate PV is found. + Add "devices/issue_discards" to lvm.conf. + Issue discards on lvremove and lvreduce etc. if enabled and supported. + Add seg_pe_ranges and devices fields to liblvm. + Fix incorrect tests for dm_snprintf() failure. + Fix some unmatching sign comparation gcc warnings in the code. + Support lv_extend() on empty LVs. + Avoid regenerating cache content when exported VG buffer is unchanged. + Extend the set of memory regions that are not locked to memory. + Workaround some problems when compiled for valgrind memcheck. + Support controlled quit of the lvm_thread_fn function in clvmd. + Fix reading of unallocated memory in lvm1 format import function. + Replace several strncmp() calls with id_equal(). + Fix lvmcache_info transfer to orphan_vginfo in _lvmcache_update_vgname(). + Fix -Wold-style-definition gcc warnings. + Rename MIRROR_NOTSYNCED to LV_NOTSYNCED. + Fix _move_lv_segments to handle empty LVs. + Fixes for lvconvert (including --repair) of temporary mirror stacks. + Avoid potential loop when removing mirror images. + Fix mirror removal always to take account of preferences as to which. + Fix MIRRORED flag usage. + Remove error messages issued by device_is_usable when run as non-root. + Add missing \0 for grown debug object in _bitset_with_random_bits(). + Fix allocation of system_id buffer in volume_group structure. + Fix readlink usage inside get_primary_dev(). + Use format instance mempool where possible and adequate. + Call destroy_instance for any PVs found in VG structure during vg_free call. + Add new free_pv_fid fn and use it throughout to free all attached fids. + Use only vg_set_fid and new pv_set_fid fn to assign the format instance. + Make create_text_context fn static and move it inside create_instance fn. + Add mem and ref_count fields to struct format_instance for own mempool use. + Use new alloc_fid fn for common format instance initialisation. + Optimise _get_token() and _eat_space(). + Add _lv_postorder_vg() to improve efficiency for all LVs in VG. + Add gdbinit script for debugging. + Use hash tables to speedup string search in vg_validate(). + Refactor allocation of VG structure adding alloc_vg(). + Avoid possible endless loop in _free_vginfo when 4 or more VGs have same name. + Use empty string instead of /dev// for LV path when there's no VG. + Don't allocate unused VG mempool in _pvsegs_sub_single. + Do not send uninitialised bytes in local clvmd messages. + Support --help option for clvmd and return error for unknown option. + Avoid reading freed memory when printing LV segment type. + Fix syslog initialisation in clvmd to respect lvm.conf setting. + Fix possible overflow in maximum stripe size and physical extent size. + Improve pvremove error message when PV belongs to a VG. + Extend normal policy to allow mirror logs on same PVs as images if necessary. + Improve cling policy to recognise PVs already used during the transaction. + Improve normal allocation algorithm to include clinging to existing areas. + Add allocation/maximise_cling & mirror_logs_require_separate_pvs to lvm.conf. + Adapt metadata balancing code to work with metadata handling changes. + Add old_id field to physical_volume and fix pvchange -u for recent changes. + Allow pvresize on a PV with two metadata areas. + Change pvcreate to use new metadata handling interface. + Restructure existing pv_setup and pv_write and add pv_initialise. + Add internal interface to support adding and removing metadata areas. + Allow internal indexing of metadata areas (PV id + mda order). + Generalise internal format_instance infrastrusture for PV and VG use. + Handle decimal digits with --units instead of ignoring them silently. + Fix remaining warnings and compile with -Wpointer-arith. + Fix gcc warnings for unused variables and const casts. + Add stack backtraces for error paths in process_each_lv(). + Temporarily suppress error from calling yes_no_prompt while locks are held. + Replace void* with char* arithmetic in _text_write, _text_read & send_message. + Fix compilation without DEVMAPPER_SUPPORT. + Remove fs_unlock() from lv_suspend error path. + Allow memory to stay locked between leaving and re-entering critical sections. + Rename memlock to critical_section throughout. + Make pv_min_size configurable and increase to 2048KB to exclude floppy drives. + Add find_config_tree_int64 to read 64-bit ints from config. + Ensure resuming exclusive cluster mirror continues to use local mirror target. + Clear temporary postorder LV status flags to allow re-use with same LV struct. + Remove invalid snapshot umount mesg which floods syslog from dmeventd plugin. + Add extended examples to pvmove man page. + Support LVM_TEST_DEVDIR env var for private /dev during testing. + +Version 2.02.84 - 9th February 2011 +=================================== + Fix CRC32 calculation on big endian CPU (2.02.75). + +Version 2.02.83 - 4th February 2011 +=================================== + Allow exclusive activation of snapshots in a cluster. + Leave EX lock unchanged when suspending a device in clvmd. + Use sync_dev_names in unlock_vg macro for cluster-wide dev name sync. + Fix fs operation stack handling when multiple operations on same device. + Increase hash table size to 1024 lv names and 64 pv uuids. + Remove fs_unlock() from lv_resume path. + Fix wipe size when setting up mda. + Remove unneeded checks for open_count in lv_info(). + Synchronize with udev before checking open_count in lv_info(). + Allow CLVMD_CMD_SYNC_NAMES to be propagated around the cluster if requested. + Add "dmsetup ls --tree" output to lvmdump. + Fix udev synchronization with no-locking --sysinit (2.02.80). + Improve man page style consistency for pvcreate, pvremove, pvresize, pvscan. + Avoid rebuilding of uuid validation table. + Improve lvcreate error text from insufficient "extents" to "free space". + Always use O_DIRECT when opening block devices to check for partitioning. + +Version 2.02.82 - 24th January 2011 +=================================== + Bring lvscan man page up-to-date. + Fix lvchange --test to exit cleanly. + Add change_tag to toollib. + Allow multiple pvchange command line options to be specified together. + Do not fail pvmove polling if another process cleaned up first. + Avoid clvmd incrementing dlm lockspace reference count more than once. + Add -f (don't fork) option to clvmd and fix clvmd -d<num> description. + +Version 2.02.81 - 17th January 2011 +=================================== + Do not scan devices in dev_reset_error_count(). + Skip unnecessary LOCK_NULL unlock call during volume deactivation. + Skip fs_unlock when calling exec_cmd within activation code (for modprobe). + Extend exec_cmd params to specify when device sync (fs_unlock) is needed. + Replace fs_unlock by sync_local_dev_names to notify local clvmd. (2.02.80) + Introduce sync_local_dev_names and CLVMD_CMD_SYNC_NAMES to issue fs_unlock. + Accept fusion fio in device type filter. + Add ability to convert mirror log type from disk to mirrored. + +Version 2.02.80 - 10th January 2011 +=================================== + Use same dm cookie for consecutive dm ops in same VG to reduce udev waits. + Speed up command processing by caching resolved config tree. + Pass config_tree to renamed function import_vg_from_config_tree(). + Detect NULL handle in get_property(). + Fix superfluous /usr in ocf_scriptdir instalation path. + Add --with-ocfdir configurable option. + Add aclocal.m4 (for pkgconfig). + Fix memory leak in persistent filter creation error path. + Check for errors setting up dm_task struct in _setup_task(). + Fail polldaemon creation when lvmcache_init() fails. + Return PERCENT_INVALID for errors in _copy_percent() and _snap_percent(). + Remove some unused variables. + Improve general lvconvert man page description. + Return 0 from cmirrord initscript 'start' if daemon is already running. + Fix wrongly paired unlocking of VG_GLOBAL in pvchange. (2.02.66) + Add backtraces for backup and backup_remove fail paths. + Detect errors from dm_task_set calls in _get_device_info (dmeventd). + Add backtraces for archive and backup_locally in check_current_backup(). + Fix memory leak in debug mode of restart_clvmd() error path. + Log error message for pthread_join() failure in clvmd. + +Version 2.02.79 - 20th December 2010 +==================================== + Remove some unused variables. + Add missing test for reallocation error in _find_parallel_space(). + Add checks for allocation errors in config node cloning. + Fix error path if regex engine cannot be created in _build_matcher(). + Use char* arithmetic in target_version(), _process_all() & _targets(). + Fixing const cast gcc warnings in the code. + Check read() and close() results in _get_cmdline(). + Add const for struct config_node usage. + Fix NULL pointer check in error path in clvmd do_command(). (2.02.78) + Fix device.c #include to ensure 64-bit fopen64 use. (2.02.51) + Add copy_percent and snap_percent to liblvm. + Enhance vg_validate to ensure integrity of LV and PV structs referenced. + Enhance vg_validate to check composition of pvmove LVs. + Create /var/run/lvm directory during clvmd initialisation if missing. + Use new dm_prepare_selinux_context instead of dm_set_selinux_context. + Avoid revalidating the label cache immediately after scanning. + Support scanning for a single VG in independent mdas. + Don't skip full scan when independent mdas are present even if memlock is set. + Set cmd->independent_metadata_areas if metadata/dirs or disk_areas in use. + Cope better with an undefined target_percent operation in _percent_run. + Avoid writing to freed memory in vg_release and rename to free_vg. (2.02.78) + +Version 2.02.78 - 6th December 2010 +=================================== + Abort if segment tag allocation fails in pool format _add_stripe_seg. + Abort in _mirrored_transient_status if referenced log/image LV is not active. + Add backtraces for dev_set() and dev_close_immediate() errors in set_lv(). + Log any unlink() error in clvmd remove_lockfile(). + Log any pipe write() or close() errors in clvmd child_init_signal(). + Detect if orphan vginfo was lost from cache before _lvmcache_update_vgname(). + Do a full rescan if some device is missing in lvm1 format read_pvs_in_vg. + Add missing check that dm_pool_create succeeded in write_config_node(). + Use dm_snprintf in clvmd-command.c to ensure an overlong buffer is truncated. + Don't write to buffer if its reallocation failed in clvmd do_command(). + Switch from float to fixed point percentage handling. + Avoid misleading missing PV warnings in vgextend --restoremissing. + Fix memory leak when VG allocation policy in metadata is invalid. + Ignore unrecognised allocation policy found in metadata instead of aborting. + Factor out tag printing into _out_tags and avoid leaking string buffer. + Remove some unused variables & assignments. + Add missing vg_release calls in _vg_read_by_vgid. + Fix debug logging of derived flag LCK_CACHE in clvmd. + Fix test for no system_dir in _init_backup(). + Disallow lvconvert ops that both allocate & free supplied PEs in a single cmd. + Fix liblvm seg_size to give bytes not sectors. + Add functions to look up LV/PV by name/uuid to liblvm. + Free cmd_context if fallback to LVM1 fails in lvm2_main(). + Free device name buffer in dmsetup parse_loop_device_name() error paths. + Close format lib if init_format_fn fails in _init_formats(). + Don't leave /proc/mounts open after dmeventd snapshot event processing. + Fix out-of-scope arg_vgnames use in process_each_lv(). + Remove incorrect dm_task_destroy(NULL) from _node_clear_table() error path. + Add missing closedir in _rm_blks after removing stray LVM1 VG files. + Suppress 'No PV label' message when removing several PVs without mdas. + Fix default /etc/lvm permissions to be 0755. (2.02.66) + +Version 2.02.77 - 22nd November 2010 +==================================== + Allocate a pool for dummy VG in _pvsegs_sub_single. + Add PV and LV segment types and functions to liblvm. + Add set_property functions to liblvm. + Remove tag length restriction and allow / = ! : # & characters. + Support repetition of --addtag and --deltag arguments. + Add infrastructure for specific cmdline arguments to be repeated in groups. + Split the_args cmdline arguments and values into arg_props and arg_values. + Fix fsadm no longer to require '-f' to resize an unmounted filesystem. + Fix fsadm to detect mounted filesystems on older systems. (2.0.75) + Extend cling allocation policy to recognise PV tags (cling_by_tags). + Add allocation/cling_tag_list to lvm.conf. + Regenerate configure with 'autoreconf' for --enable-ocf. (2.02.76) + +Version 2.02.76 - 8th November 2010 +=================================== + Clarify error messages when activation fails due to activation filter use. + Add pacemaker script VolumeGroup.ocf with configure --enable-ocf. + Import make.tmpl into include/ Makefile. + Fix handling of online filesystem resize (using new fsadm return code). + Add DIAGNOSTICS section to fsadm man page. + Modify fsadm to return different status code for check of mounted filesystem. + Update VG metadata only once in vgchange when making multiple changes. + Allow independent vgchange arguments to be used together. + Automatically unmount invalidated snapshots in dmeventd. + Suppress some superfluous messages from clang static analysis. + Fix a deadlock caused by double close in clvmd. + Fix NULL pointer dereference on too-large MDA error path in _vg_read_raw_area. + Use static for internal _align_chunk() and _new_chunk() from pool-fast.c. + Fix vgchange to process -a, --refresh, --monitor and --poll like lvchange. + Add lvm2app functions to query any pv, vg, or lv property / report field. + +Version 2.02.75 - 25th October 2010 +=================================== + Annotate more variables and parameters as const. + Fix missing variable initialization in cluster_send() function from cmirrord. + Fix pointer for VG name in _pv_resize_single error code path. + Fix warning for changed alignment requirements for dmeventd read/write func. + Add global/metadata_read_only to use unrepaired metadata in read-only cmds. + Don't take write lock in vgchange --refresh, --poll or --monitor. + Skip dm devices in scan if they contain only error targets or are empty. + Fix strict-aliasing compile warning in partition table scanning. + Fix pthread mutex usage deadlock in clvmd. + Automatically extend snapshots with dmeventd according to policy in lvm.conf. + Add activation/snapshot_autoextend_threshold/percent to lvm.conf. + Fix liblvm2cmd link order to support --as-needed. + Remove dependency on libm by replacing floor() by an integer-based algorithm. + Fix hang when repairing a mirrored-log that had both devs fail. + Convey need for snapshot-merge target in lvconvert error message and man page. + Add devices/disable_after_error_count config to limit access to failing devs. + Give correct error message when creating a too-small snapshot. + Implement vgextend --restoremissing to reinstate missing devs that return. + Make lvconvert respect --yes and --force when converting an inactive log. + Refactor and add 'get' functions for lv properties/fields. + Update script for fsadm testing. + Better support of noninteractive shell execution of fsadm. + Fix usage of --yes flag for ReiserFS resize in fsadm. + Fix detection of mounted filesystems for fsadm when udev is used. + Fix assignment of default value to LVM variable in fsadm. + Fix support for --yes flag for fsadm. + Do not execute lvresize from fsadm --dry-run. + Fix fsadm return error code from user's break action. + Allow CC to be overridden at build time (for 'scan-build make'). + Rename 'flags' to 'status' in struct metadata_area. + Avoid segfault by limiting partial mode for lvm1 metadata. (2.02.74) + Use dm_zalloc and dm_pool_zalloc throughout. + Add pv_get_property and create generic internal _get_property function. + Add 'get' functions for pv and vg properties/fields. + Make generic GET_*_PROPERTY_FN macros with secondary macro for vg, pv & lv. + Add tags_format_and_copy() common function and call from _tags_disp. + Add id_format_and_copy() common function and call from _uuid_disp. + Refactor report.c '*_disp' functions to call supporting functions. + Move parts of metadata*.[ch] into new {pv|vg|lv}.[ch] files. + Fix vg_read memory leak with directory-based metadata. + Fix memory leak of config_tree in reinitialization code path. + Fix pool destruction order in dmeventd_lvm2_exit() to avoid leak debug mesg. + Read whole /proc/self/maps file before working with maps entries. + Speed up unquoting of quoted double quotes and backslashes. + Speed up CRC32 calculations by using a larger lookup table. + +Version 2.02.74 - 24th September 2010 +===================================== + Allow : and @ to be escaped with \ in device names of PVs. + Replace alloca with dm_malloc in _aligned_io to avoid stack corruption. + Fix partial mode operations for lvm1 metadata format. + Track recursive filter iteration to avoid refreshing while in use. (2.02.56) + Revert to old glibc vsnprintf behaviour in emit_to_buffer() to catch overflow. + Allocate buffer for metadata tags dynamically to remove 4k limit. + Add random suffix to archive file names to prevent races when being created. + Reinitialize archive and backup handling on toolcontext refresh. + Make poll_mirror_progress report PROGRESS_CHECK_FAILED if LV is not a mirror. + Like mirrors, don't scan origins if ignore_suspended_devices() is set. + Fix return type qualifier to avoid compiler warning. (2.02.69) + Automatically generate LSB Requires-Start for clvmd init script. + Fix return code of pvmove --abort PV. + Fix pvmove --abort to remove even for empty pvmove LV. + Add configure --with-default-data-alignment. + Update heuristic used for default and detected data alignment. + Add "devices/default_data_alignment" to lvm.conf. + Add implementation for simple numeric 'get' property functions. + Define GET_NUM_PROPERTY_FN macro to simplify numeric property 'get' function + Add properties.[ch] to lib/report using columns.h. + Add macro definitions to report infrastructure for character array length. + Remove explicit double quotes from columns.h 'id' entries. + Add 'flags' field to columns.h and define FIELD_MODIFIABLE. + Add vg_mda_size and vg_mda_free functions. + Simplify MD/swap signature detection in pvcreate and allow aborting. + Allow --yes to be used without --force mode. + Fix file descriptor leak in swap signature detection error path. + Detect and allow abort in pvcreate if LUKS signature is detected. + Always mask lock flags correctly when checking for LCK_WRITE. + +Version 2.02.73 - 18th August 2010 +================================== + Fix potential for corruption during cluster mirror device failure. + Use 'SINGLENODE' instead of 'dead' in clvmd singlenode messages. + Ignore snapshots when performing mirror recovery beneath an origin. + Pass LCK_ORIGIN_ONLY flag around cluster. + Add suspend_lv_origin and resume_lv_origin using LCK_ORIGIN_ONLY. + Allow internal suspend and resume of origin without its snapshots. + Fix dev_manager_transient to access -real device not snapshot-origin. + Monitor origin -real device below snapshot instead of overlay device. + Don't really change monitoring status when in test mode. + Fix some exit statuses when starting/stopping monitoring fails. + Enable snapshot monitoring by default when dmeventd is enabled. + Move cloned libdevmapper-event client code from segments into lib/activate. + Fix 'lvconvert --splitmirrors' in cluster operation. + Fix clvmd init script exit code to return 4 when executed as non-root user. + Change default alignment of pe_start to 1MB. + Add --norestorefile option to pvcreate. + Require --restorefile when using pvcreate --uuid. + Recognise and give preference to md device partitions (blkext major). + Never scan internal LVM devices. + Don't ignore user-specified PVs in split-mirror operations. (2.02.71) + Fix data corruption bug in cluster mirrors. + Require logical volume(s) to be explicitly named for lvconvert --merge. + Avoid changing aligned pe_start as a side-effect of very verbose logging. + Use built-in rule for device aliases: block/ < dm- < disk/ < mapper/ < other. + Fix const warning in dev_manager_info() and _dev_manager_lv_rmnodes(). + Fix const warning in archive_file structure from archive.c. + Clean generated files .exported_symbols_generated, example.conf for distclean. + Handle failure of all mirrored log devices and all but one mirror leg. + Disallow 'mirrored' log type for cluster mirrors. + Do not use VPATH in include/Makefile. + Fix exported_symbols generation to use standard compiler arguments. + Use #include <> not "" in lvm2app.h which gets installed on the system. + Make lib and liblvm.device-mapper wait for include file generation. + Fix configure to supply DEFAULT_RUN_DIR to Makefiles. + Fix allocation of wrong number of mirror logs with 'remove' fault policy. + +Version 2.02.72 - 28th July 2010 [CVE-2010-2526] +================================================= + Change clvmd to communicate with lvm2 via a socket in /var/run/lvm. + Return controlled error if clvmd is run by non-root user. + Add configure --default-run-dir for /var/run/lvm. + Never use clvmd singlenode unless explicitly requested with -Isinglenode. + +Version 2.02.71 - 28th July 2010 +================================ + Document LVM fault handling in doc/lvm_fault_handling.txt. + Make vgck warn about missing PVs. + Clarify help text for vg_mda_count. + Check if cluster log daemon is running before allowing cmirror create. + Add unit-tests dir. + Add configure --enable-testing and reports and report-generators dirs. + Correct LV list order used by lvconvert when splitting a mirror. + Check if LV with specified name already exists when splitting a mirror. + Fix suspend/resume logic for LVs resulting from splitting a mirror. + Update pvcreate, {pv|vg}change, and lvm.conf man pages about metadataignore. + Switch cmirrord and clvmd to use dm_create_lockfile. + Allow clvmd pidfile to be configurable. + Update comments about memory handling in lvm2app.h. + Add more verbose messages while checking volume_list and hosttags settings. + Add log_error when strdup fails in {vg|lv}_change_tag(). + Remove unnecessary includes in liblvm files. + Use __attribute__ consistently throughout. + Fix redundant declarations and always compile with -Wredundant-decls. + Fix possible hang when all mirror images of a mirrored log fail. + Pass metadataignore to pv_create, pv_setup, _mda_setup, and add_mda. + Init mda->list in mda_copy. + Do not log backtrace in valid _lv_resume() code path. + Cleanup help strings in configure.in. + Prompt if metadataignore with vgextend or pvchange would adjust vg_mda_copies. + Adjust vg_mda_copies if metadataignore given with vgextend or pvchange. + Adjust auto-metadata repair and caching logic to try to cope with empty mdas. + +Version 2.02.70 - 6th July 2010 +=============================== + Remove log directly if all mirror images of a mirrored log fail. + Randomly select which mdas to use or ignore. + Add some missing standard configure.in checks. + Add printf format attributes to yes_no_prompt and fix a caller. + Always pass unsuspended dm devices through persistent filter to other filters. + Move test for suspended dm devices ahead of other filters. + Fix another segfault in clvmd -R if no response from daemon. (2.02.68) + Remove superfluous suspended device counter from clvmd. + Fix lvm shell crash when input is entirely whitespace. + Update partial mode warning message. + Preserve memlock balance in clvmd when activation triggers a resume. + Restore the removemissing behaviour of lvconvert --repair --use-policies. + +Version 2.02.69 - 30th June 2010 +================================ + Fix vgremove to allow removal of VG with missing PVs. (2.02.52) + Add metadata/vgmetadatacopies to lvm.conf. + Add --metadataignore to pvcreate and vgextend. + Add vg_mda_copies, pv_mda_used_count and vg_mda_used_count to reports. + Describe --vgmetadatacopies in lvm.conf and other man pages. + Add --[vg]metadatacopies to select number of mdas to use in a VG. + Make the metadata ignore bit control read/write metadata areas in a PV. + Add pvchange --metadataignore to set or clear a metadata ignore bit. + Refactor metadata code to prepare for --metadataignore / --vgmetadatacopies. + Ensure region_size of mirrored log does not exceed its full size. + Generate liblvm2app exported symbols from header file. + Preload libc locale messages to prevent reading it in memory locked state. + Fix handling of simultaneous mirror image and mirrored log image failure. + +Version 2.02.68 - 23rd June 2010 +================================ + Fix clvmd initscript status to print only active clustered LVs. + Add lv_path to reports to offer full /dev pathname. + Fix typo in warning message about missing device with allocated data areas. + Add device name and offset to raw_read_mda_header error messages. + Honour log argument when down-converting stacked mirror. + Sleep to workaround clvmd -S race: socket closed early and server drops cmd. + Use early udev synchronisation and update of dev nodes for clustered mirrors. + Remove incorrect inclusion of kdev_t.h from cmirrord/functions.h. + Add man pages for lvmconf and non-existent lvmsadc and lvmsar tools. + Exit successfully when using -o help (but not -o +help) with LVM reports. + Do not use internal DLM lock definitions in generic LVM2 clvmd code. + Add --force, --nofsck and --resizefs to lvresize/extend/reduce man pages. + Fix lvm2cmd example in documentation. + Allow use of lvm2app and lvm2cmd headers in C++ code. + Remove unused #includes from clvmd files and introduce clvmd-common.h. + Move common inclusions to clvmd-common.h. + Use #include "" for libdevmapper.h and configure.h throughout tree. + Fix LVM_PATH expansion when exec_prefix=NONE. (2.02.67) + Fix segfault in clvmd -R if no response from daemon received. + +Version 2.02.67 - 4th June 2010 +=============================== + Handle failed restart of clvmd using -S switch properly. + Fix clvmd initscript restart command to start clvmd if not yet running. + Use built-in absolute paths in clvmd (clvmd restart and PV and LV queries). + Require partial option in lvchange --refresh for partial LVs. + Do not fail lvm_init() if init_logging() or _init_rand() generates an errno. + Don't merge unchanged persistent cache file before dumping if tool scanned. + Fix incorrect memory pool deallocation while using vg_read for files. + Add --type parameter description to the lvcreate man page. + Replace strncmp kernel version number checks with proper ones. + Avoid selecting names under /dev/block if there is an alternative. + Update clustered log kernel module name to log-userspace for 2.6.31 onwards. + Add replicators' LVs to dtree for activation. + Supress activation message if there is a missing replicator VG. + Fix scripts/relpath.awk to work in mawk + Extend lock_vol to check for missing replicator VGs first. + Update _process_one_vg and process_each_lv_in_vg to populate cmd_vg. + Add cmd_vg structure and associated functions for replicator. + Extend _lv_each_dependency() to handle replicator dependencies. + Add check_replicator_segment() to catch internal replicator errors. + Initial support for replicator metadata. + Extend process_each_lv_in_vg() to provide list of failed lvnames. + Consistently return ECMD_FAILED if process_each_*lv() is interrupted. + +Version 2.02.66 - 20th May 2010 +=============================== + If unable to obtain snapshot percentage leave value blank on reports. + Add install_system_dirs and install_initscripts makefile targets. + Add configure options for system and locking directories. + Generate example.conf so default lvm.conf contents can be configured. + Install lvmconf script by default. + Remove unnecessary versioned dmeventd plugin symlinks. + Add tests for lvm_vgname_from_{pvid|device}. + Add lvm2app interfaces to lookup a vgname from a pvid and pvname. + Update pvchange to always obtain a vg handle for each pv to process. + Add find_vgname_from_{pvname|pvid} functions. + Add pvid_from_devname and lvmcache_vgname_from_pvid lvmcache functions. + Validate orphan and VG_GLOBAL lock order too. + Accept orphan VG names as parameters to lock_vol() and related functions. + Use is_orphan_vg in place of hard-coded prefix tests and add is_global_vg. + +Version 2.02.65 - 17th May 2010 +=============================== + Fix clvmd init script never to deactivate non-clustered volume groups. + Disallow vgchange --clustered if there are active mirrors or snapshots. + Introduce lv_is_mirrored. + Use /bin/bash for scripts with bashisms. + Skip internal lvm devices in scan if ignore_suspended_devices is set. + Do not merge old device cache after we run full scan. (2.02.56) + Add pkgconfigdir Makefile variable for make install override. + Configure pkgconfig udev and selinux dependencies. + Switch Libs.private to Requires.private in devmapper.pc and lvm2app.pc. + Use pkgconfig Requires.private for devmapper-event.pc. + Add libdevmapper to linked libdevmapper-event.so. + Link liblvm2cmd.so with libdevmapper-event and libdevmapper. + Fix truncated total size displayed by pvscan. + Add new --sysinit compound option to vgchange and lvchange. + Drop duplicate errors for read failures and missing devices to verbose level. + Use $(libdir)/lvm2 with make install_lvm2_plugin. + Use $(libdir)/device-mapper with make install_dm_plugin. + Add dm_list_splice() function to join two lists together. + +Version 2.02.64 - 30th April 2010 +================================= + Avoid pointless initialisation when the 'version' command is run directly. + Fix memory leak for invalid regex pattern input. + Display invalid regex pattern for filter configuration in case of error. + Remove no-longer-used arg_ptr_value. + Fix -M and --type to use strings, not pointers that change on config refresh. + Fix lvconvert error message when existing mirrored LV is not found. + Set appropriate udev flags for reserved LVs. + Disallow the direct removal of a merging snapshot. + Don't preload the origin when removing a snapshot whose merge is pending. + Disallow the addition of mirror images while a conversion is happening. + Disallow primary mirror image removal when mirror is not in-sync. + Remove obsolete --name parameter from vgcfgrestore. + Add -S command to clvmd to restart the daemon preserving exclusive locks. + Increment lvm2app version from 1 to 2 (memory allocation changes). + Change lvm2app memory alloc/free for pv/vg/lv properties. + Change daemon lock filename from lvm2_monitor to lvm2-monitor for consistency. + Install symbolic .so links with relative paths between usrlibdir and libdir. + Add awk script relpath.awk to calculate paths for relative symlinks. + Use @AWK@ in makefiles. + Fix double DESTDIR usage for infodir and mandir. + +Version 2.02.63 - 14th April 2010 +================================= + Rename lvm_dump.sh to lvmdump.sh. + Allow incomplete mirror restore in lvconvert --repair upon insufficient space. + Do not reset position in metadata ring buffer on vgrename and vgcfgrestore. + Allow VGs with active LVs to be renamed. + Use UUIDs instead of names while processing event handlers. + Only pass visible LVs to tools in cmdline VG name/tag expansions without -a. + Use typedefs for toollib process_each functions. + Use C locales and use_mlockall for clvmd. + Refactor code related to vg->pvs list and add pv->vg link. + Mask LCK_HOLD flag in cluster VG locks for backwards compatibility. + Add activation/polling_interval to lvm.conf as --interval default. + Don't ignore error if resuming any LV fails in resume_lvs. + Skip closing persistent filter cache file if open failed. + Install .a and .so links into $(usrlibdir). + Add --enable-write_install options to install user-writable files. + Use INSTALL_PROGRAM/DATA/WDATA target. + Switch from using VPATH to vpath in Makefiles. + Permit mimage LVs to be striped in lvcreate, lvresize and lvconvert. + Fix pvmove allocation to take existing parallel stripes into account. + Add pvmove_source_seg to struct lv_segment. + Fix incorrect removal of symlinks after LV deactivation fails. + Fix is_partitioned_dev not to attempt to reopen device. + Fix another thread race in clvmd. + Refactor management of vg->pvs list. + Fix lcov rules and generate better coverage report. + Improve vg_validate to detect some loops in lists. + Change most remaining log_error WARNING messages to log_warn. + Always use blocking lock for VGs and orphan locks. + Allocate all memory for segments from private VG mempool. + Return newly allocated PV segment after segment split. + Optimise searching PV segments for seeking the most recently-added. + Remove vg_validate call when parsing cached metadata. + Use hash table of LVs to speed up parsing of text metadata with many LVs. + Fix two vg_validate messages, adding whitespace and parentheses. + When dmeventd is not forking because of -d flag, don't kill parent process. + Fix 'make install' when $(builddir) is different from $(srcdir). + Fix dso resource leak in error path of dmeventd. + Use C locales and use_mlockall for dmeventd. + Fix --alloc contiguous policy only to allocate one set of parallel areas. + Do not allow {vg|lv}change --ignoremonitoring if on clustered VG. + Improved dependency tracking for dmeventd and liblvm2cmd sources. + Improved Makefile rules for distclean and cflow targets. + Add ability to create mirrored logs for mirror LVs. + Fix clvmd cluster propagation of dmeventd monitoring mode. + Allow ALLOC_ANYWHERE to split contiguous areas. + Use INTERNAL_ERROR for internal errors throughout tree. + Add some assertions to allocation code. + Introduce pv_area_used into allocation algorithm and add debug messages. + Add activation/monitoring to lvm.conf. + Add --monitor and --ignoremonitoring to lvcreate. + Allow dynamic extension of array of areas selected as allocation candidates. + Export and use only valid cookie value in test suite. + Remove const modifier for struct volume_group* from process_each_lv_in_vg(). + Don't allow resizing of internal logical volumes. + Fix libdevmapper-event pkgconfig version string to match libdevmapper. + Avoid scanning all pvs in the system if operating on a device with mdas. + Add configure --with-clvmd=singlenode to use clvmd w/o cluster infrastructure. + Get stacktrace if testsuite test drops core and lvm was built with debugging. + Disable long living process flag in lvm2app. + Fix pvcreate device md filter check. + Suppress repeated errors about the same missing PV uuids. + Bypass full device scans when using internally-cached VG metadata. + Only do one full device scan during each read of text format metadata. + Remove unnecessary full_scan parameter from get_vgids and get_vgnames calls. + Look up missing PVs by uuid not dev_name in _pvs_single to avoid invalid stat. + Make find_pv_in_vg_by_uuid() return same type as related functions. + Introduce is_missing_pv(). + Fix clvmd Makefile to not overwrite LIBS from template definition. + +Version 2.02.62 - 9th March 2010 +================================ + Add use_mlockall and mlock_filter to activation section of lvm.conf. + Add default alternative to mlockall using mlock to reduce pinned memory size. + Remove -rdynamic from static builds. + Update checks for pthread, readline & selinux libs and link only when needed. + Introduce makefile vars UDEV_LIBS, DL_LIBS, SELINUX_LIBS, STATIC_LIBS. + Introduce makefile vars LVMINTERNAL_LIBS, READLINE_LIBS, PTHREAD_LIBS. + Toggle configure help to print --disable-fsadm. + Use $() instead of ${} consistently for all Makefile variables. + Replace CFLOW_CMD only in make.tmpl and use it as variable elsewhere. + Use $(top_builddir) for inclusion of make.tmpl in Makefiles. + Fix autoconf warning about ignored datarootdir. + Increase AC_PREREQ version to 2.61 (for AC_PROC_SED, AC_PROG_MKDIR_P). + Handle misaligned devices that report alignment_offset of -1. + Extend core allocation code in preparation for mirrored log areas. + Rewrite clvmd init script. + Remove lvs_in_vg_activated_by_uuid_only call. + No longer fall back to looking up active devices by name if uuid not found. + Don't touch /dev in vgmknodes if activation is disabled. + Update lvm2app.h Doxygen comments and add lvm2app Doxygen config file. + Update nightly tests and lvm2app unit tests to cover tags. + Add lvm2app functions lvm_{vg|lv}_{get|add|remove}_tag() functions. + Add dm_pool_strdup to allocate and copy memory in tag library function. + Refactor vgcreate, vgchange, and lvchange for tag library function. + Refactor snapshot-merge deptree and device removal to support info-by-uuid. + +Version 2.02.61 - 15th February 2010 +==================================== + Fix some consts and floating point gcc warnings. + Fix dm_report_field_uint64 function to accept 64-bit ints. + Change readhead display to use 32-bit -1 const instead of 64-bit. + Add LVM_SUPPRESS_LOCKING_FAILURE_MESSAGES environment variable. + Remove hard-coding that skipped _mimage devices from 11-dm-lvm.rules. + Use udev transactions in test suite. + Set udev state automatically instead of using LVM_UDEV_DISABLE_CHECKING. + Add lvm_pv_get_size, lvm_pv_get_free and lvm_pv_get_dev_size to lvm2app. + Change lvm2app to return all sizes in bytes as documented (not sectors). + Add 'fail_if_percent_unsupported' arg to _percent and _percent_run. + Remove false "failed to find tree node" error when activating merging origin. + Exit with success when lvconvert --repair --use-policies performs no action. + Accept a list of LVs with 'lvconvert --merge @tag' using process_each_lv. + Avoid unnecessary second resync when adding mimage to core-logged mirror. + Exclude internal VG names and uuids from lists returned through lvm2app. + Add %ORIGIN support to lv{create,extend,reduce,resize} --extents. + Add _mda_copy to clone a struct metadata_area. + Remove pointless versioned symlinks to dmeventd plugin libraries. + Fix dmeventd snapshot plugin build dependency. + Make clvmd -V return status zero. + Remove unnecessary 'dmsetup resume' following 'dmsetup create' in tests. + Fix cmirrord segfault in clog_cpg list processing when converting mirror log. + Deactivate temporary pvmove mirror cluster-wide when activating it fails. + Always query device by uuid and not name in clvmd. + Add missing metadata vg_reverts in pvmove error paths. + Unlock shared lock in clvmd if activation calls fail. + Return success from dev_manager_info with non-existent uuid if ioctl succeeds. + +Version 2.02.60 - 23rd January 2010 +=================================== + Extend cmirrord man page. + Sleep before first progress check if pvmove/lvconvert interval has prefix '+'. + Default to checking progress before waiting in _wait_for_single_lv. + Fix cmirror initscript (including syntax error). + Eliminate avoidable ioctls for checking open_count in _add_new_lv_to_dtree. + Disable memory debugging if dmeventd is configured. (Not thread-safe.) + Fix first log message prefix in syslog for dmeventd plugins. + Fix exported symbols names for dmeventd lvm2 wrapper plugin. + Make failed locking initialisation messages more descriptive. + +Version 2.02.59 - 21st January 2010 +=================================== + Add libdevmapper-event-lvm2.so to serialise dmeventd plugin liblvm2cmd use. + Cleanup memory initialization and freeing in pv_read() and pv_create(). + Clear pointer and counters after their release in _fin_commands(). + Stop dmeventd trying to access already-removed snapshots. + Remove (fallback) /dev mknod from cmirrord. + Add t-topology-support.sh and t-snapshot-merge.sh tests. + Fix clvmd to never scan suspended devices. + Fix dmeventd build outside source tree. + Assorted cmirror code changes to remove various compiler warnings. + Fix detection of completed snapshot merge. + Add Red Hat cmirror initscript (unfinished). + Add cmirrord man page (incomplete). + Make cluster log communication structures architecture independant. + Fix cluster log in-memory bitmap handling. + Improve snapshot merge metadata import validation. + Improve target type compatibility checking in _percent_run(). + Add 'target_status_compatible' method to 'struct segtype_handler'. + Change underscore to hyphen in table line for clustered log type. + +Version 2.02.58 - 14th January 2010 +=================================== + Cleanup some minor gcc warnings. + Add --merge to lvconvert to merge a snapshot into its origin. + Fix clvmd automatic target module loading crash (no reset_locking fn). + Fix allocation code not to stop at the first area of a PV that fits. + +Version 2.02.57 - 12th January 2010 +=================================== + Ensure exactly one process returns from poll_daemon(), never two. + Reset _vgs_locked in lvmcache_init() in child after forking. + Define {DM, LVM}_UDEV_DISABLE_CHECKING=1 environment variables during tests. + Enable udev_sync and udev_rules in lvm.conf by default while running tests. + If LVM_UDEV_DISABLE_CHECKING in set in environment, disable udev warnings. + Add --splitmirrors to lvconvert to split off part of a mirror. + Change background polldaemon's process name to "(lvm2)". + Allow vgremove to remove a VG with PVs missing after a prompt. + Return success in lvconvert --repair --use-policies on failed allocation. + Keep log type consistent when changing mirror image count. + Always set environment variables for an LVM2 device in 11-dm-lvm.rules. + Add activation/udev_rules config option in lvm.conf. + Add consts to text metadata flag structs. + Add macros outfc, outsize, outhint and function out_text_with_comment. + Reimplement report FIELD macro using offsetof instead of static structs. + Fix fsadm man page typo (fsdam). + Rename mirror_device_fault_policy to mirror_image_fault policy. + Remove empty PV devices if lvconvert --repair is using defined policies. + Use fixed buffer to prevent stack overflow in persistent filter dump. + Use extended status of new kernel snapshot target 1.8.0 to detect when empty. + Insert stack macros in suspend_lv, resume_lv & (de)activate_lv callers. + Add --poll flag to vgchange and lvchange to control background daemon launch. + Propagate metadata commit and revert notifications to other cluster nodes. + Use proper mask for VG lock mode in clvmd. + Allow precommitted metadata to be dropped from lvmcache. + Move processing of VG locks to separate function in clvmd. + Properly decode all flags in clvmd messages including VG locks. + Properly handle precommitted cache flag when only committed metadata present. + Resume renamed volumes in reverse order to preserve memlock pairing. + Drop cached metadata after device was auto-repaired and removed from VG. + Clear MISSING_PV flag if PV reappeared and is empty. + Fix removal of multiple devices from a mirror. + Also clean up PVs flagged as missing in vgreduce --removemissing --force. + Introduce INTERNAL_ERROR macro for error messages and use throughout. + Remove superfluous returns from void functions. + Destroy allocated mempool in _vg_read_orphans() error path. + Fix some pvresize and toollib error paths with missing VG releases/unlocks. + Explicitly call suspend for temporary mirror layer. + Allow use of precommitted metadata when a PV is missing. + Add memlock information to do_lock_lv debug output. + Always bypass calls to remote cluster nodes for non-clustered VGs. + Permit implicit cluster lock conversion in pre/post callbacks on local node. + Permit implicit cluster lock conversion to the lock mode already held. + Fix lock flag masking in clvmd so intended code paths get invoked. + Replace magic masks in cluster locking code by defined masks. + Remove newly-created mirror log from metadata if initial deactivation fails. + Correct activated or deactivated text in vgchange summary message. + Improve pvmove error message when all source LVs are skipped. + Fix memlock imbalance in lv_suspend if already suspended. + Fix pvmove test mode not to poll (and fail). + Fix vgcreate error message if VG already exists. + Fix tools to use log_error when aborted due to user response to prompt. + Fix ignored readahead setting in lvcreate --readahead. + Fix clvmd memory leak in lv_info_by_lvid by calling release_vg. + If aborting due to internal error, always send that message to stderr. + Add global/abort_on_internal_errors to lvm.conf to assist testing. + Fix test Makefiles when builddir and srcdir differ. + Impose limit of 8 mirror images to match the in-kernel kcopyd restriction. + Use locking_type 3 (compiled in) for lvmconf --enable-cluster. + Remove list.c and list.h with no-longer-used dm_list macros and functions. + Log failure type and recognise type 'F' (flush) in dmeventd mirror plugin. + Extend internal PV/VG/LV/segment status variables from 32-bit to 64-bit. + +Version 2.02.56 - 24th November 2009 +==================================== + Add missing vg_release to pvs and pvdisplay to fix memory leak. + Do not try to unlock VG which is not locked in _process_one_vg. + Move is_long_lived persistent_filter_dump to happen after every full scan. + Refresh device filters before full device rescan in lvmcache. + Return error status if vgchange fails to activate some volume. + Fix suspend/resume lock type test causing unbalanced memory locking. + Revert vg_read_internal change as clvmd was not ready for vg_read. (2.02.55) + +Version 2.02.55 - 19th November 2009 +==================================== + Fix deadlock when changing mirrors due to unpaired memlock refcount changes. + Use separate memlock counter for dmeventd handlers to permit device scanning. + Directly restrict vgchange to activating visible LVs. + Fix pvmove region_size overflow for very large PVs. + Fix lvcreate and lvresize %PVS argument always to use sensible total size. + Tidy some uses of arg_count and introduce arg_is_set. + Export outnl and indent functions for modules. + Flush stdout after yes/no prompt. + Update vgsplit and vgcreate to use vg_set_clustered. + Add vg_mda_count and vg_set_clustered library functions. + Add more vgcreate and vgsplit nightly tests. + Insert some missing stack macros into activation code. + Recognise DRBD devices and handle them like md devices. + +Version 2.02.54 - 26th October 2009 +=================================== + Update lvcreate/lvconvert man pages to explain PhysicalVolume parameter. + Document --all option in man pages, cleanup {pv|vg|lv}{s|display} man pages. + Permit snapshots of mirrors. + Cleanup mimagetmp LV if allocation fails for new lvconvert mimage. + Fix clvmd segfault when refresh_toolcontext fails. + Remember to clear 'global lock held during cache refresh' state after use. + Use udev flags support in LVM and apply various fixes to udev rules. + Delay announcing mirror monitoring to syslog until initialisation succeeded. + Handle metadata with unknown segment types more gracefully. + Set default owner and group to null. + Add dmeventd.static to the build. + Disable realtime support code by default. + Make clvmd return 0 on success rather than 1. + Add --pvmetadatacopies for pvcreate, vgcreate, vgextend, vgconvert. + Add implict pvcreate support to vgcreate and vgextend. + Correct example.conf to indicate that lvm2 not lvm1 is the default format. + Remove an unused stray LVM1_SUPPORT ifdef. + Only include selinux libs in libdevmapper.pc when selinux build enabled. + Allow for a build directory separate from the source. + Update distclean target for rename clogd to cmirrord. (2.02.52) + Only do lock conversions in clvmd if we are explicitly asked for one. + Introduce percent_range_t and centralise snapshot full/mirror in-sync checks. + Factor out poll_mirror_progress and introduce progress_t. + Distinguish between powers of 1000 and powers of 1024 in unit suffixes. + Restart lvconverts in vgchange by sharing lv_spawn_background_polling. + Generalise polldaemon code by changing mirror-specific variable names. + Don't attempt to deactivate an LV if any of its snapshots are in use. + Return error if lv_deactivate fails to remove device from kernel. + Provide alternative implementation of obsolete siginterrupt(). + Consolidate LV allocation into alloc_lv(). + Treat input units of both 's' and 'S' as 512-byte sectors. (2.02.49) + Use standard output units for 'PE Size' and 'Stripe size' in pv/lvdisplay. + Add configure --enable-units-compat to set si_unit_consistency off by default. + Add global/si_unit_consistency to enable cleaned-up use of units in output. + +Version 2.02.53 - 25th September 2009 +===================================== + Create any directories in /dev with DM_DEV_DIR_UMASK (022). + Enable dmeventd monitoring section of config file by default. + Update lvm2 monitoring script to lvm2_monitoring_init_red_hat.in. + Fix lvm2app test to run under test/api subdirectory only when configured. + Add vg_is_resizeable() and cleanup reference to VG_RESIZEABLE. + +Version 2.02.52 - 15th September 2009 +===================================== + Update _process_one_vg to cleanup properly after vg_read_error. + Add lots of missing stack debug messages to tools. + Make readonly locking available as locking type 4. + Fix readonly locking to permit writeable global locks (for vgscan). (2.02.49) + Add DM_UDEV_RULES_VSN environment variable to udev rules. + Update vgsplit, vgmerge, and vgrename to obey new vgname ordering rules. + Make lvm2app pv_t, lv_t, vg_t handle definitions consistent with lvm_t. + Enforce an alphabetical lock ordering on vgname locking. + Prioritise write locks over read locks by default for file locking. + Add local lock files with suffix ':aux' to serialise locking requests. + Fix global locking in PV reporting commands (2.02.49). + Fix pvcreate string termination in duplicate uuid warning message. + Don't loop reading sysfs with pvcreate on a non-blkext partition (2.02.51). + Fix vgcfgrestore error paths when locking fails (2.02.49). + Update Makefile distclean target. + Add libudev configuration check. + Make clvmd check corosync to see what cluster interface it should use. + Add clvmd autodetection check and cleanup related configure messages. + Rewrite clvmd configuration code to cope with all combinations of libs. + Added configure --enable-cmirrord to build the cluster mirror log daemon. + Rename clogd to cmirrord. + Make lvchange --refresh only take a read lock on volume group. + Fix race where non-blocking file locks could be granted in error. + Fix vgextend error path - if ORPHAN lock fails, unlock / release vg (2.02.49). + Fix compile warning in clvmd. + Clarify use of PE ranges in lv{convert|create|extend|resize} man pages. + Remove useless _pv_write wrapper. + Add lvm2app.sh to tests conditional upon configure --enable-applib. + Add lvm_vg_is_clustered, lvm_vg_is_exported, and lvm_vg_is_partial. + Update lvm_vg_remove to require lvm_vg_write to commit remove to disk. + Update test/api/test.c to call lvm_vg_create and lvm_vg_remove. + +Version 2.02.51 - 6th August 2009 +================================= + Fix locking in clvmd (2.02.50). + Add --noudevsync option for relevant LVM tools. + Add activation/udev_sync to lvm.conf. + Only change LV symlinks on ACTIVATE not PRELOAD. + Make lvconvert honour log mirror options combined with downconversion. + Allow LV suspend while --ignorelockingfailure is in force. + Update synopsis in lvconvert manpage to mention --repair. + Set cookies in activation code and wait for udev to complete processing. + Added configure --enable-udev_rules --enable-udev_sync. + Added configure --with-udev-prefix --with-udevdir. + Added udev dir to hold udev rules. + Add devices/data_alignment_detection to lvm.conf. + Add devices/data_alignment_offset_detection to lvm.conf. + Add --dataalignmentoffset to pvcreate to shift start of aligned data area. + Fix _mda_setup() to not check first mda's size before pe_align rounding. + Document -I option of clvmd in the man page. + Fix configure script to handle multiple clvmd selections. + Fix lvm2app.pc installation filename. + Remove pv_t, vg_t & lv_t handles from lib. Only liblvm uses them. + Rename lvm.h to lvm2app.h for now. + +Version 2.02.50 - 28th July 2009 +================================ + Change test/api/test.c prompt so it's not confused with the main lvm prompt. + Update liblvm unit tests in test/api to cover latest liblvm changes. + Add unimplemented lvm_lv_resize and lvm_pv_resize skeletons to liblvm. + Add lvm_library_get_version to liblvm. + Add lvm_config_override to liblvm to allow caller to override LVM config. + Add lvm_lv_is_active and lvm_lv_is_suspended to liblvm. + Add lvm_lv_activate and lvm_lv_deactivate to liblvm. + Add lvm_scan, lvm_vg_reduce and lvm_vg_remove_lv to liblvm. + Add functions to get numeric properties to liblvm. + Add lvm_{pv|vg|lv}_get_{name|uuid} to liblvm. + Add lvm_vg_list_pvs and lvm_vg_list_lvs to liblvm. + Add lvm_vg_open and lvm_vg_create_lv_linear to liblvm. + Add lvm_list_vg_names/uuids to liblvm. + Add lvm_errno and lvm_errmsg to liblvm to obtain failure information. + Rename lvm_create/destroy to lvm_init/quit. + Rename lvm_reload_config to lvm_config_reload. + Refactor _override_settings to use new override_config_tree_from_string. + Add vg_reduce to metadata.c and metadata-exported.h. + Update lvm.h to clarify API behavior and return codes. + Update lvm_vg_extend to do an implicit pvcreate on the device. + Update display.c to use vg_free(vg) instead of duplicating the calculation. + Refactor vg_size, vg_free, and pv_mda_count field calculations for liblvm. + Refactor pvcreate and lvcreate for liblvm. + Add global/wait_for_locks to lvm.conf so blocking for locks can be disabled. + All LV locks are non-blocking so remove LCK_NONBLOCK from separate macros. + Fix race condition with vgcreate and vgextend on same device (2.02.49). + Remove redundant validate_name call from vgreduce. + Remove unused handles lvseg, pvseg inside liblvm/lvm.h. + Add liblvm2app Makefile installation targets. + Add liblvm pkgconfig file. + Use newly-independent LVM_LIBAPI in liblvm soname. E.g. liblvm2app.so.2.1. + Add an API version number, LVM_LIBAPI, to the VERSION string for liblvm. + Pass a pointer to struct cmd_context to init_multiple_segtypes + Return EINVALID_CMD_LINE not success when invalid VG name format is used. + Remove unnecessary messages after vgcreate/vgsplit refactor (2.02.49). + Add log_errno to set a specific errno and replace log_error in due course. + Change create_toolcontext to still return an object if it fails part-way. + Add EUNCLASSIFIED (-1) as the default LVM errno code. + Store any errno and error messages issued while processing each command. + Use log_error macro consistently throughout in place of log_err. + +Version 2.02.49 - 15th July 2009 +================================ + Add readonly locking type to replace implementation of --ignorelockingfailure. + Exclude VG_GLOBAL from vg_write_lock_held so scans open devs read-only again. + Add unit test case for liblvm VG create/delete APIs. + Add liblvm APIs to implement creation and deletion of VGs. + Initialize cmd->cmd_line to "liblvm" in new liblvm library. + Place handles to liblvm objects for pv, vg, lv, lvseg, pvseg inside lvm.h. + Refactor vgsplit and vgextend to remove READ_REQUIRE_RESIZEABLE flag. + Use _exit() not exit() after forking to avoid flushing libc buffers twice. + Add cast to log_info arg in _find_labeller to avoid Sparc64 warning. + Make cmd->cmd_line const. + Fix dev name mismatch in vgcreate man page example. + Refactor vg_remove_single for use in liblvm. + Make all tools use consistent lock ordering obtaining VG_ORPHAN lock second. + Check md devices for a partition table during device scan. + Add extended device (blkext) and md partition (mdp) types to filters. + Make text metadata read errors for segment areas more precise. + Fix text segment metadata read errors to mention correct segment name. + Include segment and LV names in text segment import error messages. + Add parent node to config_node structure. + Update vgsplit and vgcreate to call new vg_create and 'set' functions. + Change vg_create to take minimal parameters, obtain a lock, and return vg_t. + Refactor vgchange extent_size, max_lv, max_pv, and alloc_policy for liblvm. + Update t-vgcreate-usage.sh to test for default vg properties. + Fix memory leak in vgsplit when re-reading the vg. + Make various exit/cleanup paths more robust after lvm init failures. + Use LCK_NONBLOCK implicitly instead of explicit vg_read() flag. + Remove unnecessary locking and existence tests from new vg_read() interface. + Permit several segment types to be registered by a single shared object. + Update the man pages to document size units uniformly. + Allow commandline sizes to be specified in terms of bytes and sectors. + Update 'md_chunk_alignment' to use stripe-width to align PV data area. + Update test/t-inconsistent-metadata.sh to match new vg_read interface. + Add lvmcache_init() to polldaemon initialization. + Convert tools to use new vg_read / vg_read_for_update. + Fix segfault in vg_release when vg->cmd is NULL. + +Version 2.02.48 - 30th June 2009 +================================ + Abort if automatic metadata correction fails when reading VG to update it. + Explicitly request fallback to default major number in device mapper. + Ignore suspended devices during repair. + Call vgreduce --removemissing automatically to fix missing PVs in dmeventd. + Suggest using lvchange --resync when adding leg to not-yet-synced mirror. + Destroy toolcontext on clvmd exit to avoid memory pool leaks. + Fix lvconvert not to poll mirror if no conversion in progress. + Fix memory leaks in toolcontext error path. + Reinstate partial activation support in clustered mode. (2.02.40) + Allow metadata correction even when PVs are missing. + Use 'lvm lvresize' instead of 'lvresize' in fsadm. + Do not use '-n' realine option in fsadm for busybox compatiblity. + Add vg_lock_newname() library function for vgrename, vgsplit and vgcreate. + Round up requested readahead to at least one page and print warning. + Try to repair vg before actual vgremove when force flag provided. + Fix possible double release of VG after recovery. + Add parameter to process_each_vg specifying what to do with inconsistent VG. + Unify error messages when processing inconsistent volume group. + Use lvconvert --repair instead of vgreduce in mirror dmeventd DSO. + Introduce lvconvert --use_policies (repair policy according to lvm.conf). + Update clvmd-corosync to match new corosync API. + Fix lib Makefile to include any shared libraries in default target. + Fix rename of active snapshot with virtual origin. + Fix convert polling to ignore LV with different UUID. + Cache underlying device readahead only before activation calls. + Fix segfault when calculating readahead on missing device in vgreduce. + Remove verbose 'visited' messages. + Handle multi-extent mirror log allocation when smallest PV has only 1 extent. + Add LSB standard headers and functions (incl. reload) to clvmd initscript. + When creating new LV, double-check that name is not already in use. + Remove /dev/vgname/lvname symlink automatically if LV is no longer visible. + Rename internal vorigin LV to match visible LV. + Suppress 'removed' messages displayed when internal LVs are removed. + Fix lvchange -a and -p for sparse LVs. + Fix lvcreate --virtualsize to activate the new device immediately. + Make --snapshot optional with lvcreate --virtualsize. + Generalise --virtualoriginsize to --virtualsize. + Skip virtual origins in process_each_lv_in_vg() without --all. + Fix counting of virtual origin LVs in vg_validate. + Attempt to load dm-zero module if zero target needed but not present. + +Version 2.02.47 - 22nd May 2009 +=============================== + Rename liblvm.so to liblvm2app.so and use configure --enable-applib. + Reinstate version in liblvm2cmd.so soname. (2.02.44) + +Version 2.02.46 - 21st May 2009 +=============================== + Inherit readahead setting from underlying devices during activation. + Detect LVs active on remote nodes by querying locks if supported. + Enable online resizing of mirrors. + Use suspend with flush when device size was changed during table preload. + Implement query_resource_fn for cluster_locking. + Support query_resource_fn in locking modules. + Introduce CLVMD_CMD_LOCK_QUERY command for clvmd. + Fix pvmove to revert operation if temporary mirror creation fails. + Fix metadata export for VG with missing PVs. + Add vgimportclone and install it and the man page by default. + Force max_lv restriction only for newly created LV. + Remove unneeded import parameter from lv_create_empty. + Merge lv_is_displayable and lv_is_visible functions. + Introduce lv_set_visible & lv_set_hidden functions. + Fix lv_is_visible to handle virtual origin. + Introduce link_lv_to_vg and unlink_lv_from_vg functions. + Remove lv_count from VG and use counter function instead. + Fix snapshot segment import to not use duplicate segments & replace. + Do not query nonexistent devices for readahead. + Remove NON_BLOCKING lock flag from tools and set a policy to auto-set. + Remove snapshot_count from VG and use function instead. + Fix first_seg() call for empty segment list. + Add install_lvm2 makefile target to install only the LVM2 components. + Reject missing PVs from allocation in toollib. + Fix PV datalignment for values starting prior to MDA area. (2.02.45) + Add sparse devices: lvcreate -s --virtualoriginsize (hidden zero origin). + Fix minimum width of devices column in reports. + Add lvs origin_size field. + Fix linux configure --enable-debug to exclude -O2. + Implement lvconvert --repair for repairing partially-failed mirrors. + Fix vgreduce --removemissing failure exit code. + Fix remote metadata backup for clvmd. + Introduce unlock_and_release_vg macro. + Introduce vg_release() to be called to free every struct volume_group. + Alloc PV internal structure from VG mempool if possible. + Fix metadata backup to run after vg_commit always. + Tidy clvmd volume lock cache functions. + Fix pvs report for orphan PVs when segment attributes are requested. + Fix pvs -a output to not read volume groups from non-PV devices. + Add MMC (mmcblk) device type to filters. + Introduce memory pools per volume group (to reduce memory for large VGs). + Use copy of PV structure when manipulating global PV lists. + Always return exit error status when locking of volume group fails. + Fix mirror log convert validation question. + Avoid referencing files from DESTDIR during build process. + Avoid creating some static libraries unless configured --enable-static_link. + Enable use of cached metadata for pvs and pvdisplay commands. + Add missing 'device-mapper' internal subdir build dependency. + Fix memory leak in mirror allocation code. + Save and restore the previous logging level when log level is changed. + Fix error message when archive initialization fails. + Make sure clvmd-corosync releases the lockspace when it exits. + Fix segfault for vgcfgrestore on VG with missing PVs. + Block SIGTERM & SIGINT in clvmd subthreads. + Detect and conditionally wipe swapspace signatures in pvcreate. + Fix maximal volume count check for snapshots if max_lv set for volume group. + Fix lvcreate to remove unused cow volume if the snapshot creation fails. + Fix error messages when PV uuid or pe_start reading fails. + Build new liblvm application-level library. + Rename liblvm.a to liblvm-internal.a. + Flush memory pool and fix locking in clvmd refresh and backup command. + Fix unlocks in clvmd-corosync. (2.02.45) + Fix error message when adding metadata directory to internal list fails. + Fix size and error message of memory allocation at backup initialization. + Remove old metadata backup file after renaming VG. + Restore log_suppress state when metadata backup file is up-to-date. + +Version 2.02.45 - 3rd March 2009 +================================ + Avoid scanning empty metadata areas for VG names. + Attempt proper clean up in child before executing new binary in exec_cmd(). + Do not scan devices if reporting only attributes from PV label. + Use pkgconfig to obtain corosync library details during configuration. + Fix error returns in clvmd-corosync interface to DLM. + Add --refresh to vgchange and vgmknodes man pages. + Pass --test from lvresize to fsadm as --dry-run. + Supply argv[] list to exec_cmd() to allow for variable number of parameters. + Prevent fsadm from checking mounted filesystems. + No longer treats any other key as 'no' when prompting in fsadm. + Tidy fsadm command line processing. + Add lib/lvm.h and lib/lvm_base.c for the new library interface. + Move tools/version.h to lib/misc/lvm-version.h. + Split LVM_VERSION into MAJOR, MINOR, PATCHLEVEL, RELEASE and RELEASE_DATE. + Add system_dir parameter to create_toolcontext(). + Add --dataalignment to pvcreate to specify alignment of data area. + Exclude LCK_CACHE locks from _vg_lock_count, fixing interrupt unblocking. + Provide da and mda locations in debug message when writing text format label. + Mention the restriction on file descriptors at invocation on the lvm man page. + Index cached vgmetadata by vgid not vgname to cope with duplicate vgnames. + No longer require kernel and metadata major numbers to match. + Add a fully-functional get_cluster_name() to clvmd corosync interface. + Remove duplicate cpg_initialize from clvmd startup. + Add option to /etc/sysconfig/cluster to select cluster type for clvmd. + Allow clvmd to start up if its lockspace already exists. + Separate PV label attributes which do not need parse metadata when reporting. + Remove external dependency on the 'cut' command from fsadm. + Fix pvs segfault when pv mda attributes requested for not available PV. + Add fsadm support for reszing ext4 filesysystems. + Move locking_type reading inside init_locking(). + Rename get_vgs() to get_vgnames() and clarify related error messages. + Allow clvmd to be built with all cluster managers & select one on cmdline. + Mention --with-clvmd=corosync in ./configure. + Replace internal vg_check_status() implementation. + Rename vg_read() to vg_read_internal(). + +Version 2.02.44 - 26th January 2009 +=================================== + Fix --enable-static_link after the recent repository changes. + Add corosync/DLM cluster interface to clvmd. + Add --nameprefixes, --unquoted, --rows to pvs, vgs, lvs man pages. + Fix lvresize size conversion for fsadm when block size is not 1K. + Fix pvs segfault when run with orphan PV and some VG fields. + Display a 'dev_size' of zero for missing devices in reports. + Add pv_mda_size to pvs and vg_mda_size to vgs. + Fix lvmdump /sys listing to include virtual devices directory. + Add "--refresh" functionality to vgchange and vgmknodes. + Avoid exceeding LV size when wiping device. + Calculate mirror log size instead of using 1 extent. + Ensure requested device number is available before activating with it. + Fix incorrect exit status from 'help <command>'. + Fix vgrename using UUID if there are VGs with identical names. + Fix segfault when invalid field given in reporting commands. + Move is_static from cmd to global is_static(). + Refactor init_lvm() for lvmcmdline and clvmd. + Add liblvm interactive test infrastructure to build. + Add skeleton lvm2.h file in preparation for a shared library interface. + Use better random seed value in temp file creation. + Add read_urandom to read /dev/urandom. Use in uuid calculation. + Use displayable_lvs_in_vg and lv_is_displayable for consistency throughout. + Fix race in vgcreate that would result in second caller overwriting first. + Fix uninitialised lv_count in vgdisplay -c. + Don't skip updating pvid hash when lvmcache_info struct got swapped. + Add tinfo to termcap search path for pld-linux. + Fix startup race in clvmd. + Generate Red Hat clvmd startup script at config time with correct paths. + Fix clvmd & dmeventd builds after tree restructuring. + Cope with snapshot dependencies when removing a whole VG with lvremove. + Make man pages and tool help text consistent using | for alternative options. + +Version 2.02.43 - 10th November 2008 +==================================== + Merge device-mapper into the lvm2 tree. + Correct prototype for --permission on lvchange and lvcreate man pages. + Exit with non-zero status from vgdisplay if couldn't show any requested VG. + Move list.c into libdevmapper and rename functions. + Rename a couple of variables that matched function names. + Use simplified x.y.z version number in libdevmapper.pc. + Remove ancient debian directory. + Split out lvm-logging.h from log.h and lvm-globals.[ch] from log.[ch]. + +Version 2.02.42 - 26th October 2008 +=================================== + Accept locking fallback_to_* options in the global section as documented. + Fix temp table activation in mirror conversions not to happen in other cmds. + Fix temp table in mirror conversions to use always-present error not zero. + +Version 2.02.41 - 17th October 2008 +=================================== + Use temp table to set device size when converting mirrors. + In resume_mirror_images replace activate_lv with resume_lv as workaround. + Avoid overwriting in-use on-disk text metadata by forgetting MDA_HEADER_SIZE. + Fix snapshot monitoring library to not cancel monitoring invalid snapshot. + Generate man pages from templates and include version. + Add usrlibdir and usrsbindir to configure. + Fix conversion of md chunk size into sectors. + Free text metadata buffer after a failure writing it. + Fix misleading error message when there are no allocatable extents in VG. + Fix handling of PVs which reappeared with old metadata version. + Fix mirror DSO to call vgreduce with proper parameters. + Fix validation of --minor and --major in lvcreate to require -My always. + Fix release: clvmd build, vgreduce consolidate & tests, /dev/ioerror warning. + +Version 2.02.40 - 19th September 2008 +===================================== + Allow lvremove to remove LVs from VGs with missing PVs. + In VG with PVs missing, by default allow activation of LVs that are complete. + Track PARTIAL_LV and MISSING_PV flags internally. + Require --force with --removemissing in vgreduce to remove partial LVs. + No longer write out PARTIAL flag into metadata backups. + Treat new default activation/missing_stripe_filler "error" as an error target. + Remove internal partial_mode. + Add devices/md_chunk_alignment to lvm.conf. + Pass struct physical_volume to pe_align and adjust for md chunk size. + Store sysfs location in struct cmd_context. + Avoid shuffling remaining mirror images when removing one, retaining primary. + Add missing LV error target activation in _remove_mirror_images. + Prevent resizing an LV while lvconvert is using it. + Avoid repeatedly wiping cache while VG_GLOBAL is held in vgscan & pvscan. + Fix pvresize to not allow resize if PV has two metadata areas. + Fix setting of volume limit count if converting to lvm1 format. + Fix vgconvert logical volume id metadata validation. + Fix lvmdump metadata gather option (-m) to work correctly. + Fix allocation bug in text metadata format write error path. + Fix vgcfgbackup to properly check filename if template is used. + configure aborts if lcov or genhtml are missing with --enable-profiling + vgremove tries to remove lv snapshot first. + Added function lv_remove_with_dependencies(). + Improve file descriptor leak detection to display likely culprit and filename. + Change clustered mirror kernel module name from cmirror to dm-log-clustered. + Avoid looping forever in _pv_analyze_mda_raw used by pvck. + Change lvchange exit status to indicate if any part of the operation failed. + Fix pvchange and pvremove to handle PVs without mdas. + Refactor _text_pv_read and always return mda list if requested. + Fix configure to work w/o readline unless --enable-readline used. (2.02.39) + Remove is_lvm_partition template which has not yet been coded. + Refactor pvcreate to separate parameter parsing from validation logic. + Check for label_write() failure in _text_pv_write(). + Add pvcreate tests and update vgsplit tests to handle lvm1 and lvm2 metadata. + Fix pvchange -M1 -u to preserve existing extent locations when there's a VG. + Cease recognising snapshot-in-use percentages returned by early devt kernels. + Add backward-compatible flags field to on-disk format_text metadata. + Fix dmeventd monitoring libraries to link against liblvm2cmd again. (2.02.39) + +Version 2.02.39 - 27th June 2008 +================================ + Enable readline by default if available. + Update autoconf to 2008-01-16. + Add $DISTCLEAN_DIRS to make.tmpl.in. + Create coverage reports with --enable-profiling and make lcov or lcov-dated. + Fix up cache for PVs without mdas after consistent VG metadata is processed. + Update validation of safe mirror log type conversions in lvconvert. + Fix lvconvert to disallow snapshot and mirror combinations. + Fix reporting of LV fields alongside unallocated PV segments. + Add --unquoted and --rows to reporting tools. + Add and use uninitialized_var() macro to suppress invalid compiler warnings. + Introduce enum for md minor sb version to suppress compiler warning. + Avoid undefined return value after _memlock manipulation in lvm2_run. + Avoid link failure if configured without --enable-cmdlib or --enable-readline. + Make clvmd return at once if other nodes down in a gulm or openais cluster. + Fix and improve readahead 'auto' calculation for stripe_size. + Fix lvchange output for -r auto setting if auto is already set. + Add test case for readahead. + Avoid ambiguous use of identifier error_message_produced. + Begin syncing configure.in for merge/unification with device-mapper. + Fix add_mirror_images not to dereference uninitialized log_lv upon failure. + Don't call openlog for every debug line output by clvmd. + Add --force to lvextend and lvresize. + Fix vgchange not to activate component mirror volumes directly. + Fix test directory clean up in make distclean. + +Version 2.02.38 - 11th June 2008 +================================ + Fix tracking of validity of PVs with no mdas in lvmcache. + Fix return values for reporting commands when run with no PVs, LVs, or VGs. + Add omitted unlock_vg() call when sigint_caught() during vg processing. + Fix free_count when reading pool metadata. + Fix segfault when using pvcreate on a device containing pool metadata. + Fix segfault after _free_vginfo by remembering to remove vginfo from list. + Tweak detection of invalid fid after changes to PVs in VG in _vg_read. + Revert assuming precommitted metadata is live when activating (unnecessary). + Drop cached metadata for disappearing VG in vgmerge. + In script-processing mode, stop if any command fails. + Warn if command exits with non-zero status code without a prior log_error. + Check lv_count in vg_validate. + Add --nameprefixes to reporting tools for field name prefix output format. + +Version 2.02.37 - 6th June 2008 +=============================== + Make clvmd-cman use a hash rather than an array for node updown info. + Correct config file line numbers in messages when parsing comments. + Drop cached metadata when renaming a VG. + Allow for vginfo changing during _vg_read. + Decode numbers in clvmd debugging output. + Add missing deactivation after activation failure in lvcreate -Zy. + When activating, if precommitted metadata is still cached, assume it's live. + When removing LV symlinks, skip any where the VG name is not determined. + Drop metadata cache if update fails in vg_revert or vg_commit. + Avoid spurious duplicate VG messages referring to VGs that are gone. + Drop dev_name_confirmed error message to debug level. + Fix setpriority error message to signed int. + Temporarily disable dmeventd mirror monitoring during lvchange --resync. + Refactor some vginfo manipulation code. + Add assertions to trap deprecated P_ and V_ lock usage. + Add missing mutex around clvmd lvmcache_drop_metadata library call. + Fix uninitialised mutex in clvmd if all daemons are not running at startup. + Avoid using DLM locks with LCK_CACHE type P_ lock requests. + When asked to drop cached committed VG metadata, invalidate cached PV labels. + Drop metadata cache before writing precommitted metadata instead of after. + Don't touch /dev in vgrename if activation is disabled. + +Version 2.02.36 - 29th April 2008 +================================= + Fix fsadm.sh to work with older blockdev, blkid & readlink binaries. + Fix lvresize to pass new size to fsadm when extending device. + Remove unused struct in clvmd-openais, and use correct node count. + Fix nodes list in clvmd-openais, and allow for broadcast messages. + Exclude VG_GLOBAL from internal concurrent VG lock counter. + Fix vgsplit internal counting of snapshot LVs. + Fix vgmerge snapshot_count when source VG contains snapshots. + Simplify clvmd-openais by using non-async saLckResourceLock. + Fix internal LV counter when a snapshot is removed. + Fix metadata corruption writing lvm1-formatted metadata with snapshots. + Fix lvconvert -m0 allocatable space check. + +Version 2.02.35 - 15th April 2008 +================================= + Drop cached VG metadata before and after committing changes to it. + Rename P_global to P_#global. + Don't attempt remote metadata backups of non-clustered VGs. (2.02.29) + Don't store fid in VG metadata cache to avoid clvmd segfault. (2.02.34) + Update vgsplit tests to verify loosening of active LV restriction. + Update vgsplit to only restrict split with active LVs involved in split. + Add lv_is_active() to determine whether an lv is active. + +Version 2.02.34 - 10th April 2008 +================================= + Improve preferred_names lvm.conf example. + Fix vgdisplay 'Cur LV' field to match lvdisplay output. + Fix lv_count report field to exclude hidden LVs. + Add vg_is_clustered() helper function. + Fix vgsplit to only move hidden 'snapshotN' LVs when necessary. + Update vgsplit tests for lvnames on the cmdline. + Update vgsplit man page to reflect lvnames on the cmdline. + Update vgsplit to take "-n LogicalVolumeName" on the cmdline. + Use clustered mirror log with pvmove in clustered VGs, if available. + Fix some pvmove error status codes. + Fix vgsplit error paths to release vg_to lock. + Indicate whether or not VG is clustered in vgcreate log message. + Mention default --clustered setting in vgcreate man page. + Add config file overrides to clvmd when it reads the active LVs list. + Fix vgreduce to use vg_split_mdas to check sufficient mdas remain. + Add (empty) orphan VGs to lvmcache during initialisation. + Fix orphan VG name used for format_pool. + Create a fid for internal orphan VGs. + Update lvmcache VG lock state for all locking types now. + Fix output if overriding command_names on cmdline. + Add detection of clustered mirror log capability. + Add check to vg_commit() ensuring VG lock held before writing new VG metadata. + Add validation of LV name to pvmove -n. + Make clvmd refresh the context correctly when lvm.conf is updated. + Add some basic internal VG lock validation. + Add per-command flags to control which commands use the VG metadata cache. + Fix vgsplit locking of new VG (2.02.30). + Avoid erroneous vgsplit error message for new VG. (2.02.29) + Suppress duplicate message when lvresize fails because of invalid vgname. + Cache VG metadata internally while VG lock is held. + Fix redundant lvresize message if vg doesn't exist. + Fix another allocation bug with clvmd and large node IDs. + Add find_lv_in_lv_list() and find_pv_in_pv_list(). + Fix uninitialised variable in clvmd that could cause odd hangs. + Add vgmerge tests. + Add pvseg_is_allocated() for identifying a PV segment allocated to a LV. + Add list_move() for moving elements from one list to another. + Add 'is_reserved_lvname()' for identifying hidden LVs. + Correct command name in lvmdiskscan man page. + clvmd no longer crashes if it sees nodeids over 50. + Fix potential deadlock in clvmd thread handling. + Refactor text format initialisation into _init_text_import. + Escape double quotes and backslashes in external metadata and config data. + Add functions for escaping double quotes in strings. + Rename count_chars_len to count_chars. + Use return_0 in a couple more places. + Correct a function name typo in _line_append error message. + Include limits.h in clvmd so it compiles with newer headers. + Add VirtIO disks (virtblk) to filters. + Fix resetting of MIRROR_IMAGE and VISIBLE_LV after removal of LV. (2.02.30) + Fix remove_layer_from_lv to empty the LV before removing it. (2.02.30) + Add missing no-longer-used segs_using_this_lv test to check_lv_segments. + Remove redundant non-NULL tests before calling free in clvmd.c. + Avoid a compiler warning: make is_orphan's parameter const. + Fix lvconvert detection of mirror conversion in progress. (2.02.30) + Avoid automatic lvconvert polldaemon invocation when -R specified. (2.02.30) + Fix 'pvs -a' to detect VGs of PVs without metadata areas. + Divide up internal orphan volume group by format type. + Update usage message for clvmd. + Fix clvmd man page not to print <br> and clarified debug options. + Fix lvresize to support /dev/mapper prefix in the LV name. + Fix unfilled parameter passed to fsadm from lvresize. + Update fsadm to call lvresize if the partition size differs (with option -l). + Fix fsadm to support VG/LV names. + +Version 2.02.33 - 31st January 2008 +=================================== + Fix mirror log name construction during lvconvert. (2.02.30) + Make monitor_dev_for_events recurse through the stack of LVs. + Clean up some more compiler warnings. + Some whitespace tidy-ups. + Use stack return macros throughout. + Rely upon internally-cached PV labels while corresponding VG lock is held. + +Version 2.02.32 - 29th January 2008 +=================================== + Fix two check_lv_segments error messages to show whole segment. + Refactor mirror log attachment code. + Fix internal metadata corruption in lvchange --resync. (2.02.30) + Fix new parameter validation in vgsplit and test mode. (2.02.30) + Remove redundant cnxman-socket.h file from clvmd directory. + Fix pvs, vgs, lvs error exit status on some error paths. + +Version 2.02.31 - 19th January 2008 +=================================== + Fix lvcreate --nosync not to wait for non-happening sync. (2.02.30) + Add very_verbose lvconvert messages. + Avoid readahead error message with default setting of lvcreate -M1. (2.02.29) + +Version 2.02.30 - 17th January 2008 +=================================== + Set default readahead to twice maximium stripe size. + Reinstate VG extent size and stripe size defaults (halved). (2.02.29) + Add lists of stacked LV segments using each LV to the internal metadata. + Change vgsplit -l (for unimplemented --list) into --maxlogicalvolumes. + Fix process_all_pvs to detect non-orphans with no MDAs correctly. + Don't use block_on_error with mirror targets version 1.12 and above. + Update vgsplit to accept vgcreate options when new VG is destination. + Update vgsplit to accept existing VG as destination. + lvconvert waits for completion of initial sync by default. + Refactor vgcreate for parameter validation and add tests. + Add new convert_lv field to lvs output. + Print warning when lvm tools are running as non-root. + Add snapshot dmeventd library (enables dmeventd snapshot monitoring). + Prevent pvcreate from overwriting MDA-less PVs belonging to active VGs. + Fix a segfault if using pvs with --all argument. (2.02.29) + Update --uuid argument description in man pages. + Fix vgreduce PV list processing not to process every PV in the VG. (2.02.29) + Extend lvconvert to use polldaemon. + Add support for stacked mirrors. + Major restructuring of pvmove and lvconvert layer manipulation code. + Replace tools/fsadm with scripts/fsadm.sh. + Append fields to report/pvsegs_cols_verbose. + Permit LV segment fields with PV segment reports. + Add seg_start_pe and seg_pe_ranges to reports. + +Version 2.02.29 - 5th December 2007 +=================================== + Make clvmd backup vg metadata on remote nodes. + Refactor pvmove allocation code. + Decode cluster locking state in log message. + Change file locking state messages from debug to very verbose. + Fix --addtag to drop @ prefix from name. + Stop clvmd going haywire if a pre_function fails. + Convert some vg_reads into vg_lock_and_reads. + Avoid nested vg_reads when processing PVs in VGs and fix associated locking. + Accept sizes with --readahead argument. + Store size arguments as sectors internally. + Attempt to remove incomplete LVs with lvcreate zeroing/activation problems. + Add read_ahead activation code. + Add activation/readahead configuration option and FMT_RESTRICTED_READAHEAD. + Extend readahead arg to accept "auto" and "none". + Add lv_read_ahead and lv_kernel_read_ahead fields to reports and lvdisplay. + Prevent lvconvert -s from using same LV as origin and snapshot. + Fix human-readable output of odd numbers of sectors. + Add pv_mda_free and vg_mda_free fields to reports for raw text format. + Add LVM2 version to 'Generated by' comment in metadata. + Show 'not usable' space when PV is too large for device in pvdisplay. + Ignore and fix up any excessive device size found in metadata. + Fix error message when fixing up PV size in lvm2 metadata (2.02.11). + Fix orphan-related locking in pvdisplay and pvs. + Fix missing VG unlocks in some pvchange error paths. + Add some missing validation of VG names. + Rename validate_vg_name() to validate_new_vg_name(). + Change orphan lock to VG_ORPHANS. + Change format1 to use ORPHAN as orphan VG name. + Convert pvchange, pvdisplay, pvscan to use is_orphan() + Add is_orphan_vg() and change all hard-coded checks to use it. + Detect md superblocks version 1.0, 1.1 and 1.2. + Add _alloc_pv() and _free_pv() from _pv_create() code and fix error paths. + Add pv_dev_name() to access PV device name. + Add const attributes to pv accessor functions. + Refactor vg_add_snapshot() and lv_create_empty(). + Handle new sysfs subsystem/block/devices directory structure. + Run test with LVM_SYSTEM_DIR pointing to private root and /dev dirs. + Fix a bug in lvm_dump.sh checks for lvm/dmsetup binaries. + Fix underquotations in lvm_dump.sh. + Refactor lvcreate stripe and mirror parameter validation. + Print --help output to stdout, not stderr. + After a cmdline processing error, don't print help text but suggest --help. + Add %PVS extents option to lvresize, lvextend, and lvcreate. + Add 'make check' to run tests in new subdirectory 'test'. + Moved the obsolete test subdirectory to old-tests. + Cope with relative paths in configure --with-dmdir. + Remove no-longer-correct restrictions on PV arg count with stripes/mirrors. + Fix strdup memory leak in str_list_dup(). + Link with -lpthread when static SELinux libraries require that. + Detect command line PE values that exceed their 32-bit range. + Include strerror string in dev_open_flags' stat failure message. + Move guts of pvresize into library. + Avoid error when --corelog is provided without --mirrorlog. (2.02.28) + Correct --mirrorlog argument name in man pages (not --log). + Clear MIRROR_NOTSYNCED LV flag when converting from mirror to linear. + Modify lvremove to prompt for removal if LV active on other cluster nodes. + Add '-f' to vgremove to force removal of VG even if LVs exist. + +Version 2.02.28 - 24th August 2007 +================================== + Fix clvmd logging so you can get lvm-level debugging out of it. + Introduce VG_GLOBAL lock type for vgscan/pvscan to trigger clvmd -R. + Change locking_flags from int to uint32_t. + Fix clvmd -R, so it fully refreshes the caches. + Change lvconvert_mirrors to use mirror segtype not striped. + Fix lvconvert_mirrors detection of number of existing mirrors. + Clean up numerous compiler warnings that appeared in recent releases. + Remove several unused parameters from _allocate(). + Only permit --force, --verbose and --debug arguments to be repeated. + Fix inconsistent licence notices: executables are GPLv2; libraries LGPLv2.1. + Move guts of vgremove and lvremove into library, including yes_no_prompt. + Allow clvmd debug to be turned on in a running daemon using clvmd -d [-C]. + Update to use autoconf 2.61, while still supporting 2.57. + Add more cluster info to lvmdump. + Add further const attributes throughout. + Add support for renaming mirrored LVs. + Factor out core of lvrename() to library function. + Add --mirrorlog argument to specify log type for mirrors. + Don't attempt to monitor devices if their creation failed in _lv_activate. + Don't leak a file descriptor in fcntl_lock_file() when fcntl fails. + Replace create_dir with dm_create_dir. + Detect stream write failure reliably with lvm_fclose using dm_fclose. + Fix clvmd if compiled with gulm support. (2.02.26) + Fix lvdisplay man page to say LV size is reported in sectors, not KB. + Add vg_lock_and_read() external library function. + Fix loading of persistent cache if cache_dir is used. (2.02.23) + Reduce _compare_paths lstat error message from log_error to log_very_verbose. + Create util.h with last_path_component replacing strdup + basename. + Use gcc's printf attribute wherever possible. + In _line_append, use "sizeof buf - 1" rather than equivalent "4095". + Introduce is_same_inode macro, now including a comparison of st_dev. + Don't leak a file descriptor in _lock_file() when flock fails. + Add SUN's LDOM virtual block device (vdisk) and ps3disk to filters. + Split metadata-external.h out from metadata.h for the tools to use. + +Version 2.02.27 - 17th July 2007 +================================ + Fix snapshot cow area deactivation if origin is not active. (2.02.13) + Fix configure libdevmapper.h check when --with-dmdir is used. + Turn _add_pv_to_vg() into external library function add_pv_to_vg(). + Add pv_by_path() external library function. + Tidy clvmd-openais of redundant bits, and improve an error report. + Cope with find_seg_by_le() failure in check_lv_segments(). + Call dev_iter_destroy() if _process_all_devs() is interrupted by sigint. + Add vg_mda_count and pv_mda_count columns to reports. + Fix dumpconfig to use log_print instead of stdout directly. + Remove unused parameter 'fid' from _add_pv_to_vg. + Add kernel and device-mapper targets versions to lvmdump. + Replace BSD (r)index with C89 str(r)chr. + Handle vgsplit of an entire VG as a vgrename. + Reinitialise internal lvmdiskscan variables when called repeatedly. + Fix missing lvm_shell symbol in lvm2cmd library. (2.02.23) + Add vg_status function and clean up vg->status in tools directory. + Add --ignoremonitoring to disable all dmeventd interaction. + Remove get_ prefix from get_pv_* functions. + clvmd-openais now uses cpg_local_get() to get nodeid, rather than Clm. + Print warnings to stderr instead of stdout. + +Version 2.02.26 - 15th June 2007 +================================ + Update vgcfgrestore man page. + Allow keyboard interrupt during user prompts when appropriate. + Remove unused clvmd system-lv code. + Replace many physical_volume struct dereferences with new get_pv_* functions. + Suppress a benign compile-time warning. + Convert find_pv_in_vg_by_uuid and pv_create to use PV handles. + Add wrappers to some functions in preparation for external LVM library. + Add -f to vgcfgrestore to list metadata backup files. + Add vg_check_status to consolidate vg status checks and error messages. + Add pvdisplay --maps implementation. + Remove unsupported LVM1 options from vgcfgrestore man page. + Update vgcfgrestore man page to show mandatory VG name. + Update vgrename man page to include UUID and be consistent with lvrename. + Add (experimental) OpenAIS support to clvmd. + Fix deactivation code to follow dependencies and remove symlinks. + Fix and clarify vgsplit error messages. + Fix a segfault in device_is_usable() if a device has no table. + Add some more debug messages to clvmd startup. + Misc clvmd cleanups. + +Version 2.02.25 - 27th April 2007 +================================= + Fix get_config_uint64() to read a 64-bit value not a 32-bit one. + Add -Wformat-security and change one fprintf() to fputs(). + Move regex functions into libdevmapper. + Change some #include lines to search only standard system directories. + Add devices/preferred_names config regex list for displayed device names. + Free a temporary dir string in fcntl_lock_file() after use. + Fix a dm_pool_destroy() in matcher_create(). + Introduce goto_bad macro. + Fix warnings on x86_64 involving ptrdiff_t in log_error messages. + Update pvck to include text metadata area and record detection. + Add support functions for token counting in config file extracts. + Update pvck to read labels on disk, with --labelsector parameter. + Add count_chars and count_chars_len functions. + Add /sys/block listings to lvm_dump.sh. + Make lvm_dump.sh list /dev recursively. + Fix thread race in clvmd. + Add scan_sector param to label_read and _find_labeller. + Make clvmd cope with quorum devices. + Add extra internal error checking to clvmd. + Add dev_read_circular. + Add pvck command stub. + Update lists of attribute characters in man pages. + Change cling alloc policy attribute character from 'C' to l'. + Fix creation and conversion of mirrors with tags. + Fix vgsplit for lvm1 format (set and validate VG name in PVs metadata). + Split metadata areas in vgsplit properly. + +Version 2.02.24 - 19th March 2007 +================================= + Fix processing of exit status in init scripts + Fix vgremove to require at least one vg argument. + Fix reading of striped LVs in LVM1 format. + Flag nolocking as clustered so clvmd startup sees clustered LVs. (2.02.10) + Add a few missing pieces of vgname command line validation. + Support the /dev/mapper prefix on most command lines. + +Version 2.02.23 - 8th March 2007 +================================ + Fix vgrename active LV check to ignore differing vgids. + Remove no-longer-used uuid_out parameter from activation info functions. + Fix two more segfaults if an empty config file section encountered. + Move .cache file into a new /etc/lvm/cache directory by default. + Add devices/cache_dir & devices/cache_file_prefix, deprecating devices/cache. + Create directory in fcntl_lock_file() if required. + Exclude readline support from lvm.static. + Fix a leak in a reporting error path (2.02.19). + +Version 2.02.22 - 13th February 2007 +==================================== + Correct -b and -P on a couple of man pages. + Add global/units to example.conf. + Fix loading of segment_libraries. + If a PV reappears after it was removed from its VG, make it an orphan. + Don't update metadata automatically if VGIDs don't match. + Fix some vgreduce --removemissing command line validation. + +Version 2.02.21 - 30th January 2007 +=================================== + Add warning to lvm2_monitoring_init_rhel4 if attempting to stop monitoring. + Fix vgsplit to handle mirrors. + Reorder fields in reporting field definitions. + Fix vgs to treat args as VGs even when PV fields are displayed. + Fix md signature check to handle both endiannesses. + +Version 2.02.20 - 25th January 2007 +=================================== + dmeventd mirror sets ignore_suspended_devices and avoids scanning mirrors. + Add devices/ignore_suspended_devices to ignore suspended dm devices. + Add some missing close() and fclose() return code checks. + Fix exit statuses of reporting tools (2.02.19). + Add init script for dmeventd monitoring. + lvm.static no longer interacts with dmeventd unless explicitly asked to. + Add field definitions to report help text. + Remove unnecessary cmd arg from target_*monitor_events(). + Add private variable to dmeventd shared library interface. + Long-lived processes write out persistent dev cache in refresh_toolcontext(). + Fix refresh_toolcontext() always to wipe persistent device filter cache. + Add is_long_lived to toolcontext. + Add --clustered to man pages. + Streamline dm_report_field_* interface. + Change remaining dmeventd terminology 'register' to 'monitor'. + Update reporting man pages. + No longer necessary to specify alignment type for report fields. + +Version 2.02.19 - 17th January 2007 +=================================== + Fix a segfault if an empty config file section encountered. + Move basic reporting functions into libdevmapper. + Fix partition table processing after sparc changes (2.02.16). + Fix cmdline PE range processing segfault (2.02.13). + Some libdevmapper-event interface changes. + Report dmeventd mirror monitoring status. + Fix dmeventd mirror status line processing. + +Version 2.02.18 - 11th January 2007 +=================================== + Revised libdevmapper-event interface for dmeventd. + Remove dmeventd mirror status line word limit. + Use CFLAGS when linking so mixed sparc builds can supply -m64. + Prevent permission changes on active mirrors. + Print warning instead of error message if lvconvert cannot zero volume. + Add snapshot options to lvconvert man page. + dumpconfig accepts a list of configuration variables to display. + Change dumpconfig to use --file to redirect output to a file. + Avoid vgreduce error when mirror code removes the log LV. + Remove 3 redundant AC_MSG_RESULTs from configure.in. + Free memory in _raw_read_mda_header() error paths. + Fix ambiguous vgsplit error message for split LV. + Fix lvextend man page typo. + Add configure --with-dmdir to compile against a device-mapper source tree. + Use no flush suspending for mirrors. + Add dmeventd_mirror register_mutex, tidy initialisation & add memlock. + Fix create mirror with name longer than 22 chars. + Fix some activate.c prototypes when compiled without devmapper. + Fix dmeventd mirror to cope if monitored device disappears. + +Version 2.02.17 - 14th December 2006 +==================================== + Add missing pvremove error message when device doesn't exist. + When lvconvert allocates a mirror log, respect parallel area constraints. + Use loop to iterate through the now-ordered policy list in _allocate(). + Check for failure to allocate just the mirror log. + Introduce calc_area_multiple(). + Support mirror log allocation when there is only one PV: area_count now 0. + Fix detection of smallest area in _alloc_parallel_area() for cling policy. + Add manpage entry for clvmd -T + Fix gulm operation of clvmd, including a hang when doing lvchange -aey + Fix hang in clvmd if a pre-command failed. + +Version 2.02.16 - 1st December 2006 +=================================== + Fix VG clustered read locks to use PR not CR. + Adjust some alignments for ia64/sparc. + Fix mirror segment removal to use temporary error segment. + Always compile debug logging into clvmd. + Add startup timeout to RHEL4 clvmd startup script. + Add -T (startup timeout) switch to clvmd. + Improve lvm_dump.sh robustness. + Update lvm2create_initrd to support gentoo. + +Version 2.02.15 - 21st November 2006 +==================================== + Fix clvmd_init_rhel4 line truncation (2.02.14). + Install lvmdump by default. + Fix check for snapshot module when activating snapshot. + Fix pvremove error path for case when PV is in use. + Warn if certain duplicate config file entries are seen. + Enhance lvm_dump.sh for sysreport integration and add man page. + Fix --autobackup argument which could never disable backups. + Fix a label_verify error path. + +Version 2.02.14 - 10th November 2006 +==================================== + Fix adjusted_mirror_region_size() to handle 64-bit size. + Add some missing bounds checks on 32-bit extent counters. + Add Petabyte and Exabyte support. + Fix lvcreate error message when 0 extents requested. + lvremove man page: volumes must be cluster inactive before being removed. + Protect .cache manipulations with fcntl locking. + Change .cache timestamp comparisons to use ctime. + Fix mirror log LV writing to set all bits in whole LV. + Fix clustered VG detection and default runlevels in clvmd_init_rhel4. + Fix high-level free space check for partial allocations. + +Version 2.02.13 - 27th October 2006 +=================================== + Add couple of missing files to tools/Makefile CLEAN_TARGETS. + When adding snapshot leave cow LV mapped device active after zeroing. + Fix a clvmd debug message. + Add dev_flush() to set_lv(). + Add lvchange --resync. + Perform high-level free space check before each allocation attempt. + Don't allow a node to remove an LV that's exclusively active on anther node. + Cope if same PV is included more than once in cmdline PE range list. + Set PV size to current device size if it is found to be zero. + Add segment parameter to target_present functions. + +Version 2.02.12 - 16th October 2006 +=================================== + Fix pvdisplay to use vg_read() for non-orphans. + Fall back to internal locking if external locking lib is missing or fails. + Retain activation state after changing LV minor number with --force. + Propagate clustered flag in vgsplit and require resizeable flag. + +Version 2.02.11 - 12th October 2006 +=================================== + Add clvmd function to return the cluster name. not used by LVM yet. + Add cling allocation policy. + Change _check_contiguous() to use _for_each_pv(). + Extend _for_each_pv() to allow termination without error. + Abstract _is_contiguous(). + Remove duplicated pv arg from _check_contiguous(). + Accept regionsize with lvconvert. + Add report columns with underscore before field names ending 'size'. + Correct regionsize default on lvcreate man page (MB). + Fix clvmd bug that could cause it to die when a node with a long name crashed. + Add device size to text metadata. + Fix format_text mda_setup pv->size and pv_setup pe_count calculations. + Fix _for_each_pv() for mirror with core log. + Add lvm_dump.sh script to create a tarball of debugging info from a system. + Capture error messages in clvmd and pass them back to the user. + Remove unused #defines from filter-md.c. + Make clvmd restart init script wait until clvmd has died before starting it. + Add -R to clvmd which tells running clvmds to reload their device cache. + Add LV column to reports listing kernel modules needed for activation. + Show available fields if report given invalid field. (e.g. lvs -o list) + Add timestamp functions with --disable-realtime configure option. + Add %VG, %LV and %FREE suffices to lvcreate/lvresize --extents arg. + Fix two potential NULL pointer derefs in error cases in vg_read(). + Separate --enable-cluster from locking lib options in lvmconf.sh. + Add a missing comma in lvcreate man page. + +Version 2.02.10 - 19th September 2006 +===================================== + Fix lvconvert mirror change case detection logic. + Fix mirror log detachment so it correctly becomes a standalone LV. + Extend _check_contiguous() to detect single-area LVs. + Include mirror log (untested) in _for_each_pv() processing. + Use MIRROR_LOG_SIZE constant. + Remove struct seg_pvs from _for_each_pv() to generalise. + Avoid adding duplicates to list of parallel PVs to avoid. + Fix several incorrect comparisons in parallel area avoidance code. + Fix segment lengths when flattening existing parallel areas. + Log existing parallel areas prior to allocation. + Fix mirror log creation when activation disabled. + Don't attempt automatic recovery without proper locking. + When using local file locking, skip clustered VGs. + Add fallback_to_clustered_locking and fallback_to_local_locking parameters. + lvm.static uses built-in cluster locking instead of external locking. + Don't attempt to load shared libraries if built statically. + Change default locking_lib to liblvm2clusterlock.so. + Add skip_dev_dir() to process command line VGs. + Stop clvmd complaining about nodes that have left the cluster. + Move lvm_snprintf(), split_words() and split_dm_name() into libdevmapper. + Add lvconvert man page. + Add mirror options to man pages. + Prevent mirror renames. + Move CMDLIB code into separate file and record whether static build. + +Version 2.02.09 - 17th August 2006 +================================== + Fix PE_ALIGN for pagesize over 32KB. + Separate out LVM1_PE_ALIGN and pe_align(). + Add lvm_getpagesize wrapper. + Add --maxphysicalvolumes to vgchange. + +Version 2.02.08 - 15th August 2006 +================================== + Add checks for duplicate LV name, lvid and PV id before writing metadata. + Report all sanity check failures, not just the first. + Fix missing lockfs on first snapshot creation. + Add unreliable --trustcache option to reporting commands. + Fix locking for mimage removal. + Fix clvmd_init_rhel4 'status' exit code. + +Version 2.02.07 - 17th July 2006 +================================ + Fix activation logic in lvchange --persistent. + Don't ignore persistent minor numbers when activating. + Use RTLD_GLOBAL when loading shared libraries. + Add some forgotten memlock checks to _vg_read to protect against full scans. + Add mutex to dmeventd_mirror to avoid concurrent execution. + Fix vgreduce --removemissing to return success if VG is already consistent. + Fix return code if VG specified on command line is not found. + Fix PV tools to include orphaned PVs in default output again. + Fixed unaligned access when using clvm. + Fix an extra dev_close in a label_read error path. + Append patches to commit emails. + Fix target_register_events args. + Prevent snapshots of mirrors. + Add DISTCLEAN_TARGETS to make template for configure.h. + More fixes to error paths. + Fix lvcreate corelog validation. + Add --config for overriding most config file settings from cmdline. + Quote arguments when printing command line. + Remove linefeed from 'initialising logging' message. + Add 'Completed' debug message. + Don't attempt library exit after reloading config files. + Always compile with libdevmapper, even if device-mapper is disabled. + +Version 2.02.06 - 12th May 2006 +=============================== + Propagate --monitor around cluster. + Add --monitor to vgcreate and lvcreate to control dmeventd registration. + Filter LCK_NONBLOCK in clvmd lock_vg. + Add --nosync to lvcreate with LV flag NOTSYNCED. + Use mirror's uuid for a core log. + Add mirror log fault-handling policy. + Improve mirror warning messages and tidy dmeventd syslog output. + Propagate nosync flag around cluster. + Allow vgreduce to handle mirror log failures. + Add --corelog to lvcreate and lvconvert. + Create a log header for replacement in-sync mirror log. + Use set_lv() and dev_set() to wipe sections of devices. + Add mirror_in_sync() flag to avoid unnecessary resync on activation. + Add mirror_library description to example.conf. + Fix uuid_from_num() buffer overrun. + Make SIZE_SHORT the default for display_size(). + Fix some memory leaks in error paths found by coverity. + Use C99 struct initialisers. + Move DEFS into configure.h. + Clean-ups to remove miscellaneous compiler warnings. + Improve stripe size validation. + Increase maximum stripe size limit to physical extent size for lvm2 metadata. + Fix activation code to check for pre-existing mirror logs. + Tighten region size validation. + Ignore empty strings in config files. + Require non-zero regionsize and document parameter on lvcreate man page. + Invalidate cache if composition of VG changed externally. + +Version 2.02.05 - 21st April 2006 +================================= + Fix vgid string termination in recent cache code. + +Version 2.02.04 - 19th April 2006 +================================= + Check for libsepol. + Add some cflow & scope support. + Separate out DEFS from CFLAGS. + Remove inlines and use unique function names. + +Version 2.02.03 - 14th April 2006 +================================= + vgrename accepts vgid and exported VG. + Add --partial to pvs. + When choosing between identically-named VGs, also consider creation_host. + Provide total log suppression with 2. + Fix vgexport/vgimport to set/reset PV exported flag so pv_attr is correct. + Add vgid to struct physical_volume and pass with vg_name to some functions. + If two or more VGs are found with the same name, use one that is not exported. + Whenever vgname is captured, also capture vgid and whether exported. + Remove an incorrect unlock_vg() from process_each_lv(). + Update extent size information in vgchange and vgcreate man pages. + Introduce origin_from_cow() and lv_is_visible(). + pvremove without -f now fails if there's no PV label. + Support lvconvert -s. + Suppress locking library load failure message if --ignorelockingfailure. + Propagate partial mode around cluster. + Fix archive file expiration. + Fix dmeventd build. + clvmd now uses libcman rather than cman ioctls. + clvmd will allow new cman to shutdown on request. + +Version 2.02.02 - 7th February 2006 +=================================== + Add %.so: %.a make template rule. + Switchover library building to use LIB_SUFFIX. + Only do lockfs filesystem sync when suspending snapshots. + Always print warning if activation is disabled. + vgreduce removes mirror images. + Add --mirrorsonly to vgreduce. + vgreduce replaces active LVs with error segment before removing them. + Set block_on_error parameter if available. + Add target_version. + Add details to format1 'Invalid LV in extent map' error message. + Fix lvscan snapshot full display. + Bring lvdisplay man page example into line. + Add mirror dmeventd library. + Add some activation logic to remove_mirror_images(). + lvconvert can remove specified PVs from a mirror. + lvconvert turns an existing LV into a mirror. + Allow signed mirrors arguments. + Move create_mirror_log() into toollib. + Determine parallel PVs to avoid with ALLOC_NORMAL allocation. + Fix lv_empty. + +Version 2.02.01 - 23rd November 2005 +==================================== + Fix lvdisplay cmdline to accept snapshots. + Fix open RO->RW promotion. + Fix missing vg_revert in lvcreate error path. + +Version 2.02.00 - 10th November 2005 +==================================== + Extend allocation areas to avoid overflow with contiguous with other PVs. + Stop lvcreate attempting to wipe zero or error segments. + Added new lvs table attributes. + Separated out activation preload. + Moved activation functions into libdevmapper. + Fixed build_dm_name. + Add return macros. + Added xen xvd devices. + Clear up precommitted metadata better. + A pvresize implementation. + Fix contiguous allocation when there are no preceding segments. + Add mirror_seg pointer to lv_segment struct. + Only keep a device open if it's known to belong to a locked VG. + Fix lvdisplay to show all mirror destinations. + Replacement suspend code using libdevmapper dependency tree. + Add DEFS to make.tmpl. + Use dm_is_dm_major instead of local copy. + Allow mapped devices to be used as PVs. + Move set_selinux_context into libdevmapper. + Fix automatic text metadata buffer expansion (using macro). + Cache formatted text metadata buffer between metadata area writes. + Add pe_start field to pvs. + Add 'LVM-' prefix to uuids. + Split lv_segment_area from lv_segment to permit extension. + Replacement deactivation code using libdevmapper dependency tree. + Simplify dev_manager_info(). + Attempt to load missing targets using modprobe. + Add -a to lvscan. + Move mknodes into libdevmapper. + Move bitset, hash, pool and dbg_malloc into libdevmapper. + +Version 2.01.15 - 16th October 2005 +=================================== + Refuse to run pvcreate/pvremove on devices we can't open exclusively. + Use ORPHAN lock definition throughout. + Validate chunksize in lvcreate. + Reduce chunksize limit to 512k. + Fix chunksize field in reports. + Don't hide snapshots from default 'lvs' output. + Add is_dm_major() for use in duplicate device detection in lvmcache_add(). + Really switch device number in lvmcache when it says it is doing so. + Option for bitset memory allocation using malloc as well as pool. + Don't assume exactly two mirrors when parsing mirror status. + Suppress fsync() error message on filesystems that don't support it. + Fix yes_no_prompt() error handling. + Add lvm.conf comment warning against multiple filter lines. + Tidy lvmconf.sh. + Add format1 dev_write debug messages. + Add clustered VG attribute to report. + Move lvconvert parameters into struct lvconvert_params. + Add clustered VG flag to LV lock requests. + Change LV locking macros to take lv instead of lvid. + Prepend 'cluster' activation parameter to mirror log when appropriate. + Pass exclusive flag to lv_activate and on to target activation code. + Prevent snapshot creation in a clustered VG for now. + Factor out adjusted_mirror_region_size() and generate_log_name_format(). + Move compose_log_line() into mirror directory. + Factor out _get_library_path(). + Don't kill idling clvmd threads. + clvmd no longer takes out locks for non-clustered LVs. + Recognise ATA over Ethernet (aoe) devices. + +Version 2.01.14 - 4th August 2005 +================================= + Fix lvconvert PV parameter in help string. + Prevent snapshots getting activated in a clustered VG. + Separate out _build_dev_string. + Move zero_lv to toollib. + Fix pool format handler to work with pv segment code. + +Version 2.01.13 - 13th July 2005 +================================ + Fix pvmove segment splitting. + Abstract vg_validate. + Only make one attempt at contiguous allocation. + Fix lvm1 format metadata read. + Fix lvm1 format non-mirror lvcreate. + +Version 2.01.12 - 14th June 2005 +================================ + Various allocation-related pvmove fixes. + Log an error if clvmd can't resolve a host name got from CCS. + Fix potential spin loop in clvmd. + +Version 2.01.11 - 13th June 2005 +================================ + Added lvmconf.sh. + Use matchpathcon mode parameter. + Don't defer closing dead FDs in clvmd. + Remove hard-coded 64k text metadata writing restriction. + Make VG name restrictions consistent. + Introduce lvconvert. So far only removes mirror images. + Allow mirror images to be resized. + Allow mirror images to have more than one segment. + Centralise restrictions on LV names. + Always insert an intermediate layer for mirrors. + Suppress hidden LVs from reports unless --all is given. + Use square brackets for hidden LVs in reports. + Allow the creation of mirrors with contiguous extents. + Always perform sanity checks against metadata before committing it to disk. + Split lv_extend into two steps: choosing extents + allocation to LV(s). + Add mirror log region size to metadata. + Use list_iterate_items throughout and add list*back macros. + Introduce seg_ macros to access areas. + Add segtype_is_ macros. + Support tiny metadata areas for pool conversions. + Mirror activation handles disk log as well as core. + Activation code recognises mirror log dependency. + Add mirror_log and regionsize fields to report. + Fix non-orphan pvchange -u. + Fix vgmerge to handle duplicate LVIDs. + Move archiver code from tools into library. + vgscan/change/display/vgs automatically create metadata backups if needed. + Merge cloned allocation functions. + Fix contiguous allocation policy with linear. + Cope with missing format1 PVs again. + Remove lists of free PV segments. + Simplify pv_maps code and remove slow bitset algorithm. + Red-Hat-ify the clvmd rhel4 initscript. + %Zu->%zu + Fix loopfiles alias alloc & mem debugging. + Un-inline dbg_strdup. + lv_reduce tidying. + Remove some unnecessary parameters. + Introduce seg_is macros. + +Version 2.01.10 - 3rd May 2005 +============================== + Don't create backup and archive dirs till needed. + Reinstate full PV size when removing from VG. + Support loopfiles for testing. + Tidy lv_segment interface. + pv_segment support. + vgchange --physicalextentsize + Internal snapshot restructuring. + Remove unused internal non-persistent snapshot option. + Allow offline extension of snapshot volumes. + Move from 2-step to 3-step on-disk metadata commit. + Scan ramdisks too and allow non-O_DIRECT fallback. + Annotate, tidy and extend list.h. + Alignment tidying. + Make clvmd work around some "bugs" in gulm's node state notifications. + Tidy clvmd's SIGHUP handler + +Version 2.01.09 - 4th April 2005 +================================ + Add --ignorelockingfailure to vgmknodes. + clvmd: Don't allow user operations to start until the lvm thread is fully up. + clvmd-gulm: set KEEPALIVE on sockets. + +Version 2.01.08 - 22nd March 2005 +================================= + Add clustered attribute so vgchange can identify clustered VGs w/o locking. + Improve detection of external changes affecting internal cache. + Add 'already in device cache' debug message. + Add -a to pvdisplay -C. + Avoid rmdir opendir error messsages when dir was already removed. + Tighten signal handlers. + Avoid some compiler warnings. + Additional rename failure error message. + read/write may be macros. + clvmd: don't take out lvm thread lock at startup, it only protects jobs list. + +Version 2.01.07 - 8th March 2005 +================================ + Cope with new devices appearing by rescanning /dev if a uuid can't be found. + Remove DESTDIR from LVM_SHARED_PATH. + clvmd fixes: make FDs close-on-exec + gulm unlocks VG & orphan locks at startup in case they are stale + gulm now unlocks VG & orphan locks if client dies. + +Version 2.01.06 - 1st March 2005 +================================ + Suppress 'open failed' error messages during scanning. + Option to suppress warnings of file descriptors left open. + Fix default value of metadatacopies in documentation (2->1). + Fix clvmd-gulm locking. + ./configure --enable-debug now enables debugging code in clvmd. + Fix clvmd-gulm node up/down code so it actually works. + clvmd-gulm now releases locks when shut down. + +Version 2.01.05 - 18th February 2005 +==================================== + Static binary invokes dynamic binary if appropriate. + Make clvmd config check a little more tolerant. + gulm clvmd can now cope with >1 message arriving in a TCP message. + +Version 2.01.04 - 9th February 2005 +=================================== + Add fixed offset to imported pool minor numbers. + Update binary pathnames in clvmd_init_rhel4. + lvm2cmd.so should skip the check for open fds. + Remove unused -f from pvmove. + Gulm clvmd doesn't report "connection refused" errors. + clvmd does a basic config file sanity check at startup. + Fix potential thread shutdown race in clvmd. + +Version 2.01.03 - 1st February 2005 +=================================== + More 64-bit display/report fixes. + More informative startup mesg if can't create /etc/lvm. + Fix snapshot device size bug (since 2.01.01). + clvmd announces startup and cluster connection in syslog. + Gulm clvmd doesn't hang trying to talk to a rebooted node. + Gulm clvmd doesn't print cman error on startup. + +Version 2.01.02 - 21st January 2005 +=================================== + Update clvmd_init_rhel4: use lvm.static and don't load dlm. + Fix some size_t printing. + Fix 64 bit xlate consts. + Split out pool sptype_names to avoid unused const. + Always fail if random id generation fails. + Recognise gnbd devices. + Fix clvmd startup bug introduced in cman/gulm amalgamation. + Improve reporting of node-specific locking errors. + +Version 2.01.01 - 19th January 2005 +=================================== + Fix clvmd lv_info_by_lvid open_count. + Store snapshot and origin sizes separately. + Update vgcreate man page. + +Version 2.01.00 - 17th January 2005 +=================================== + Fix vgscan metadata auto-correction. + Only ask libdevmapper for open_count when we need it. + Adjust RHEL4 clvmd init script priority. + Enable building of CMAN & GULM versions of clvmd into a single binary + +Version 2.00.33 - 7th January 2005 +================================== + pvcreate wipes first 4 sectors unless given --zero n. + gulm clvmd now uses new ccsd key names. + gulm clvmd now doesn't ignore the first node in cluster.conf + Improve clvmd failure message if it's already running. + Allow user to kill clvmd during initialisation. + Fix off-by-one error in cluster_locking that could cause read hangs. + +Version 2.00.32 - 22nd December 2004 +==================================== + Drop static/dl restriction for now. + Fix an error fprintf. + Fix vgdisplay -s. Breaks (undocumented) lvs/pvs/vgs -s instead for now. + Fix device reference counting on re-opens. + Ignore sysfs symlinks when DT_UNKNOWN. + Add clvmd init script for RHEL4. + Skip devices that are too small to be PVs. + Fix pvchange -x segfault with lvm2-format orphan. + Cope with empty msdos partition tables. + Add CONTRIBUTORS file. + +Version 2.00.31 - 12th December 2004 +==================================== + Reopen RO file descriptors RW if necessary. + +Version 2.00.30 - 10th December 2004 +==================================== + Additional device-handling debug messages. + Additional verbosity level -vvvv includes line numbers and backtraces. + Verbose messages now go to stderr not stdout. + Close any stray file descriptors before starting. + Refine partitionable checks for certain device types. + Allow devices/types to override built-ins. + Fix lvreduce man page .i->.I + Fix vgsplit man page title. + Fix clvmd man makefile. + Extend dev_open logging. + Make clvmd_fix_conf.sh UNDOable. + +Version 2.00.29 - 27th November 2004 +==================================== + xlate compilation fix. + +Version 2.00.28 - 27th November 2004 +==================================== + Fix partition table & md signature detection. + Minor configure/makefile tidy. + Export version.h from tools for clvmd. + +Version 2.00.27 - 24th November 2004 +==================================== + Trap large memory allocation requests. + Fix to partition table detection code. + Improve filter debug mesgs. + Make clvmd_fix_conf.sh UNDOable + +Version 2.00.26 - 23rd November 2004 +==================================== + Improve pool debugging stats. + Detect partition table signature. + pvcreate wipes md superblocks. (With --uuid or --restorefile it prompts.) + Separate out md superblock detection code. + Prevent snapshot origin resizing. + Improve a vgremove error message. + Update some man pages. + Allow y/n with -ae args (exclusive activation). + Fixes to lvcreate vgname parsing. + Fix dm_name string size calculation. + Improve clvmd error reporting during startup. + Make clvmd cope with large gaps in node numbers IDs. + Make clvmd initialisation cope better with debugging output. + Tidy clvmd socket callbacks so all work happens outside main loop. + clvmd -V now displays lvm version too. + Add optional gulm build for clvmd + +Version 2.00.25 - 29th September 2004 +===================================== + Fix return code from rm_link for vgmknodes. + Make clvmd LV hash table thread-safe. + Fix clvmd locking so it will lock out multiple users on the same node. + Fix clvmd VG locking to it can cope with multiple VG locks. + Remove spurious trailing dot in lvreduce man page. + Fix vgremove locking. + +Version 2.00.24 - 16th September 2004 +===================================== + Fix pool_empty so it really does empty the memory pool. + Rename old segtypes files to segtype. + Some fixes to memory debugging code. + Exclude internal commands formats & segtypes from install. + +Version 2.00.23 - 15th September 2004 +===================================== + Export dm name build & split functions. + Use O_NOATIME on devices if available. + Write log message when each segtype/format gets initialised. + New commands 'segtypes' and 'formats'. + Suppress pvmove abort message in test mode. + Improve pvcreate/remove device not found error message. + Allow pvmove to move data within the same PV. + Describe how pvmove works on man page. + Test for incompatible format/segtype combinations in lv_extend. + Fix lvchange example on man page. + +Version 2.00.22 - 3rd September 2004 +==================================== + Fix /dev/vgname perms. + Restructure xlate.h. + Add clvmd man page. + +Version 2.00.21 - 19th August 2004 +================================== + Update cnxman-socket.h from cman. + Recognise iseries/vd devices. + Use 'make install_cluster' to install cluster extensions only. + Cope with DT_UNKNOWN in sysfs. + Fix extents_moved metadata size comment. + Remove duplicate line in pvremove help text. + Support variable mirror region size. + Support PE ranges in pvmove source PV. + Fixes to as-yet-unused LV segment splitting code. + Change alloc_areas to pe_ranges and allow suppression of availability checks. + Add dev_size column to pvs. + Add report columns for in-kernel device number. + +Version 2.00.20 - 3 July 2004 +============================= + More autoconf fixes. + Fix device number handling for 2.6 kernels. + +Version 2.00.19 - 29 June 2004 +============================== + Reduce severity of setlocale failure message. + Recognise argv[0] "initrd-lvm" (pld-linux). + Make -O2 configurable. + Added --disable-selinux to configure script. + LD_FLAGS->LDFLAGS & LD_DEPS->LDDEPS in configure script. + Add init_debug to clvmd. + +Version 2.00.18 - 24 June 2004 +============================== + Fix vgchange activation. + Add cluster support. + +Version 2.00.17 - 20 June 2004 +============================== + configure --enable-fsadm to try out fsadm. fsadm is not tested yet. + Display all filtered devices, not just PVs, with pvs -a. + Fix sync_dir() when no / in filename + vgcfgbackup -f accepts template with %s for VG name. + Extend hash functions to handle non-null-terminated data. + Add local activation support. + Tidy relative paths in makefile includes. + fsadm support for fsck and resizing - needs testing. + Add read-only GFS pool support. + Add lvm2create_initrd script from http://poochiereds.net/svn/lvm2/ + Fix rounding of large diplayed sizes. + Suppress decimal point when using units of sectors/bytes. + Additional kernel target checks before pvmove & snapshot creation. + Add i2o_block. + +Version 2.00.16 - 24 May 2004 +============================= + Set area_count within alloc_lv_segment. + Remove error labels from lvresize. + Fix a pvs error path. + xxchange -ae for exclusive activation. + Don't return non-zero status if there aren't any volume groups. + Add --alloc argument to tools. + Rename allocation policies to contiguous, normal, anywhere, inherit. + nextfree becomes normal; anywhere isn't implemented yet. + LV inherits allocation policy from VG. Defaults: LV - inherit; VG - normal + Additional status character added to vgs to indicate allocation policy. + Add reset_fn to external_locking. + Ensure presence of virtual targets before attempting activating. + Attempt to fix resizing of snapshot origins. + Restructure lvresize, bringing it closer to lvcreate. + A quick sanity check on vg_disk struct when read in. More checks needed. + Only include visible LVs in active/open counts. + Add virtual segment types, zero and error. A large sparse device can be +constructed as a writeable snapshot of a large zero segment. + Add --type to lvcreate/resize. + Push lv_create & alloc policy up to tool level. + Fix pvdisplay return code. + Detect invalid LV names in arg lists. + Reporting uses line-at-a-time output. + lvm2 format sets unlimited_vols format flag. + Internal-only metadata flag support. + Basic checking for presence of device-mapper targets. + Separate out polldaemon. + Revise internal locking semantics. + Move find_pv_by_name to library. + Rename move->copy. + Add devices to segments report. + Begin separating out segment code. There's a lot of change here. + Compress any (obsolete) long LVM1 pvids encountered. + Support for tagged config files. + Don't abort operations if selinux present but disabled. + Fix typo in configure which left HAVE_LIBDL unset. + +Version 2.00.15 - 19 Apr 2004 +============================= + configure --with-owner= --with-group= to avoid -o and -g args to 'install' + +Version 2.00.14 - 16 Apr 2004 +============================= + Use 64-bit file functions by default. + +Version 2.00.13 - 16 Apr 2004 +============================= + Set devices/md_component_detection = 1 to ignore devices containing md + superblocks. [Luca Berra] + Ignore error setting selinux file context if fs doesn't support it. + +Version 2.00.12 - 14 Apr 2004 +============================= + Install a default lvm.conf into /etc/lvm if there isn't one already. + Allow different installation dir for lvm.static (configure --staticdir=) + Fix inverted selinux error check. + Recognise power2 in /proc/devices. + Fix counting in lvs_in_vg_opened. [It ignored devices open more than once.] + +Version 2.00.11 - 8 Apr 2004 +============================ + Set fallback_to_lvm1 in lvm.conf (or configure --enable-lvm1_fallback) + to run lvm1 binaries if running a 2.4 kernel without device-mapper. + +Version 2.00.10 - 7 Apr 2004 +============================ + More fixes for static build. + Add basic selinux support. + Fix sysfs detection. + +Version 2.00.09 - 31 Mar 2004 +============================= + Update copyright notices for Red Hat. + Fix vgmknodes to remove dud /dev/mapper entries. (libdevmapper update reqd). + Add LVM1-style colon output to vgdisplay. + lvchange --refresh to reload active LVs. + Add string display to memory leak dump. + Add locking flags & memlock option. + Add list_versions to library. + Ignore open hidden LVs when checking if deactivation is OK. + Suppress move percentage when device inactive. + Add lv_info_by_lvid. + Various tidy-ups to the build process. + Rebaseline internal verbose level. + Add --nolocking option for read operations if locking is failing. + Add option to compile into a library. + When compiled without libdevmapper, only print warning message once. + Fix lvreduce PV extent calculations. + Fix DESTDIR to work with configure path overrides. + Always use / as config file separator & rename internal config file variables. + Add support for tagging PV/VG/LVs and hosts. + Fix rare bug in recognition of long cmdline argument forms. + Add basic internationalisation infrastructure. + Don't recurse symlinked dirs such as /dev/fd on 2.6 kernels. + Update autoconf files. + Add sysfs block device filtering for 2.6 kernels. + Update refs for move to sources.redhat.com. + +Friday 14th November 2003 +========================= +Some bug fixes & minor enhancements, including: + Backwards compatibility with LVM1 metadata improved. + Missing man pages written. + Tool error codes made more consistent. + vgmknodes written. + O_DIRECT can be turned off if it doesn't work in your kernel. + dumpconfig to display the active configuration file + +You need to update libdevmapper before using 'vgmknodes' or 'vgscan --mknodes'. +If your root filesystem is on an LV, you should run one of those two +commands to fix up the special files in /dev in your real root filesystem +after finishing with your initrd. Also, remember you can use +'vgchange --ignorelockingfailure' on your initrd if the tool fails because +it can't write a lock file to a read-only filesystem. + +Wednesday 30th April 2003 +========================= +A pvmove implementation is now available for the new metadata format. + +When running a command that allocates space (e.g. lvcreate), you can now +restrict not only which disk(s) may be used but also the Physical Extents +on those disks. e.g. lvcreate -L 10 vg1 /dev/hda6:1000-2000:3000-4000 + + +Monday 18th November 2002 +======================== + +The new format of LVM metadata is ready for you to test! + We expect it to be more efficient and more robust than the original format. + It's more compact and supports transactional changes and replication. + Should things go wrong on a system, it's human-readable (and editable). + +Please report any problems you find to the mailing list, +linux-lvm@sistina.com. The software has NOT yet been thoroughly +tested and so quite possibly there'll still be some bugs in it. +Be aware of the disclaimer in the COPYING file. + +While testing, we recommend turning logging on in the configuration file +to provide us with diagnostic information: + log { + file="/tmp/lvm2.log" + level=7 + activation=1 + } + +You should schedule regular backups of your configuration file and +metadata backups and archives (normally kept under /etc/lvm). + +Please read docs/example.conf and "man lvm.conf" to find out more about +the configuration file. + +To convert an existing volume group called vg1 to the new format using +the default settings, use "vgconvert -M2 vg1". See "man vgconvert". + +-M (or --metadatatype in its long form) is a new flag to indicate which +format of metadata the command should use for anything it creates. +Currently, the valid types are "lvm1" and "lvm2" and they can be +abbreviated to "1" and "2" respectively. The default value for this +flag can be changed in the global section in the config file. + +Backwards-compatible support for the original LVM1 metadata format is +maintained, but it can be moved into a shared library or removed +completely with configure's --with-lvm1 option. + +Under LVM2, the basic unit of metadata is the volume group. Different +volume groups can use different formats of metadata - vg1 could use +the original LVM1 format while vg2 used the new format - but you can't +mix formats within a volume group. So to add a PV to an LVM2-format +volume group you must run "pvcreate -M2" on it, followed by "vgextend". + +With LVM2-format metadata, lvextend will let you specify striping +parameters. So an LV could consist of two or more "segments" - the +first segment could have 3 stripes while the second segment has just 2. + +LVM2 maintains a backup of the current metadata for each volume group +in /etc/lvm/backup, and puts copies of previous versions in +/etc/lvm/archive. "vgcfgbackup" and "vgcfgrestore" can be used to +create and restore from these files. If you fully understand what +you're doing, metadata can be changed by editing a copy of a current +backup file and using vgcfgrestore to reload it. + +Please read the pvcreate man page for more information on the new +format for metadata. + +All tools that can change things have a --test flag which can be used +to check the effect of a set of cmdline args without really making the +changes. + + +What's not finished? +==================== +The internal cache. If you turn on debugging output you'll see lots of +repeated messages, many of which will eventually get optimised out. + +--test sometimes causes a command to fail (e.g. vgconvert --test) even +though the real command would work: again, fixing this is waiting for +the work on the cache. + +Several of the tools do not yet contain the logic to handle full +recovery: combinations of pvcreate and vgcfgrestore may sometimes be +needed to restore metadata if a tool gets interrupted or crashes or +finds something unexpected. This applies particularly to tools that +work on more than one volume group at once (e.g. vgsplit). + +Display output. Some metadata information cannot yet be displayed. + +Recovery tools to salvage "lost" metadata directly from the disks: +but we hope the new format will mean such tools are hardly ever needed!
diff --git a/WHATS_NEW_DM b/WHATS_NEW_DM new file mode 100644 index 0000000..74722c5 --- /dev/null +++ b/WHATS_NEW_DM
@@ -0,0 +1,1291 @@ +Version 1.02.133 - +================================= + +Version 1.02.132 - 28th July 2016 +================================= + Fix json reporting to escape '"' character that may appear in reported string. + +Version 1.02.131 - 15th July 2016 +================================= + Disable queueing on mpath devs in blk-availability systemd service/initscript. + Add new -m|--mpathoption disablequeueing to blkdeactivate. + Automatically group regions with 'create --segments' unless --nogroup. + Fix resource leak when deleting the first member of a group. + Allow --bounds with 'create --filemap' for dmstats. + Enable creation of filemap regions with histograms. + Enable histogram aggregation for regions with more than one area. + Enable histogram aggregation for groups of regions. + Add a --filemap option to 'dmstats create' to allow mapping of files. + Add dm_stats_create_regions_from_fd() to map file extents to regions. + +Version 1.02.130 - 6th July 2016 +================================ + Minor fixes from coverity. + +Version 1.02.129 - 6th July 2016 +================================ + Update default dmstats field selections for groups. + Add 'obj_type', 'group_id', and 'statsname' fields to dmstats reports. + Add --area, --region, and --group to dmstats to control object selection. + Add --alias, --groupid, --regions to dmstats for group creation and deletion. + Add 'group' and 'ungroup' commands to dmstats. + Allow dm_stats_delete_group() to optionally delete all group members. + Add dm_stats_get_object_type() to return the type of object present. + Add dm_stats_walk_init() allowing control of objects visited by walks. + Add dm_stats_get_group_descriptor() to return the member list as a string. + Introduce dm_stats_get_nr_groups() and dm_stats_group_present(). + Add dm_stats_{get,set}_alias() to set and retrieve alias names for groups. + Add dm_stats_get_group_id() to return the group ID for a given region. + Add dm_stats_{create,delete}_group() to allow grouping of stats regions. + Add enum-driven dm_stats_get_{metric,counter}() interfaces. + Add dm_bitset_parse_list() to parse a string representation of a bitset. + Thin dmeventd plugin umounts lvm2 volume only when pool is 95% or more. + +Version 1.02.128 - 25th June 2016 +================================= + Recognize 'all' keyword used in selection as synonym for "" (no selection). + Add dm_report_set_selection to set selection for multiple output of report. + Add DM_REPORT_OUTPUT_MULTIPLE_TIMES flag for multiple output of same report. + Move field width handling/sort init from dm_report_object to dm_report_output. + Add _LOG_BYPASS_REPORT flag for bypassing any log report currently set. + Introduce DM_REPORT_GROUP_JSON for report group with JSON output format. + Introduce DM_REPORT_GROUP_BASIC for report group with basic report output. + Introduce DM_REPORT_GROUP_SINGLE for report group having single report only. + Add dm_report_group_{create,push,pop,destroy} to support report grouping. + +Version 1.02.127 - 11th June 2016 +================================= + Fix blkdeactivate regression causing skipping of dm + md devices. (1.02.126) + +Version 1.02.126 - 3rd June 2016 +================================ + Report passthrough caching mode when parsing cache mode. + +Version 1.02.125 - 14th May 2016 +================================ + Show library version in message even if dm driver version is unavailable. + +Version 1.02.124 - 30th April 2016 +================================== + Add dm_udev_wait_immediate to libdevmapper for waiting outside the library. + +Version 1.02.123 - 23rd April 2016 +================================== + Do not strip LVM- when debug reporting not found uuid. + +Version 1.02.122 - 9th April 2016 +================================= + Change log_debug ioctl flags from single characters into words. + +Version 1.02.121 - 26th March 2016 +================================== + Adjust raid status function. + +Version 1.02.120 - 11th March 2016 +================================== + Improve parsing of cache status and report Fail, Error, needs_check, ro. + +Version 1.02.119 - 4th March 2016 +================================= + Fix dm_config_write_node and variants to return error on subsection failures. + Remove 4096 char limit due to buffer size if writing dm_config_node. + +Version 1.02.118 - 26th February 2016 +===================================== + Fix string boundary check in _get_canonical_field_name(). + Always initialized hist struct in _stats_parse_histogram(). + +Version 1.02.117 - 21st February 2016 +===================================== + Improve status parsing for thin-pool and thin devices. + +Version 1.02.116 - 15th February 2016 +===================================== + Use fully aligned allocations for dm_pool_strdup/strndup() (1.02.64). + Fix thin-pool table parameter feature order to match kernel output. + +Version 1.02.115 - 25th January 2016 +==================================== + Fix man page for dmsetup udevcreatecookie. + +Version 1.02.114 - 14th December 2015 +===================================== + Better support for dmsetup static linkage. + Extend validity checks on dmeventd client socket. + +Version 1.02.113 - 5th December 2015 +==================================== + Mirror plugin in dmeventd uses dm_get_status_mirror(). + Add dm_get_status_mirror() for parsing mirror status line. + +Version 1.02.112 - 28th November 2015 +===================================== + Show error message when trying to create unsupported raid type. + Improve preloading sequence of an active thin-pool target. + Drop extra space from cache target line to fix unneded table reloads. + +Version 1.02.111 - 23rd November 2015 +===================================== + Extend dm_hash to support multiple values with the same key. + Add missing check for allocation inside dm_split_lvm_name(). + Test dm_task_get_message_response for !NULL in dm_stats_print_region(). + Add checks for failing dm_stats_create() in dmsetup. + Add missing fifo close when failed to initialize client connection. + +Version 1.02.110 - 30th October 2015 +==================================== + Disable thin monitoring plugin when it fails too often (>10 times). + Fix/restore parsing of empty field '-' when processing dmeventd event. + Enhance dm_tree_node_size_changed() to recognize size reduction. + Support exit on idle for dmenventd (1 hour). + Add support to allow unmonitor device from plugin itself. + New design for thread co-operation in dmeventd. + Dmeventd read device status with 'noflush'. + Dmeventd closes control device when no device is monitored. + Thin plugin for dmeventd improved percentage usage. + Snapshot plugin for dmeventd improved percentage usage. + Add dm_hold_control_dev to allow holding of control device open. + Add dm_report_compact_given_fields to remove given empty fields from report. + Use libdm status parsing and local mem raid dmeventd plugin. + Use local mem pool and lock only lvm2 execution for mirror dmeventd plugin. + Lock protect only lvm2 execution for snapshot and thin dmeventd plugin. + Use local mempool for raid and mirror plugins. + Reworked thread initialization for dmeventd plugins. + Dmeventd handles snapshot overflow for now equally as invalid. + Convert dmeventd to use common logging macro system from libdm. + Return -ENOMEM when device registration fails instead of 0 (=success). + Enforce writethrough mode for cleaner policy. + Add support for recognition and deactivation of MD devices to blkdeactivate. + Move target status functions out of libdm-deptree. + Correct use of max_write_behind parameter when generating raid target line. + Fix dm-event systemd service to make sure it is executed before mounting. + +Version 1.02.109 - 22nd September 2015 +====================================== + Update man pages for dmsetup and dmstats. + Improve help text for dmsetup. + Use --noflush and --nolockfs when removing device with --force. + Parse new Overflow status string for snapshot target. + Check dir path components are valid if using dm_create_dir, error out if not. + Fix /dev/mapper handling to remove dangling entries if symlinks are found. + Make it possible to use blank value as selection for string list report field. + +Version 1.02.108 - 15th September 2015 +====================================== + Do not check for full thin pool when activating without messages (1.02.107). + +Version 1.02.107 - 5th September 2015 +===================================== + Parse thin-pool status with one single routine internally. + Add --histogram to select default histogram fields for list and report. + Add report fields for displaying latency histogram configuration and data. + Add dmstats --bounds to specify histogram boundaries for a new region. + Add dm_histogram_to_string() to format histogram data in string form. + Add public methods to libdm to access numerical histogram config and data. + Parse and store histogram data in dm_stats_list() and dm_stats_populate(). + Add an argument to specify histogram bounds to dm_stats_create_region(). + Add dm_histogram_bounds_from_{string,uint64_t}() to parse histogram bounds. + Add dm_histogram handle type to represent a latency histogram and its bounds. + Fix devmapper.pc pkgconfig file to not reference non-existent rt.pc file. + Reinstate dm_task_get_info@Base to libdevmapper exports. (1.02.106) + +Version 1.02.106 - 26th August 2015 +=================================== + Add 'precise' column to statistics reports. + Add --precise switch to 'dmstats create' to request nanosecond counters. + Add precise argument to dm_stats_create_region(). + Add support to libdm-stats for precise_timestamps + +Version 1.02.105 - 17th August 2015 +=================================== + Fix 'dmstats list -o all' segfault. + Separate dmstats statistics fields from region information fields. + Add interval and interval_ns fields to dmstats reports. + Do not include internal glibc headers in libdm-timestamp.c (1.02.104) + Exit immediately if no device is supplied to dmsetup wipe_table. + Suppress dmsetup report headings when no data is output. (1.02.104) + Adjust dmsetup usage/help output selection to match command invoked. + Fix dmsetup -o all to select correct fields in splitname report. + Restructure internal dmsetup argument handling across all commands. + Add dm_report_is_empty() to indicate there is no data awaiting output. + Add more arg validation for dm_tree_node_add_cache_target(). + Add --alldevices switch to replace use of --force for stats create / delete. + +Version 1.02.104 - 10th August 2015 +=================================== + Add dmstats.8 man page + Add dmstats --segments switch to create one region per device segment. + Add dmstats --regionid, --allregions to specify a single / all stats regions. + Add dmstats --allprograms for stats commands that filter by program ID. + Add dmstats --auxdata and --programid args to specify aux data and program ID. + Add report stats sub-command to provide repeating stats reports. + Add clear, delete, list, and print stats sub-commands. + Add create stats sub-command and --start, --length, --areas and --areasize. + Recognize 'dmstats' as an alias for 'dmsetup stats' when run with this name. + Add a 'stats' command to dmsetup to configure, manage and report stats data. + Add statistics fields to dmsetup -o. + Add libdm-stats library to allow management of device-mapper statistics. + Add --nosuffix to suppress dmsetup unit suffixes in report output. + Add --units to control dmsetup report field output units. + Add support to redisplay column headings for repeating column reports. + Fix report header and row resource leaks. + Report timestamps of ioctls with dmsetup -vvv. + Recognize report field name variants without any underscores too. + Add dmsetup --interval and --count to repeat reports at specified intervals. + Add dm_timestamp functions to libdevmapper. + Recognise vg/lv name format in dmsetup. + Move size display code to libdevmapper as dm_size_to_string. + +Version 1.02.103 - 24th July 2015 +================================= + Introduce libdevmapper wrappers for all malloc-related functions. + +Version 1.02.102 - 7th July 2015 +================================ + Include tool.h for default non-library use. + Introduce format macros with embedded % such as FMTu64. + +Version 1.02.101 - 3rd July 2015 +================================ + Add experimental support to passing messages in suspend tree. + Add dm_report_value_cache_{set,get} to support caching during report/select. + Add dm_report_reserved_handler to handle report reserved value actions. + Support dynamic value in select: DM_REPORT_FIELD_RESERVED_VALUE_DYNAMIC_VALUE. + Support fuzzy names in select: DM_REPORT_FIELD_RESERVED_VALUE_FUZZY_NAMES. + Thin pool trace messages show a device name and major:minor. + +Version 1.02.100 - 30th June 2015 +================================= + Add since, after, until and before time operators to be used in selection. + Add support for time in reports and selection: DM_REPORT_FIELD_TYPE_TIME. + Support report reserved value ranges: DM_REPORT_FIELD_RESERVED_VALUE_RANGE. + Support report reserved value names: DM_REPORT_FIELD_RESERVED_VALUE_NAMED. + Add DM_CONFIG_VALUE_FMT_{INT_OCTAL,STRING_NO_QUOTES} config value format flag. + Add DM_CONFIG_VALUE_FMT_COMMON_{ARRAY,EXTRA_SPACE} config value format flag. + Add dm_config_value_{get,set}_format_flags to get and set config value format. + +Version 1.02.99 - 20th June 2015 +================================ + New dm_tree_node_set_thin_pool_read_only(DM_1_02_99) for read-only thin pool. + Enhance error message when thin-pool message fails. + Fix dmeventd logging to avoid threaded use of static variable. + Remove redundant dmeventd SIGALRM coded. + +Version 1.02.98 - 12th June 2015 +================================ + Add dm_task_get_errno() to return any unexpected errno from a dm ioctl call. + Use copy of errno made after each dm ioctl call in case errno changes later. + +Version 1.02.97 - 15th May 2015 +=============================== + New dm_task_get_info(DM_1_02_97) supports internal_suspend state. + New symbols are versioned and comes with versioned symbol name (DM_1_02_97). + +Version 1.02.96 - 2nd May 2015 +============================== + Fix selection to not match if using reserved value in criteria with >,<,>=,<. + Fix selection to not match reserved values for size fields if using >,<,>=,<. + Include uuid or device number in log message after ioctl failure. + Add DM_INTERNAL_SUSPEND_FLAG to dm-ioctl.h. + Install blkdeactivate script and its man page with make install_device-mapper. + +Version 1.02.95 - 15th March 2015 +================================= + Makefile regenerated. + +Version 1.02.94 - 4th March 2015 +================================ + Add dm_report_object_is_selected for generalized interface for report/select. + +Version 1.02.93 - 21st January 2015 +=================================== + Reduce severity of ioctl error message when dmeventd waitevent is interrupted. + Report 'unknown version' when incompatible version numbers were not obtained. + Report more info from thin pool status (out of data, metadata-ro, fail). + Support error_if_no_space for thin pool target. + Fix segfault while using selection with regex and unbuffered reporting. + Add dm_report_compact_fields to remove empty fields from report output. + Remove unimplemented dm_report_set_output_selection from libdevmapper.h. + +Version 1.02.92 - 24th November 2014 +==================================== + Fix memory corruption with sorting empty string lists (1.02.86). + Fix man dmsetup.8 syntax warning of Groff + Accept unquoted strings and / in place of {} when parsing configs. + +Version 1.02.91 - 11th November 2014 +==================================== + Update cache creation and dm_config_node to pass policy. + Allow activation of any thin-pool if transaction_id supplied is 0. + Don't print uninitialized stack bytes when non-root uses dm_check_version(). + Fix selection criteria to not match reserved values when using >, <, >=, <. + Add DM_LIST_HEAD_INIT macro to libdevmapper.h. + Fix dm_is_dm_major to not issue error about missing /proc lines for dm module. + +Version 1.02.90 - 1st September 2014 +==================================== + Restore proper buffer size for parsing mountinfo line (1.02.89) + +Version 1.02.89 - 26th August 2014 +================================== + Improve libdevmapper-event select() error handling. + Add extra check for matching transation_id after message submitting. + Add dm_report_field_string_list_unsorted for str. list report without sorting. + Support --deferred with dmsetup remove to defer removal of open devices. + Update dm-ioctl.h to include DM_DEFERRED_REMOVE flag. + Add support for selection to match string list subset, recognize { } operator. + Fix string list selection with '[value]' to not match list that's superset. + Fix string list selection to match whole words only, not prefixes. + +Version 1.02.88 - 5th August 2014 +================================= + Add dm_tree_set_optional_uuid_suffixes to handle upgrades. + +Version 1.02.87 - 23rd July 2014 +================================ + Fix dm_report_field_string_list to handle delimiter with multiple chars. + Add dm_report_field_reserved_value for per-field reserved value definition. + +Version 1.02.86 - 23rd June 2014 +================================ + Make "help" and "?" reporting fields implicit. + Recognize implicit "selected" field if using dm_report_init_with_selection. + Add support for implicit reporting fields which are predefined in libdm. + Add DM_REPORT_FIELD_TYPE_PERCENT: separate number and percent fields. + Add dm_percent_range_t,dm_percent_to_float,dm_make_percent to libdm for reuse. + Add dm_report_reserved_value to libdevmapper for reserved value definition. + Also display field types when listing all fields in selection help. + Recognize "help" keyword in selection string to show brief help for selection. + Always order items reported as string list field lexicographically. + Add dm_report_field_string_list to libdevmapper for direct string list report. + Add DM_REPORT_FIELD_TYPE_STRING_LIST: separate string and string list fields. + Add dm_str_list to libdevmapper for string list type definition and its reuse. + Add dmsetup -S/--select to define selection criteria for dmsetup reports. + Add dm_report_init_with_selection to intialize report with selection criteria. + Add DM_REPORT_FIELD_TYPE_SIZE: separate number and size reporting fields. + Use RemoveOnStop for dm-event.socket systemd unit. + Document env var 'DM_DEFAULT_NAME_MANGLING_MODE' in dmsetup man page. + Warn user about incorrect use of cookie with 'dmsetup remove --force'. + Also recognize 'help'/'?' as reserved sort key name to show help. + Add dm_units_to_factor for size unit parsing. + Increase bitset size for minors for thin dmeventd plugin. + +Version 1.02.85 - 10th April 2014 +================================= + Check for sprintf error when building internal device path. + Check for sprintf error when creating path for dm control node. + When buffer for dm_get_library_version() is too small, return error code. + Always reinitialize _name_mangling_mode in dm_lib_init(). + Add tracking flag about implicitly added devices into dm_tree. + Stop timeout thread immediately when the last worker thread is finished. + Fix dmeventd logging with parallel wait event processing. + Reuse _node_send_messages() for validation of transaction_id in preload. + Transaction_id could be lower by one only when messages are prepared. + Do not call callback when preload fails. + Wrap is_selinux_enabled() to be called just once. + Use correctly signed 64b constant when working with raid volumes. + Exit dmeventd with pidfile cleanup instead of raising SIGKILL on DIE request. + Add new DM_EVENT_GET_PARAMETERS request to dmeventd protocol. + Do not use systemd's reload for dmeventd restart, use dmeventd -R instead. + Drop cryptsetup rules from 10-dm.rules - cryptsetup >= 1.1.3 sets them. + +Version 1.02.84 - 20th January 2014 +=================================== + Revert activation of activated nodes if a node preload callback fails. + Avoid busy looping on CPU when dmeventd reads event DM_WAIT_RETRY. + Ensure global mutex is held when working with dmeventd thread. + Drop taking timeout mutex for un/registering dmeventd monitor. + Allow section names in config file data to be quoted strings. + Close fifos before exiting in dmeventd restart() error path. + Move printf format string directly into dm_asprintf args list. + Catch invalid use of string sort values when reporting numerical fields. + +Version 1.02.83 - 13th November 2013 +==================================== + Consistently report on stderr when device is not found for dmsetup info. + Skip race errors when non-udev dmsetup build runs on udev-enabled system. + Skip error message when holders are not present in sysfs. + Use __linux__ instead of linux define to make libdevmapper.h C compliant. + Use mutex to avoid possible race while creating/destroying memory pools. + Require libpthread to build now. + +Version 1.02.82 - 4th October 2013 +================================== + Define symbolic names for subsystem udev flags in libdevmapper for easier use. + Make subsystem udev rules responsible for importing DM_SUBSYSTEM_UDEV_FLAG*. + +Version 1.02.81 - 23rd September 2013 +===================================== + Tidy dmeventd fifo initialisation. + +Version 1.02.80 - 20th September 2013 +===================================== + Detect invalid sector supplied to 'dmsetup message'. + Free any previously-set string if a dm_task_set_* function is called again. + Do not allow passing empty new name for dmsetup rename. + Display any output returned by 'dmsetup message'. + Add dm_task_get_message_response to libdevmapper. + +Version 1.02.79 - 13th August 2013 +================================== + Create dmeventd timeout threads as "detached" so exit status is freed. + Add DM_ABORT_ON_INTERNAL_ERRORS env var support to abort on internal errors. + +Version 1.02.78 - 24th July 2013 +================================ + Process thin messages once to active thin pool target for dm_tree. + Optimize out setting the same value or read_ahead. + Add DM_ARRAY_SIZE public macro. + Move syslog code out of signal handle in dmeventd. + Add DM_TO_STRING public macro. + Always return success on dmeventd -V command call. + Fix parsing of 64bit snapshot status in dmeventd snapshot plugin. + Add dm_get_status_snapshot() for parsing snapshot status. + Detecte mounted fs also via reading /proc/self/mountinfo. + Add dm_mountinfo_read() for parsing /proc/self/mountinfo. + Report error for nonexisting devices in dmeventd communication. + Prevent double free error after dmeventd call of _fill_device_data(). + Update dmevent structure message_data to simplify/fix error path handling. + Validate passed params to dm_get_status_raid/thin/thin_pool(). + Fix 'dmsetup splitname -o' to not fail if used without '-c' switch (1.02.68). + Add dm_config_write_{node_out/one_node_out} for enhanced config output. + Add dm_config_value_is_bool to check for boolean value in supported formats. + Fix config node lookup inside empty sections to not return the section itself. + Append discards and read-only fields to exported struct dm_status_thin_pool. + Fix segfault for truncated string token in config file after the first '"'. + Close open dmeventd FIFO file descriptors on exec (FD_CLOEXEC). + Fix resource leak in error path of dmeventd's umount of thin volume. + Automatically deactivate failed preloaded dm tree node. + Add DM_DISABLE_UDEV environment variable to manage dev nodes by libdm only. + Fix dm_task_set_cookie to properly process udev flags if udev_sync disabled. + +Version 1.02.77 - 15th October 2012 +=================================== + Support unmount of thin volumes from pool above thin pool threshold. + Update man page to reflect that dm UUIDs are being mangled as well. + Apply 'dmsetup mangle' for dm UUIDs besides dm names. + Add 'mangled_uuid' and 'unmangled_uuid' fields to dmsetup info -c -o. + Mangle device UUID on dm_task_set_uuid/newuuid call if necessary. + Add dm_task_get_uuid_mangled/unmangled to libdevmapper. + Always reset delay_resume_if_new flag when stacking thin pool over anything. + Don't create value for dm_config_node and require dm_config_create_value call. + Check for existing new_name for dmsetup rename. + Fix memory leak in dmsetup _get_split_name() error path. + +Version 1.02.76 - 7th August 2012 +================================= + Add dm_vasprintf to libdevmapper. + Allow --noflush with dmsetup status and wait (for thin target). + Add dm_config_write_one_node to libdevmapper. + Support thin pool message release/reserve_metadata_snap in libdevmapper. + Support thin pool discards and external origin features in libdevmapper. + Add configure --enable-udev-rule-exec-detection to detect exec path in rules. + Use sbindir in udev rules by default and remove executable path detection. + Remove hard-coded paths for dmeventd fifos and use default-dm-run-dir. + Add configure --with-lvmetad-pidfile to remove hard-coded value. + Add configure --with-default-pid-dir for common directory with pid files. + Add configure --with-default-dm-run-dir to set run directory for dm tools. + Detect kernel_send() errors in cmirrord. + Add __attribute__ instrumentation to libdevmapper.h. + Print clean_bits instead of sync_bits in pull_state in cmirrord. + Add tests for errors from closedir(), close() in cmirrord. + Add documentation references in systemd units. + Remove veritysetup. Now maintained with cryptsetup. + +Version 1.02.75 - 8th June 2012 +=============================== + Upstream source repo now fedorahosted.org git not sources.redhat.com CVS. + Remove unsupported udev_get_dev_path libudev call used for checking udev dir. + Set delay_resume_if_new on deptree snapshot origin. + Log value chosen in _find_config_bool like other variable types do. + Wait for dmeventd to exit after sending it DM_EVENT_CMD_DIE when restarting. + Append 'Used' to {Blk}DevNames/DevNos dmsetup report headers for clarity. + Add configure --with-veritysetup for independent veritysetup tool. + Properly support supplied dmevent path in dm_event_register_handler(). + Remove dmeventd fifos on exit if they are not managed by systemd. + Use SD_ACTIVATION environment variable in systemd units to detect systemd. + Only start a new dmeventd instance on restart if one was already running. + Extend the time waited for input from dmeventd fifo to 5 secs. (1.02.73) + +Version 1.02.74 - 6th March 2012 +================================ + Check for multiply-mangled names in auto mangling mode. + Fix dm_task_get_name_unmangled to not unmangle already unmangled name. + Check whether device names are properly mangled on ioctl return. + Deactivation of failed thin check on thin pool returns success. + +Version 1.02.73 - 3rd March 2012 +================================ + Test _thread_registry list with holding mutex in dmeventd. + Add dm_tree_node_set_callback() for preload and deactivation hooks. + Drop unsupported TRIM message for thin pool. + Improve logging for fifo startup in dmeventd. + Better detection of missing dmeventd fifo connection (1.02.71). + Add a few pointer validations in dmsetup. + Support dm_task_get_driver_version() query without version string. + Log failure of pthread_join when cleaning unused threads in dmeventd. + Fix empty string warning logic in _find_config_str. (1.02.68) + Fix dm_task_set_name to properly resolve path to dm name (1.02.71). + Add dm_strncpy() function as a faster strncpy() replacement. + +Version 1.02.72 - 23rd February 2012 +==================================== + Avoid memory reallocation for dm_asprintf. + +Version 1.02.71 - 20th February 2012 +==================================== + Switch to using built-in blkid in 13-dm-disk.rules. + Add "watch" rule to 13-dm-disk.rules. + Detect failing fifo and skip 20s retry communication period. + Add DM_DEFAULT_NAME_MANGLING_MODE environment variable as an override. + Add dm_lib_init to automatically initialise device-mapper library on load. + Replace any '\' char with '\\' in dm table specification on input. + Add mangle command to dmsetup to provide renaming to correct mangled form. + Add 'mangled_name' and 'unmangled_name' fields to dmsetup info -c -o. + Add --manglename option to dmsetup to select the name mangling mode. + Add dm_task_get_name_mangled/unmangled to libdevmapper. + Mangle device name on dm_task_set_name/newname call if necessary. + Add dm_set/get_name_mangling_mode to set/get name mangling in libdevmapper. + Add configure --with-default-name-mangling for udev-friendly dev name charset. + Test for parsed words in _umount() dmeventd snapshot plugin. + Fix memory leak in fail path of parse_loop_device_name() in dmsetup. + Check for missing reply_uuid in dm_event_get_registered_device(). + Check for allocation failure in dmeventd restart(). + Add few missing allocation failures tests in dmsetup. + Fix potential risk of writing in front of buffer in _sysfs_get_dm_name(). + +Version 1.02.70 - 12th February 2012 +==================================== + Fix dm_event_get_version() check. + Add pointer test for dependency check in _add_dev(). + Validate name and uuid params of dm_tree_add_new_dev_with_udev_flags(). + Do not crash for dm_report_init() sort_key == NULL and behave like "". + Return error for failing allocation in dm_asprintf(). + Add missing test for failing allocation in dm_realloc() code. + Add test for memory allocation failures in regex matcher code. + Simplify dm_task_set_geometry() and use dm_asprintf(). + Set all parameters to 0 for dm_get_next_target() for NULL return. + Fix fd resource leak in error path for _udev_notify_sem_create(). + Leave space for '\0' for readline() call in _sysfs_get_kernel_name(). + +Version 1.02.69 - 1st February 2012 +=================================== + Clean up dmeventd systemd unit ordering and requirements. + +Version 1.02.68 - 26th January 2012 +=================================== + Reset all members of info struct in dm_tree_add_new_dev_with_udev_flags. + Add dmsetup wipe_table to replace table with one that uses error target. + Add 'blkdevname' and 'blkdevs_used' fields to dmsetup info -c -o. + Add 'blkdevname' option to dmsetup ls --tree to see block device names. + Add -o devno/blkdevname/devname to dmsetup deps and ls. + Add dm_device_get_name to get map name or block device name for given devno. + Remove empty devices when clearing left-over inactive tables in deptree. + Add dm_uuid_prefix/dm_set_uuid_prefix to override hard-coded LVM- prefix. + Improve dmsetup man page description of readahead parameter. + Use sysfs to set/get readahead if possible. + Fix lvm2-monitor init script to use normalized output when using vgs. + Add test for max length (DM_MAX_TYPE_NAME) of target type name. + Include a copy of kernel DM documentation in doc/kernel. + Improve man page style for dmsetup and mention more targets. + Fix _get_proc_number to be tolerant of malformed /proc/misc entries. + Fix missing thread list manipulation protection in dmeventd. + Add ExecReload to dm-event.service for systemd to reload dmeventd properly. + Add dm_config_tree_find_str_allow_empty and dm_config_find_str_allow_empty. + Fix compile-time pool memory locking with DEBUG_MEM. + Fix valgrind error reports in free of pool chunks with DEBUG_MEM. + Align size of structure chunk for fast pool allocator to 8 bytes. + Simplify some pointer operations in dm_free_aux() debug code. + Remove unused dbg_malloc.h file from source tree. + Cleanup backtraces for _create_and_load_v4(). + Fix alignment warning in bitcount calculation for raid segment. + Allocate dm_tree structure from dm_tree pool. + Update debug logging for _resume_node. + Add functions to support thin provisioning target. + Improve libdm-config error path reporting. + Update dmsetup resume man with --addnodeonresume/create options. + Add dependency for dm man pages to man subdirectory make all target. + Add dm_tree_retry_remove to use retry logic for device removal in a dm_tree. + Add dm_device_has_mounted_fs fn to check mounted filesystem on a device. + Add dm_device_has_holders fn to to check use of the device by another device. + Add dm_sysfs_dir to libdevmapper to retrieve sysfs location set. + Add dm_set_sysfs_dir to libdevmapper to set sysfs location. + Add --retry option for dmsetup remove to retry removal if not successful. + Add dm_task_retry_remove fn to use retry logic for device removal. + Remove unused passed parameters for _mirror_emit_segment_line(). + Add dm_config and string character escaping functions to libdevmapper. + Mark unreleased memory pools as internal error. + +Version 1.02.67 - 19th August 2011 +================================== + Add dm_tree_node_add_null_area for temporarily-missing raid devs tracked. + +Version 1.02.66 - 12th August 2011 +================================== + Release geometry buffer in dm_task_destroy. + Update udev rules to skip DM flags decoding for removed devices. + Add compile-time pool memory locking options (to debug shared VG structs). + Remove device name prefix from dmsetup line output if -j & -m or -u supplied. + Remove support for the original version 1 dm ioctls. + Add missing check for allocation failure _create_dir_recursive(). + Add support for systemd file descriptor handover in dmeventd. + Fix memory leak in dmsetup _message() memory allocation error path. + Use new oom killer adjustment interface (oom_score_adj) when available. + Add systemd unit files for dmeventd. + Fix read-only identical table reload supression. + +Version 1.02.65 - 8th July 2011 +=============================== + Remove dev name prefix from dmsetup line output if exactly one dev requested. + Report internal error if suspending a device using an already-suspended dev. + Report error if a table load requiring target parameters has none supplied. + Add dmsetup --checks and dm_task_enable_checks framework to validate ioctls. + Add age_in_minutes parameter to dmsetup udevcomplete_all. + Return immediately from dm_lib_exit() if called more than once. + Disable udev fallback by default and add --verifyudev option to dmsetup. + Report internal error if any table is loaded while any dev is known suspended. + Add dm_get_suspended_counter() for number of devs in suspended state by lib. + Fix "all" report field prefix matching to include label fields with pv_all. + Delay resuming new preloaded mirror devices with core logs in deptree code. + Accept new kernel version 3 uname formats in initialisation. + +Version 1.02.64 - 29th April 2011 +================================== + Require libudev >= 143 when compiling with udev support. + Use word alignment for dm_pool_strdup() and dm_pool_strndup(). + Use dm_snprintf() to fix signedness warning in dm_set_dev_dir(). + Use unsigned loop counter to fix signedness warning in _other_node_ops(). + Fix const cast in dmsetup calls of dm_report_field_string(). + Streamline /dev/mapper/control node code for common cases. + Use hard-coded dm control node device number for 2.6.36 kernels and above. + Improve stack debug reporting in dm_task_create(). + Fallback to control node creation only if node doesn't exist yet. + Change dm_hash binary functions to take void *key instead of char *. + Fix uninitialised memory use with empty params in _reload_with_suppression_v4. + Lower severity of selabel_lookup and matchpathcon failure to log_debug. + Add test for failed allocation from dm_task_set_uuid() in dmeventd. + Add dm_event_get_version to dmeventd for use with -R. + Avoid dmeventd core dumps when handling request with unknown command ID. + Have dmeventd -R start up even when no existing copy is running. + Accept multiple mapped device names on many dmsetup command lines. + Fix dm_udev_wait calls in dmsetup to occur before readahead display not after. + Include an implicit dm_task_update_nodes() within dm_udev_wait(). + Fix _create_and_load_v4 not to lose the --addnodeoncreate setting (1.02.62). + Add inactive table query support for kernel driver >= 4.11.6 (RHEL 5.7). + Log debug open_count in _node_has_closed_parents(). + Add a const to dm_report_field_string() data parameter. + +Version 1.02.63 - 9th February 2011 +=================================== + Reinstate DEBUG_MEM as it's part of the API. (1.02.62) + +Version 1.02.62 - 4th February 2011 +=================================== + Add configure --with-device-nodes-on=create for previous behaviour. + Move creation of device nodes from 'create' to 'resume'. + Add --addnodeonresume and --addnodeoncreate options to dmsetup. + Add dm_task_set_add_node to libdevmapper to control dev node creation time. + Add dm_task_secure_data to libdevmapper to wipe ioctl buffers in kernel. + Log debug message when expected uevent is not generated. + Only compile memory debugging code when DEBUG_MEM is set. + Set DM_UDEV_DISABLE_OTHER_RULES_FLAG for suspended DM devices in udev rules. + Begin a new pool object for each row in _output_as_rows() correctly. + +Version 1.02.61 - 10th January 2011 +=================================== + Add DM_COOKIE_AUTO_CREATE to libdevmapper.h. + Export DM_CONTROL_NODE_UMASK and use it while creating /dev/mapper/control. + +Version 1.02.60 - 20th December 2010 +==================================== + Check for unlink failure in remove_lockfile() in dmeventd. + Use dm_free for dm_malloc-ed areas in _clog_ctr/_clog_dtr in cmirrord. + Use char* arithmetic in _process_all() & _targets() in dmsetup. + Change dm_regex_create() API to accept const char * const *patterns. + Add new dm_prepare_selinux_context fn to libdevmapper and use it throughout. + Detect existence of new SELinux selabel interface during configure. + +Version 1.02.59 - 6th December 2010 +=================================== + Add backtraces to _process_mapper_dir and _create_and_load_v4 error paths. + Remove superfluous checks for NULL before calling dm_free. + +Version 1.02.58 - 22nd November 2010 +==================================== + Fix _output_field crash from field_id free with DEBUG_MEM. (1.02.57) + +Version 1.02.57 - 8th November 2010 +=================================== + Fix regex optimiser not to ignore RHS of OR nodes in _find_leftmost_common. + Add dmeventd -R to restart dmeventd without losing monitoring state. (1.02.56) + Fix memory leak of field_id in _output_field function. + Allocate buffer for reporting functions dynamically to support long outputs. + +Version 1.02.56 - 25th October 2010 +=================================== + Return const pointer from dm_basename() in libdevmapper. + Implement dmeventd -R to restart without state loss. + Add dm_zalloc and use it and dm_pool_zalloc throughout. + Add --setuuid to dmsetup rename. + Add dm_task_set_newuuid to set uuid of mapped device post-creation. + +Version 1.02.55 - 24th September 2010 +===================================== + Fix the way regions are marked complete to avoid slow --nosync cmirror I/O. + Add DM_REPORT_FIELD_TYPE_ID_LEN to libdevmapper.h. + +Version 1.02.54 - 18th August 2010 +================================== + Fix dm-mod autoloading logic to not assume control node is set correctly. + Add dmeventd/executable to lvm.conf to test alternative dmeventd. + Export dm_event_handler_set_dmeventd_path to override built-in dmeventd path. + Generate libdevmapper-event exported symbols. + Remove superfluous NULL pointer tests before dm_free from dmeventd. + Assume dm-mod autoloading support is in kernel 2.6.36 and higher, not 2.6.35. + Fix udev rules to support udev database content generated by older rules. + Reinstate detection of inappropriate uevent with DISK_RO set and suppress it. + Fix regex ttree off-by-one error. + Add --enable-valgrind-pool to configure. + Fix segfault in regex matcher with characters of ordinal value > 127. + Fix 'void*' arithmetic warnings in dbg_malloc.c and libdm-iface.c. + Wait for node creation before displaying debug info in dmsetup. + Fix return status 0 for "dmsetup info -c -o help". + Add check for kernel semaphore support and disable udev_sync if not available. + +Version 1.02.53 - 28th July 2010 +================================ + Revert failed table load preparation after "create, load and resume". + Switch dmeventd to use dm_create_lockfile and drop duplicate code. + Add dm_create_lockfile to libdm to handle pidfiles for all daemons. + Replace lookup with next in struct dfa_state & calculate states on demand. + Improve the regex matcher, reducing the number of charset nodes used. + Add dm_regex_fingerprint to facilitate regex testing. + Skip ffs(0) in _test_word in bitset functions. + Use "nowatch" udev rule for inappropriate devices. + +Version 1.02.52 - 6th July 2010 +=============================== + Fix dmlosetup snprintf %llu compiler warning. + Add parentheses to some libdevmapper.h macro arguments. + Add printf format attributes to dm_{sn,as}printf and fix a caller. + Move dmeventd man page from install_lvm2 to install_device-mapper. (1.02.50) + +Version 1.02.51 - 30th June 2010 +================================ + Generate libdevmapper exported symbols from header file. + +Version 1.02.50 - 23rd June 2010 +================================ + Fix INTERNAL_ERROR typo in ioctl iface unknown task message. + Fix udev rules to handle spurious events properly. + Use C99 [] not [0] in dm_ulog_request struct to avoid abort when fortified. + Allow use of devmapper header file in C++ mode (extern "C" and __typeof__). + Add dmeventd man page. + +Version 1.02.49 - 4th June 2010 +=============================== + Support autoloading of dm-mod module for kernels from 2.6.35. + Document 'clear' in dmsetup man page. + Fix semctl parameter (union) to avoid misaligned parameter on some arches. + Add dm_tree_node_set_presuspend_node() to presuspend child when deactivating. + Initial support for replicator target. + +Version 1.02.48 - 17th May 2010 +================================ + Use -d to control level of messages sent to syslog by dmeventd. + Change -d to -f to run dmeventd in foreground. + Do not print encryption key in message debug output (cryptsetup luksResume). + Fix dmeventd static build library dependencies. + Fix udev flags on remove in create_and_load error path. + +Version 1.02.47 - 30th April 2010 +================================= + Add support for new IMPORT{db} udev rule. + Add DM_UDEV_PRIMARY_SOURCE_FLAG udev flag to recognize proper DM events. + Also include udev libs in libdevmapper.pc when udev_sync is enabled. + Cache bitset locations to speed up _calc_states. + Add a regex optimisation pass for shared prefixes and suffixes. + Add dm_bit_and and dm_bitset_equal to libdevmapper. + Simplify dm_bitset_create. + Speed up dm_bit_get_next with ffs(). + +Version 1.02.46 - 14th April 2010 +================================= + Change dm_tree_deactivate_children to fail if device is open. + Wipe memory buffers for dm-ioctl parameters before releasing. + Strictly require libudev if udev_sync is used. + Add support for ioctl's DM_UEVENT_GENERATED_FLAG. + +Version 1.02.45 - 9th March 2010 +================================ + Add --showkeys parameter description to dmsetup man page. + Add --help option as synonym for help command. + +Version 1.02.44 - 15th February 2010 +==================================== + Add DM_UDEV_DISABLE_LIBRARY_FALLBACK udev flag to rely on udev only. + Export dm_udev_create_cookie function to create new cookies on demand. + Add --udevcookie, udevcreatecookie and udevreleasecookie to dmsetup. + Set udev state automatically instead of using DM_UDEV_DISABLE_CHECKING. + +Version 1.02.43 - 21st January 2010 +=================================== + Remove bitset, hash and pool headers superceded by libdevmapper.h. + Fix off-by-one error causing bad cluster mirror table construction. + +Version 1.02.42 - 14th January 2010 +=================================== + Add support for the "snapshot-merge" kernel target (2.6.33-rc1). + Introduce a third activation_priority level in dm_tree_activate_children. + +Version 1.02.41 - 12th January 2010 +=================================== + If DM_UDEV_DISABLE_CHECKING is set in environment, disable udev warnings. + Add dm_tree_add_dev_with_udev_flags to provide wider support for udev flags. + Add --noudevrules option for dmsetup to disable /dev node management by udev. + Fix 'dmsetup info -c -o all' to show all fields. + Return errors if dm_tree_*_children functions fail. + Fix coredump and memory leak for 'dmsetup help -c'. + Disable udev rules for change events with DISK_RO set. + +Version 1.02.40 - 19th November 2009 +==================================== + Fix install_device-mapper Makefile target to not build dmeventd plugins. + Support udev flags even when udev_sync is disabled or not compiled in. + Remove 'last_rule' from udev rules: honour DM_UDEV_DISABLE_OTHER_RULES_FLAG. + Add dmsetup --inactive support. + Add dm_task_query_inactive_table to libdevmapper for kernel driver >= 4.16. + Fix hash lookup segfault when keys compared are different lengths. + +Version 1.02.39 - 26th October 2009 +=================================== + Remove strict default permissions for DM devices from 95-dm-notify.rules. + Add dmsetup udevflags command to decode udev flags in given cookie value. + Support udev flags in libdevmapper incl. dm_tree_add_new_dev_with_udev_flags. + Make libdm ABI consistent when built with/without selinux support. + +Version 1.02.38 - 25th September 2009 +===================================== + Export DM_DEV_DIR_UMASK, the default umask for /dev directories created. + Handle any path supplied to dm_task_set_name by looking up in /dev/mapper. + Add several examples to 12-dm-permissions.rules. + Add splitname and --yes to dmsetup man page. + Fix _mirror_emit_segment_line return code. + Fix dmeventd _temporary_log_fn parameters. (2.02.50) + +Version 1.02.37 - 15th September 2009 +===================================== + Add dmsetup manpage entries for udevcomplete_all and udevcookies. + Check udev is running when processing cookies and retain state internally. + Add y|--yes option to dmsetup for default 'yes' answer to prompts. + Fix tools Makefile to process dmsetup sources separately. + Restore umask when device node creation fails. + Check kernel vsn to use 'block_on_error' or 'handle_errors' in mirror table. + Add dm-log-userspace.h to tree for cmirrord builds. + +Version 1.02.36 - 6th August 2009 +================================= + Add udevcookies, udevcomplete, udevcomplete_all and --noudevwait to dmsetup. + Add libdevmapper functions to support synchronisation with udev. + +Version 1.02.35 - 28th July 2009 +================================ + Add LOG_LINE_WITH_ERRNO macro. + Use log_error macro consistently throughout in place of log_err. + +Version 1.02.34 - 15th July 2009 +================================ + Use _exit() not exit() after forking to avoid flushing libc buffers twice. + Rename plog macro to LOG_LINE & add LOG_MESG variant for dm_dump_memory_debug. + Change plog to use dm_log_with_errno unless deprecated dm_log_init was used. + Add dm_log_with_errno and dm_log_with_errno_init, deprecating the old fns. + Fix whitespace in linear target line to fix identical table line detection. + Add device number to more log messages during activation. + +Version 1.02.33 - 30th June 2009 +================================ + Don't fallback to default major number: use dm_task_set_major_minor. (1.02.31) + Do not fork daemon when dmeventd cannot be found. + Add crypt target handling to libdevmapper tree nodes. + Add splitname command to dmsetup. + Add subsystem, vg_name, lv_name, lv_layer fields to dmsetup reports. + Make mempool optional in dm_split_lvm_name(). + +Version 1.02.32 - 21st May 2009 +=============================== + Only generate libdevmapper.a when configured to link statically. + Export dm_tree_node_size_changed() from libdevmapper. + Propagate the table size_changed property up the dm device tree. + Detect failure to free memory pools when releasing the library. + Fix segfault when getopt processes dmsetup -U, -G and -M options. + +Version 1.02.31 - 3rd March 2009 +================================ + If kernel supports only one dm major number, use in place of any supplied. + +Version 1.02.30 - 26th January 2009 +==================================== + Add "all" field to reports expanding to all fields of report type. + Enforce device name length and character limitations in libdm. + Replace _dm_snprintf with EMIT_PARAMS macro for creating target lines. + +Version 1.02.29 - 10th November 2008 +==================================== + Merge device-mapper into the LVM2 tree. + Split out dm-logging.h from log.h. + Use lvm-types.h. + Add usrsbindir to configure. + +Version 1.02.28 - 18th September 2008 +===================================== + Only resume devices in dm_tree_preload_children if size changes. + Extend deptree buffers so the largest possible device numbers fit. + Generate versioned libdevmapper-event.so. + Underline longer report help text headings. + +Version 1.02.27 - 25th June 2008 +================================ + Align struct memblock in dbg_malloc for sparc. + Add --unquoted and --rows to dmsetup. + Avoid compiler warning about cast in dmsetup.c's OFFSET_OF macro. + Fix inverted no_flush debug message. + Remove --enable-jobs from configure. (Set at runtime instead.) + Bring configure.in and list.h into line with the lvm2 versions. + +Version 1.02.26 - 6th June 2008 +=============================== + Initialise params buffer to empty string in _emit_segment. + Skip add_dev_node when ioctls disabled. + Make dm_hash_iter safe against deletion. + Accept a NULL pointer to dm_free silently. + Add tables_loaded, readonly and suspended columns to reports. + Add --nameprefixes to dmsetup. + Add field name prefix option to reporting functions. + Calculate string size within dm_pool_grow_object. + +Version 1.02.25 - 10th April 2008 +================================= + Remove redundant if-before-free tests. + Use log_warn for reporting field help text instead of log_print. + Change cluster mirror log type name (s/clustered_/clustered-/) + +Version 1.02.24 - 20th December 2007 +==================================== + Fix deptree to pass new name to _resume_node after a rename. + Suppress other node operations if node is deleted. + Add node operation stack debug messages. + Report error when empty device name passed to readahead functions. + Fix minimum readahead debug message. + +Version 1.02.23 - 5th December 2007 +=================================== + Update dm-ioctl.h after removal of compat code. + Add readahead support to libdevmapper and dmsetup. + Fix double free in a libdevmapper-event error path. + Fix configure --with-dmeventd-path substitution. + Allow a DM_DEV_DIR environment variable to override /dev in dmsetup. + Create a libdevmapper.so.$LIB_VERSION symlink within the build tree. + Avoid static link failure with some SELinux libraries that require libpthread. + Remove obsolete dmfs code from tree and update INSTALL. + +Version 1.02.22 - 21st August 2007 +================================== + Fix inconsistent licence notices: executables are GPLv2; libraries LGPLv2.1. + Update to use autoconf 2.61, while still supporting 2.57. + Avoid repeated dm_task free on some dm_event_get_registered_device errors. + Introduce log_sys_* macros from LVM2. + Export dm_fclose and dm_create_dir; remove libdm-file.h. + Don't log EROFS mkdir failures in _create_dir_recursive (for LVM2). + Add fclose wrapper dm_fclose that catches write failures (using ferror). + +Version 1.02.21 - 13th July 2007 +================================ + Introduce _LOG_STDERR to send log_warn() messages to stderr not stdout. + Fix dmsetup -o devno string termination. (1.02.20) + +Version 1.02.20 - 15th June 2007 +================================ + Fix default dmsetup report buffering and add --unbuffered. + Add tree-based and dependency fields to dmsetup reports. + +Version 1.02.19 - 27th April 2007 +================================= + Standardise protective include file #defines. + Add regex functions to library. + Avoid trailing separator in reports when there are hidden sort fields. + Fix segfault in 'dmsetup status' without --showkeys against crypt target. + Deal with some more compiler warnings. + Introduce _add_field() and _is_same_field() to libdm-report.c. + Fix some libdevmapper-event and dmeventd memory leaks. + Remove unnecessary memset() return value checks. + Fix a few leaks in reporting error paths. [1.02.15+] + +Version 1.02.18 - 13th February 2007 +==================================== + Improve dmeventd messaging protocol: drain pipe and tag messages. + +Version 1.02.17 - 29th January 2007 +=================================== + Add recent reporting options to dmsetup man page. + Revise some report fields names. + Add dmsetup 'help' command and update usage text. + Use fixed-size fields in report interface and reorder. + +Version 1.02.16 - 25th January 2007 +=================================== + Add some missing close() and fclose() return value checks. + Migrate dmsetup column-based output over to new libdevmapper report framework. + Add descriptions to reporting field definitions. + Add a dso-private variable to dmeventd dso interface. + Add dm_event_handler_[gs]et_timeout functions. + Streamline dm_report_field_* interface. + Add cmdline debug & version options to dmeventd. + Add DM_LIB_VERSION definition to configure.h. + Suppress 'Unrecognised field' error if report field is 'help'. + Add --separator and --sort to dmsetup (unused). + Make alignment flag optional when specifying report fields. + +Version 1.02.15 - 17th January 2007 +=================================== + Add basic reporting functions to libdevmapper. + Fix a malloc error path in dmsetup message. + More libdevmapper-event interface changes and fixes. + Rename dm_saprintf() to dm_asprintf(). + Report error if NULL pointer is supplied to dm_strdup_aux(). + Reinstate dm_event_get_registered_device. + +Version 1.02.14 - 11th January 2007 +=================================== + Add dm_saprintf(). + Use CFLAGS when linking so mixed sparc builds can supply -m64. + Add dm_tree_use_no_flush_suspend(). + Lots of dmevent changes including revised interface. + Export dm_basename(). + Cope with a trailing space when comparing tables prior to possible reload. + Fix dmeventd to cope if monitored device disappears. + +Version 1.02.13 - 28 Nov 2006 +============================= + Update dmsetup man page (setgeometry & message). + Fix dmsetup free after getline with debug. + Suppress encryption key in 'dmsetup table' output unless --showkeys supplied. + +Version 1.02.12 - 13 Oct 2006 +============================= + Avoid deptree attempting to suspend a device that's already suspended. + +Version 1.02.11 - 12 Oct 2006 +============================== + Add suspend noflush support. + Add basic dmsetup loop support. + Switch dmsetup to use dm_malloc and dm_free. + +Version 1.02.10 - 19 Sep 2006 +============================= + Add dm_snprintf(), dm_split_words() and dm_split_lvm_name() to libdevmapper. + Reorder mm bounds_check code to reduce window for a dmeventd race. + +Version 1.02.09 - 15 Aug 2006 +============================= + Add --table argument to dmsetup for a one-line table. + Abort if errors are found during cmdline option processing. + Add lockfs indicator to debug output. + +Version 1.02.08 - 17 July 2006 +============================== + Append full patch to check in emails. + Avoid duplicate dmeventd subdir with 'make distclean'. + Update dmsetup man page. + Add --force to dmsetup remove* to load error target. + dmsetup remove_all also performs mknodes. + Don't suppress identical table reloads if permission changes. + Fix corelog segment line. + Suppress some compiler warnings. + +Version 1.02.07 - 11 May 2006 +============================= + Add DM_CORELOG flag to dm_tree_node_add_mirror_target(). + Avoid a dmeventd compiler warning. + +Version 1.02.06 - 10 May 2006 +============================= + Move DEFS into configure.h. + Fix leaks in error paths found by coverity. + Remove dmsetup line buffer limitation. + +Version 1.02.05 - 19 Apr 2006 +============================= + Separate install_include target in makefiles. + Separate out DEFS from CFLAGS. + Support pkg-config. + Check for libsepol. + +Version 1.02.04 - 14 Apr 2006 +============================= + Bring dmsetup man page up-to-date. + Use name-based device refs if kernel doesn't support device number refs. + Fix memory leak (struct dm_ioctl) when struct dm_task is reused. + If _create_and_load_v4 fails part way through, revert the creation. + dmeventd thread/fifo fixes. + Add file & line to dm_strdup_aux(). + Add setgeometry. + +Version 1.02.03 - 7 Feb 2006 +============================ + Add exported functions to set uid, gid and mode. + Rename _log to dm_log and export. + Add dm_tree_skip_lockfs. + Fix dm_strdup debug definition. + Fix hash function to avoid using a negative array offset. + Don't inline _find in hash.c and tidy signed/unsigned etc. + Fix libdevmapper.h #endif. + Fix dmsetup version driver version. + Add sync, nosync and block_on_error mirror log parameters. + Add hweight32. + Fix dmeventd build. + +Version 1.02.02 - 2 Dec 2005 +============================ + dmeventd added. + Export dm_task_update_nodes. + Use names instead of numbers in messages when ioctls fail. + +Version 1.02.01 - 23 Nov 2005 +============================= + Resume snapshot-origins last. + Drop leading zeros from dm_format_dev. + Suppress attempt to reload identical table. + Additional LVM- prefix matching for transitional period. + +Version 1.02.00 - 10 Nov 2005 +============================= + Added activation functions to library. + Added return macros. + Also suppress error if device doesn't exist with DM_DEVICE_STATUS. + Export dm_set_selinux_context(). + Add dm_driver_version(). + Added dependency tree functions to library. + Added hash, bitset, pool, dbg_malloc to library. + Added ls --tree to dmsetup. + Added dmsetup --nolockfs support for suspend/reload. + +Version 1.01.05 - 26 Sep 2005 +============================= + Resync list.h with LVM2. + Remember increased buffer size and use for subsequent calls. + On 'buffer full' condition, double buffer size and repeat ioctl. + Fix termination of getopt_long() option array. + Report 'buffer full' condition with v4 ioctl as well as with v1. + +Version 1.01.04 - 2 Aug 2005 +============================ + Fix dmsetup ls -j and status --target with empty table. + +Version 1.01.03 - 13 Jun 2005 +============================= + Use matchpathcon mode parameter. + Fix configure script to re-enable selinux. + +Version 1.01.02 - 17 May 2005 +============================= + Call dm_lib_exit() and dm_lib_release() automatically now. + Add --target <target_type> filter to dmsetup table/status/ls. + Add --exec <command> to dmsetup ls. + Fix dmsetup getopt_long usage. + +Version 1.01.01 - 29 Mar 2005 +============================= + Update dmsetup man page. + Drop-in devmap_name replacement. + Add option to compile without ioctl for testing. + Fix DM_LIB_VERSION sed. + +Version 1.01.00 - 17 Jan 2005 +============================= + Add dm_task_no_open_count() to skip getting open_count. + +Version 1.00.21 - 7 Jan 2005 +============================ + Fix /proc/devices parsing. + +Version 1.00.20 - 6 Jan 2005 +============================ + Attempt to fix /dev/mapper/control transparently if it's wrong. + Configuration-time option for setting uid/gid/mode for /dev/mapper nodes. + Update kernel patches for 2.4.27/2.4.28-pre-4 (includes minor fixes). + Add --noheadings columns option for colon-separated dmsetup output. + Support device referencing by uuid or major/minor. + Warn if kernel data didn't fit in buffer. + Fix a printf. + +Version 1.00.19 - 3 July 2004 +============================= + More autoconf fixes. + Fix a dmsetup newline. + Fix device number handling for 2.6 kernels. + +Version 1.00.18 - 20 Jun 2004 +============================= + Fix a uuid free in libdm-iface. + Fix a targets string size calc in driver. + Add -c to dmsetup for column-based output. + Add target message-passing ioctl. + +Version 1.00.17 - 17 Apr 2004 +============================= + configure --with-owner= --with-group= to avoid -o and -g args to 'install' + Fix library selinux linking. + +Version 1.00.16 - 16 Apr 2004 +============================= + Ignore error setting selinux file context if fs doesn't support it. + +Version 1.00.15 - 7 Apr 2004 +============================ + Fix status overflow check in kernel patches. + +Version 1.00.14 - 6 Apr 2004 +============================ + Fix static selinux build. + +Version 1.00.13 - 6 Apr 2004 +============================ + Add some basic selinux support. + +Version 1.00.12 - 6 Apr 2004 +============================ + Fix dmsetup.static install. + +Version 1.00.11 - 5 Apr 2004 +============================ + configure --enable-static_link does static build in addition to dynamic. + Moved Makefile library targets definition into template. + +Version 1.00.10 - 2 Apr 2004 +============================ + Fix DESTDIR handling. + Static build installs to dmsetup.static. + Basic support for internationalisation. + Minor Makefile tidy-ups/fixes. + +Version 1.00.09 - 31 Mar 2004 +============================= + Update copyright notices to Red Hat. + Move full mknodes functionality from dmsetup into libdevmapper. + Avoid sscanf %as for uClibc compatibility. + Cope if DM_LIST_VERSIONS is not defined. + Add DM_LIST_VERSIONS functionality to kernel patches. + Generate new kernel patches for 2.4.26-rc1. + +Version 1.00.08 - 27 Feb 2004 +============================= + Added 'dmsetup targets'. + Added event_nr support to 'dmsetup wait'. + Updated dmsetup man page. + Allow logging function to be reset to use internal one. + Bring log macros in line with LVM2 ones. + Added 'make install_static_lib' which installs libdevmapper.a. + Made configure/makefiles closer to LVM2 versions. + Fixed DESTDIR for make install/install_static_lib. + Updated README/INSTALL to reflect move to sources.redhat.com. + Updated autoconf files to 2003-06-17.
diff --git a/acinclude.m4 b/acinclude.m4 new file mode 100644 index 0000000..b6c9b18 --- /dev/null +++ b/acinclude.m4
@@ -0,0 +1,63 @@ +dnl AC_GCC_VERSION +dnl check for compiler version +dnl sets COMPILER_VERSION and GCC_VERSION + +AC_DEFUN([AC_CC_VERSION], +[ + AC_MSG_CHECKING([C compiler version]) + COMPILER_VERSION=`$CC -v 2>&1 | grep version` + case "$COMPILER_VERSION" in + *gcc*) + dnl Ok, how to turn $3 into the real $3 + GCC_VERSION=`echo $COMPILER_VERSION | \ + sed -e 's/[[^ ]]*\ [[^ ]]*\ \([[^ ]]*\)\ .*/\1/'` ;; + *) GCC_VERSION=unknown ;; + esac + AC_MSG_RESULT($GCC_VERSION) +]) + +dnl AC_TRY_CCFLAG([CCFLAG], [VAR], [ACTION-IF-WORKS], [ACTION-IF-FAILS]) +dnl check if $CC supports a given flag + +AC_DEFUN([AC_TRY_CCFLAG], +[ + AC_REQUIRE([AC_PROG_CC]) + ac_save_CFLAGS=$CFLAGS + CFLAGS=$1 + AC_CACHE_CHECK([whether $CC accepts $1 flag], [ac_cv_flag_$2], + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM()], + [AS_VAR_SET([ac_cv_flag_$2], [yes])], + [AS_VAR_SET([ac_cv_flag_$2], [no])])]) + CFLAGS=$ac_save_CFLAGS + $2=AS_VAR_GET([ac_cv_flag_$2]) + if test "$2" = yes; then + ifelse([$3], [], [:], [$3]) + else + ifelse([$4], [], [:], [$4]) + fi +]) + +dnl AC_IF_YES([TEST-FOR-YES], [ACTION-IF-TRUE], [ACTION-IF-FALSE]) +dnl AS_IF() abstraction, checks shell variable for 'yes' +AC_DEFUN([AC_IF_YES], [AS_IF([test $$1 = yes], [$2], [$3])]) + +dnl AC_TRY_LDFLAGS([LDFLAGS], [VAR], [ACTION-IF-WORKS], [ACTION-IF-FAILS]) +dnl check if $CC supports given ld flags + +AC_DEFUN([AC_TRY_LDFLAGS], +[ + AC_REQUIRE([AC_PROG_CC]) + ac_save_LDFLAGS=$LDFLAGS + LDFLAGS=$1 + AC_CACHE_CHECK([whether $CC accepts $1 ld flags], [ac_cv_flag_$2], + [AC_LINK_IFELSE([AC_LANG_PROGRAM()], + [AS_VAR_SET([ac_cv_flag_$2], [yes])], + [AS_VAR_SET([ac_cv_flag_$2], [no])])]) + LDFLAGS=$ac_save_LDFLAGS + $2=AS_VAR_GET([ac_cv_flag_$2]) + if test "$2" = yes; then + ifelse([$3], [], [:], [$3]) + else + ifelse([$4], [], [:], [$4]) + fi +])
diff --git a/aclocal.m4 b/aclocal.m4 new file mode 100644 index 0000000..35107ac --- /dev/null +++ b/aclocal.m4
@@ -0,0 +1,539 @@ +# generated automatically by aclocal 1.15 -*- Autoconf -*- + +# Copyright (C) 1996-2014 Free Software Foundation, Inc. + +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) +# =========================================================================== +# http://www.gnu.org/software/autoconf-archive/ax_python_module.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_PYTHON_MODULE(modname[, fatal, python]) +# +# DESCRIPTION +# +# Checks for Python module. +# +# If fatal is non-empty then absence of a module will trigger an error. +# The third parameter can either be "python" for Python 2 or "python3" for +# Python 3; defaults to Python 3. +# +# LICENSE +# +# Copyright (c) 2008 Andrew Collier +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 8 + +AU_ALIAS([AC_PYTHON_MODULE], [AX_PYTHON_MODULE]) +AC_DEFUN([AX_PYTHON_MODULE],[ + if test -z $PYTHON; + then + if test -z "$3"; + then + PYTHON="python3" + else + PYTHON="$3" + fi + fi + PYTHON_NAME=`basename $PYTHON` + AC_MSG_CHECKING($PYTHON_NAME module: $1) + $PYTHON -c "import $1" 2>/dev/null + if test $? -eq 0; + then + AC_MSG_RESULT(yes) + eval AS_TR_CPP(HAVE_PYMOD_$1)=yes + else + AC_MSG_RESULT(no) + eval AS_TR_CPP(HAVE_PYMOD_$1)=no + # + if test -n "$2" + then + AC_MSG_ERROR(failed to find required module $1) + exit 1 + fi + fi +]) + +# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- +# serial 1 (pkg-config-0.24) +# +# Copyright © 2004 Scott James Remnant <scott@netsplit.com>. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# PKG_PROG_PKG_CONFIG([MIN-VERSION]) +# ---------------------------------- +AC_DEFUN([PKG_PROG_PKG_CONFIG], +[m4_pattern_forbid([^_?PKG_[A-Z_]+$]) +m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$]) +m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$]) +AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility]) +AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path]) +AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path]) + +if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then + AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) +fi +if test -n "$PKG_CONFIG"; then + _pkg_min_version=m4_default([$1], [0.9.0]) + AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) + if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then + AC_MSG_RESULT([yes]) + else + AC_MSG_RESULT([no]) + PKG_CONFIG="" + fi +fi[]dnl +])# PKG_PROG_PKG_CONFIG + +# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) +# +# Check to see whether a particular set of modules exists. Similar +# to PKG_CHECK_MODULES(), but does not set variables or print errors. +# +# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG]) +# only at the first occurence in configure.ac, so if the first place +# it's called might be skipped (such as if it is within an "if", you +# have to call PKG_CHECK_EXISTS manually +# -------------------------------------------------------------- +AC_DEFUN([PKG_CHECK_EXISTS], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +if test -n "$PKG_CONFIG" && \ + AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then + m4_default([$2], [:]) +m4_ifvaln([$3], [else + $3])dnl +fi]) + +# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) +# --------------------------------------------- +m4_define([_PKG_CONFIG], +[if test -n "$$1"; then + pkg_cv_[]$1="$$1" + elif test -n "$PKG_CONFIG"; then + PKG_CHECK_EXISTS([$3], + [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes ], + [pkg_failed=yes]) + else + pkg_failed=untried +fi[]dnl +])# _PKG_CONFIG + +# _PKG_SHORT_ERRORS_SUPPORTED +# ----------------------------- +AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG]) +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi[]dnl +])# _PKG_SHORT_ERRORS_SUPPORTED + + +# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], +# [ACTION-IF-NOT-FOUND]) +# +# +# Note that if there is a possibility the first call to +# PKG_CHECK_MODULES might not happen, you should be sure to include an +# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac +# +# +# -------------------------------------------------------------- +AC_DEFUN([PKG_CHECK_MODULES], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl +AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl + +pkg_failed=no +AC_MSG_CHECKING([for $1]) + +_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) +_PKG_CONFIG([$1][_LIBS], [libs], [$2]) + +m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS +and $1[]_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details.]) + +if test $pkg_failed = yes; then + AC_MSG_RESULT([no]) + _PKG_SHORT_ERRORS_SUPPORTED + if test $_pkg_short_errors_supported = yes; then + $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1` + else + $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD + + m4_default([$4], [AC_MSG_ERROR( +[Package requirements ($2) were not met: + +$$1_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +_PKG_TEXT])[]dnl + ]) +elif test $pkg_failed = untried; then + AC_MSG_RESULT([no]) + m4_default([$4], [AC_MSG_FAILURE( +[The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +_PKG_TEXT + +To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl + ]) +else + $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS + $1[]_LIBS=$pkg_cv_[]$1[]_LIBS + AC_MSG_RESULT([yes]) + $3 +fi[]dnl +])# PKG_CHECK_MODULES + + +# PKG_INSTALLDIR(DIRECTORY) +# ------------------------- +# Substitutes the variable pkgconfigdir as the location where a module +# should install pkg-config .pc files. By default the directory is +# $libdir/pkgconfig, but the default can be changed by passing +# DIRECTORY. The user can override through the --with-pkgconfigdir +# parameter. +AC_DEFUN([PKG_INSTALLDIR], +[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])]) +m4_pushdef([pkg_description], + [pkg-config installation directory @<:@]pkg_default[@:>@]) +AC_ARG_WITH([pkgconfigdir], + [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],, + [with_pkgconfigdir=]pkg_default) +AC_SUBST([pkgconfigdir], [$with_pkgconfigdir]) +m4_popdef([pkg_default]) +m4_popdef([pkg_description]) +]) dnl PKG_INSTALLDIR + + +# PKG_NOARCH_INSTALLDIR(DIRECTORY) +# ------------------------- +# Substitutes the variable noarch_pkgconfigdir as the location where a +# module should install arch-independent pkg-config .pc files. By +# default the directory is $datadir/pkgconfig, but the default can be +# changed by passing DIRECTORY. The user can override through the +# --with-noarch-pkgconfigdir parameter. +AC_DEFUN([PKG_NOARCH_INSTALLDIR], +[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])]) +m4_pushdef([pkg_description], + [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@]) +AC_ARG_WITH([noarch-pkgconfigdir], + [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],, + [with_noarch_pkgconfigdir=]pkg_default) +AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir]) +m4_popdef([pkg_default]) +m4_popdef([pkg_description]) +]) dnl PKG_NOARCH_INSTALLDIR + + +# PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE, +# [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) +# ------------------------------------------- +# Retrieves the value of the pkg-config variable for the given module. +AC_DEFUN([PKG_CHECK_VAR], +[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl +AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl + +_PKG_CONFIG([$1], [variable="][$3]["], [$2]) +AS_VAR_COPY([$1], [pkg_cv_][$1]) + +AS_VAR_IF([$1], [""], [$5], [$4])dnl +])# PKG_CHECK_VAR + +# Copyright (C) 1999-2014 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + + +# AM_PATH_PYTHON([MINIMUM-VERSION], [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) +# --------------------------------------------------------------------------- +# Adds support for distributing Python modules and packages. To +# install modules, copy them to $(pythondir), using the python_PYTHON +# automake variable. To install a package with the same name as the +# automake package, install to $(pkgpythondir), or use the +# pkgpython_PYTHON automake variable. +# +# The variables $(pyexecdir) and $(pkgpyexecdir) are provided as +# locations to install python extension modules (shared libraries). +# Another macro is required to find the appropriate flags to compile +# extension modules. +# +# If your package is configured with a different prefix to python, +# users will have to add the install directory to the PYTHONPATH +# environment variable, or create a .pth file (see the python +# documentation for details). +# +# If the MINIMUM-VERSION argument is passed, AM_PATH_PYTHON will +# cause an error if the version of python installed on the system +# doesn't meet the requirement. MINIMUM-VERSION should consist of +# numbers and dots only. +AC_DEFUN([AM_PATH_PYTHON], + [ + dnl Find a Python interpreter. Python versions prior to 2.0 are not + dnl supported. (2.0 was released on October 16, 2000). + m4_define_default([_AM_PYTHON_INTERPRETER_LIST], +[python python2 python3 python3.3 python3.2 python3.1 python3.0 python2.7 dnl + python2.6 python2.5 python2.4 python2.3 python2.2 python2.1 python2.0]) + + AC_ARG_VAR([PYTHON], [the Python interpreter]) + + m4_if([$1],[],[ + dnl No version check is needed. + # Find any Python interpreter. + if test -z "$PYTHON"; then + AC_PATH_PROGS([PYTHON], _AM_PYTHON_INTERPRETER_LIST, :) + fi + am_display_PYTHON=python + ], [ + dnl A version check is needed. + if test -n "$PYTHON"; then + # If the user set $PYTHON, use it and don't search something else. + AC_MSG_CHECKING([whether $PYTHON version is >= $1]) + AM_PYTHON_CHECK_VERSION([$PYTHON], [$1], + [AC_MSG_RESULT([yes])], + [AC_MSG_RESULT([no]) + AC_MSG_ERROR([Python interpreter is too old])]) + am_display_PYTHON=$PYTHON + else + # Otherwise, try each interpreter until we find one that satisfies + # VERSION. + AC_CACHE_CHECK([for a Python interpreter with version >= $1], + [am_cv_pathless_PYTHON],[ + for am_cv_pathless_PYTHON in _AM_PYTHON_INTERPRETER_LIST none; do + test "$am_cv_pathless_PYTHON" = none && break + AM_PYTHON_CHECK_VERSION([$am_cv_pathless_PYTHON], [$1], [break]) + done]) + # Set $PYTHON to the absolute path of $am_cv_pathless_PYTHON. + if test "$am_cv_pathless_PYTHON" = none; then + PYTHON=: + else + AC_PATH_PROG([PYTHON], [$am_cv_pathless_PYTHON]) + fi + am_display_PYTHON=$am_cv_pathless_PYTHON + fi + ]) + + if test "$PYTHON" = :; then + dnl Run any user-specified action, or abort. + m4_default([$3], [AC_MSG_ERROR([no suitable Python interpreter found])]) + else + + dnl Query Python for its version number. Getting [:3] seems to be + dnl the best way to do this; it's what "site.py" does in the standard + dnl library. + + AC_CACHE_CHECK([for $am_display_PYTHON version], [am_cv_python_version], + [am_cv_python_version=`$PYTHON -c "import sys; sys.stdout.write(sys.version[[:3]])"`]) + AC_SUBST([PYTHON_VERSION], [$am_cv_python_version]) + + dnl Use the values of $prefix and $exec_prefix for the corresponding + dnl values of PYTHON_PREFIX and PYTHON_EXEC_PREFIX. These are made + dnl distinct variables so they can be overridden if need be. However, + dnl general consensus is that you shouldn't need this ability. + + AC_SUBST([PYTHON_PREFIX], ['${prefix}']) + AC_SUBST([PYTHON_EXEC_PREFIX], ['${exec_prefix}']) + + dnl At times (like when building shared libraries) you may want + dnl to know which OS platform Python thinks this is. + + AC_CACHE_CHECK([for $am_display_PYTHON platform], [am_cv_python_platform], + [am_cv_python_platform=`$PYTHON -c "import sys; sys.stdout.write(sys.platform)"`]) + AC_SUBST([PYTHON_PLATFORM], [$am_cv_python_platform]) + + # Just factor out some code duplication. + am_python_setup_sysconfig="\ +import sys +# Prefer sysconfig over distutils.sysconfig, for better compatibility +# with python 3.x. See automake bug#10227. +try: + import sysconfig +except ImportError: + can_use_sysconfig = 0 +else: + can_use_sysconfig = 1 +# Can't use sysconfig in CPython 2.7, since it's broken in virtualenvs: +# <https://github.com/pypa/virtualenv/issues/118> +try: + from platform import python_implementation + if python_implementation() == 'CPython' and sys.version[[:3]] == '2.7': + can_use_sysconfig = 0 +except ImportError: + pass" + + dnl Set up 4 directories: + + dnl pythondir -- where to install python scripts. This is the + dnl site-packages directory, not the python standard library + dnl directory like in previous automake betas. This behavior + dnl is more consistent with lispdir.m4 for example. + dnl Query distutils for this directory. + AC_CACHE_CHECK([for $am_display_PYTHON script directory], + [am_cv_python_pythondir], + [if test "x$prefix" = xNONE + then + am_py_prefix=$ac_default_prefix + else + am_py_prefix=$prefix + fi + am_cv_python_pythondir=`$PYTHON -c " +$am_python_setup_sysconfig +if can_use_sysconfig: + sitedir = sysconfig.get_path('purelib', vars={'base':'$am_py_prefix'}) +else: + from distutils import sysconfig + sitedir = sysconfig.get_python_lib(0, 0, prefix='$am_py_prefix') +sys.stdout.write(sitedir)"` + case $am_cv_python_pythondir in + $am_py_prefix*) + am__strip_prefix=`echo "$am_py_prefix" | sed 's|.|.|g'` + am_cv_python_pythondir=`echo "$am_cv_python_pythondir" | sed "s,^$am__strip_prefix,$PYTHON_PREFIX,"` + ;; + *) + case $am_py_prefix in + /usr|/System*) ;; + *) + am_cv_python_pythondir=$PYTHON_PREFIX/lib/python$PYTHON_VERSION/site-packages + ;; + esac + ;; + esac + ]) + AC_SUBST([pythondir], [$am_cv_python_pythondir]) + + dnl pkgpythondir -- $PACKAGE directory under pythondir. Was + dnl PYTHON_SITE_PACKAGE in previous betas, but this naming is + dnl more consistent with the rest of automake. + + AC_SUBST([pkgpythondir], [\${pythondir}/$PACKAGE]) + + dnl pyexecdir -- directory for installing python extension modules + dnl (shared libraries) + dnl Query distutils for this directory. + AC_CACHE_CHECK([for $am_display_PYTHON extension module directory], + [am_cv_python_pyexecdir], + [if test "x$exec_prefix" = xNONE + then + am_py_exec_prefix=$am_py_prefix + else + am_py_exec_prefix=$exec_prefix + fi + am_cv_python_pyexecdir=`$PYTHON -c " +$am_python_setup_sysconfig +if can_use_sysconfig: + sitedir = sysconfig.get_path('platlib', vars={'platbase':'$am_py_prefix'}) +else: + from distutils import sysconfig + sitedir = sysconfig.get_python_lib(1, 0, prefix='$am_py_prefix') +sys.stdout.write(sitedir)"` + case $am_cv_python_pyexecdir in + $am_py_exec_prefix*) + am__strip_prefix=`echo "$am_py_exec_prefix" | sed 's|.|.|g'` + am_cv_python_pyexecdir=`echo "$am_cv_python_pyexecdir" | sed "s,^$am__strip_prefix,$PYTHON_EXEC_PREFIX,"` + ;; + *) + case $am_py_exec_prefix in + /usr|/System*) ;; + *) + am_cv_python_pyexecdir=$PYTHON_EXEC_PREFIX/lib/python$PYTHON_VERSION/site-packages + ;; + esac + ;; + esac + ]) + AC_SUBST([pyexecdir], [$am_cv_python_pyexecdir]) + + dnl pkgpyexecdir -- $(pyexecdir)/$(PACKAGE) + + AC_SUBST([pkgpyexecdir], [\${pyexecdir}/$PACKAGE]) + + dnl Run any user-specified action. + $2 + fi + +]) + + +# AM_PYTHON_CHECK_VERSION(PROG, VERSION, [ACTION-IF-TRUE], [ACTION-IF-FALSE]) +# --------------------------------------------------------------------------- +# Run ACTION-IF-TRUE if the Python interpreter PROG has version >= VERSION. +# Run ACTION-IF-FALSE otherwise. +# This test uses sys.hexversion instead of the string equivalent (first +# word of sys.version), in order to cope with versions such as 2.2c1. +# This supports Python 2.0 or higher. (2.0 was released on October 16, 2000). +AC_DEFUN([AM_PYTHON_CHECK_VERSION], + [prog="import sys +# split strings by '.' and convert to numeric. Append some zeros +# because we need at least 4 digits for the hex conversion. +# map returns an iterator in Python 3.0 and a list in 2.x +minver = list(map(int, '$2'.split('.'))) + [[0, 0, 0]] +minverhex = 0 +# xrange is not present in Python 3.0 and range returns an iterator +for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[[i]] +sys.exit(sys.hexversion < minverhex)" + AS_IF([AM_RUN_LOG([$1 -c "$prog"])], [$3], [$4])]) + +# Copyright (C) 2001-2014 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_RUN_LOG(COMMAND) +# ------------------- +# Run COMMAND, save the exit status in ac_status, and log it. +# (This has been adapted from Autoconf's _AC_RUN_LOG macro.) +AC_DEFUN([AM_RUN_LOG], +[{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD + ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD + (exit $ac_status); }]) + +m4_include([acinclude.m4])
diff --git a/autoconf/config.guess b/autoconf/config.guess new file mode 100755 index 0000000..4438cd7 --- /dev/null +++ b/autoconf/config.guess
@@ -0,0 +1,1568 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright 1992-2014 Free Software Foundation, Inc. + +timestamp='2014-01-01' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see <http://www.gnu.org/licenses/>. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that +# program. This Exception is an additional permission under section 7 +# of the GNU General Public License, version 3 ("GPLv3"). +# +# Originally written by Per Bothner. +# +# You can get the latest version of this script from: +# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD +# +# Please send patches with a ChangeLog entry to config-patches@gnu.org. + + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to <config-patches@gnu.org>." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright 1992-2014 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ; set_cc_for_build= ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +case "${UNAME_SYSTEM}" in +Linux|GNU|GNU/*) + # If the system lacks a compiler, then just pick glibc. + # We could probably try harder. + LIBC=gnu + + eval $set_cc_for_build + cat <<-EOF > $dummy.c + #include <features.h> + #if defined(__UCLIBC__) + LIBC=uclibc + #elif defined(__dietlibc__) + LIBC=dietlibc + #else + LIBC=gnu + #endif + EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` + ;; +esac + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ELF__ + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit ;; + *:Bitrig:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE} + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Reset EXIT trap before exiting to avoid spurious non-zero exit code. + exitcode=$? + trap '' 0 + exit $exitcode ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit ;; + arm*:riscos:*:*|arm*:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + s390x:SunOS:*:*) + echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) + echo i386-pc-auroraux${UNAME_RELEASE} + exit ;; + i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) + eval $set_cc_for_build + SUN_ARCH="i386" + # If there is a compiler, see if it is configured for 64-bit objects. + # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. + # This test works for both compilers. + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + SUN_ARCH="x86_64" + fi + fi + echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include <stdio.h> /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos${UNAME_RELEASE} + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include <sys/systemcfg.h> + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[4567]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include <stdlib.h> + #include <unistd.h> + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep -q __LP64__ + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include <unistd.h> + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:FreeBSD:*:*) + UNAME_PROCESSOR=`/usr/bin/uname -p` + case ${UNAME_PROCESSOR} in + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit ;; + *:MINGW64*:*) + echo ${UNAME_MACHINE}-pc-mingw64 + exit ;; + *:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit ;; + i*:MSYS*:*) + echo ${UNAME_MACHINE}-pc-msys + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit ;; + *:Interix*:*) + case ${UNAME_MACHINE} in + x86) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + authenticamd | genuineintel | EM64T) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + IA64) + echo ia64-unknown-interix${UNAME_RELEASE} + exit ;; + esac ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit ;; + 8664:Windows_NT:*) + echo x86_64-pc-mks + exit ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + aarch64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + aarch64_be:Linux:*:*) + UNAME_MACHINE=aarch64_be + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep -q ld.so.1 + if test "$?" = 0 ; then LIBC="gnulibc1" ; fi + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + arc:Linux:*:* | arceb:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + arm*:Linux:*:*) + eval $set_cc_for_build + if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_EABI__ + then + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + else + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then + echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi + else + echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf + fi + fi + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + cris:Linux:*:*) + echo ${UNAME_MACHINE}-axis-linux-${LIBC} + exit ;; + crisv32:Linux:*:*) + echo ${UNAME_MACHINE}-axis-linux-${LIBC} + exit ;; + frv:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + hexagon:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + i*86:Linux:*:*) + echo ${UNAME_MACHINE}-pc-linux-${LIBC} + exit ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + mips:Linux:*:* | mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef ${UNAME_MACHINE} + #undef ${UNAME_MACHINE}el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=${UNAME_MACHINE}el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=${UNAME_MACHINE} + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } + ;; + or1k:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + or32:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + padre:Linux:*:*) + echo sparc-unknown-linux-${LIBC} + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-${LIBC} + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; + PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; + *) echo hppa-unknown-linux-${LIBC} ;; + esac + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-${LIBC} + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-${LIBC} + exit ;; + ppc64le:Linux:*:*) + echo powerpc64le-unknown-linux-${LIBC} + exit ;; + ppcle:Linux:*:*) + echo powerpcle-unknown-linux-${LIBC} + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux-${LIBC} + exit ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + tile*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-${LIBC} + exit ;; + x86_64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + xtensa*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name` + echo ${UNAME_MACHINE}-pc-isc$UNAME_REL + elif /bin/uname -X 2>/dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i586. + # Note: whatever this is, it MUST be the same as what config.sub + # prints for the "djgpp" host, or else GDB configury will decide that + # this is a cross-build. + echo i586-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + NCR*:*:4.2:* | MPRAS*:*:4.2:*) + OS_REL='.3' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says <Richard.M.Bartel@ccMail.Census.GOV> + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes <hewes@openmarket.com>. + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + BePC:Haiku:*:*) # Haiku running on Intel PC compatible. + echo i586-pc-haiku + exit ;; + x86_64:Haiku:*:*) + echo x86_64-unknown-haiku + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit ;; + SX-7:SUPER-UX:*:*) + echo sx7-nec-superux${UNAME_RELEASE} + exit ;; + SX-8:SUPER-UX:*:*) + echo sx8-nec-superux${UNAME_RELEASE} + exit ;; + SX-8R:SUPER-UX:*:*) + echo sx8r-nec-superux${UNAME_RELEASE} + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + eval $set_cc_for_build + if test "$UNAME_PROCESSOR" = unknown ; then + UNAME_PROCESSOR=powerpc + fi + if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + case $UNAME_PROCESSOR in + i386) UNAME_PROCESSOR=x86_64 ;; + powerpc) UNAME_PROCESSOR=powerpc64 ;; + esac + fi + fi + elif test "$UNAME_PROCESSOR" = i386 ; then + # Avoid executing cc on OS X 10.9, as it ships with a stub + # that puts up a graphical alert prompting to install + # developer tools. Any system running Mac OS X 10.7 or + # later (Darwin 11 and later) is required to have a 64-bit + # processor. This is not true of the ARM version of Darwin + # that Apple uses in portable devices. + UNAME_PROCESSOR=x86_64 + fi + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NEO-?:NONSTOP_KERNEL:*:*) + echo neo-tandem-nsk${UNAME_RELEASE} + exit ;; + NSE-*:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; + i*86:AROS:*:*) + echo ${UNAME_MACHINE}-pc-aros + exit ;; + x86_64:VMkernel:*:*) + echo ${UNAME_MACHINE}-unknown-esx + exit ;; +esac + +eval $set_cc_for_build +cat >$dummy.c <<EOF +#ifdef _SEQUENT_ +# include <sys/types.h> +# include <sys/utsname.h> +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include <sys/param.h> + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix\n"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include <sys/param.h> +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + c34*) + echo c34-convex-bsd + exit ;; + c38*) + echo c38-convex-bsd + exit ;; + c4*) + echo c4-convex-bsd + exit ;; + esac +fi + +cat >&2 <<EOF +$0: unable to guess system type + +This script, last modified $timestamp, has failed to recognize +the operating system you are using. It is advised that you +download the most up to date version of the config scripts from + + http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD +and + http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD + +If the version you run ($0) is already up to date, please +send the following data and any information you think might be +pertinent to <config-patches@gnu.org> in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End:
diff --git a/autoconf/config.sub b/autoconf/config.sub new file mode 100755 index 0000000..092cff0 --- /dev/null +++ b/autoconf/config.sub
@@ -0,0 +1,1793 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright 1992-2014 Free Software Foundation, Inc. + +timestamp='2014-01-01' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see <http://www.gnu.org/licenses/>. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that +# program. This Exception is an additional permission under section 7 +# of the GNU General Public License, version 3 ("GPLv3"). + + +# Please send patches with a ChangeLog entry to config-patches@gnu.org. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# You can get the latest version of this script from: +# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to <config-patches@gnu.org>." + +version="\ +GNU config.sub ($timestamp) + +Copyright 1992-2014 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ + linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ + knetbsd*-gnu* | netbsd*-gnu* | \ + kopensolaris*-gnu* | \ + storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + android-linux) + os=-linux-android + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis | -knuth | -cray | -microblaze*) + os= + basic_machine=$1 + ;; + -bluegene*) + os=-cnk + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco6) + os=-sco5v6 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5v6*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*178) + os=-lynxos178 + ;; + -lynx*5) + os=-lynxos5 + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | aarch64 | aarch64_be \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arceb \ + | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \ + | avr | avr32 \ + | be32 | be64 \ + | bfin \ + | c4x | c8051 | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | epiphany \ + | fido | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | hexagon \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | k1om \ + | le32 | le64 \ + | lm32 \ + | m32c | m32r | m32rle | m68000 | m68k | m88k \ + | maxq | mb | microblaze | microblazeel | mcore | mep | metag \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64octeon | mips64octeonel \ + | mips64orion | mips64orionel \ + | mips64r5900 | mips64r5900el \ + | mips64vr | mips64vrel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mips64vr5900 | mips64vr5900el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipsr5900 | mipsr5900el \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | moxie \ + | mt \ + | msp430 \ + | nds32 | nds32le | nds32be \ + | nios | nios2 | nios2eb | nios2el \ + | ns16k | ns32k \ + | open8 \ + | or1k | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle \ + | pyramid \ + | rl78 | rx \ + | score \ + | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ + | spu \ + | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ + | ubicom32 \ + | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ + | we32k \ + | x86 | xc16x | xstormy16 | xtensa \ + | z8k | z80) + basic_machine=$basic_machine-unknown + ;; + c54x) + basic_machine=tic54x-unknown + ;; + c55x) + basic_machine=tic55x-unknown + ;; + c6x) + basic_machine=tic6x-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip) + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + ms1) + basic_machine=mt-unknown + ;; + + strongarm | thumb | xscale) + basic_machine=arm-unknown + ;; + xgate) + basic_machine=$basic_machine-unknown + os=-none + ;; + xscaleeb) + basic_machine=armeb-unknown + ;; + + xscaleel) + basic_machine=armel-unknown + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | aarch64-* | aarch64_be-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* | avr32-* \ + | be32-* | be64-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* \ + | c8051-* | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | hexagon-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | k1om-* \ + | le32-* | le64-* \ + | lm32-* \ + | m32c-* | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \ + | microblaze-* | microblazeel-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64octeon-* | mips64octeonel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64r5900-* | mips64r5900el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mips64vr5900-* | mips64vr5900el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipsr5900-* | mipsr5900el-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | mt-* \ + | msp430-* \ + | nds32-* | nds32le-* | nds32be-* \ + | nios-* | nios2-* | nios2eb-* | nios2el-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | open8-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ + | pyramid-* \ + | rl78-* | romp-* | rs6000-* | rx-* \ + | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ + | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ + | tahoe-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ + | tile*-* \ + | tron-* \ + | ubicom32-* \ + | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ + | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xc16x-* | xps100-* \ + | xstormy16-* | xtensa*-* \ + | ymp-* \ + | z8k-* | z80-*) + ;; + # Recognize the basic CPU types without company name, with glob match. + xtensa*) + basic_machine=$basic_machine-unknown + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aros) + basic_machine=i386-pc + os=-aros + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + blackfin) + basic_machine=bfin-unknown + os=-linux + ;; + blackfin-*) + basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + bluegene*) + basic_machine=powerpc-ibm + os=-cnk + ;; + c54x-*) + basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + c55x-*) + basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + c6x-*) + basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + cegcc) + basic_machine=arm-unknown + os=-cegcc + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + craynv) + basic_machine=craynv-cray + os=-unicosmp + ;; + cr16 | cr16-*) + basic_machine=cr16-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + crisv32 | crisv32-* | etraxfs*) + basic_machine=crisv32-axis + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + dicos) + basic_machine=i686-pc + os=-dicos + ;; + djgpp) + basic_machine=i586-pc + os=-msdosdjgpp + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m68knommu) + basic_machine=m68k-unknown + os=-linux + ;; + m68knommu-*) + basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + microblaze*) + basic_machine=microblaze-xilinx + ;; + mingw64) + basic_machine=x86_64-pc + os=-mingw64 + ;; + mingw32) + basic_machine=i686-pc + os=-mingw32 + ;; + mingw32ce) + basic_machine=arm-unknown + os=-mingw32ce + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + ms1-*) + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; + msys) + basic_machine=i686-pc + os=-msys + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + nacl) + basic_machine=le32-unknown + os=-nacl + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + neo-tandem) + basic_machine=neo-tandem + ;; + nse-tandem) + basic_machine=nse-tandem + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + openrisc | openrisc-*) + basic_machine=or32-unknown + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + parisc) + basic_machine=hppa-unknown + os=-linux + ;; + parisc-*) + basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pc98) + basic_machine=i386-pc + ;; + pc98-*) + basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc | ppcbe) basic_machine=powerpc-unknown + ;; + ppc-* | ppcbe-*) + basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rdos | rdos64) + basic_machine=x86_64-pc + os=-rdos + ;; + rdos32) + basic_machine=i386-pc + os=-rdos + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sde) + basic_machine=mipsisa32-sde + os=-elf + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh5el) + basic_machine=sh5le-unknown + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + strongarm-* | thumb-*) + basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tile*) + basic_machine=$basic_machine-unknown + os=-linux-gnu + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xbox) + basic_machine=i686-pc + os=-mingw32 + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + xscale-* | xscalee[bl]-*) + basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + z80-*-coff) + basic_machine=z80-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + mmix) + basic_machine=mmix-knuth + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -auroraux) + os=-auroraux + ;; + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ + | -sym* | -kopensolaris* | -plan9* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* | -aros* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -bitrig* | -openbsd* | -solidbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* | -cegcc* \ + | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ + | -linux-newlib* | -linux-musl* | -linux-uclibc* \ + | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ + | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -zvmoe) + os=-zvmoe + ;; + -dicos*) + os=-dicos + ;; + -nacl*) + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + score-*) + os=-elf + ;; + spu-*) + os=-elf + ;; + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + c8051-*) + os=-elf + ;; + hexagon-*) + os=-elf + ;; + tic54x-*) + os=-coff + ;; + tic55x-*) + os=-coff + ;; + tic6x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + ;; + m68*-cisco) + os=-aout + ;; + mep-*) + os=-elf + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or1k-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-haiku) + os=-haiku + ;; + *-ibm) + os=-aix + ;; + *-knuth) + os=-mmixware + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -cnk*|-aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End:
diff --git a/autoconf/install-sh b/autoconf/install-sh new file mode 100755 index 0000000..4fbbae7 --- /dev/null +++ b/autoconf/install-sh
@@ -0,0 +1,507 @@ +#!/bin/sh +# install - install a program, script, or datafile + +scriptversion=2006-10-14.15 + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. + +nl=' +' +IFS=" "" $nl" + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" +if test -z "$doit"; then + doit_exec=exec +else + doit_exec=$doit +fi + +# Put in absolute file names if you don't have them in your path; +# or use environment vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +posix_glob= +posix_mkdir= + +# Desired mode of installed file. +mode=0755 + +chmodcmd=$chmodprog +chowncmd= +chgrpcmd= +stripcmd= +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src= +dst= +dir_arg= +dstarg= +no_target_directory= + +usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... + +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. + +Options: +-c (ignored) +-d create directories instead of installing files. +-g GROUP $chgrpprog installed files to GROUP. +-m MODE $chmodprog installed files to MODE. +-o USER $chownprog installed files to USER. +-s $stripprog installed files. +-t DIRECTORY install into DIRECTORY. +-T report an error if DSTFILE is a directory. +--help display this help and exit. +--version display version info and exit. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG +" + +while test $# -ne 0; do + case $1 in + -c) shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + --help) echo "$usage"; exit $?;; + + -m) mode=$2 + shift + shift + case $mode in + *' '* | *' '* | *' +'* | *'*'* | *'?'* | *'['*) + echo "$0: invalid mode: $mode" >&2 + exit 1;; + esac + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -s) stripcmd=$stripprog + shift + continue;; + + -t) dstarg=$2 + shift + shift + continue;; + + -T) no_target_directory=true + shift + continue;; + + --version) echo "$0 $scriptversion"; exit $?;; + + --) shift + break;; + + -*) echo "$0: invalid option: $1" >&2 + exit 1;; + + *) break;; + esac +done + +if test $# -ne 0 && test -z "$dir_arg$dstarg"; then + # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dstarg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dstarg" + shift # fnord + fi + shift # arg + dstarg=$arg + done +fi + +if test $# -eq 0; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call `install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +if test -z "$dir_arg"; then + trap '(exit $?); exit' 1 2 13 15 + + # Set umask so as not to create temps with too-generous modes. + # However, 'strip' requires both read and write access to temps. + case $mode in + # Optimize common cases. + *644) cp_umask=133;; + *755) cp_umask=22;; + + *[0-7]) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw='% 200' + fi + cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; + *) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw=,u+rw + fi + cp_umask=$mode$u_plus_rw;; + esac +fi + +for src +do + # Protect names starting with `-'. + case $src in + -*) src=./$src ;; + esac + + if test -n "$dir_arg"; then + dst=$src + dstdir=$dst + test -d "$dstdir" + dstdir_status=$? + else + + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dstarg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + + dst=$dstarg + # Protect names starting with `-'. + case $dst in + -*) dst=./$dst ;; + esac + + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + if test -n "$no_target_directory"; then + echo "$0: $dstarg: Is a directory" >&2 + exit 1 + fi + dstdir=$dst + dst=$dstdir/`basename "$src"` + dstdir_status=0 + else + # Prefer dirname, but fall back on a substitute if dirname fails. + dstdir=` + (dirname "$dst") 2>/dev/null || + expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$dst" : 'X\(//\)[^/]' \| \ + X"$dst" : 'X\(//\)$' \| \ + X"$dst" : 'X\(/\)' \| . 2>/dev/null || + echo X"$dst" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q' + ` + + test -d "$dstdir" + dstdir_status=$? + fi + fi + + obsolete_mkdir_used=false + + if test $dstdir_status != 0; then + case $posix_mkdir in + '') + # Create intermediate dirs using mode 755 as modified by the umask. + # This is like FreeBSD 'install' as of 1997-10-28. + umask=`umask` + case $stripcmd.$umask in + # Optimize common cases. + *[2367][2367]) mkdir_umask=$umask;; + .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; + + *[0-7]) + mkdir_umask=`expr $umask + 22 \ + - $umask % 100 % 40 + $umask % 20 \ + - $umask % 10 % 4 + $umask % 2 + `;; + *) mkdir_umask=$umask,go-w;; + esac + + # With -d, create the new directory with the user-specified mode. + # Otherwise, rely on $mkdir_umask. + if test -n "$dir_arg"; then + mkdir_mode=-m$mode + else + mkdir_mode= + fi + + posix_mkdir=false + case $umask in + *[123567][0-7][0-7]) + # POSIX mkdir -p sets u+wx bits regardless of umask, which + # is incompatible with FreeBSD 'install' when (umask & 300) != 0. + ;; + *) + tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ + trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 + + if (umask $mkdir_umask && + exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 + then + if test -z "$dir_arg" || { + # Check for POSIX incompatibilities with -m. + # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or + # other-writeable bit of parent directory when it shouldn't. + # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. + ls_ld_tmpdir=`ls -ld "$tmpdir"` + case $ls_ld_tmpdir in + d????-?r-*) different_mode=700;; + d????-?--*) different_mode=755;; + *) false;; + esac && + $mkdirprog -m$different_mode -p -- "$tmpdir" && { + ls_ld_tmpdir_1=`ls -ld "$tmpdir"` + test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" + } + } + then posix_mkdir=: + fi + rmdir "$tmpdir/d" "$tmpdir" + else + # Remove any dirs left behind by ancient mkdir implementations. + rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null + fi + trap '' 0;; + esac;; + esac + + if + $posix_mkdir && ( + umask $mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" + ) + then : + else + + # The umask is ridiculous, or mkdir does not conform to POSIX, + # or it failed possibly due to a race condition. Create the + # directory the slow way, step by step, checking for races as we go. + + case $dstdir in + /*) prefix=/ ;; + -*) prefix=./ ;; + *) prefix= ;; + esac + + case $posix_glob in + '') + if (set -f) 2>/dev/null; then + posix_glob=true + else + posix_glob=false + fi ;; + esac + + oIFS=$IFS + IFS=/ + $posix_glob && set -f + set fnord $dstdir + shift + $posix_glob && set +f + IFS=$oIFS + + prefixes= + + for d + do + test -z "$d" && continue + + prefix=$prefix$d + if test -d "$prefix"; then + prefixes= + else + if $posix_mkdir; then + (umask=$mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break + # Don't fail if two instances are running concurrently. + test -d "$prefix" || exit 1 + else + case $prefix in + *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; + *) qprefix=$prefix;; + esac + prefixes="$prefixes '$qprefix'" + fi + fi + prefix=$prefix/ + done + + if test -n "$prefixes"; then + # Don't fail if two instances are running concurrently. + (umask $mkdir_umask && + eval "\$doit_exec \$mkdirprog $prefixes") || + test -d "$dstdir" || exit 1 + obsolete_mkdir_used=true + fi + fi + fi + + if test -n "$dir_arg"; then + { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && + { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || + test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 + else + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + + # Copy the file name to the temp name. + (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && + + # Now rename the file to the real destination. + { $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null \ + || { + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + if test -f "$dst"; then + $doit $rmcmd -f "$dst" 2>/dev/null \ + || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null \ + && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }; }\ + || { + echo "$0: cannot unlink or rename $dst" >&2 + (exit 1); exit 1 + } + else + : + fi + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dst" + } + } || exit 1 + + trap '' 0 + fi +done + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End:
diff --git a/autoconf/py-compile b/autoconf/py-compile new file mode 100755 index 0000000..bc20391 --- /dev/null +++ b/autoconf/py-compile
@@ -0,0 +1,170 @@ +#!/bin/sh +# py-compile - Compile a Python program + +scriptversion=2011-06-08.12; # UTC + +# Copyright (C) 2000-2014 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# This file is maintained in Automake, please report +# bugs to <bug-automake@gnu.org> or send patches to +# <automake-patches@gnu.org>. + +if [ -z "$PYTHON" ]; then + PYTHON=python +fi + +me=py-compile + +usage_error () +{ + echo "$me: $*" >&2 + echo "Try '$me --help' for more information." >&2 + exit 1 +} + +basedir= +destdir= +while test $# -ne 0; do + case "$1" in + --basedir) + if test $# -lt 2; then + usage_error "option '--basedir' requires an argument" + else + basedir=$2 + fi + shift + ;; + --destdir) + if test $# -lt 2; then + usage_error "option '--destdir' requires an argument" + else + destdir=$2 + fi + shift + ;; + -h|--help) + cat <<\EOF +Usage: py-compile [--help] [--version] [--basedir DIR] [--destdir DIR] FILES..." + +Byte compile some python scripts FILES. Use --destdir to specify any +leading directory path to the FILES that you don't want to include in the +byte compiled file. Specify --basedir for any additional path information you +do want to be shown in the byte compiled file. + +Example: + py-compile --destdir /tmp/pkg-root --basedir /usr/share/test test.py test2.py + +Report bugs to <bug-automake@gnu.org>. +EOF + exit $? + ;; + -v|--version) + echo "$me $scriptversion" + exit $? + ;; + --) + shift + break + ;; + -*) + usage_error "unrecognized option '$1'" + ;; + *) + break + ;; + esac + shift +done + +files=$* +if test -z "$files"; then + usage_error "no files given" +fi + +# if basedir was given, then it should be prepended to filenames before +# byte compilation. +if [ -z "$basedir" ]; then + pathtrans="path = file" +else + pathtrans="path = os.path.join('$basedir', file)" +fi + +# if destdir was given, then it needs to be prepended to the filename to +# byte compile but not go into the compiled file. +if [ -z "$destdir" ]; then + filetrans="filepath = path" +else + filetrans="filepath = os.path.normpath('$destdir' + os.sep + path)" +fi + +$PYTHON -c " +import sys, os, py_compile, imp + +files = '''$files''' + +sys.stdout.write('Byte-compiling python modules...\n') +for file in files.split(): + $pathtrans + $filetrans + if not os.path.exists(filepath) or not (len(filepath) >= 3 + and filepath[-3:] == '.py'): + continue + sys.stdout.write(file) + sys.stdout.flush() + if hasattr(imp, 'get_tag'): + py_compile.compile(filepath, imp.cache_from_source(filepath), path) + else: + py_compile.compile(filepath, filepath + 'c', path) +sys.stdout.write('\n')" || exit $? + +# this will fail for python < 1.5, but that doesn't matter ... +$PYTHON -O -c " +import sys, os, py_compile, imp + +# pypy does not use .pyo optimization +if hasattr(sys, 'pypy_translation_info'): + sys.exit(0) + +files = '''$files''' +sys.stdout.write('Byte-compiling python modules (optimized versions) ...\n') +for file in files.split(): + $pathtrans + $filetrans + if not os.path.exists(filepath) or not (len(filepath) >= 3 + and filepath[-3:] == '.py'): + continue + sys.stdout.write(file) + sys.stdout.flush() + if hasattr(imp, 'get_tag'): + py_compile.compile(filepath, imp.cache_from_source(filepath, False), path) + else: + py_compile.compile(filepath, filepath + 'o', path) +sys.stdout.write('\n')" 2>/dev/null || : + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC" +# time-stamp-end: "; # UTC" +# End:
diff --git a/conf/.gitignore b/conf/.gitignore new file mode 100644 index 0000000..4bfc4d3 --- /dev/null +++ b/conf/.gitignore
@@ -0,0 +1,6 @@ +command_profile_template.profile +example.conf +lvmlocal.conf +metadata_profile_template.profile +configure.h +lvm-version.h
diff --git a/conf/Makefile.in b/conf/Makefile.in new file mode 100644 index 0000000..c88045c --- /dev/null +++ b/conf/Makefile.in
@@ -0,0 +1,57 @@ +# +# Copyright (C) 2004-2015 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +CONFSRC=example.conf +CONFDEST=lvm.conf +CONFLOCAL=lvmlocal.conf + +PROFILE_TEMPLATES=command_profile_template.profile metadata_profile_template.profile +PROFILES=$(PROFILE_TEMPLATES) \ + $(srcdir)/cache-mq.profile \ + $(srcdir)/cache-smq.profile \ + $(srcdir)/thin-generic.profile \ + $(srcdir)/thin-performance.profile + +include $(top_builddir)/make.tmpl + +.PHONY: install_conf install_localconf install_profiles + +generate: + (cat $(top_srcdir)/conf/example.conf.base && LD_LIBRARY_PATH=$(top_builddir)/libdm:$(LD_LIBRARY_PATH) $(top_builddir)/tools/lvm dumpconfig --type default --unconfigured --withcomments --ignorelocal --withspaces) > example.conf.in + (cat $(top_srcdir)/conf/lvmlocal.conf.base && LD_LIBRARY_PATH=$(top_builddir)/libdm:$(LD_LIBRARY_PATH) $(top_builddir)/tools/lvm dumpconfig --type default --unconfigured --withcomments --withspaces local) > lvmlocal.conf.in + +install_conf: $(CONFSRC) + @if [ ! -e $(confdir)/$(CONFDEST) ]; then \ + echo "$(INSTALL_WDATA) -D $< $(confdir)/$(CONFDEST)"; \ + $(INSTALL_WDATA) -D $< $(confdir)/$(CONFDEST); \ + fi + +install_localconf: $(CONFLOCAL) + @if [ ! -e $(confdir)/$(CONFLOCAL) ]; then \ + echo "$(INSTALL_WDATA) -D $< $(confdir)/$(CONFLOCAL)"; \ + $(INSTALL_WDATA) -D $< $(confdir)/$(CONFLOCAL); \ + fi + +install_profiles: $(PROFILES) + $(INSTALL_DIR) $(DESTDIR)$(DEFAULT_PROFILE_DIR) + $(INSTALL_DATA) $(PROFILES) $(DESTDIR)$(DEFAULT_PROFILE_DIR)/ + +install_lvm2: install_conf install_localconf install_profiles + +install: install_lvm2 + +DISTCLEAN_TARGETS += $(CONFSRC) $(CONFLOCAL) $(PROFILE_TEMPLATES)
diff --git a/conf/cache-mq.profile b/conf/cache-mq.profile new file mode 100644 index 0000000..3c90331 --- /dev/null +++ b/conf/cache-mq.profile
@@ -0,0 +1,20 @@ +# Demo configuration 'mq' cache policy +# +# Note: This policy has been deprecated in favor of the smq policy +# keyword "default" means, setting is left with kernel defaults. +# + +allocation { + cache_pool_chunk_size = 64 + cache_mode = "writethrough" + cache_policy = "mq" + cache_settings { + mq { + sequential_threshold = "default" # #nr_sequential_ios + random_threshold = "default" # #nr_random_ios + read_promote_adjustment = "default" + write_promote_adjustment = "default" + discard_promote_adjustment = "default" + } + } +}
diff --git a/conf/cache-smq.profile b/conf/cache-smq.profile new file mode 100644 index 0000000..c0d6266 --- /dev/null +++ b/conf/cache-smq.profile
@@ -0,0 +1,14 @@ +# Demo configuration 'smq' cache policy +# +# The stochastic multi-queue (smq) policy addresses some of the problems +# with the multiqueue (mq) policy and uses less memory. +# + +allocation { + cache_pool_chunk_size = 64 + cache_mode = "writethrough" + cache_policy = "smq" + cache_settings { + # currently no settins for "smq" policy + } +}
diff --git a/conf/command_profile_template.profile.in b/conf/command_profile_template.profile.in new file mode 100644 index 0000000..156dc0d --- /dev/null +++ b/conf/command_profile_template.profile.in
@@ -0,0 +1,74 @@ +# This is a command profile template for the LVM2 system. +# +# It contains all configuration settings that are customizable by command +# profiles. To create a new command profile, select the settings you want +# to customize and add them in a new file named <profile_name>.profile. +# Then install the new profile in a directory as defined by config/profile_dir +# setting found in @DEFAULT_SYS_DIR@/lvm.conf file. +# +# Command profiles can be referenced by using the --commandprofile option then. +# +# Refer to 'man lvm.conf' for further information about profiles and +# general configuration file layout. +# +allocation { + cache_mode="writethrough" + cache_settings { + } +} +log { + report_command_log=0 + command_log_sort="log_seq_num" + command_log_cols="log_seq_num,log_type,log_context,log_object_type,log_object_name,log_object_id,log_object_group,log_object_group_id,log_message,log_errno,log_ret_code" + command_log_selection="!(log_type=status && message=success)" +} +global { + units="h" + si_unit_consistency=1 + suffix=1 + lvdisplay_shows_full_device_path=0 +} +report { + output_format="basic" + compact_output=0 + compact_output_cols="" + aligned=1 + buffered=1 + headings=1 + separator=" " + list_item_separator="," + prefixes=0 + quoted=1 + colums_as_rows=0 + binary_values_as_numeric=0 + time_format="%Y-%m-%d %T %z" + devtypes_sort="devtype_name" + devtypes_cols="devtype_name,devtype_max_partitions,devtype_description" + devtypes_cols_verbose="devtype_name,devtype_max_partitions,devtype_description" + lvs_sort="vg_name,lv_name" + lvs_cols="lv_name,vg_name,lv_attr,lv_size,pool_lv,origin,data_percent,metadata_percent,move_pv,mirror_log,copy_percent,convert_lv" + lvs_cols_verbose="lv_name,vg_name,seg_count,lv_attr,lv_size,lv_major,lv_minor,lv_kernel_major,lv_kernel_minor,pool_lv,origin,data_percent,metadata_percent,move_pv,copy_percent,mirror_log,convert_lv,lv_uuid,lv_profile" + vgs_sort="vg_name" + vgs_cols="vg_name,pv_count,lv_count,snap_count,vg_attr,vg_size,vg_free" + vgs_cols_verbose="vg_name,vg_attr,vg_extent_size,pv_count,lv_count,snap_count,vg_size,vg_free,vg_uuid,vg_profile" + pvs_sort="pv_name" + pvs_cols="pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free" + pvs_cols_verbose="pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,dev_size,pv_uuid" + segs_sort="vg_name,lv_name,seg_start" + segs_cols="lv_name,vg_name,lv_attr,stripes,segtype,seg_size" + segs_cols_verbose="lv_name,vg_name,lv_attr,seg_start,seg_size,stripes,segtype,stripesize,chunksize" + pvsegs_sort="pv_name,pvseg_start" + pvsegs_cols="pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,pvseg_start,pvseg_size" + pvsegs_cols_verbose="pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,pvseg_start,pvseg_size,lv_name,seg_start_pe,segtype,seg_pe_ranges" + vgs_cols_full="vg_all" + pvs_cols_full="pv_all" + lvs_cols_full="lv_all" + pvsegs_cols_full="pvseg_all,pv_uuid,lv_uuid" + segs_cols_full="seg_all,lv_uuid" + vgs_sort_full="vg_name" + pvs_sort_full="pv_name" + lvs_sort_full="vg_name,lv_name" + pvsegs_sort_full="pv_uuid,pvseg_start" + segs_sort_full="lv_uuid,seg_start" + mark_hidden_devices=1 +}
diff --git a/conf/example.conf.base b/conf/example.conf.base new file mode 100644 index 0000000..5c49899 --- /dev/null +++ b/conf/example.conf.base
@@ -0,0 +1,23 @@ +# This is an example configuration file for the LVM2 system. +# It contains the default settings that would be used if there was no +# @DEFAULT_SYS_DIR@/lvm.conf file. +# +# Refer to 'man lvm.conf' for further information including the file layout. +# +# Refer to 'man lvm.conf' for information about how settings configured in +# this file are combined with built-in values and command line options to +# arrive at the final values used by LVM. +# +# Refer to 'man lvmconfig' for information about displaying the built-in +# and configured values used by LVM. +# +# If a default value is set in this file (not commented out), then a +# new version of LVM using this file will continue using that value, +# even if the new version of LVM changes the built-in default value. +# +# To put this file in a different directory and override @DEFAULT_SYS_DIR@ set +# the environment variable LVM_SYSTEM_DIR before running the tools. +# +# N.B. Take care that each setting only appears once if uncommenting +# example settings in this file. +
diff --git a/conf/example.conf.in b/conf/example.conf.in new file mode 100644 index 0000000..b98a19f --- /dev/null +++ b/conf/example.conf.in
@@ -0,0 +1,2089 @@ +# This is an example configuration file for the LVM2 system. +# It contains the default settings that would be used if there was no +# @DEFAULT_SYS_DIR@/lvm.conf file. +# +# Refer to 'man lvm.conf' for further information including the file layout. +# +# Refer to 'man lvm.conf' for information about how settings configured in +# this file are combined with built-in values and command line options to +# arrive at the final values used by LVM. +# +# Refer to 'man lvmconfig' for information about displaying the built-in +# and configured values used by LVM. +# +# If a default value is set in this file (not commented out), then a +# new version of LVM using this file will continue using that value, +# even if the new version of LVM changes the built-in default value. +# +# To put this file in a different directory and override @DEFAULT_SYS_DIR@ set +# the environment variable LVM_SYSTEM_DIR before running the tools. +# +# N.B. Take care that each setting only appears once if uncommenting +# example settings in this file. + + +# Configuration section config. +# How LVM configuration settings are handled. +config { + + # Configuration option config/checks. + # If enabled, any LVM configuration mismatch is reported. + # This implies checking that the configuration key is understood by + # LVM and that the value of the key is the proper type. If disabled, + # any configuration mismatch is ignored and the default value is used + # without any warning (a message about the configuration key not being + # found is issued in verbose mode only). + checks = 1 + + # Configuration option config/abort_on_errors. + # Abort the LVM process if a configuration mismatch is found. + abort_on_errors = 0 + + # Configuration option config/profile_dir. + # Directory where LVM looks for configuration profiles. + profile_dir = "@DEFAULT_SYS_DIR@/@DEFAULT_PROFILE_SUBDIR@" +} + +# Configuration section devices. +# How LVM uses block devices. +devices { + + # Configuration option devices/dir. + # Directory in which to create volume group device nodes. + # Commands also accept this as a prefix on volume group names. + # This configuration option is advanced. + dir = "/dev" + + # Configuration option devices/scan. + # Directories containing device nodes to use with LVM. + # This configuration option is advanced. + scan = [ "/dev" ] + + # Configuration option devices/obtain_device_list_from_udev. + # Obtain the list of available devices from udev. + # This avoids opening or using any inapplicable non-block devices or + # subdirectories found in the udev directory. Any device node or + # symlink not managed by udev in the udev directory is ignored. This + # setting applies only to the udev-managed device directory; other + # directories will be scanned fully. LVM needs to be compiled with + # udev support for this setting to apply. + obtain_device_list_from_udev = 1 + + # Configuration option devices/external_device_info_source. + # Select an external device information source. + # Some information may already be available in the system and LVM can + # use this information to determine the exact type or use of devices it + # processes. Using an existing external device information source can + # speed up device processing as LVM does not need to run its own native + # routines to acquire this information. For example, this information + # is used to drive LVM filtering like MD component detection, multipath + # component detection, partition detection and others. + # + # Accepted values: + # none + # No external device information source is used. + # udev + # Reuse existing udev database records. Applicable only if LVM is + # compiled with udev support. + # + external_device_info_source = "none" + + # Configuration option devices/preferred_names. + # Select which path name to display for a block device. + # If multiple path names exist for a block device, and LVM needs to + # display a name for the device, the path names are matched against + # each item in this list of regular expressions. The first match is + # used. Try to avoid using undescriptive /dev/dm-N names, if present. + # If no preferred name matches, or if preferred_names are not defined, + # the following built-in preferences are applied in order until one + # produces a preferred name: + # Prefer names with path prefixes in the order of: + # /dev/mapper, /dev/disk, /dev/dm-*, /dev/block. + # Prefer the name with the least number of slashes. + # Prefer a name that is a symlink. + # Prefer the path with least value in lexicographical order. + # + # Example + # preferred_names = [ "^/dev/mpath/", "^/dev/mapper/mpath", "^/dev/[hs]d" ] + # + # This configuration option does not have a default value defined. + + # Configuration option devices/filter. + # Limit the block devices that are used by LVM commands. + # This is a list of regular expressions used to accept or reject block + # device path names. Each regex is delimited by a vertical bar '|' + # (or any character) and is preceded by 'a' to accept the path, or + # by 'r' to reject the path. The first regex in the list to match the + # path is used, producing the 'a' or 'r' result for the device. + # When multiple path names exist for a block device, if any path name + # matches an 'a' pattern before an 'r' pattern, then the device is + # accepted. If all the path names match an 'r' pattern first, then the + # device is rejected. Unmatching path names do not affect the accept + # or reject decision. If no path names for a device match a pattern, + # then the device is accepted. Be careful mixing 'a' and 'r' patterns, + # as the combination might produce unexpected results (test changes.) + # Run vgscan after changing the filter to regenerate the cache. + # See the use_lvmetad comment for a special case regarding filters. + # + # Example + # Accept every block device: + # filter = [ "a|.*/|" ] + # Reject the cdrom drive: + # filter = [ "r|/dev/cdrom|" ] + # Work with just loopback devices, e.g. for testing: + # filter = [ "a|loop|", "r|.*|" ] + # Accept all loop devices and ide drives except hdc: + # filter = [ "a|loop|", "r|/dev/hdc|", "a|/dev/ide|", "r|.*|" ] + # Use anchors to be very specific: + # filter = [ "a|^/dev/hda8$|", "r|.*/|" ] + # + # This configuration option has an automatic default value. + # filter = [ "a|.*/|" ] + + # Configuration option devices/global_filter. + # Limit the block devices that are used by LVM system components. + # Because devices/filter may be overridden from the command line, it is + # not suitable for system-wide device filtering, e.g. udev and lvmetad. + # Use global_filter to hide devices from these LVM system components. + # The syntax is the same as devices/filter. Devices rejected by + # global_filter are not opened by LVM. + # This configuration option has an automatic default value. + # global_filter = [ "a|.*/|" ] + + # Configuration option devices/cache_dir. + # Directory in which to store the device cache file. + # The results of filtering are cached on disk to avoid rescanning dud + # devices (which can take a very long time). By default this cache is + # stored in a file named .cache. It is safe to delete this file; the + # tools regenerate it. If obtain_device_list_from_udev is enabled, the + # list of devices is obtained from udev and any existing .cache file + # is removed. + cache_dir = "@DEFAULT_SYS_DIR@/@DEFAULT_CACHE_SUBDIR@" + + # Configuration option devices/cache_file_prefix. + # A prefix used before the .cache file name. See devices/cache_dir. + cache_file_prefix = "" + + # Configuration option devices/write_cache_state. + # Enable/disable writing the cache file. See devices/cache_dir. + write_cache_state = 1 + + # Configuration option devices/types. + # List of additional acceptable block device types. + # These are of device type names from /proc/devices, followed by the + # maximum number of partitions. + # + # Example + # types = [ "fd", 16 ] + # + # This configuration option is advanced. + # This configuration option does not have a default value defined. + + # Configuration option devices/sysfs_scan. + # Restrict device scanning to block devices appearing in sysfs. + # This is a quick way of filtering out block devices that are not + # present on the system. sysfs must be part of the kernel and mounted.) + sysfs_scan = 1 + + # Configuration option devices/multipath_component_detection. + # Ignore devices that are components of DM multipath devices. + multipath_component_detection = 1 + + # Configuration option devices/md_component_detection. + # Ignore devices that are components of software RAID (md) devices. + md_component_detection = 1 + + # Configuration option devices/fw_raid_component_detection. + # Ignore devices that are components of firmware RAID devices. + # LVM must use an external_device_info_source other than none for this + # detection to execute. + fw_raid_component_detection = 0 + + # Configuration option devices/md_chunk_alignment. + # Align PV data blocks with md device's stripe-width. + # This applies if a PV is placed directly on an md device. + md_chunk_alignment = 1 + + # Configuration option devices/default_data_alignment. + # Default alignment of the start of a PV data area in MB. + # If set to 0, a value of 64KiB will be used. + # Set to 1 for 1MiB, 2 for 2MiB, etc. + # This configuration option has an automatic default value. + # default_data_alignment = 1 + + # Configuration option devices/data_alignment_detection. + # Detect PV data alignment based on sysfs device information. + # The start of a PV data area will be a multiple of minimum_io_size or + # optimal_io_size exposed in sysfs. minimum_io_size is the smallest + # request the device can perform without incurring a read-modify-write + # penalty, e.g. MD chunk size. optimal_io_size is the device's + # preferred unit of receiving I/O, e.g. MD stripe width. + # minimum_io_size is used if optimal_io_size is undefined (0). + # If md_chunk_alignment is enabled, that detects the optimal_io_size. + # This setting takes precedence over md_chunk_alignment. + data_alignment_detection = 1 + + # Configuration option devices/data_alignment. + # Alignment of the start of a PV data area in KiB. + # If a PV is placed directly on an md device and md_chunk_alignment or + # data_alignment_detection are enabled, then this setting is ignored. + # Otherwise, md_chunk_alignment and data_alignment_detection are + # disabled if this is set. Set to 0 to use the default alignment or the + # page size, if larger. + data_alignment = 0 + + # Configuration option devices/data_alignment_offset_detection. + # Detect PV data alignment offset based on sysfs device information. + # The start of a PV aligned data area will be shifted by the + # alignment_offset exposed in sysfs. This offset is often 0, but may + # be non-zero. Certain 4KiB sector drives that compensate for windows + # partitioning will have an alignment_offset of 3584 bytes (sector 7 + # is the lowest aligned logical block, the 4KiB sectors start at + # LBA -1, and consequently sector 63 is aligned on a 4KiB boundary). + # pvcreate --dataalignmentoffset will skip this detection. + data_alignment_offset_detection = 1 + + # Configuration option devices/ignore_suspended_devices. + # Ignore DM devices that have I/O suspended while scanning devices. + # Otherwise, LVM waits for a suspended device to become accessible. + # This should only be needed in recovery situations. + ignore_suspended_devices = 0 + + # Configuration option devices/ignore_lvm_mirrors. + # Do not scan 'mirror' LVs to avoid possible deadlocks. + # This avoids possible deadlocks when using the 'mirror' segment type. + # This setting determines whether LVs using the 'mirror' segment type + # are scanned for LVM labels. This affects the ability of mirrors to + # be used as physical volumes. If this setting is enabled, it is + # impossible to create VGs on top of mirror LVs, i.e. to stack VGs on + # mirror LVs. If this setting is disabled, allowing mirror LVs to be + # scanned, it may cause LVM processes and I/O to the mirror to become + # blocked. This is due to the way that the mirror segment type handles + # failures. In order for the hang to occur, an LVM command must be run + # just after a failure and before the automatic LVM repair process + # takes place, or there must be failures in multiple mirrors in the + # same VG at the same time with write failures occurring moments before + # a scan of the mirror's labels. The 'mirror' scanning problems do not + # apply to LVM RAID types like 'raid1' which handle failures in a + # different way, making them a better choice for VG stacking. + ignore_lvm_mirrors = 1 + + # Configuration option devices/disable_after_error_count. + # Number of I/O errors after which a device is skipped. + # During each LVM operation, errors received from each device are + # counted. If the counter of a device exceeds the limit set here, + # no further I/O is sent to that device for the remainder of the + # operation. Setting this to 0 disables the counters altogether. + disable_after_error_count = 0 + + # Configuration option devices/require_restorefile_with_uuid. + # Allow use of pvcreate --uuid without requiring --restorefile. + require_restorefile_with_uuid = 1 + + # Configuration option devices/pv_min_size. + # Minimum size in KiB of block devices which can be used as PVs. + # In a clustered environment all nodes must use the same value. + # Any value smaller than 512KiB is ignored. The previous built-in + # value was 512. + pv_min_size = 2048 + + # Configuration option devices/issue_discards. + # Issue discards to PVs that are no longer used by an LV. + # Discards are sent to an LV's underlying physical volumes when the LV + # is no longer using the physical volumes' space, e.g. lvremove, + # lvreduce. Discards inform the storage that a region is no longer + # used. Storage that supports discards advertise the protocol-specific + # way discards should be issued by the kernel (TRIM, UNMAP, or + # WRITE SAME with UNMAP bit set). Not all storage will support or + # benefit from discards, but SSDs and thinly provisioned LUNs + # generally do. If enabled, discards will only be issued if both the + # storage and kernel provide support. + issue_discards = 0 + + # Configuration option devices/allow_changes_with_duplicate_pvs. + # Allow VG modification while a PV appears on multiple devices. + # When a PV appears on multiple devices, LVM attempts to choose the + # best device to use for the PV. If the devices represent the same + # underlying storage, the choice has minimal consequence. If the + # devices represent different underlying storage, the wrong choice + # can result in data loss if the VG is modified. Disabling this + # setting is the safest option because it prevents modifying a VG + # or activating LVs in it while a PV appears on multiple devices. + # Enabling this setting allows the VG to be used as usual even with + # uncertain devices. + allow_changes_with_duplicate_pvs = 0 +} + +# Configuration section allocation. +# How LVM selects space and applies properties to LVs. +allocation { + + # Configuration option allocation/cling_tag_list. + # Advise LVM which PVs to use when searching for new space. + # When searching for free space to extend an LV, the 'cling' allocation + # policy will choose space on the same PVs as the last segment of the + # existing LV. If there is insufficient space and a list of tags is + # defined here, it will check whether any of them are attached to the + # PVs concerned and then seek to match those PV tags between existing + # extents and new extents. + # + # Example + # Use the special tag "@*" as a wildcard to match any PV tag: + # cling_tag_list = [ "@*" ] + # LVs are mirrored between two sites within a single VG, and + # PVs are tagged with either @site1 or @site2 to indicate where + # they are situated: + # cling_tag_list = [ "@site1", "@site2" ] + # + # This configuration option does not have a default value defined. + + # Configuration option allocation/maximise_cling. + # Use a previous allocation algorithm. + # Changes made in version 2.02.85 extended the reach of the 'cling' + # policies to detect more situations where data can be grouped onto + # the same disks. This setting can be used to disable the changes + # and revert to the previous algorithm. + maximise_cling = 1 + + # Configuration option allocation/use_blkid_wiping. + # Use blkid to detect existing signatures on new PVs and LVs. + # The blkid library can detect more signatures than the native LVM + # detection code, but may take longer. LVM needs to be compiled with + # blkid wiping support for this setting to apply. LVM native detection + # code is currently able to recognize: MD device signatures, + # swap signature, and LUKS signatures. To see the list of signatures + # recognized by blkid, check the output of the 'blkid -k' command. + use_blkid_wiping = @DEFAULT_USE_BLKID_WIPING@ + + # Configuration option allocation/wipe_signatures_when_zeroing_new_lvs. + # Look for and erase any signatures while zeroing a new LV. + # The --wipesignatures option overrides this setting. + # Zeroing is controlled by the -Z/--zero option, and if not specified, + # zeroing is used by default if possible. Zeroing simply overwrites the + # first 4KiB of a new LV with zeroes and does no signature detection or + # wiping. Signature wiping goes beyond zeroing and detects exact types + # and positions of signatures within the whole LV. It provides a + # cleaner LV after creation as all known signatures are wiped. The LV + # is not claimed incorrectly by other tools because of old signatures + # from previous use. The number of signatures that LVM can detect + # depends on the detection code that is selected (see + # use_blkid_wiping.) Wiping each detected signature must be confirmed. + # When this setting is disabled, signatures on new LVs are not detected + # or erased unless the --wipesignatures option is used directly. + wipe_signatures_when_zeroing_new_lvs = 1 + + # Configuration option allocation/mirror_logs_require_separate_pvs. + # Mirror logs and images will always use different PVs. + # The default setting changed in version 2.02.85. + mirror_logs_require_separate_pvs = 0 + + # Configuration option allocation/raid_stripe_all_devices. + # Stripe across all PVs when RAID stripes are not specified. + # If enabled, all PVs in the VG or on the command line are used for raid0/4/5/6/10 + # when the command does not specify the number of stripes to use. + # This was the default behaviour until release 2.02.162. + # This configuration option has an automatic default value. + # raid_stripe_all_devices = 0 + + # Configuration option allocation/cache_pool_metadata_require_separate_pvs. + # Cache pool metadata and data will always use different PVs. + cache_pool_metadata_require_separate_pvs = 0 + + # Configuration option allocation/cache_mode. + # The default cache mode used for new cache. + # + # Accepted values: + # writethrough + # Data blocks are immediately written from the cache to disk. + # writeback + # Data blocks are written from the cache back to disk after some + # delay to improve performance. + # + # This setting replaces allocation/cache_pool_cachemode. + # This configuration option has an automatic default value. + # cache_mode = "writethrough" + + # Configuration option allocation/cache_policy. + # The default cache policy used for new cache volume. + # Since kernel 4.2 the default policy is smq (Stochastic multique), + # otherwise the older mq (Multiqueue) policy is selected. + # This configuration option does not have a default value defined. + + # Configuration section allocation/cache_settings. + # Settings for the cache policy. + # See documentation for individual cache policies for more info. + # This configuration section has an automatic default value. + # cache_settings { + # } + + # Configuration option allocation/cache_pool_chunk_size. + # The minimal chunk size in KiB for cache pool volumes. + # Using a chunk_size that is too large can result in wasteful use of + # the cache, where small reads and writes can cause large sections of + # an LV to be mapped into the cache. However, choosing a chunk_size + # that is too small can result in more overhead trying to manage the + # numerous chunks that become mapped into the cache. The former is + # more of a problem than the latter in most cases, so the default is + # on the smaller end of the spectrum. Supported values range from + # 32KiB to 1GiB in multiples of 32. + # This configuration option does not have a default value defined. + + # Configuration option allocation/thin_pool_metadata_require_separate_pvs. + # Thin pool metdata and data will always use different PVs. + thin_pool_metadata_require_separate_pvs = 0 + + # Configuration option allocation/thin_pool_zero. + # Thin pool data chunks are zeroed before they are first used. + # Zeroing with a larger thin pool chunk size reduces performance. + # This configuration option has an automatic default value. + # thin_pool_zero = 1 + + # Configuration option allocation/thin_pool_discards. + # The discards behaviour of thin pool volumes. + # + # Accepted values: + # ignore + # nopassdown + # passdown + # + # This configuration option has an automatic default value. + # thin_pool_discards = "passdown" + + # Configuration option allocation/thin_pool_chunk_size_policy. + # The chunk size calculation policy for thin pool volumes. + # + # Accepted values: + # generic + # If thin_pool_chunk_size is defined, use it. Otherwise, calculate + # the chunk size based on estimation and device hints exposed in + # sysfs - the minimum_io_size. The chunk size is always at least + # 64KiB. + # performance + # If thin_pool_chunk_size is defined, use it. Otherwise, calculate + # the chunk size for performance based on device hints exposed in + # sysfs - the optimal_io_size. The chunk size is always at least + # 512KiB. + # + # This configuration option has an automatic default value. + # thin_pool_chunk_size_policy = "generic" + + # Configuration option allocation/thin_pool_chunk_size. + # The minimal chunk size in KiB for thin pool volumes. + # Larger chunk sizes may improve performance for plain thin volumes, + # however using them for snapshot volumes is less efficient, as it + # consumes more space and takes extra time for copying. When unset, + # lvm tries to estimate chunk size starting from 64KiB. Supported + # values are in the range 64KiB to 1GiB. + # This configuration option does not have a default value defined. + + # Configuration option allocation/physical_extent_size. + # Default physical extent size in KiB to use for new VGs. + # This configuration option has an automatic default value. + # physical_extent_size = 4096 +} + +# Configuration section log. +# How LVM log information is reported. +log { + + # Configuration option log/report_command_log. + # Enable or disable LVM log reporting. + # If enabled, LVM will collect a log of operations, messages, + # per-object return codes with object identification and associated + # error numbers (errnos) during LVM command processing. Then the + # log is either reported solely or in addition to any existing + # reports, depending on LVM command used. If it is a reporting command + # (e.g. pvs, vgs, lvs, lvm fullreport), then the log is reported in + # addition to any existing reports. Otherwise, there's only log report + # on output. For all applicable LVM commands, you can request that + # the output has only log report by using --logonly command line + # option. Use log/command_log_cols and log/command_log_sort settings + # to define fields to display and sort fields for the log report. + # You can also use log/command_log_selection to define selection + # criteria used each time the log is reported. + # This configuration option has an automatic default value. + # report_command_log = 0 + + # Configuration option log/command_log_sort. + # List of columns to sort by when reporting command log. + # See <lvm command> --logonly --configreport log -o help + # for the list of possible fields. + # This configuration option has an automatic default value. + # command_log_sort = "log_seq_num" + + # Configuration option log/command_log_cols. + # List of columns to report when reporting command log. + # See <lvm command> --logonly --configreport log -o help + # for the list of possible fields. + # This configuration option has an automatic default value. + # command_log_cols = "log_seq_num,log_type,log_context,log_object_type,log_object_name,log_object_id,log_object_group,log_object_group_id,log_message,log_errno,log_ret_code" + + # Configuration option log/command_log_selection. + # Selection criteria used when reporting command log. + # You can define selection criteria that are applied each + # time log is reported. This way, it is possible to control the + # amount of log that is displayed on output and you can select + # only parts of the log that are important for you. To define + # selection criteria, use fields from log report. See also + # <lvm command> --logonly --configreport log -S help for the + # list of possible fields and selection operators. You can also + # define selection criteria for log report on command line directly + # using <lvm command> --configreport log -S <selection criteria> + # which has precedence over log/command_log_selection setting. + # For more information about selection criteria in general, see + # lvm(8) man page. + # This configuration option has an automatic default value. + # command_log_selection = "!(log_type=status && message=success)" + + # Configuration option log/verbose. + # Controls the messages sent to stdout or stderr. + verbose = 0 + + # Configuration option log/silent. + # Suppress all non-essential messages from stdout. + # This has the same effect as -qq. When enabled, the following commands + # still produce output: dumpconfig, lvdisplay, lvmdiskscan, lvs, pvck, + # pvdisplay, pvs, version, vgcfgrestore -l, vgdisplay, vgs. + # Non-essential messages are shifted from log level 4 to log level 5 + # for syslog and lvm2_log_fn purposes. + # Any 'yes' or 'no' questions not overridden by other arguments are + # suppressed and default to 'no'. + silent = 0 + + # Configuration option log/syslog. + # Send log messages through syslog. + syslog = 1 + + # Configuration option log/file. + # Write error and debug log messages to a file specified here. + # This configuration option does not have a default value defined. + + # Configuration option log/overwrite. + # Overwrite the log file each time the program is run. + overwrite = 0 + + # Configuration option log/level. + # The level of log messages that are sent to the log file or syslog. + # There are 6 syslog-like log levels currently in use: 2 to 7 inclusive. + # 7 is the most verbose (LOG_DEBUG). + level = 0 + + # Configuration option log/indent. + # Indent messages according to their severity. + indent = 1 + + # Configuration option log/command_names. + # Display the command name on each line of output. + command_names = 0 + + # Configuration option log/prefix. + # A prefix to use before the log message text. + # (After the command name, if selected). + # Two spaces allows you to see/grep the severity of each message. + # To make the messages look similar to the original LVM tools use: + # indent = 0, command_names = 1, prefix = " -- " + prefix = " " + + # Configuration option log/activation. + # Log messages during activation. + # Don't use this in low memory situations (can deadlock). + activation = 0 + + # Configuration option log/debug_classes. + # Select log messages by class. + # Some debugging messages are assigned to a class and only appear in + # debug output if the class is listed here. Classes currently + # available: memory, devices, activation, allocation, lvmetad, + # metadata, cache, locking, lvmpolld. Use "all" to see everything. + debug_classes = [ "memory", "devices", "activation", "allocation", "lvmetad", "metadata", "cache", "locking", "lvmpolld", "dbus" ] +} + +# Configuration section backup. +# How LVM metadata is backed up and archived. +# In LVM, a 'backup' is a copy of the metadata for the current system, +# and an 'archive' contains old metadata configurations. They are +# stored in a human readable text format. +backup { + + # Configuration option backup/backup. + # Maintain a backup of the current metadata configuration. + # Think very hard before turning this off! + backup = 1 + + # Configuration option backup/backup_dir. + # Location of the metadata backup files. + # Remember to back up this directory regularly! + backup_dir = "@DEFAULT_SYS_DIR@/@DEFAULT_BACKUP_SUBDIR@" + + # Configuration option backup/archive. + # Maintain an archive of old metadata configurations. + # Think very hard before turning this off. + archive = 1 + + # Configuration option backup/archive_dir. + # Location of the metdata archive files. + # Remember to back up this directory regularly! + archive_dir = "@DEFAULT_SYS_DIR@/@DEFAULT_ARCHIVE_SUBDIR@" + + # Configuration option backup/retain_min. + # Minimum number of archives to keep. + retain_min = 10 + + # Configuration option backup/retain_days. + # Minimum number of days to keep archive files. + retain_days = 30 +} + +# Configuration section shell. +# Settings for running LVM in shell (readline) mode. +shell { + + # Configuration option shell/history_size. + # Number of lines of history to store in ~/.lvm_history. + history_size = 100 +} + +# Configuration section global. +# Miscellaneous global LVM settings. +global { + + # Configuration option global/umask. + # The file creation mask for any files and directories created. + # Interpreted as octal if the first digit is zero. + umask = 077 + + # Configuration option global/test. + # No on-disk metadata changes will be made in test mode. + # Equivalent to having the -t option on every command. + test = 0 + + # Configuration option global/units. + # Default value for --units argument. + units = "h" + + # Configuration option global/si_unit_consistency. + # Distinguish between powers of 1024 and 1000 bytes. + # The LVM commands distinguish between powers of 1024 bytes, + # e.g. KiB, MiB, GiB, and powers of 1000 bytes, e.g. KB, MB, GB. + # If scripts depend on the old behaviour, disable this setting + # temporarily until they are updated. + si_unit_consistency = 1 + + # Configuration option global/suffix. + # Display unit suffix for sizes. + # This setting has no effect if the units are in human-readable form + # (global/units = "h") in which case the suffix is always displayed. + suffix = 1 + + # Configuration option global/activation. + # Enable/disable communication with the kernel device-mapper. + # Disable to use the tools to manipulate LVM metadata without + # activating any logical volumes. If the device-mapper driver + # is not present in the kernel, disabling this should suppress + # the error messages. + activation = 1 + + # Configuration option global/fallback_to_lvm1. + # Try running LVM1 tools if LVM cannot communicate with DM. + # This option only applies to 2.4 kernels and is provided to help + # switch between device-mapper kernels and LVM1 kernels. The LVM1 + # tools need to be installed with .lvm1 suffices, e.g. vgscan.lvm1. + # They will stop working once the lvm2 on-disk metadata format is used. + # This configuration option has an automatic default value. + # fallback_to_lvm1 = @DEFAULT_FALLBACK_TO_LVM1@ + + # Configuration option global/format. + # The default metadata format that commands should use. + # The -M 1|2 option overrides this setting. + # + # Accepted values: + # lvm1 + # lvm2 + # + # This configuration option has an automatic default value. + # format = "lvm2" + + # Configuration option global/format_libraries. + # Shared libraries that process different metadata formats. + # If support for LVM1 metadata was compiled as a shared library use + # format_libraries = "liblvm2format1.so" + # This configuration option does not have a default value defined. + + # Configuration option global/segment_libraries. + # This configuration option does not have a default value defined. + + # Configuration option global/proc. + # Location of proc filesystem. + # This configuration option is advanced. + proc = "/proc" + + # Configuration option global/etc. + # Location of /etc system configuration directory. + etc = "@CONFDIR@" + + # Configuration option global/locking_type. + # Type of locking to use. + # + # Accepted values: + # 0 + # Turns off locking. Warning: this risks metadata corruption if + # commands run concurrently. + # 1 + # LVM uses local file-based locking, the standard mode. + # 2 + # LVM uses the external shared library locking_library. + # 3 + # LVM uses built-in clustered locking with clvmd. + # This is incompatible with lvmetad. If use_lvmetad is enabled, + # LVM prints a warning and disables lvmetad use. + # 4 + # LVM uses read-only locking which forbids any operations that + # might change metadata. + # 5 + # Offers dummy locking for tools that do not need any locks. + # You should not need to set this directly; the tools will select + # when to use it instead of the configured locking_type. + # Do not use lvmetad or the kernel device-mapper driver with this + # locking type. It is used by the --readonly option that offers + # read-only access to Volume Group metadata that cannot be locked + # safely because it belongs to an inaccessible domain and might be + # in use, for example a virtual machine image or a disk that is + # shared by a clustered machine. + # + locking_type = 1 + + # Configuration option global/wait_for_locks. + # When disabled, fail if a lock request would block. + wait_for_locks = 1 + + # Configuration option global/fallback_to_clustered_locking. + # Attempt to use built-in cluster locking if locking_type 2 fails. + # If using external locking (type 2) and initialisation fails, with + # this enabled, an attempt will be made to use the built-in clustered + # locking. Disable this if using a customised locking_library. + fallback_to_clustered_locking = 1 + + # Configuration option global/fallback_to_local_locking. + # Use locking_type 1 (local) if locking_type 2 or 3 fail. + # If an attempt to initialise type 2 or type 3 locking failed, perhaps + # because cluster components such as clvmd are not running, with this + # enabled, an attempt will be made to use local file-based locking + # (type 1). If this succeeds, only commands against local VGs will + # proceed. VGs marked as clustered will be ignored. + fallback_to_local_locking = 1 + + # Configuration option global/locking_dir. + # Directory to use for LVM command file locks. + # Local non-LV directory that holds file-based locks while commands are + # in progress. A directory like /tmp that may get wiped on reboot is OK. + locking_dir = "@DEFAULT_LOCK_DIR@" + + # Configuration option global/prioritise_write_locks. + # Allow quicker VG write access during high volume read access. + # When there are competing read-only and read-write access requests for + # a volume group's metadata, instead of always granting the read-only + # requests immediately, delay them to allow the read-write requests to + # be serviced. Without this setting, write access may be stalled by a + # high volume of read-only requests. This option only affects + # locking_type 1 viz. local file-based locking. + prioritise_write_locks = 1 + + # Configuration option global/library_dir. + # Search this directory first for shared libraries. + # This configuration option does not have a default value defined. + + # Configuration option global/locking_library. + # The external locking library to use for locking_type 2. + # This configuration option has an automatic default value. + # locking_library = "liblvm2clusterlock.so" + + # Configuration option global/abort_on_internal_errors. + # Abort a command that encounters an internal error. + # Treat any internal errors as fatal errors, aborting the process that + # encountered the internal error. Please only enable for debugging. + abort_on_internal_errors = 0 + + # Configuration option global/detect_internal_vg_cache_corruption. + # Internal verification of VG structures. + # Check if CRC matches when a parsed VG is used multiple times. This + # is useful to catch unexpected changes to cached VG structures. + # Please only enable for debugging. + detect_internal_vg_cache_corruption = 0 + + # Configuration option global/metadata_read_only. + # No operations that change on-disk metadata are permitted. + # Additionally, read-only commands that encounter metadata in need of + # repair will still be allowed to proceed exactly as if the repair had + # been performed (except for the unchanged vg_seqno). Inappropriate + # use could mess up your system, so seek advice first! + metadata_read_only = 0 + + # Configuration option global/mirror_segtype_default. + # The segment type used by the short mirroring option -m. + # The --type mirror|raid1 option overrides this setting. + # + # Accepted values: + # mirror + # The original RAID1 implementation from LVM/DM. It is + # characterized by a flexible log solution (core, disk, mirrored), + # and by the necessity to block I/O while handling a failure. + # There is an inherent race in the dmeventd failure handling logic + # with snapshots of devices using this type of RAID1 that in the + # worst case could cause a deadlock. (Also see + # devices/ignore_lvm_mirrors.) + # raid1 + # This is a newer RAID1 implementation using the MD RAID1 + # personality through device-mapper. It is characterized by a + # lack of log options. (A log is always allocated for every + # device and they are placed on the same device as the image, + # so no separate devices are required.) This mirror + # implementation does not require I/O to be blocked while + # handling a failure. This mirror implementation is not + # cluster-aware and cannot be used in a shared (active/active) + # fashion in a cluster. + # + mirror_segtype_default = "@DEFAULT_MIRROR_SEGTYPE@" + + # Configuration option global/raid10_segtype_default. + # The segment type used by the -i -m combination. + # The --type raid10|mirror option overrides this setting. + # The --stripes/-i and --mirrors/-m options can both be specified + # during the creation of a logical volume to use both striping and + # mirroring for the LV. There are two different implementations. + # + # Accepted values: + # raid10 + # LVM uses MD's RAID10 personality through DM. This is the + # preferred option. + # mirror + # LVM layers the 'mirror' and 'stripe' segment types. The layering + # is done by creating a mirror LV on top of striped sub-LVs, + # effectively creating a RAID 0+1 array. The layering is suboptimal + # in terms of providing redundancy and performance. + # + raid10_segtype_default = "@DEFAULT_RAID10_SEGTYPE@" + + # Configuration option global/sparse_segtype_default. + # The segment type used by the -V -L combination. + # The --type snapshot|thin option overrides this setting. + # The combination of -V and -L options creates a sparse LV. There are + # two different implementations. + # + # Accepted values: + # snapshot + # The original snapshot implementation from LVM/DM. It uses an old + # snapshot that mixes data and metadata within a single COW + # storage volume and performs poorly when the size of stored data + # passes hundreds of MB. + # thin + # A newer implementation that uses thin provisioning. It has a + # bigger minimal chunk size (64KiB) and uses a separate volume for + # metadata. It has better performance, especially when more data + # is used. It also supports full snapshots. + # + sparse_segtype_default = "@DEFAULT_SPARSE_SEGTYPE@" + + # Configuration option global/lvdisplay_shows_full_device_path. + # Enable this to reinstate the previous lvdisplay name format. + # The default format for displaying LV names in lvdisplay was changed + # in version 2.02.89 to show the LV name and path separately. + # Previously this was always shown as /dev/vgname/lvname even when that + # was never a valid path in the /dev filesystem. + # This configuration option has an automatic default value. + # lvdisplay_shows_full_device_path = 0 + + # Configuration option global/use_lvmetad. + # Use lvmetad to cache metadata and reduce disk scanning. + # When enabled (and running), lvmetad provides LVM commands with VG + # metadata and PV state. LVM commands then avoid reading this + # information from disks which can be slow. When disabled (or not + # running), LVM commands fall back to scanning disks to obtain VG + # metadata. lvmetad is kept updated via udev rules which must be set + # up for LVM to work correctly. (The udev rules should be installed + # by default.) Without a proper udev setup, changes in the system's + # block device configuration will be unknown to LVM, and ignored + # until a manual 'pvscan --cache' is run. If lvmetad was running + # while use_lvmetad was disabled, it must be stopped, use_lvmetad + # enabled, and then started. When using lvmetad, LV activation is + # switched to an automatic, event-based mode. In this mode, LVs are + # activated based on incoming udev events that inform lvmetad when + # PVs appear on the system. When a VG is complete (all PVs present), + # it is auto-activated. The auto_activation_volume_list setting + # controls which LVs are auto-activated (all by default.) + # When lvmetad is updated (automatically by udev events, or directly + # by pvscan --cache), devices/filter is ignored and all devices are + # scanned by default. lvmetad always keeps unfiltered information + # which is provided to LVM commands. Each LVM command then filters + # based on devices/filter. This does not apply to other, non-regexp, + # filtering settings: component filters such as multipath and MD + # are checked during pvscan --cache. To filter a device and prevent + # scanning from the LVM system entirely, including lvmetad, use + # devices/global_filter. + use_lvmetad = @DEFAULT_USE_LVMETAD@ + + # Configuration option global/lvmetad_update_wait_time. + # The number of seconds a command will wait for lvmetad update to finish. + # After waiting for this period, a command will not use lvmetad, and + # will revert to disk scanning. + # This configuration option has an automatic default value. + # lvmetad_update_wait_time = 10 + + # Configuration option global/use_lvmlockd. + # Use lvmlockd for locking among hosts using LVM on shared storage. + # Applicable only if LVM is compiled with lockd support in which + # case there is also lvmlockd(8) man page available for more + # information. + use_lvmlockd = 0 + + # Configuration option global/lvmlockd_lock_retries. + # Retry lvmlockd lock requests this many times. + # Applicable only if LVM is compiled with lockd support + # This configuration option has an automatic default value. + # lvmlockd_lock_retries = 3 + + # Configuration option global/sanlock_lv_extend. + # Size in MiB to extend the internal LV holding sanlock locks. + # The internal LV holds locks for each LV in the VG, and after enough + # LVs have been created, the internal LV needs to be extended. lvcreate + # will automatically extend the internal LV when needed by the amount + # specified here. Setting this to 0 disables the automatic extension + # and can cause lvcreate to fail. Applicable only if LVM is compiled + # with lockd support + # This configuration option has an automatic default value. + # sanlock_lv_extend = 256 + + # Configuration option global/thin_check_executable. + # The full path to the thin_check command. + # LVM uses this command to check that a thin metadata device is in a + # usable state. When a thin pool is activated and after it is + # deactivated, this command is run. Activation will only proceed if + # the command has an exit status of 0. Set to "" to skip this check. + # (Not recommended.) Also see thin_check_options. + # (See package device-mapper-persistent-data or thin-provisioning-tools) + # This configuration option has an automatic default value. + # thin_check_executable = "@THIN_CHECK_CMD@" + + # Configuration option global/thin_dump_executable. + # The full path to the thin_dump command. + # LVM uses this command to dump thin pool metadata. + # (See package device-mapper-persistent-data or thin-provisioning-tools) + # This configuration option has an automatic default value. + # thin_dump_executable = "@THIN_DUMP_CMD@" + + # Configuration option global/thin_repair_executable. + # The full path to the thin_repair command. + # LVM uses this command to repair a thin metadata device if it is in + # an unusable state. Also see thin_repair_options. + # (See package device-mapper-persistent-data or thin-provisioning-tools) + # This configuration option has an automatic default value. + # thin_repair_executable = "@THIN_REPAIR_CMD@" + + # Configuration option global/thin_check_options. + # List of options passed to the thin_check command. + # With thin_check version 2.1 or newer you can add the option + # --ignore-non-fatal-errors to let it pass through ignorable errors + # and fix them later. With thin_check version 3.2 or newer you should + # include the option --clear-needs-check-flag. + # This configuration option has an automatic default value. + # thin_check_options = [ "-q", "--clear-needs-check-flag" ] + + # Configuration option global/thin_repair_options. + # List of options passed to the thin_repair command. + # This configuration option has an automatic default value. + # thin_repair_options = [ "" ] + + # Configuration option global/thin_disabled_features. + # Features to not use in the thin driver. + # This can be helpful for testing, or to avoid using a feature that is + # causing problems. Features include: block_size, discards, + # discards_non_power_2, external_origin, metadata_resize, + # external_origin_extend, error_if_no_space. + # + # Example + # thin_disabled_features = [ "discards", "block_size" ] + # + # This configuration option does not have a default value defined. + + # Configuration option global/cache_disabled_features. + # Features to not use in the cache driver. + # This can be helpful for testing, or to avoid using a feature that is + # causing problems. Features include: policy_mq, policy_smq. + # + # Example + # cache_disabled_features = [ "policy_smq" ] + # + # This configuration option does not have a default value defined. + + # Configuration option global/cache_check_executable. + # The full path to the cache_check command. + # LVM uses this command to check that a cache metadata device is in a + # usable state. When a cached LV is activated and after it is + # deactivated, this command is run. Activation will only proceed if the + # command has an exit status of 0. Set to "" to skip this check. + # (Not recommended.) Also see cache_check_options. + # (See package device-mapper-persistent-data or thin-provisioning-tools) + # This configuration option has an automatic default value. + # cache_check_executable = "@CACHE_CHECK_CMD@" + + # Configuration option global/cache_dump_executable. + # The full path to the cache_dump command. + # LVM uses this command to dump cache pool metadata. + # (See package device-mapper-persistent-data or thin-provisioning-tools) + # This configuration option has an automatic default value. + # cache_dump_executable = "@CACHE_DUMP_CMD@" + + # Configuration option global/cache_repair_executable. + # The full path to the cache_repair command. + # LVM uses this command to repair a cache metadata device if it is in + # an unusable state. Also see cache_repair_options. + # (See package device-mapper-persistent-data or thin-provisioning-tools) + # This configuration option has an automatic default value. + # cache_repair_executable = "@CACHE_REPAIR_CMD@" + + # Configuration option global/cache_check_options. + # List of options passed to the cache_check command. + # With cache_check version 5.0 or newer you should include the option + # --clear-needs-check-flag. + # This configuration option has an automatic default value. + # cache_check_options = [ "-q", "--clear-needs-check-flag" ] + + # Configuration option global/cache_repair_options. + # List of options passed to the cache_repair command. + # This configuration option has an automatic default value. + # cache_repair_options = [ "" ] + + # Configuration option global/system_id_source. + # The method LVM uses to set the local system ID. + # Volume Groups can also be given a system ID (by vgcreate, vgchange, + # or vgimport.) A VG on shared storage devices is accessible only to + # the host with a matching system ID. See 'man lvmsystemid' for + # information on limitations and correct usage. + # + # Accepted values: + # none + # The host has no system ID. + # lvmlocal + # Obtain the system ID from the system_id setting in the 'local' + # section of an lvm configuration file, e.g. lvmlocal.conf. + # uname + # Set the system ID from the hostname (uname) of the system. + # System IDs beginning localhost are not permitted. + # machineid + # Use the contents of the machine-id file to set the system ID. + # Some systems create this file at installation time. + # See 'man machine-id' and global/etc. + # file + # Use the contents of another file (system_id_file) to set the + # system ID. + # + system_id_source = "none" + + # Configuration option global/system_id_file. + # The full path to the file containing a system ID. + # This is used when system_id_source is set to 'file'. + # Comments starting with the character # are ignored. + # This configuration option does not have a default value defined. + + # Configuration option global/use_lvmpolld. + # Use lvmpolld to supervise long running LVM commands. + # When enabled, control of long running LVM commands is transferred + # from the original LVM command to the lvmpolld daemon. This allows + # the operation to continue independent of the original LVM command. + # After lvmpolld takes over, the LVM command displays the progress + # of the ongoing operation. lvmpolld itself runs LVM commands to + # manage the progress of ongoing operations. lvmpolld can be used as + # a native systemd service, which allows it to be started on demand, + # and to use its own control group. When this option is disabled, LVM + # commands will supervise long running operations by forking themselves. + # Applicable only if LVM is compiled with lvmpolld support. + use_lvmpolld = @DEFAULT_USE_LVMPOLLD@ + + # Configuration option global/notify_dbus. + # Enable D-Bus notification from LVM commands. + # When enabled, an LVM command that changes PVs, changes VG metadata, + # or changes the activation state of an LV will send a notification. + notify_dbus = 1 +} + +# Configuration section activation. +activation { + + # Configuration option activation/checks. + # Perform internal checks of libdevmapper operations. + # Useful for debugging problems with activation. Some of the checks may + # be expensive, so it's best to use this only when there seems to be a + # problem. + checks = 0 + + # Configuration option activation/udev_sync. + # Use udev notifications to synchronize udev and LVM. + # The --nodevsync option overrides this setting. + # When disabled, LVM commands will not wait for notifications from + # udev, but continue irrespective of any possible udev processing in + # the background. Only use this if udev is not running or has rules + # that ignore the devices LVM creates. If enabled when udev is not + # running, and LVM processes are waiting for udev, run the command + # 'dmsetup udevcomplete_all' to wake them up. + udev_sync = 1 + + # Configuration option activation/udev_rules. + # Use udev rules to manage LV device nodes and symlinks. + # When disabled, LVM will manage the device nodes and symlinks for + # active LVs itself. Manual intervention may be required if this + # setting is changed while LVs are active. + udev_rules = 1 + + # Configuration option activation/verify_udev_operations. + # Use extra checks in LVM to verify udev operations. + # This enables additional checks (and if necessary, repairs) on entries + # in the device directory after udev has completed processing its + # events. Useful for diagnosing problems with LVM/udev interactions. + verify_udev_operations = 0 + + # Configuration option activation/retry_deactivation. + # Retry failed LV deactivation. + # If LV deactivation fails, LVM will retry for a few seconds before + # failing. This may happen because a process run from a quick udev rule + # temporarily opened the device. + retry_deactivation = 1 + + # Configuration option activation/missing_stripe_filler. + # Method to fill missing stripes when activating an incomplete LV. + # Using 'error' will make inaccessible parts of the device return I/O + # errors on access. You can instead use a device path, in which case, + # that device will be used in place of missing stripes. Using anything + # other than 'error' with mirrored or snapshotted volumes is likely to + # result in data corruption. + # This configuration option is advanced. + missing_stripe_filler = "error" + + # Configuration option activation/use_linear_target. + # Use the linear target to optimize single stripe LVs. + # When disabled, the striped target is used. The linear target is an + # optimised version of the striped target that only handles a single + # stripe. + use_linear_target = 1 + + # Configuration option activation/reserved_stack. + # Stack size in KiB to reserve for use while devices are suspended. + # Insufficent reserve risks I/O deadlock during device suspension. + reserved_stack = 64 + + # Configuration option activation/reserved_memory. + # Memory size in KiB to reserve for use while devices are suspended. + # Insufficent reserve risks I/O deadlock during device suspension. + reserved_memory = 8192 + + # Configuration option activation/process_priority. + # Nice value used while devices are suspended. + # Use a high priority so that LVs are suspended + # for the shortest possible time. + process_priority = -18 + + # Configuration option activation/volume_list. + # Only LVs selected by this list are activated. + # If this list is defined, an LV is only activated if it matches an + # entry in this list. If this list is undefined, it imposes no limits + # on LV activation (all are allowed). + # + # Accepted values: + # vgname + # The VG name is matched exactly and selects all LVs in the VG. + # vgname/lvname + # The VG name and LV name are matched exactly and selects the LV. + # @tag + # Selects an LV if the specified tag matches a tag set on the LV + # or VG. + # @* + # Selects an LV if a tag defined on the host is also set on the LV + # or VG. See tags/hosttags. If any host tags exist but volume_list + # is not defined, a default single-entry list containing '@*' + # is assumed. + # + # Example + # volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ] + # + # This configuration option does not have a default value defined. + + # Configuration option activation/auto_activation_volume_list. + # Only LVs selected by this list are auto-activated. + # This list works like volume_list, but it is used only by + # auto-activation commands. It does not apply to direct activation + # commands. If this list is defined, an LV is only auto-activated + # if it matches an entry in this list. If this list is undefined, it + # imposes no limits on LV auto-activation (all are allowed.) If this + # list is defined and empty, i.e. "[]", then no LVs are selected for + # auto-activation. An LV that is selected by this list for + # auto-activation, must also be selected by volume_list (if defined) + # before it is activated. Auto-activation is an activation command that + # includes the 'a' argument: --activate ay or -a ay. The 'a' (auto) + # argument for auto-activation is meant to be used by activation + # commands that are run automatically by the system, as opposed to LVM + # commands run directly by a user. A user may also use the 'a' flag + # directly to perform auto-activation. Also see pvscan(8) for more + # information about auto-activation. + # + # Accepted values: + # vgname + # The VG name is matched exactly and selects all LVs in the VG. + # vgname/lvname + # The VG name and LV name are matched exactly and selects the LV. + # @tag + # Selects an LV if the specified tag matches a tag set on the LV + # or VG. + # @* + # Selects an LV if a tag defined on the host is also set on the LV + # or VG. See tags/hosttags. If any host tags exist but volume_list + # is not defined, a default single-entry list containing '@*' + # is assumed. + # + # Example + # auto_activation_volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ] + # + # This configuration option does not have a default value defined. + + # Configuration option activation/read_only_volume_list. + # LVs in this list are activated in read-only mode. + # If this list is defined, each LV that is to be activated is checked + # against this list, and if it matches, it is activated in read-only + # mode. This overrides the permission setting stored in the metadata, + # e.g. from --permission rw. + # + # Accepted values: + # vgname + # The VG name is matched exactly and selects all LVs in the VG. + # vgname/lvname + # The VG name and LV name are matched exactly and selects the LV. + # @tag + # Selects an LV if the specified tag matches a tag set on the LV + # or VG. + # @* + # Selects an LV if a tag defined on the host is also set on the LV + # or VG. See tags/hosttags. If any host tags exist but volume_list + # is not defined, a default single-entry list containing '@*' + # is assumed. + # + # Example + # read_only_volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ] + # + # This configuration option does not have a default value defined. + + # Configuration option activation/raid_region_size. + # Size in KiB of each raid or mirror synchronization region. + # For raid or mirror segment types, this is the amount of data that is + # copied at once when initializing, or moved at once by pvmove. + raid_region_size = 512 + + # Configuration option activation/error_when_full. + # Return errors if a thin pool runs out of space. + # The --errorwhenfull option overrides this setting. + # When enabled, writes to thin LVs immediately return an error if the + # thin pool is out of data space. When disabled, writes to thin LVs + # are queued if the thin pool is out of space, and processed when the + # thin pool data space is extended. New thin pools are assigned the + # behavior defined here. + # This configuration option has an automatic default value. + # error_when_full = 0 + + # Configuration option activation/readahead. + # Setting to use when there is no readahead setting in metadata. + # + # Accepted values: + # none + # Disable readahead. + # auto + # Use default value chosen by kernel. + # + readahead = "auto" + + # Configuration option activation/raid_fault_policy. + # Defines how a device failure in a RAID LV is handled. + # This includes LVs that have the following segment types: + # raid1, raid4, raid5*, and raid6*. + # If a device in the LV fails, the policy determines the steps + # performed by dmeventd automatically, and the steps perfomed by the + # manual command lvconvert --repair --use-policies. + # Automatic handling requires dmeventd to be monitoring the LV. + # + # Accepted values: + # warn + # Use the system log to warn the user that a device in the RAID LV + # has failed. It is left to the user to run lvconvert --repair + # manually to remove or replace the failed device. As long as the + # number of failed devices does not exceed the redundancy of the LV + # (1 device for raid4/5, 2 for raid6), the LV will remain usable. + # allocate + # Attempt to use any extra physical volumes in the VG as spares and + # replace faulty devices. + # + raid_fault_policy = "warn" + + # Configuration option activation/mirror_image_fault_policy. + # Defines how a device failure in a 'mirror' LV is handled. + # An LV with the 'mirror' segment type is composed of mirror images + # (copies) and a mirror log. A disk log ensures that a mirror LV does + # not need to be re-synced (all copies made the same) every time a + # machine reboots or crashes. If a device in the LV fails, this policy + # determines the steps perfomed by dmeventd automatically, and the steps + # performed by the manual command lvconvert --repair --use-policies. + # Automatic handling requires dmeventd to be monitoring the LV. + # + # Accepted values: + # remove + # Simply remove the faulty device and run without it. If the log + # device fails, the mirror would convert to using an in-memory log. + # This means the mirror will not remember its sync status across + # crashes/reboots and the entire mirror will be re-synced. If a + # mirror image fails, the mirror will convert to a non-mirrored + # device if there is only one remaining good copy. + # allocate + # Remove the faulty device and try to allocate space on a new + # device to be a replacement for the failed device. Using this + # policy for the log is fast and maintains the ability to remember + # sync state through crashes/reboots. Using this policy for a + # mirror device is slow, as it requires the mirror to resynchronize + # the devices, but it will preserve the mirror characteristic of + # the device. This policy acts like 'remove' if no suitable device + # and space can be allocated for the replacement. + # allocate_anywhere + # Not yet implemented. Useful to place the log device temporarily + # on the same physical volume as one of the mirror images. This + # policy is not recommended for mirror devices since it would break + # the redundant nature of the mirror. This policy acts like + # 'remove' if no suitable device and space can be allocated for the + # replacement. + # + mirror_image_fault_policy = "remove" + + # Configuration option activation/mirror_log_fault_policy. + # Defines how a device failure in a 'mirror' log LV is handled. + # The mirror_image_fault_policy description for mirrored LVs also + # applies to mirrored log LVs. + mirror_log_fault_policy = "allocate" + + # Configuration option activation/snapshot_autoextend_threshold. + # Auto-extend a snapshot when its usage exceeds this percent. + # Setting this to 100 disables automatic extension. + # The minimum value is 50 (a smaller value is treated as 50.) + # Also see snapshot_autoextend_percent. + # Automatic extension requires dmeventd to be monitoring the LV. + # + # Example + # Using 70% autoextend threshold and 20% autoextend size, when a 1G + # snapshot exceeds 700M, it is extended to 1.2G, and when it exceeds + # 840M, it is extended to 1.44G: + # snapshot_autoextend_threshold = 70 + # + snapshot_autoextend_threshold = 100 + + # Configuration option activation/snapshot_autoextend_percent. + # Auto-extending a snapshot adds this percent extra space. + # The amount of additional space added to a snapshot is this + # percent of its current size. + # + # Example + # Using 70% autoextend threshold and 20% autoextend size, when a 1G + # snapshot exceeds 700M, it is extended to 1.2G, and when it exceeds + # 840M, it is extended to 1.44G: + # snapshot_autoextend_percent = 20 + # + snapshot_autoextend_percent = 20 + + # Configuration option activation/thin_pool_autoextend_threshold. + # Auto-extend a thin pool when its usage exceeds this percent. + # Setting this to 100 disables automatic extension. + # The minimum value is 50 (a smaller value is treated as 50.) + # Also see thin_pool_autoextend_percent. + # Automatic extension requires dmeventd to be monitoring the LV. + # + # Example + # Using 70% autoextend threshold and 20% autoextend size, when a 1G + # thin pool exceeds 700M, it is extended to 1.2G, and when it exceeds + # 840M, it is extended to 1.44G: + # thin_pool_autoextend_threshold = 70 + # + thin_pool_autoextend_threshold = 100 + + # Configuration option activation/thin_pool_autoextend_percent. + # Auto-extending a thin pool adds this percent extra space. + # The amount of additional space added to a thin pool is this + # percent of its current size. + # + # Example + # Using 70% autoextend threshold and 20% autoextend size, when a 1G + # thin pool exceeds 700M, it is extended to 1.2G, and when it exceeds + # 840M, it is extended to 1.44G: + # thin_pool_autoextend_percent = 20 + # + thin_pool_autoextend_percent = 20 + + # Configuration option activation/mlock_filter. + # Do not mlock these memory areas. + # While activating devices, I/O to devices being (re)configured is + # suspended. As a precaution against deadlocks, LVM pins memory it is + # using so it is not paged out, and will not require I/O to reread. + # Groups of pages that are known not to be accessed during activation + # do not need to be pinned into memory. Each string listed in this + # setting is compared against each line in /proc/self/maps, and the + # pages corresponding to lines that match are not pinned. On some + # systems, locale-archive was found to make up over 80% of the memory + # used by the process. + # + # Example + # mlock_filter = [ "locale/locale-archive", "gconv/gconv-modules.cache" ] + # + # This configuration option is advanced. + # This configuration option does not have a default value defined. + + # Configuration option activation/use_mlockall. + # Use the old behavior of mlockall to pin all memory. + # Prior to version 2.02.62, LVM used mlockall() to pin the whole + # process's memory while activating devices. + use_mlockall = 0 + + # Configuration option activation/monitoring. + # Monitor LVs that are activated. + # The --ignoremonitoring option overrides this setting. + # When enabled, LVM will ask dmeventd to monitor activated LVs. + monitoring = 1 + + # Configuration option activation/polling_interval. + # Check pvmove or lvconvert progress at this interval (seconds). + # When pvmove or lvconvert must wait for the kernel to finish + # synchronising or merging data, they check and report progress at + # intervals of this number of seconds. If this is set to 0 and there + # is only one thing to wait for, there are no progress reports, but + # the process is awoken immediately once the operation is complete. + polling_interval = 15 + + # Configuration option activation/auto_set_activation_skip. + # Set the activation skip flag on new thin snapshot LVs. + # The --setactivationskip option overrides this setting. + # An LV can have a persistent 'activation skip' flag. The flag causes + # the LV to be skipped during normal activation. The lvchange/vgchange + # -K option is required to activate LVs that have the activation skip + # flag set. When this setting is enabled, the activation skip flag is + # set on new thin snapshot LVs. + # This configuration option has an automatic default value. + # auto_set_activation_skip = 1 + + # Configuration option activation/activation_mode. + # How LVs with missing devices are activated. + # The --activationmode option overrides this setting. + # + # Accepted values: + # complete + # Only allow activation of an LV if all of the Physical Volumes it + # uses are present. Other PVs in the Volume Group may be missing. + # degraded + # Like complete, but additionally RAID LVs of segment type raid1, + # raid4, raid5, radid6 and raid10 will be activated if there is no + # data loss, i.e. they have sufficient redundancy to present the + # entire addressable range of the Logical Volume. + # partial + # Allows the activation of any LV even if a missing or failed PV + # could cause data loss with a portion of the LV inaccessible. + # This setting should not normally be used, but may sometimes + # assist with data recovery. + # + activation_mode = "degraded" + + # Configuration option activation/lock_start_list. + # Locking is started only for VGs selected by this list. + # The rules are the same as those for volume_list. + # This configuration option does not have a default value defined. + + # Configuration option activation/auto_lock_start_list. + # Locking is auto-started only for VGs selected by this list. + # The rules are the same as those for auto_activation_volume_list. + # This configuration option does not have a default value defined. +} + +# Configuration section metadata. +# This configuration section has an automatic default value. +# metadata { + + # Configuration option metadata/check_pv_device_sizes. + # Check device sizes are not smaller than corresponding PV sizes. + # If device size is less than corresponding PV size found in metadata, + # there is always a risk of data loss. If this option is set, then LVM + # issues a warning message each time it finds that the device size is + # less than corresponding PV size. You should not disable this unless + # you are absolutely sure about what you are doing! + # This configuration option is advanced. + # This configuration option has an automatic default value. + # check_pv_device_sizes = 1 + + # Configuration option metadata/record_lvs_history. + # When enabled, LVM keeps history records about removed LVs in + # metadata. The information that is recorded in metadata for + # historical LVs is reduced when compared to original + # information kept in metadata for live LVs. Currently, this + # feature is supported for thin and thin snapshot LVs only. + # This configuration option has an automatic default value. + # record_lvs_history = 0 + + # Configuration option metadata/lvs_history_retention_time. + # Retention time in seconds after which a record about individual + # historical logical volume is automatically destroyed. + # A value of 0 disables this feature. + # This configuration option has an automatic default value. + # lvs_history_retention_time = 0 + + # Configuration option metadata/pvmetadatacopies. + # Number of copies of metadata to store on each PV. + # The --pvmetadatacopies option overrides this setting. + # + # Accepted values: + # 2 + # Two copies of the VG metadata are stored on the PV, one at the + # front of the PV, and one at the end. + # 1 + # One copy of VG metadata is stored at the front of the PV. + # 0 + # No copies of VG metadata are stored on the PV. This may be + # useful for VGs containing large numbers of PVs. + # + # This configuration option is advanced. + # This configuration option has an automatic default value. + # pvmetadatacopies = 1 + + # Configuration option metadata/vgmetadatacopies. + # Number of copies of metadata to maintain for each VG. + # The --vgmetadatacopies option overrides this setting. + # If set to a non-zero value, LVM automatically chooses which of the + # available metadata areas to use to achieve the requested number of + # copies of the VG metadata. If you set a value larger than the the + # total number of metadata areas available, then metadata is stored in + # them all. The value 0 (unmanaged) disables this automatic management + # and allows you to control which metadata areas are used at the + # individual PV level using pvchange --metadataignore y|n. + # This configuration option has an automatic default value. + # vgmetadatacopies = 0 + + # Configuration option metadata/pvmetadatasize. + # Approximate number of sectors to use for each metadata copy. + # VGs with large numbers of PVs or LVs, or VGs containing complex LV + # structures, may need additional space for VG metadata. The metadata + # areas are treated as circular buffers, so unused space becomes filled + # with an archive of the most recent previous versions of the metadata. + # This configuration option has an automatic default value. + # pvmetadatasize = 255 + + # Configuration option metadata/pvmetadataignore. + # Ignore metadata areas on a new PV. + # The --metadataignore option overrides this setting. + # If metadata areas on a PV are ignored, LVM will not store metadata + # in them. + # This configuration option is advanced. + # This configuration option has an automatic default value. + # pvmetadataignore = 0 + + # Configuration option metadata/stripesize. + # This configuration option is advanced. + # This configuration option has an automatic default value. + # stripesize = 64 + + # Configuration option metadata/dirs. + # Directories holding live copies of text format metadata. + # These directories must not be on logical volumes! + # It's possible to use LVM with a couple of directories here, + # preferably on different (non-LV) filesystems, and with no other + # on-disk metadata (pvmetadatacopies = 0). Or this can be in addition + # to on-disk metadata areas. The feature was originally added to + # simplify testing and is not supported under low memory situations - + # the machine could lock up. Never edit any files in these directories + # by hand unless you are absolutely sure you know what you are doing! + # Use the supplied toolset to make changes (e.g. vgcfgrestore). + # + # Example + # dirs = [ "/etc/lvm/metadata", "/mnt/disk2/lvm/metadata2" ] + # + # This configuration option is advanced. + # This configuration option does not have a default value defined. +# } + +# Configuration section report. +# LVM report command output formatting. +# This configuration section has an automatic default value. +# report { + + # Configuration option report/output_format. + # Format of LVM command's report output. + # If there is more than one report per command, then the format + # is applied for all reports. You can also change output format + # directly on command line using --reportformat option which + # has precedence over log/output_format setting. + # Accepted values: + # basic + # Original format with columns and rows. If there is more than + # one report per command, each report is prefixed with report's + # name for identification. + # json + # JSON format. + # This configuration option has an automatic default value. + # output_format = "basic" + + # Configuration option report/compact_output. + # Do not print empty values for all report fields. + # If enabled, all fields that don't have a value set for any of the + # rows reported are skipped and not printed. Compact output is + # applicable only if report/buffered is enabled. If you need to + # compact only specified fields, use compact_output=0 and define + # report/compact_output_cols configuration setting instead. + # This configuration option has an automatic default value. + # compact_output = 0 + + # Configuration option report/compact_output_cols. + # Do not print empty values for specified report fields. + # If defined, specified fields that don't have a value set for any + # of the rows reported are skipped and not printed. Compact output + # is applicable only if report/buffered is enabled. If you need to + # compact all fields, use compact_output=1 instead in which case + # the compact_output_cols setting is then ignored. + # This configuration option has an automatic default value. + # compact_output_cols = "" + + # Configuration option report/aligned. + # Align columns in report output. + # This configuration option has an automatic default value. + # aligned = 1 + + # Configuration option report/buffered. + # Buffer report output. + # When buffered reporting is used, the report's content is appended + # incrementally to include each object being reported until the report + # is flushed to output which normally happens at the end of command + # execution. Otherwise, if buffering is not used, each object is + # reported as soon as its processing is finished. + # This configuration option has an automatic default value. + # buffered = 1 + + # Configuration option report/headings. + # Show headings for columns on report. + # This configuration option has an automatic default value. + # headings = 1 + + # Configuration option report/separator. + # A separator to use on report after each field. + # This configuration option has an automatic default value. + # separator = " " + + # Configuration option report/list_item_separator. + # A separator to use for list items when reported. + # This configuration option has an automatic default value. + # list_item_separator = "," + + # Configuration option report/prefixes. + # Use a field name prefix for each field reported. + # This configuration option has an automatic default value. + # prefixes = 0 + + # Configuration option report/quoted. + # Quote field values when using field name prefixes. + # This configuration option has an automatic default value. + # quoted = 1 + + # Configuration option report/colums_as_rows. + # Output each column as a row. + # If set, this also implies report/prefixes=1. + # This configuration option has an automatic default value. + # colums_as_rows = 0 + + # Configuration option report/binary_values_as_numeric. + # Use binary values 0 or 1 instead of descriptive literal values. + # For columns that have exactly two valid values to report + # (not counting the 'unknown' value which denotes that the + # value could not be determined). + # This configuration option has an automatic default value. + # binary_values_as_numeric = 0 + + # Configuration option report/time_format. + # Set time format for fields reporting time values. + # Format specification is a string which may contain special character + # sequences and ordinary character sequences. Ordinary character + # sequences are copied verbatim. Each special character sequence is + # introduced by the '%' character and such sequence is then + # substituted with a value as described below. + # + # Accepted values: + # %a + # The abbreviated name of the day of the week according to the + # current locale. + # %A + # The full name of the day of the week according to the current + # locale. + # %b + # The abbreviated month name according to the current locale. + # %B + # The full month name according to the current locale. + # %c + # The preferred date and time representation for the current + # locale (alt E) + # %C + # The century number (year/100) as a 2-digit integer. (alt E) + # %d + # The day of the month as a decimal number (range 01 to 31). + # (alt O) + # %D + # Equivalent to %m/%d/%y. (For Americans only. Americans should + # note that in other countries%d/%m/%y is rather common. This + # means that in international context this format is ambiguous and + # should not be used. + # %e + # Like %d, the day of the month as a decimal number, but a leading + # zero is replaced by a space. (alt O) + # %E + # Modifier: use alternative local-dependent representation if + # available. + # %F + # Equivalent to %Y-%m-%d (the ISO 8601 date format). + # %G + # The ISO 8601 week-based year with century as adecimal number. + # The 4-digit year corresponding to the ISO week number (see %V). + # This has the same format and value as %Y, except that if the + # ISO week number belongs to the previous or next year, that year + # is used instead. + # %g + # Like %G, but without century, that is, with a 2-digit year + # (00-99). + # %h + # Equivalent to %b. + # %H + # The hour as a decimal number using a 24-hour clock + # (range 00 to 23). (alt O) + # %I + # The hour as a decimal number using a 12-hour clock + # (range 01 to 12). (alt O) + # %j + # The day of the year as a decimal number (range 001 to 366). + # %k + # The hour (24-hour clock) as a decimal number (range 0 to 23); + # single digits are preceded by a blank. (See also %H.) + # %l + # The hour (12-hour clock) as a decimal number (range 1 to 12); + # single digits are preceded by a blank. (See also %I.) + # %m + # The month as a decimal number (range 01 to 12). (alt O) + # %M + # The minute as a decimal number (range 00 to 59). (alt O) + # %O + # Modifier: use alternative numeric symbols. + # %p + # Either "AM" or "PM" according to the given time value, + # or the corresponding strings for the current locale. Noon is + # treated as "PM" and midnight as "AM". + # %P + # Like %p but in lowercase: "am" or "pm" or a corresponding + # string for the current locale. + # %r + # The time in a.m. or p.m. notation. In the POSIX locale this is + # equivalent to %I:%M:%S %p. + # %R + # The time in 24-hour notation (%H:%M). For a version including + # the seconds, see %T below. + # %s + # The number of seconds since the Epoch, + # 1970-01-01 00:00:00 +0000 (UTC) + # %S + # The second as a decimal number (range 00 to 60). (The range is + # up to 60 to allow for occasional leap seconds.) (alt O) + # %t + # A tab character. + # %T + # The time in 24-hour notation (%H:%M:%S). + # %u + # The day of the week as a decimal, range 1 to 7, Monday being 1. + # See also %w. (alt O) + # %U + # The week number of the current year as a decimal number, + # range 00 to 53, starting with the first Sunday as the first + # day of week 01. See also %V and %W. (alt O) + # %V + # The ISO 8601 week number of the current year as a decimal number, + # range 01 to 53, where week 1 is the first week that has at least + # 4 days in the new year. See also %U and %W. (alt O) + # %w + # The day of the week as a decimal, range 0 to 6, Sunday being 0. + # See also %u. (alt O) + # %W + # The week number of the current year as a decimal number, + # range 00 to 53, starting with the first Monday as the first day + # of week 01. (alt O) + # %x + # The preferred date representation for the current locale without + # the time. (alt E) + # %X + # The preferred time representation for the current locale without + # the date. (alt E) + # %y + # The year as a decimal number without a century (range 00 to 99). + # (alt E, alt O) + # %Y + # The year as a decimal number including the century. (alt E) + # %z + # The +hhmm or -hhmm numeric timezone (that is, the hour and minute + # offset from UTC). + # %Z + # The timezone name or abbreviation. + # %% + # A literal '%' character. + # + # This configuration option has an automatic default value. + # time_format = "%Y-%m-%d %T %z" + + # Configuration option report/devtypes_sort. + # List of columns to sort by when reporting 'lvm devtypes' command. + # See 'lvm devtypes -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # devtypes_sort = "devtype_name" + + # Configuration option report/devtypes_cols. + # List of columns to report for 'lvm devtypes' command. + # See 'lvm devtypes -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # devtypes_cols = "devtype_name,devtype_max_partitions,devtype_description" + + # Configuration option report/devtypes_cols_verbose. + # List of columns to report for 'lvm devtypes' command in verbose mode. + # See 'lvm devtypes -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # devtypes_cols_verbose = "devtype_name,devtype_max_partitions,devtype_description" + + # Configuration option report/lvs_sort. + # List of columns to sort by when reporting 'lvs' command. + # See 'lvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # lvs_sort = "vg_name,lv_name" + + # Configuration option report/lvs_cols. + # List of columns to report for 'lvs' command. + # See 'lvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # lvs_cols = "lv_name,vg_name,lv_attr,lv_size,pool_lv,origin,data_percent,metadata_percent,move_pv,mirror_log,copy_percent,convert_lv" + + # Configuration option report/lvs_cols_verbose. + # List of columns to report for 'lvs' command in verbose mode. + # See 'lvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # lvs_cols_verbose = "lv_name,vg_name,seg_count,lv_attr,lv_size,lv_major,lv_minor,lv_kernel_major,lv_kernel_minor,pool_lv,origin,data_percent,metadata_percent,move_pv,copy_percent,mirror_log,convert_lv,lv_uuid,lv_profile" + + # Configuration option report/vgs_sort. + # List of columns to sort by when reporting 'vgs' command. + # See 'vgs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # vgs_sort = "vg_name" + + # Configuration option report/vgs_cols. + # List of columns to report for 'vgs' command. + # See 'vgs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # vgs_cols = "vg_name,pv_count,lv_count,snap_count,vg_attr,vg_size,vg_free" + + # Configuration option report/vgs_cols_verbose. + # List of columns to report for 'vgs' command in verbose mode. + # See 'vgs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # vgs_cols_verbose = "vg_name,vg_attr,vg_extent_size,pv_count,lv_count,snap_count,vg_size,vg_free,vg_uuid,vg_profile" + + # Configuration option report/pvs_sort. + # List of columns to sort by when reporting 'pvs' command. + # See 'pvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvs_sort = "pv_name" + + # Configuration option report/pvs_cols. + # List of columns to report for 'pvs' command. + # See 'pvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvs_cols = "pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free" + + # Configuration option report/pvs_cols_verbose. + # List of columns to report for 'pvs' command in verbose mode. + # See 'pvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvs_cols_verbose = "pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,dev_size,pv_uuid" + + # Configuration option report/segs_sort. + # List of columns to sort by when reporting 'lvs --segments' command. + # See 'lvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # segs_sort = "vg_name,lv_name,seg_start" + + # Configuration option report/segs_cols. + # List of columns to report for 'lvs --segments' command. + # See 'lvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # segs_cols = "lv_name,vg_name,lv_attr,stripes,segtype,seg_size" + + # Configuration option report/segs_cols_verbose. + # List of columns to report for 'lvs --segments' command in verbose mode. + # See 'lvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # segs_cols_verbose = "lv_name,vg_name,lv_attr,seg_start,seg_size,stripes,segtype,stripesize,chunksize" + + # Configuration option report/pvsegs_sort. + # List of columns to sort by when reporting 'pvs --segments' command. + # See 'pvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvsegs_sort = "pv_name,pvseg_start" + + # Configuration option report/pvsegs_cols. + # List of columns to sort by when reporting 'pvs --segments' command. + # See 'pvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvsegs_cols = "pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,pvseg_start,pvseg_size" + + # Configuration option report/pvsegs_cols_verbose. + # List of columns to sort by when reporting 'pvs --segments' command in verbose mode. + # See 'pvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvsegs_cols_verbose = "pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,pvseg_start,pvseg_size,lv_name,seg_start_pe,segtype,seg_pe_ranges" + + # Configuration option report/vgs_cols_full. + # List of columns to report for lvm fullreport's 'vgs' subreport. + # See 'vgs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # vgs_cols_full = "vg_all" + + # Configuration option report/pvs_cols_full. + # List of columns to report for lvm fullreport's 'vgs' subreport. + # See 'pvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvs_cols_full = "pv_all" + + # Configuration option report/lvs_cols_full. + # List of columns to report for lvm fullreport's 'lvs' subreport. + # See 'lvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # lvs_cols_full = "lv_all" + + # Configuration option report/pvsegs_cols_full. + # List of columns to report for lvm fullreport's 'pvseg' subreport. + # See 'pvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvsegs_cols_full = "pvseg_all,pv_uuid,lv_uuid" + + # Configuration option report/segs_cols_full. + # List of columns to report for lvm fullreport's 'seg' subreport. + # See 'lvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # segs_cols_full = "seg_all,lv_uuid" + + # Configuration option report/vgs_sort_full. + # List of columns to sort by when reporting lvm fullreport's 'vgs' subreport. + # See 'vgs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # vgs_sort_full = "vg_name" + + # Configuration option report/pvs_sort_full. + # List of columns to sort by when reporting lvm fullreport's 'vgs' subreport. + # See 'pvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvs_sort_full = "pv_name" + + # Configuration option report/lvs_sort_full. + # List of columns to sort by when reporting lvm fullreport's 'lvs' subreport. + # See 'lvs -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # lvs_sort_full = "vg_name,lv_name" + + # Configuration option report/pvsegs_sort_full. + # List of columns to sort by when reporting for lvm fullreport's 'pvseg' subreport. + # See 'pvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # pvsegs_sort_full = "pv_uuid,pvseg_start" + + # Configuration option report/segs_sort_full. + # List of columns to sort by when reporting lvm fullreport's 'seg' subreport. + # See 'lvs --segments -o help' for the list of possible fields. + # This configuration option has an automatic default value. + # segs_sort_full = "lv_uuid,seg_start" + + # Configuration option report/mark_hidden_devices. + # Use brackets [] to mark hidden devices. + # This configuration option has an automatic default value. + # mark_hidden_devices = 1 + + # Configuration option report/two_word_unknown_device. + # Use the two words 'unknown device' in place of '[unknown]'. + # This is displayed when the device for a PV is not known. + # This configuration option has an automatic default value. + # two_word_unknown_device = 0 +# } + +# Configuration section dmeventd. +# Settings for the LVM event daemon. +dmeventd { + + # Configuration option dmeventd/mirror_library. + # The library dmeventd uses when monitoring a mirror device. + # libdevmapper-event-lvm2mirror.so attempts to recover from + # failures. It removes failed devices from a volume group and + # reconfigures a mirror as necessary. If no mirror library is + # provided, mirrors are not monitored through dmeventd. + mirror_library = "libdevmapper-event-lvm2mirror.so" + + # Configuration option dmeventd/raid_library. + # This configuration option has an automatic default value. + # raid_library = "libdevmapper-event-lvm2raid.so" + + # Configuration option dmeventd/snapshot_library. + # The library dmeventd uses when monitoring a snapshot device. + # libdevmapper-event-lvm2snapshot.so monitors the filling of snapshots + # and emits a warning through syslog when the usage exceeds 80%. The + # warning is repeated when 85%, 90% and 95% of the snapshot is filled. + snapshot_library = "libdevmapper-event-lvm2snapshot.so" + + # Configuration option dmeventd/thin_library. + # The library dmeventd uses when monitoring a thin device. + # libdevmapper-event-lvm2thin.so monitors the filling of a pool + # and emits a warning through syslog when the usage exceeds 80%. The + # warning is repeated when 85%, 90% and 95% of the pool is filled. + thin_library = "libdevmapper-event-lvm2thin.so" + + # Configuration option dmeventd/executable. + # The full path to the dmeventd binary. + # This configuration option has an automatic default value. + # executable = "@DMEVENTD_PATH@" +} + +# Configuration section tags. +# Host tag settings. +# This configuration section has an automatic default value. +# tags { + + # Configuration option tags/hosttags. + # Create a host tag using the machine name. + # The machine name is nodename returned by uname(2). + # This configuration option has an automatic default value. + # hosttags = 0 + + # Configuration section tags/<tag>. + # Replace this subsection name with a custom tag name. + # Multiple subsections like this can be created. The '@' prefix for + # tags is optional. This subsection can contain host_list, which is a + # list of machine names. If the name of the local machine is found in + # host_list, then the name of this subsection is used as a tag and is + # applied to the local machine as a 'host tag'. If this subsection is + # empty (has no host_list), then the subsection name is always applied + # as a 'host tag'. + # + # Example + # The host tag foo is given to all hosts, and the host tag + # bar is given to the hosts named machine1 and machine2. + # tags { foo { } bar { host_list = [ "machine1", "machine2" ] } } + # + # This configuration section has variable name. + # This configuration section has an automatic default value. + # tag { + + # Configuration option tags/<tag>/host_list. + # A list of machine names. + # These machine names are compared to the nodename returned + # by uname(2). If the local machine name matches an entry in + # this list, the name of the subsection is applied to the + # machine as a 'host tag'. + # This configuration option does not have a default value defined. + # } +# }
diff --git a/conf/lvmlocal.conf.base b/conf/lvmlocal.conf.base new file mode 100644 index 0000000..e2a9e2f --- /dev/null +++ b/conf/lvmlocal.conf.base
@@ -0,0 +1,19 @@ +# This is a local configuration file template for the LVM2 system +# which should be installed as @DEFAULT_SYS_DIR@/lvmlocal.conf . +# +# Refer to 'man lvm.conf' for information about the file layout. +# +# To put this file in a different directory and override +# @DEFAULT_SYS_DIR@ set the environment variable LVM_SYSTEM_DIR before +# running the tools. +# +# The lvmlocal.conf file is normally expected to contain only the +# "local" section which contains settings that should not be shared or +# repeated among different hosts. (But if other sections are present, +# they *will* get processed. Settings in this file override equivalent +# ones in lvm.conf and are in turn overridden by ones in any enabled +# lvm_<tag>.conf files.) +# +# Please take care that each setting only appears once if uncommenting +# example settings in this file and never copy this file between hosts. +
diff --git a/conf/lvmlocal.conf.in b/conf/lvmlocal.conf.in new file mode 100644 index 0000000..04414bf --- /dev/null +++ b/conf/lvmlocal.conf.in
@@ -0,0 +1,57 @@ +# This is a local configuration file template for the LVM2 system +# which should be installed as @DEFAULT_SYS_DIR@/lvmlocal.conf . +# +# Refer to 'man lvm.conf' for information about the file layout. +# +# To put this file in a different directory and override +# @DEFAULT_SYS_DIR@ set the environment variable LVM_SYSTEM_DIR before +# running the tools. +# +# The lvmlocal.conf file is normally expected to contain only the +# "local" section which contains settings that should not be shared or +# repeated among different hosts. (But if other sections are present, +# they *will* get processed. Settings in this file override equivalent +# ones in lvm.conf and are in turn overridden by ones in any enabled +# lvm_<tag>.conf files.) +# +# Please take care that each setting only appears once if uncommenting +# example settings in this file and never copy this file between hosts. + + +# Configuration section local. +# LVM settings that are specific to the local host. +local { + + # Configuration option local/system_id. + # Defines the local system ID for lvmlocal mode. + # This is used when global/system_id_source is set to 'lvmlocal' in the + # main configuration file, e.g. lvm.conf. When used, it must be set to + # a unique value among all hosts sharing access to the storage, + # e.g. a host name. + # + # Example + # Set no system ID: + # system_id = "" + # Set the system_id to a specific name: + # system_id = "host1" + # + # This configuration option has an automatic default value. + # system_id = "" + + # Configuration option local/extra_system_ids. + # A list of extra VG system IDs the local host can access. + # VGs with the system IDs listed here (in addition to the host's own + # system ID) can be fully accessed by the local host. (These are + # system IDs that the host sees in VGs, not system IDs that identify + # the local host, which is determined by system_id_source.) + # Use this only after consulting 'man lvmsystemid' to be certain of + # correct usage and possible dangers. + # This configuration option does not have a default value defined. + + # Configuration option local/host_id. + # The lvmlockd sanlock host_id. + # This must be unique among all hosts, and must be between 1 and 2000. + # Applicable only if LVM is compiled with lockd support + # This configuration option has an automatic default value. + # host_id = 0 +}
diff --git a/conf/metadata_profile_template.profile.in b/conf/metadata_profile_template.profile.in new file mode 100644 index 0000000..b08d32c --- /dev/null +++ b/conf/metadata_profile_template.profile.in
@@ -0,0 +1,24 @@ +# This is a metadata profile template for the LVM2 system. +# +# It contains all configuration settings that are customizable by metadata +# profiles. To create a new metadata profile, select the settings you want +# to customize and add them in a new file named <profile_name>.profile. +# Then install the new profile in a directory as defined by config/profile_dir +# setting found in @DEFAULT_SYS_DIR@/lvm.conf file. +# +# Metadata profiles can be referenced by using the --metadataprofile LVM2 +# command line option. +# +# Refer to 'man lvm.conf' for further information about profiles and +# general configuration file layout. +# +allocation { + thin_pool_zero=1 + thin_pool_discards="passdown" + thin_pool_chunk_size_policy="generic" +# thin_pool_chunk_size=128 +} +activation { + thin_pool_autoextend_threshold=100 + thin_pool_autoextend_percent=20 +}
diff --git a/conf/thin-generic.profile b/conf/thin-generic.profile new file mode 100644 index 0000000..229a7fc --- /dev/null +++ b/conf/thin-generic.profile
@@ -0,0 +1,4 @@ +allocation { + thin_pool_chunk_size_policy = "generic" + thin_pool_zero = 1 +}
diff --git a/conf/thin-performance.profile b/conf/thin-performance.profile new file mode 100644 index 0000000..2914de2 --- /dev/null +++ b/conf/thin-performance.profile
@@ -0,0 +1,4 @@ +allocation { + thin_pool_chunk_size_policy = "performance" + thin_pool_zero = 0 +}
diff --git a/configure b/configure new file mode 100755 index 0000000..8253bfc --- /dev/null +++ b/configure
@@ -0,0 +1,16732 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.69. +# +# +# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +# Use a proper internal environment variable to ensure we don't fall + # into an infinite loop, continuously re-executing ourselves. + if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then + _as_can_reexec=no; export _as_can_reexec; + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +as_fn_exit 255 + fi + # We don't want this to propagate to other subprocesses. + { _as_can_reexec=; unset _as_can_reexec;} +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1 +test -x / || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes +else + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : + +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi + done;; + esac + as_found=false +done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } +IFS=$as_save_IFS + + + if test "x$CONFIG_SHELL" != x; then : + export CONFIG_SHELL + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, +$0: including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # If we had to re-execute with $CONFIG_SHELL, we're ensured to have + # already done that, so ensure we don't try to do so again and fall + # in an infinite loop. This has already happened in practice. + _as_can_reexec=no; export _as_can_reexec + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +test -n "$DJDIR" || exec 7<&0 </dev/null +exec 6>&1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME= +PACKAGE_TARNAME= +PACKAGE_VERSION= +PACKAGE_STRING= +PACKAGE_BUGREPORT= +PACKAGE_URL= + +ac_unique_file="lib/device/dev-cache.h" +# Factoring default headers for most tests. +ac_includes_default="\ +#include <stdio.h> +#ifdef HAVE_SYS_TYPES_H +# include <sys/types.h> +#endif +#ifdef HAVE_SYS_STAT_H +# include <sys/stat.h> +#endif +#ifdef STDC_HEADERS +# include <stdlib.h> +# include <stddef.h> +#else +# ifdef HAVE_STDLIB_H +# include <stdlib.h> +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include <memory.h> +# endif +# include <string.h> +#endif +#ifdef HAVE_STRINGS_H +# include <strings.h> +#endif +#ifdef HAVE_INTTYPES_H +# include <inttypes.h> +#endif +#ifdef HAVE_STDINT_H +# include <stdint.h> +#endif +#ifdef HAVE_UNISTD_H +# include <unistd.h> +#endif" + +ac_header_list= +ac_func_list= +ac_default_prefix=/usr +ac_subst_vars='LTLIBOBJS +usrsbindir +usrlibdir +tmpfilesdir +systemdutildir +systemdsystemunitdir +udevdir +udev_prefix +tmpdir +kernelvsn +missingkernel +kerneldir +interface +CMIRRORD_PIDFILE +CLVMD_PIDFILE +LVMLOCKD_PIDFILE +LVMPOLLD_PIDFILE +LVMETAD_PIDFILE +DMEVENTD_PIDFILE +WRITE_INSTALL +VALGRIND_POOL +USE_TRACKING +UDEV_HAS_BUILTIN_BLKID +UDEV_RULE_EXEC_DETECTION +UDEV_SYSTEMD_BACKGROUND_JOBS +UDEV_SYNC +UDEV_RULES +UDEV_PC +THIN +TESTSUITE_DATA +TESTING +STATIC_LINK +STATICDIR +SNAPSHOTS +SELINUX_PC +SELINUX_LIBS +REPLICATORS +READLINE_LIBS +RT_LIB +RAID +PYTHON3DIR +PYTHON2DIR +PYTHON3_LIBDIRS +PYTHON2_LIBDIRS +PYTHON3_INCDIRS +PYTHON2_INCDIRS +PYTHON3_BINDINGS +PYTHON2_BINDINGS +PYTHON_BINDINGS +PYTHON3 +PTHREAD_LIBS +M_LIBS +POOL +PKGCONFIG +OCFDIR +OCF +MIRRORS +MANGLING +LVM_RELEASE_DATE +LVM_RELEASE +LVM_PATH +LVM_PATCHLEVEL +LVM_MINOR +LVM_MAJOR +LVM_LIBAPI +LVM_VERSION +LVM1_FALLBACK +LVM1 +LIB_SUFFIX +LDDEPS +JOBS +INTL +HAVE_VALGRIND +HAVE_REALTIME +HAVE_LIBDL +BLKDEACTIVATE +FSADM +ELDFLAGS +DM_LIB_PATCHLEVEL +DMEVENTD_PATH +DMEVENTD +DL_LIBS +DEVMAPPER +DEFAULT_USE_LVMLOCKD +DEFAULT_USE_LVMPOLLD +DEFAULT_USE_LVMETAD +DEFAULT_USE_BLKID_WIPING +DEFAULT_SYS_DIR +DEFAULT_SPARSE_SEGTYPE +DEFAULT_RUN_DIR +DEFAULT_RAID10_SEGTYPE +DEFAULT_PROFILE_SUBDIR +DEFAULT_PID_DIR +DEFAULT_MIRROR_SEGTYPE +DEFAULT_FALLBACK_TO_LVM1 +DEFAULT_LOCK_DIR +DEFAULT_DM_RUN_DIR +DEFAULT_DATA_ALIGNMENT +DEFAULT_CACHE_SUBDIR +DEFAULT_BACKUP_SUBDIR +DEFAULT_ARCHIVE_SUBDIR +DEBUG +COPTIMISE_FLAG +CONFDIR +CMDLIB +CLVMD_PATH +CLVMD_CMANAGERS +CLVMD +CLUSTER +CLDWHOLEARCHIVE +CLDNOWHOLEARCHIVE +CLDFLAGS +CACHE +BUILD_NOTIFYDBUS +BUILD_LOCKDDLM +BUILD_LOCKDSANLOCK +BUILD_LVMLOCKD +BUILD_LVMPOLLD +BUILD_LVMETAD +BUILD_LVMDBUSD +BUILD_DMEVENTD +BUILD_CMIRRORD +BLKID_PC +APPLIB +MODPROBE_CMD +MSGFMT +PYTHON3_CONFIG +PYTHON2_CONFIG +PYTHON2 +pkgpyexecdir +pyexecdir +pkgpythondir +pythondir +PYTHON_PLATFORM +PYTHON_EXEC_PREFIX +PYTHON_PREFIX +PYTHON_VERSION +PYTHON +LVM2CMD_LIB +LVM2APP_LIB +UDEV_LIBS +UDEV_CFLAGS +SYSTEMD_LIBS +SYSTEMD_CFLAGS +BLKID_LIBS +BLKID_CFLAGS +NOTIFY_DBUS_LIBS +NOTIFY_DBUS_CFLAGS +LOCKD_DLM_LIBS +LOCKD_DLM_CFLAGS +LOCKD_SANLOCK_LIBS +LOCKD_SANLOCK_CFLAGS +VALGRIND_LIBS +VALGRIND_CFLAGS +CUNIT_LIBS +CUNIT_CFLAGS +GENPNG +GENHTML +LCOV +HAVE_WSYNCNAND +HAVE_WCLOBBERED +HAVE_WJUMP +SACKPT_LIBS +SACKPT_CFLAGS +DLM_LIBS +DLM_CFLAGS +CPG_LIBS +CPG_CFLAGS +CMAP_LIBS +CMAP_CFLAGS +CONFDB_LIBS +CONFDB_CFLAGS +SALCK_LIBS +SALCK_CFLAGS +QUORUM_LIBS +QUORUM_CFLAGS +COROSYNC_LIBS +COROSYNC_CFLAGS +CMAN_LIBS +CMAN_CFLAGS +PKGCONFIGINIT_LIBS +PKGCONFIGINIT_CFLAGS +PKG_CONFIG_LIBDIR +PKG_CONFIG_PATH +PKG_CONFIG +CACHE_RESTORE_CMD +CACHE_REPAIR_CMD +CACHE_DUMP_CMD +CACHE_CHECK_CMD +THIN_RESTORE_CMD +THIN_REPAIR_CMD +THIN_DUMP_CMD +THIN_CHECK_CMD +HAVE_FULL_RELRO +HAVE_PIE +POW_LIB +LIBOBJS +ALLOCA +CHMOD +CSCOPE_CMD +CFLOW_CMD +RANLIB +MKDIR_P +SET_MAKE +LN_S +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +EGREP +GREP +CPP +ac_ct_CXX +CXXFLAGS +CXX +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +AWK +SED +target_os +target_vendor +target_cpu +target +host_os +host_vendor +host_cpu +host +build_os +build_vendor +build_cpu +build +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_dependency_tracking +enable_static_link +with_user +with_group +with_device_uid +with_device_gid +with_device_mode +with_device_nodes_on +with_default_name_mangling +enable_lvm1_fallback +with_lvm1 +with_pool +with_cluster +with_snapshots +with_mirrors +with_raid +with_default_mirror_segtype +with_default_raid10_segtype +with_replicators +with_default_sparse_segtype +with_thin +with_thin_check +with_thin_dump +with_thin_repair +with_thin_restore +enable_thin_check_needs_check +with_cache +with_cache_check +with_cache_dump +with_cache_repair +with_cache_restore +enable_cache_check_needs_check +enable_readline +enable_realtime +enable_ocf +with_ocfdir +with_default_pid_dir +with_default_dm_run_dir +with_default_run_dir +with_clvmd +with_clvmd_pidfile +enable_cmirrord +with_cmirrord_pidfile +enable_debug +with_optimisation +enable_profiling +enable_testing +enable_valgrind_pool +enable_devmapper +enable_lvmetad +enable_lvmpolld +enable_lockd_sanlock +enable_lockd_dlm +enable_use_lvmlockd +with_lvmlockd_pidfile +enable_use_lvmetad +with_lvmetad_pidfile +enable_use_lvmpolld +with_lvmpolld_pidfile +enable_notify_dbus +enable_blkid_wiping +enable_udev_systemd_background_jobs +enable_udev_sync +enable_udev_rules +enable_udev_rule_exec_detection +enable_compat +enable_units_compat +enable_ioctl +enable_o_direct +enable_applib +enable_cmdlib +enable_dbus_service +enable_python_bindings +enable_python2_bindings +enable_python3_bindings +enable_pkgconfig +enable_write_install +enable_fsadm +enable_blkdeactivate +enable_dmeventd +enable_selinux +enable_nls +with_localedir +with_confdir +with_staticdir +with_usrlibdir +with_usrsbindir +with_udev_prefix +with_udevdir +with_systemdsystemunitdir +with_tmpfilesdir +with_dmeventd_pidfile +with_dmeventd_path +with_default_system_dir +with_default_profile_subdir +with_default_archive_subdir +with_default_backup_subdir +with_default_cache_subdir +with_default_locking_dir +with_default_data_alignment +with_interface +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CXX +CXXFLAGS +CCC +CPP +PKG_CONFIG +PKG_CONFIG_PATH +PKG_CONFIG_LIBDIR +PKGCONFIGINIT_CFLAGS +PKGCONFIGINIT_LIBS +CMAN_CFLAGS +CMAN_LIBS +COROSYNC_CFLAGS +COROSYNC_LIBS +QUORUM_CFLAGS +QUORUM_LIBS +SALCK_CFLAGS +SALCK_LIBS +CONFDB_CFLAGS +CONFDB_LIBS +CMAP_CFLAGS +CMAP_LIBS +CPG_CFLAGS +CPG_LIBS +DLM_CFLAGS +DLM_LIBS +SACKPT_CFLAGS +SACKPT_LIBS +CUNIT_CFLAGS +CUNIT_LIBS +VALGRIND_CFLAGS +VALGRIND_LIBS +LOCKD_SANLOCK_CFLAGS +LOCKD_SANLOCK_LIBS +LOCKD_DLM_CFLAGS +LOCKD_DLM_LIBS +NOTIFY_DBUS_CFLAGS +NOTIFY_DBUS_LIBS +BLKID_CFLAGS +BLKID_LIBS +SYSTEMD_CFLAGS +SYSTEMD_LIBS +UDEV_CFLAGS +UDEV_LIBS +PYTHON' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures this package to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/PACKAGE] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] + --target=TARGET configure for building compilers for TARGET [HOST] +_ACEOF +fi + +if test -n "$ac_init_help"; then + + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --disable-dependency-tracking + speeds up one-time build. + --enable-static_link use this to link the tools to their libraries + statically (default is dynamic linking + --enable-lvm1_fallback use this to fall back and use LVM1 binaries if + device-mapper is missing from the kernel + --disable-thin_check_needs_check + required if thin_check version is < 0.3.0 + --disable-cache_check_needs_check + required if cache_check version is < 0.5 + --disable-readline disable readline support + --disable-realtime disable realtime clock support + --enable-ocf enable Open Cluster Framework (OCF) compliant + resource agents + --enable-cmirrord enable the cluster mirror log daemon + --enable-debug enable debugging + --enable-profiling gather gcov profiling data + --enable-testing enable testing targets in the makefile + --enable-valgrind-pool enable valgrind awareness of pools + --disable-devmapper disable LVM2 device-mapper interaction + --enable-lvmetad enable the LVM Metadata Daemon + --enable-lvmpolld enable the LVM Polling Daemon + --enable-lockd-sanlock enable the LVM lock daemon using sanlock + --enable-lockd-dlm enable the LVM lock daemon using dlm + --disable-use-lvmlockd disable usage of LVM lock daemon + --disable-use-lvmetad disable usage of LVM Metadata Daemon + --disable-use-lvmpolld disable usage of LVM Poll Daemon + --enable-notify-dbus enable LVM notification using dbus + --disable-blkid_wiping disable libblkid detection of signatures when wiping + and use native code instead + --disable-udev-systemd-background-jobs + disable udev-systemd protocol to instantiate a + service for background job + --enable-udev_sync enable synchronisation with udev processing + --enable-udev_rules install rule files needed for udev synchronisation + --enable-udev-rule-exec-detection + enable executable path detection in udev rules + --enable-compat enable support for old device-mapper versions + --enable-units-compat enable output compatibility with old versions that + that do not use KiB-style unit suffixes + --disable-ioctl disable ioctl calls to device-mapper in the kernel + --disable-o_direct disable O_DIRECT + --enable-applib build application library + --enable-cmdlib build shared command library + --enable-dbus-service install D-Bus support + --enable-python_bindings + build default Python applib bindings + --enable-python2_bindings + build Python2 applib bindings + --enable-python3_bindings + build Python3 applib bindings + --enable-pkgconfig install pkgconfig support + --enable-write_install install user writable files + --disable-fsadm disable fsadm + --disable-blkdeactivate disable blkdeactivate + --enable-dmeventd enable the device-mapper event daemon + --disable-selinux disable selinux support + --enable-nls enable Native Language Support + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-user=USER set the owner of installed files [USER=] + --with-group=GROUP set the group owner of installed files [GROUP=] + --with-device-uid=UID set the owner used for new device nodes [UID=0] + --with-device-gid=GID set the group used for new device nodes [GID=0] + --with-device-mode=MODE set the mode used for new device nodes [MODE=0600] + --with-device-nodes-on=ON + create nodes on resume or create [ON=resume] + --with-default-name-mangling=MANGLING + default name mangling: auto/none/hex [auto] + --with-lvm1=TYPE LVM1 metadata support: internal/shared/none + [internal] + --with-pool=TYPE GFS pool read-only support: internal/shared/none + [internal] + --with-cluster=TYPE cluster LVM locking support: internal/shared/none + [internal] + --with-snapshots=TYPE snapshot support: internal/shared/none [internal] + --with-mirrors=TYPE mirror support: internal/shared/none [internal] + --with-raid=TYPE raid support: internal/shared/none [internal] + --with-default-mirror-segtype=TYPE + default mirror segtype: raid1/mirror [raid1] + --with-default-raid10-segtype=TYPE + default mirror segtype: raid10/mirror [raid10] + --with-replicators=TYPE replicator support: internal/shared/none [none] + --with-default-sparse-segtype=TYPE + default sparse segtype: thin/snapshot [thin] + --with-thin=TYPE thin provisioning support: internal/shared/none + [internal] + --with-thin-check=PATH thin_check tool: [autodetect] + --with-thin-dump=PATH thin_dump tool: [autodetect] + --with-thin-repair=PATH thin_repair tool: [autodetect] + --with-thin-restore=PATH + thin_restore tool: [autodetect] + --with-cache=TYPE cache support: internal/shared/none [internal] + --with-cache-check=PATH cache_check tool: [autodetect] + --with-cache-dump=PATH cache_dump tool: [autodetect] + --with-cache-repair=PATH + cache_repair tool: [autodetect] + --with-cache-restore=PATH + cache_restore tool: [autodetect] + --with-ocfdir=DIR install OCF files in + [PREFIX/lib/ocf/resource.d/lvm2] + --with-default-pid-dir=PID_DIR + Default directory to keep PID files in. [autodetect] + --with-default-dm-run-dir=DM_RUN_DIR + Default DM run directory. [autodetect] + --with-default-run-dir=RUN_DIR + Default LVM run directory. [autodetect_run_dir/lvm] + --with-clvmd=TYPE build cluster LVM Daemon + The following cluster manager combinations are valid: + * cman (RHEL5 or equivalent) + * cman,corosync,openais (or selection of them) + * singlenode (localhost only) + * all (autodetect) + * none (disable build) + [none] + --with-clvmd-pidfile=PATH + clvmd pidfile [PID_DIR/clvmd.pid] + --with-cmirrord-pidfile=PATH + cmirrord pidfile [PID_DIR/cmirrord.pid] + --with-optimisation=OPT C optimisation flag [OPT=-O2] + --with-lvmlockd-pidfile=PATH + lvmlockd pidfile [PID_DIR/lvmlockd.pid] + --with-lvmetad-pidfile=PATH + lvmetad pidfile [PID_DIR/lvmetad.pid] + --with-lvmpolld-pidfile=PATH + lvmpolld pidfile [PID_DIR/lvmpolld.pid] + --with-localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --with-confdir=DIR configuration files in DIR [/etc] + --with-staticdir=DIR static binaries in DIR [EPREFIX/sbin] + --with-usrlibdir=DIR usrlib in DIR [PREFIX/lib] + --with-usrsbindir=DIR usrsbin executables in DIR [PREFIX/sbin] + --with-udev-prefix=UPREFIX + install udev rule files in UPREFIX [EPREFIX] + --with-udevdir=DIR udev rules in DIR [UPREFIX/lib/udev/rules.d] + --with-systemdsystemunitdir=DIR + systemd service files in DIR + --with-tmpfilesdir=DIR install configuration files for management of + volatile files and directories in DIR + [PREFIX/lib/tmpfiles.d] + --with-dmeventd-pidfile=PATH + dmeventd pidfile [PID_DIR/dmeventd.pid] + --with-dmeventd-path=PATH + dmeventd path [EPREFIX/sbin/dmeventd] + --with-default-system-dir=DIR + default LVM system directory [/etc/lvm] + --with-default-profile-subdir=SUBDIR + default configuration profile subdir [profile] + --with-default-archive-subdir=SUBDIR + default metadata archive subdir [archive] + --with-default-backup-subdir=SUBDIR + default metadata backup subdir [backup] + --with-default-cache-subdir=SUBDIR + default metadata cache subdir [cache] + --with-default-locking-dir=DIR + default locking directory [autodetect_lock_dir/lvm] + --with-default-data-alignment=NUM + set the default data alignment in MiB [1] + --with-interface=IFACE choose kernel interface (ioctl) [ioctl] + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L<lib dir> if you have libraries in a + nonstandard directory <lib dir> + LIBS libraries to pass to the linker, e.g. -l<library> + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if + you have headers in a nonstandard directory <include dir> + CXX C++ compiler command + CXXFLAGS C++ compiler flags + CPP C preprocessor + PKG_CONFIG path to pkg-config utility + PKG_CONFIG_PATH + directories to add to pkg-config's search path + PKG_CONFIG_LIBDIR + path overriding pkg-config's built-in search path + PKGCONFIGINIT_CFLAGS + C compiler flags for PKGCONFIGINIT, overriding pkg-config + PKGCONFIGINIT_LIBS + linker flags for PKGCONFIGINIT, overriding pkg-config + CMAN_CFLAGS C compiler flags for CMAN, overriding pkg-config + CMAN_LIBS linker flags for CMAN, overriding pkg-config + COROSYNC_CFLAGS + C compiler flags for COROSYNC, overriding pkg-config + COROSYNC_LIBS + linker flags for COROSYNC, overriding pkg-config + QUORUM_CFLAGS + C compiler flags for QUORUM, overriding pkg-config + QUORUM_LIBS linker flags for QUORUM, overriding pkg-config + SALCK_CFLAGS + C compiler flags for SALCK, overriding pkg-config + SALCK_LIBS linker flags for SALCK, overriding pkg-config + CONFDB_CFLAGS + C compiler flags for CONFDB, overriding pkg-config + CONFDB_LIBS linker flags for CONFDB, overriding pkg-config + CMAP_CFLAGS C compiler flags for CMAP, overriding pkg-config + CMAP_LIBS linker flags for CMAP, overriding pkg-config + CPG_CFLAGS C compiler flags for CPG, overriding pkg-config + CPG_LIBS linker flags for CPG, overriding pkg-config + DLM_CFLAGS C compiler flags for DLM, overriding pkg-config + DLM_LIBS linker flags for DLM, overriding pkg-config + SACKPT_CFLAGS + C compiler flags for SACKPT, overriding pkg-config + SACKPT_LIBS linker flags for SACKPT, overriding pkg-config + CUNIT_CFLAGS + C compiler flags for CUNIT, overriding pkg-config + CUNIT_LIBS linker flags for CUNIT, overriding pkg-config + VALGRIND_CFLAGS + C compiler flags for VALGRIND, overriding pkg-config + VALGRIND_LIBS + linker flags for VALGRIND, overriding pkg-config + LOCKD_SANLOCK_CFLAGS + C compiler flags for LOCKD_SANLOCK, overriding pkg-config + LOCKD_SANLOCK_LIBS + linker flags for LOCKD_SANLOCK, overriding pkg-config + LOCKD_DLM_CFLAGS + C compiler flags for LOCKD_DLM, overriding pkg-config + LOCKD_DLM_LIBS + linker flags for LOCKD_DLM, overriding pkg-config + NOTIFY_DBUS_CFLAGS + C compiler flags for NOTIFY_DBUS, overriding pkg-config + NOTIFY_DBUS_LIBS + linker flags for NOTIFY_DBUS, overriding pkg-config + BLKID_CFLAGS + C compiler flags for BLKID, overriding pkg-config + BLKID_LIBS linker flags for BLKID, overriding pkg-config + SYSTEMD_CFLAGS + C compiler flags for SYSTEMD, overriding pkg-config + SYSTEMD_LIBS + linker flags for SYSTEMD, overriding pkg-config + UDEV_CFLAGS C compiler flags for UDEV, overriding pkg-config + UDEV_LIBS linker flags for UDEV, overriding pkg-config + PYTHON the Python interpreter + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to the package provider. +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +configure +generated by GNU Autoconf 2.69 + +Copyright (C) 2012 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_cxx_try_compile LINENO +# ---------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_cxx_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_cxx_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_cxx_try_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + test -x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if eval \${$3+:} false; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.i conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_mongrel + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_type + +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +$as_echo_n "checking for $2.$3... " >&6; } +if eval \${$4+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$4 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_member + +# ac_fn_c_find_intX_t LINENO BITS VAR +# ----------------------------------- +# Finds a signed integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_intX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for int$2_t" >&5 +$as_echo_n "checking for int$2_t... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in int$2_t 'int' 'long int' \ + 'long long int' 'short int' 'signed char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; +test_array [0] = 0; +return test_array [0]; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) + < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))]; +test_array [0] = 0; +return test_array [0]; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + case $ac_type in #( + int$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if eval test \"x\$"$3"\" = x"no"; then : + +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_find_intX_t + +# ac_fn_c_find_uintX_t LINENO BITS VAR +# ------------------------------------ +# Finds an unsigned integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_uintX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for uint$2_t" >&5 +$as_echo_n "checking for uint$2_t... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in uint$2_t 'unsigned int' 'unsigned long int' \ + 'unsigned long long int' 'unsigned short int' 'unsigned char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +static int test_array [1 - 2 * !((($ac_type) -1 >> ($2 / 2 - 1)) >> ($2 / 2 - 1) == 3)]; +test_array [0] = 0; +return test_array [0]; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + case $ac_type in #( + uint$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if eval test \"x\$"$3"\" = x"no"; then : + +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_find_uintX_t + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case <limits.h> declares $2. + For example, HP-UX 11i <limits.h> declares gettimeofday. */ +#define $2 innocuous_$2 + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer <limits.h> to <assert.h> if __STDC__ is defined, since + <limits.h> exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include <limits.h> +#else +# include <assert.h> +#endif + +#undef $2 + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int +main () +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func + +# ac_fn_c_check_decl LINENO SYMBOL VAR INCLUDES +# --------------------------------------------- +# Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR +# accordingly. +ac_fn_c_check_decl () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + as_decl_name=`echo $2|sed 's/ *(.*//'` + as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'` + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5 +$as_echo_n "checking whether $as_decl_name is declared... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +#ifndef $as_decl_name +#ifdef __cplusplus + (void) $as_decl_use; +#else + (void) $as_decl_name; +#endif +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_decl +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by $as_me, which was +generated by GNU Autoconf 2.69. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + $as_echo "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + $as_echo "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + $as_echo "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + $as_echo "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +$as_echo "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +as_fn_append ac_header_list " sys/time.h" +as_fn_append ac_header_list " unistd.h" +as_fn_append ac_func_list " alarm" +as_fn_append ac_header_list " stdlib.h" +as_fn_append ac_header_list " sys/param.h" +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +ac_config_headers="$ac_config_headers include/configure.h" + + +################################################################################ +ac_aux_dir= +for ac_dir in autoconf "$srcdir"/autoconf; do + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + as_fn_error $? "cannot find install-sh, install.sh, or shtool in autoconf \"$srcdir\"/autoconf" "$LINENO" 5 +fi + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + + +################################################################################ +# Make sure we can run config.sub. +$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || + as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 +$as_echo_n "checking build system type... " >&6; } +if ${ac_cv_build+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` +test "x$ac_build_alias" = x && + as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 +ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 +$as_echo "$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 +$as_echo_n "checking host system type... " >&6; } +if ${ac_cv_host+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 +$as_echo "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5 +$as_echo_n "checking target system type... " >&6; } +if ${ac_cv_target+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$target_alias" = x; then + ac_cv_target=$ac_cv_host +else + ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5 +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5 +$as_echo "$ac_cv_target" >&6; } +case $ac_cv_target in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5;; +esac +target=$ac_cv_target +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_target +shift +target_cpu=$1 +target_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +target_os=$* +IFS=$ac_save_IFS +case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac + + +# The aliases save the names the user supplied, while $host etc. +# will get canonicalized. +test -n "$target_alias" && + test "$program_prefix$program_suffix$program_transform_name" = \ + NONENONEs,x,x, && + program_prefix=${target_alias}- + +if test -z "$CFLAGS"; then : + COPTIMISE_FLAG="-O2" +fi +case "$host_os" in + linux*) + CLDFLAGS="$CLDFLAGS -Wl,--version-script,.export.sym" + ELDFLAGS="-Wl,--export-dynamic" + # FIXME Generate list and use --dynamic-list=.dlopen.sym + CLDWHOLEARCHIVE="-Wl,-whole-archive" + CLDNOWHOLEARCHIVE="-Wl,-no-whole-archive" + LDDEPS="$LDDEPS .export.sym" + LIB_SUFFIX=so + DEVMAPPER=yes + BUILD_LVMETAD=no + BUILD_LVMPOLLD=no + LOCKDSANLOCK=no + LOCKDDLM=no + ODIRECT=yes + DM_IOCTLS=yes + SELINUX=yes + CLUSTER=internal + FSADM=yes + BLKDEACTIVATE=yes + ;; + darwin*) + CFLAGS="$CFLAGS -no-cpp-precomp -fno-common" + CLDFLAGS="$CLDFLAGS" + ELDFLAGS= + CLDWHOLEARCHIVE="-all_load" + CLDNOWHOLEARCHIVE= + LIB_SUFFIX=dylib + DEVMAPPER=yes + ODIRECT=no + DM_IOCTLS=no + SELINUX=no + CLUSTER=none + FSADM=no + BLKDEACTIVATE=no + ;; +esac + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 +$as_echo_n "checking for a sed that does not truncate output... " >&6; } +if ${ac_cv_path_SED+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ + for ac_i in 1 2 3 4 5 6 7; do + ac_script="$ac_script$as_nl$ac_script" + done + echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed + { ac_script=; unset ac_script;} + if test -z "$SED"; then + ac_path_SED_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in sed gsed; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_SED" || continue +# Check for GNU ac_path_SED and select it if it is found. + # Check for GNU $ac_path_SED +case `"$ac_path_SED" --version 2>&1` in +*GNU*) + ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo '' >> "conftest.nl" + "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_SED_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_SED="$ac_path_SED" + ac_path_SED_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_SED_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_SED"; then + as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 + fi +else + ac_cv_path_SED=$SED +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 +$as_echo "$ac_cv_path_SED" >&6; } + SED="$ac_cv_path_SED" + rm -f conftest.sed + +for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_AWK+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_AWK="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 +$as_echo "$AWK" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$AWK" && break +done + +save_CFLAGS=$CFLAGS +save_CXXFLAGS=$CXXFLAGS +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <stdio.h> +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if ${ac_cv_objext+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if ${ac_cv_c_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if ${ac_cv_prog_cc_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if ${ac_cv_prog_cc_c89+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <stdarg.h> +#include <stdio.h> +struct stat; +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : + +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +ac_ext=cpp +ac_cpp='$CXXCPP $CPPFLAGS' +ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_cxx_compiler_gnu +if test -z "$CXX"; then + if test -n "$CCC"; then + CXX=$CCC + else + if test -n "$ac_tool_prefix"; then + for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CXX"; then + ac_cv_prog_CXX="$CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CXX=$ac_cv_prog_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CXX" && break + done +fi +if test -z "$CXX"; then + ac_ct_CXX=$CXX + for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CXX+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CXX"; then + ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CXX="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CXX=$ac_cv_prog_ac_ct_CXX +if test -n "$ac_ct_CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 +$as_echo "$ac_ct_CXX" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CXX" && break +done + + if test "x$ac_ct_CXX" = x; then + CXX="g++" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CXX=$ac_ct_CXX + fi +fi + + fi +fi +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 +$as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } +if ${ac_cv_cxx_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_cxx_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 +$as_echo "$ac_cv_cxx_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GXX=yes +else + GXX= +fi +ac_test_CXXFLAGS=${CXXFLAGS+set} +ac_save_CXXFLAGS=$CXXFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 +$as_echo_n "checking whether $CXX accepts -g... " >&6; } +if ${ac_cv_prog_cxx_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_cxx_werror_flag=$ac_cxx_werror_flag + ac_cxx_werror_flag=yes + ac_cv_prog_cxx_g=no + CXXFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + ac_cv_prog_cxx_g=yes +else + CXXFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + +else + ac_cxx_werror_flag=$ac_save_cxx_werror_flag + CXXFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_cxx_try_compile "$LINENO"; then : + ac_cv_prog_cxx_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_cxx_werror_flag=$ac_save_cxx_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 +$as_echo "$ac_cv_prog_cxx_g" >&6; } +if test "$ac_test_CXXFLAGS" = set; then + CXXFLAGS=$ac_save_CXXFLAGS +elif test $ac_cv_prog_cxx_g = yes; then + if test "$GXX" = yes; then + CXXFLAGS="-g -O2" + else + CXXFLAGS="-g" + fi +else + if test "$GXX" = yes; then + CXXFLAGS="-O2" + else + CXXFLAGS= + fi +fi +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +CFLAGS=$save_CFLAGS +CXXFLAGS=$save_CXXFLAGS + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if ${ac_cv_prog_CPP+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since + # <limits.h> exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include <limits.h> +#else +# include <assert.h> +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <ac_nonexistent.h> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since + # <limits.h> exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include <limits.h> +#else +# include <assert.h> +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <ac_nonexistent.h> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if ${ac_cv_path_GREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_GREP" || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if ${ac_cv_path_EGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +if test $ac_cv_c_compiler_gnu = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC needs -traditional" >&5 +$as_echo_n "checking whether $CC needs -traditional... " >&6; } +if ${ac_cv_prog_gcc_traditional+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_pattern="Autoconf.*'x'" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sgtty.h> +Autoconf TIOCGETP +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "$ac_pattern" >/dev/null 2>&1; then : + ac_cv_prog_gcc_traditional=yes +else + ac_cv_prog_gcc_traditional=no +fi +rm -f conftest* + + + if test $ac_cv_prog_gcc_traditional = no; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <termio.h> +Autoconf TCGETA +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "$ac_pattern" >/dev/null 2>&1; then : + ac_cv_prog_gcc_traditional=yes +fi +rm -f conftest* + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_gcc_traditional" >&5 +$as_echo "$ac_cv_prog_gcc_traditional" >&6; } + if test $ac_cv_prog_gcc_traditional = yes; then + CC="$CC -traditional" + fi +fi + +# Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if ${ac_cv_path_install+:} false; then : + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in #(( + ./ | .// | /[cC]/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; +esac + + done +IFS=$as_save_IFS + +rm -rf conftest.one conftest.two conftest.dir + +fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 +$as_echo_n "checking whether ln -s works... " >&6; } +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 +$as_echo "no, using $LN_S" >&6; } +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + SET_MAKE= +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 +$as_echo_n "checking for a thread-safe mkdir -p... " >&6; } +if test -z "$MKDIR_P"; then + if ${ac_cv_path_mkdir+:} false; then : + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in mkdir gmkdir; do + for ac_exec_ext in '' $ac_executable_extensions; do + as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue + case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( + 'mkdir (GNU coreutils) '* | \ + 'mkdir (coreutils) '* | \ + 'mkdir (fileutils) '4.1*) + ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext + break 3;; + esac + done + done + done +IFS=$as_save_IFS + +fi + + test -d ./--version && rmdir ./--version + if test "${ac_cv_path_mkdir+set}" = set; then + MKDIR_P="$ac_cv_path_mkdir -p" + else + # As a last resort, use the slow shell script. Don't cache a + # value for MKDIR_P within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + MKDIR_P="$ac_install_sh -d" + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 +$as_echo "$MKDIR_P" >&6; } + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cflow", so it can be a program name with args. +set dummy ${ac_tool_prefix}cflow; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_CFLOW_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $CFLOW_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_CFLOW_CMD="$CFLOW_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_CFLOW_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CFLOW_CMD=$ac_cv_path_CFLOW_CMD +if test -n "$CFLOW_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CFLOW_CMD" >&5 +$as_echo "$CFLOW_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_CFLOW_CMD"; then + ac_pt_CFLOW_CMD=$CFLOW_CMD + # Extract the first word of "cflow", so it can be a program name with args. +set dummy cflow; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_CFLOW_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_CFLOW_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_CFLOW_CMD="$ac_pt_CFLOW_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_CFLOW_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_CFLOW_CMD=$ac_cv_path_ac_pt_CFLOW_CMD +if test -n "$ac_pt_CFLOW_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_CFLOW_CMD" >&5 +$as_echo "$ac_pt_CFLOW_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_CFLOW_CMD" = x; then + CFLOW_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CFLOW_CMD=$ac_pt_CFLOW_CMD + fi +else + CFLOW_CMD="$ac_cv_path_CFLOW_CMD" +fi + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cscope", so it can be a program name with args. +set dummy ${ac_tool_prefix}cscope; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_CSCOPE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $CSCOPE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_CSCOPE_CMD="$CSCOPE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_CSCOPE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CSCOPE_CMD=$ac_cv_path_CSCOPE_CMD +if test -n "$CSCOPE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CSCOPE_CMD" >&5 +$as_echo "$CSCOPE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_CSCOPE_CMD"; then + ac_pt_CSCOPE_CMD=$CSCOPE_CMD + # Extract the first word of "cscope", so it can be a program name with args. +set dummy cscope; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_CSCOPE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_CSCOPE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_CSCOPE_CMD="$ac_pt_CSCOPE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_CSCOPE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_CSCOPE_CMD=$ac_cv_path_ac_pt_CSCOPE_CMD +if test -n "$ac_pt_CSCOPE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_CSCOPE_CMD" >&5 +$as_echo "$ac_pt_CSCOPE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_CSCOPE_CMD" = x; then + CSCOPE_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CSCOPE_CMD=$ac_pt_CSCOPE_CMD + fi +else + CSCOPE_CMD="$ac_cv_path_CSCOPE_CMD" +fi + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}chmod", so it can be a program name with args. +set dummy ${ac_tool_prefix}chmod; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_CHMOD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $CHMOD in + [\\/]* | ?:[\\/]*) + ac_cv_path_CHMOD="$CHMOD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_CHMOD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CHMOD=$ac_cv_path_CHMOD +if test -n "$CHMOD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CHMOD" >&5 +$as_echo "$CHMOD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_CHMOD"; then + ac_pt_CHMOD=$CHMOD + # Extract the first word of "chmod", so it can be a program name with args. +set dummy chmod; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_CHMOD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_CHMOD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_CHMOD="$ac_pt_CHMOD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_CHMOD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_CHMOD=$ac_cv_path_ac_pt_CHMOD +if test -n "$ac_pt_CHMOD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_CHMOD" >&5 +$as_echo "$ac_pt_CHMOD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_CHMOD" = x; then + CHMOD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CHMOD=$ac_pt_CHMOD + fi +else + CHMOD="$ac_cv_path_CHMOD" +fi + + +################################################################################ +ac_header_dirent=no +for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do + as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 +$as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } +if eval \${$as_ac_Header+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/types.h> +#include <$ac_hdr> + +int +main () +{ +if ((DIR *) 0) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$as_ac_Header=yes" +else + eval "$as_ac_Header=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$as_ac_Header + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 +_ACEOF + +ac_header_dirent=$ac_hdr; break +fi + +done +# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. +if test $ac_header_dirent = dirent.h; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if ${ac_cv_search_opendir+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char opendir (); +int +main () +{ +return opendir (); + ; + return 0; +} +_ACEOF +for ac_lib in '' dir; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_opendir=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_opendir+:} false; then : + break +fi +done +if ${ac_cv_search_opendir+:} false; then : + +else + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if ${ac_cv_search_opendir+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char opendir (); +int +main () +{ +return opendir (); + ; + return 0; +} +_ACEOF +for ac_lib in '' x; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_opendir=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_opendir+:} false; then : + break +fi +done +if ${ac_cv_search_opendir+:} false; then : + +else + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> +#include <float.h> + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <string.h> + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <stdlib.h> + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <ctype.h> +#include <stdlib.h> +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/types.h defines makedev" >&5 +$as_echo_n "checking whether sys/types.h defines makedev... " >&6; } +if ${ac_cv_header_sys_types_h_makedev+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/types.h> +int +main () +{ +return makedev(0, 0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_header_sys_types_h_makedev=yes +else + ac_cv_header_sys_types_h_makedev=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_types_h_makedev" >&5 +$as_echo "$ac_cv_header_sys_types_h_makedev" >&6; } + +if test $ac_cv_header_sys_types_h_makedev = no; then +ac_fn_c_check_header_mongrel "$LINENO" "sys/mkdev.h" "ac_cv_header_sys_mkdev_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_mkdev_h" = xyes; then : + +$as_echo "#define MAJOR_IN_MKDEV 1" >>confdefs.h + +fi + + + + if test $ac_cv_header_sys_mkdev_h = no; then + ac_fn_c_check_header_mongrel "$LINENO" "sys/sysmacros.h" "ac_cv_header_sys_sysmacros_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_sysmacros_h" = xyes; then : + +$as_echo "#define MAJOR_IN_SYSMACROS 1" >>confdefs.h + +fi + + + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for stdbool.h that conforms to C99" >&5 +$as_echo_n "checking for stdbool.h that conforms to C99... " >&6; } +if ${ac_cv_header_stdbool_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #include <stdbool.h> + #ifndef bool + "error: bool is not defined" + #endif + #ifndef false + "error: false is not defined" + #endif + #if false + "error: false is not 0" + #endif + #ifndef true + "error: true is not defined" + #endif + #if true != 1 + "error: true is not 1" + #endif + #ifndef __bool_true_false_are_defined + "error: __bool_true_false_are_defined is not defined" + #endif + + struct s { _Bool s: 1; _Bool t; } s; + + char a[true == 1 ? 1 : -1]; + char b[false == 0 ? 1 : -1]; + char c[__bool_true_false_are_defined == 1 ? 1 : -1]; + char d[(bool) 0.5 == true ? 1 : -1]; + /* See body of main program for 'e'. */ + char f[(_Bool) 0.0 == false ? 1 : -1]; + char g[true]; + char h[sizeof (_Bool)]; + char i[sizeof s.t]; + enum { j = false, k = true, l = false * true, m = true * 256 }; + /* The following fails for + HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]. */ + _Bool n[m]; + char o[sizeof n == m * sizeof n[0] ? 1 : -1]; + char p[-1 - (_Bool) 0 < 0 && -1 - (bool) 0 < 0 ? 1 : -1]; + /* Catch a bug in an HP-UX C compiler. See + http://gcc.gnu.org/ml/gcc-patches/2003-12/msg02303.html + http://lists.gnu.org/archive/html/bug-coreutils/2005-11/msg00161.html + */ + _Bool q = true; + _Bool *pq = &q; + +int +main () +{ + + bool e = &s; + *pq |= q; + *pq |= ! q; + /* Refer to every declared value, to avoid compiler optimizations. */ + return (!a + !b + !c + !d + !e + !f + !g + !h + !i + !!j + !k + !!l + + !m + !n + !o + !p + !q + !pq); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdbool_h=yes +else + ac_cv_header_stdbool_h=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdbool_h" >&5 +$as_echo "$ac_cv_header_stdbool_h" >&6; } + ac_fn_c_check_type "$LINENO" "_Bool" "ac_cv_type__Bool" "$ac_includes_default" +if test "x$ac_cv_type__Bool" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE__BOOL 1 +_ACEOF + + +fi + + +if test $ac_cv_header_stdbool_h = yes; then + +$as_echo "#define HAVE_STDBOOL_H 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> +#include <float.h> + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <string.h> + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <stdlib.h> + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <ctype.h> +#include <stdlib.h> +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sys/wait.h that is POSIX.1 compatible" >&5 +$as_echo_n "checking for sys/wait.h that is POSIX.1 compatible... " >&6; } +if ${ac_cv_header_sys_wait_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/types.h> +#include <sys/wait.h> +#ifndef WEXITSTATUS +# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) +#endif +#ifndef WIFEXITED +# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) +#endif + +int +main () +{ + int s; + wait (&s); + s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_sys_wait_h=yes +else + ac_cv_header_sys_wait_h=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_wait_h" >&5 +$as_echo "$ac_cv_header_sys_wait_h" >&6; } +if test $ac_cv_header_sys_wait_h = yes; then + +$as_echo "#define HAVE_SYS_WAIT_H 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } +if ${ac_cv_header_time+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/types.h> +#include <sys/time.h> +#include <time.h> + +int +main () +{ +if ((struct tm *) 0) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time=yes +else + ac_cv_header_time=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 +$as_echo "$ac_cv_header_time" >&6; } +if test $ac_cv_header_time = yes; then + +$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h + +fi + + +for ac_header in assert.h ctype.h dirent.h errno.h fcntl.h float.h \ + getopt.h inttypes.h langinfo.h libgen.h limits.h locale.h paths.h \ + signal.h stdarg.h stddef.h stdio.h stdlib.h string.h sys/file.h \ + sys/ioctl.h syslog.h sys/mman.h sys/param.h sys/resource.h sys/stat.h \ + sys/time.h sys/types.h sys/utsname.h sys/wait.h time.h \ + unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else + as_fn_error $? "bailing out" "$LINENO" 5 +fi + +done + + +for ac_header in termios.h sys/statvfs.h sys/timerfd.h linux/magic.h linux/fiemap.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +case "$host_os" in + linux*) + for ac_header in asm/byteorder.h linux/fs.h malloc.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else + as_fn_error $? "bailing out" "$LINENO" 5 +fi + +done + ;; + darwin*) + for ac_header in machine/endian.h sys/disk.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else + as_fn_error $? "bailing out" "$LINENO" 5 +fi + +done + ;; +esac + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } +if ${ac_cv_c_const+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + +#ifndef __cplusplus + /* Ultrix mips cc rejects this sort of thing. */ + typedef int charset[2]; + const charset cs = { 0, 0 }; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* AIX XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this sort of thing. */ + char tx; + char *t = &tx; + char const *s = 0 ? (char *) 0 : (char const *) 0; + + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; } bx; + struct s *b = &bx; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_const=yes +else + ac_cv_c_const=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then + +$as_echo "#define const /**/" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5 +$as_echo_n "checking for inline... " >&6; } +if ${ac_cv_c_inline+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_c_inline=no +for ac_kw in inline __inline__ __inline; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifndef __cplusplus +typedef int foo_t; +static $ac_kw foo_t static_foo () {return 0; } +$ac_kw foo_t foo () {return 0; } +#endif + +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_inline=$ac_kw +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + test "$ac_cv_c_inline" != no && break +done + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5 +$as_echo "$ac_cv_c_inline" >&6; } + +case $ac_cv_c_inline in + inline | yes) ;; + *) + case $ac_cv_c_inline in + no) ac_val=;; + *) ac_val=$ac_cv_c_inline;; + esac + cat >>confdefs.h <<_ACEOF +#ifndef __cplusplus +#define inline $ac_val +#endif +_ACEOF + ;; +esac + +ac_fn_c_check_member "$LINENO" "struct stat" "st_rdev" "ac_cv_member_struct_stat_st_rdev" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_rdev" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_RDEV 1 +_ACEOF + + +fi + +ac_fn_c_check_type "$LINENO" "ptrdiff_t" "ac_cv_type_ptrdiff_t" "$ac_includes_default" +if test "x$ac_cv_type_ptrdiff_t" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_PTRDIFF_T 1 +_ACEOF + + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in sys/time.h or time.h" >&5 +$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } +if ${ac_cv_struct_tm+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/types.h> +#include <time.h> + +int +main () +{ +struct tm tm; + int *p = &tm.tm_sec; + return !p; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_tm=time.h +else + ac_cv_struct_tm=sys/time.h +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_tm" >&5 +$as_echo "$ac_cv_struct_tm" >&6; } +if test $ac_cv_struct_tm = sys/time.h; then + +$as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h + +fi + +ac_fn_c_check_type "$LINENO" "off_t" "ac_cv_type_off_t" "$ac_includes_default" +if test "x$ac_cv_type_off_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define off_t long int +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" +if test "x$ac_cv_type_pid_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define pid_t int +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5 +$as_echo_n "checking return type of signal handlers... " >&6; } +if ${ac_cv_type_signal+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/types.h> +#include <signal.h> + +int +main () +{ +return *(signal (0, 0)) (0) == 1; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_type_signal=int +else + ac_cv_type_signal=void +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5 +$as_echo "$ac_cv_type_signal" >&6; } + +cat >>confdefs.h <<_ACEOF +#define RETSIGTYPE $ac_cv_type_signal +_ACEOF + + +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define size_t unsigned int +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "mode_t" "ac_cv_type_mode_t" "$ac_includes_default" +if test "x$ac_cv_type_mode_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define mode_t int +_ACEOF + +fi + +ac_fn_c_find_intX_t "$LINENO" "8" "ac_cv_c_int8_t" +case $ac_cv_c_int8_t in #( + no|yes) ;; #( + *) + +cat >>confdefs.h <<_ACEOF +#define int8_t $ac_cv_c_int8_t +_ACEOF +;; +esac + +ac_fn_c_find_intX_t "$LINENO" "16" "ac_cv_c_int16_t" +case $ac_cv_c_int16_t in #( + no|yes) ;; #( + *) + +cat >>confdefs.h <<_ACEOF +#define int16_t $ac_cv_c_int16_t +_ACEOF +;; +esac + +ac_fn_c_find_intX_t "$LINENO" "32" "ac_cv_c_int32_t" +case $ac_cv_c_int32_t in #( + no|yes) ;; #( + *) + +cat >>confdefs.h <<_ACEOF +#define int32_t $ac_cv_c_int32_t +_ACEOF +;; +esac + +ac_fn_c_find_intX_t "$LINENO" "64" "ac_cv_c_int64_t" +case $ac_cv_c_int64_t in #( + no|yes) ;; #( + *) + +cat >>confdefs.h <<_ACEOF +#define int64_t $ac_cv_c_int64_t +_ACEOF +;; +esac + +ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" +if test "x$ac_cv_type_ssize_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define ssize_t int +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5 +$as_echo_n "checking for uid_t in sys/types.h... " >&6; } +if ${ac_cv_type_uid_t+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/types.h> + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "uid_t" >/dev/null 2>&1; then : + ac_cv_type_uid_t=yes +else + ac_cv_type_uid_t=no +fi +rm -f conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5 +$as_echo "$ac_cv_type_uid_t" >&6; } +if test $ac_cv_type_uid_t = no; then + +$as_echo "#define uid_t int" >>confdefs.h + + +$as_echo "#define gid_t int" >>confdefs.h + +fi + +ac_fn_c_find_uintX_t "$LINENO" "8" "ac_cv_c_uint8_t" +case $ac_cv_c_uint8_t in #( + no|yes) ;; #( + *) + +$as_echo "#define _UINT8_T 1" >>confdefs.h + + +cat >>confdefs.h <<_ACEOF +#define uint8_t $ac_cv_c_uint8_t +_ACEOF +;; + esac + +ac_fn_c_find_uintX_t "$LINENO" "16" "ac_cv_c_uint16_t" +case $ac_cv_c_uint16_t in #( + no|yes) ;; #( + *) + + +cat >>confdefs.h <<_ACEOF +#define uint16_t $ac_cv_c_uint16_t +_ACEOF +;; + esac + +ac_fn_c_find_uintX_t "$LINENO" "32" "ac_cv_c_uint32_t" +case $ac_cv_c_uint32_t in #( + no|yes) ;; #( + *) + +$as_echo "#define _UINT32_T 1" >>confdefs.h + + +cat >>confdefs.h <<_ACEOF +#define uint32_t $ac_cv_c_uint32_t +_ACEOF +;; + esac + +ac_fn_c_find_uintX_t "$LINENO" "64" "ac_cv_c_uint64_t" +case $ac_cv_c_uint64_t in #( + no|yes) ;; #( + *) + +$as_echo "#define _UINT64_T 1" >>confdefs.h + + +cat >>confdefs.h <<_ACEOF +#define uint64_t $ac_cv_c_uint64_t +_ACEOF +;; + esac + + +################################################################################ +for ac_func in ftruncate gethostname getpagesize gettimeofday localtime_r \ + memchr memset mkdir mkfifo munmap nl_langinfo realpath rmdir setenv \ + setlocale strcasecmp strchr strcspn strdup strerror strncasecmp strndup \ + strrchr strspn strstr strtol strtoul uname +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +else + as_fn_error $? "bailing out" "$LINENO" 5 +fi +done + +# The Ultrix 4.2 mips builtin alloca declared by alloca.h only works +# for constant arguments. Useless! +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working alloca.h" >&5 +$as_echo_n "checking for working alloca.h... " >&6; } +if ${ac_cv_working_alloca_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <alloca.h> +int +main () +{ +char *p = (char *) alloca (2 * sizeof (int)); + if (p) return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_working_alloca_h=yes +else + ac_cv_working_alloca_h=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_working_alloca_h" >&5 +$as_echo "$ac_cv_working_alloca_h" >&6; } +if test $ac_cv_working_alloca_h = yes; then + +$as_echo "#define HAVE_ALLOCA_H 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for alloca" >&5 +$as_echo_n "checking for alloca... " >&6; } +if ${ac_cv_func_alloca_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __GNUC__ +# define alloca __builtin_alloca +#else +# ifdef _MSC_VER +# include <malloc.h> +# define alloca _alloca +# else +# ifdef HAVE_ALLOCA_H +# include <alloca.h> +# else +# ifdef _AIX + #pragma alloca +# else +# ifndef alloca /* predefined by HP cc +Olibcalls */ +void *alloca (size_t); +# endif +# endif +# endif +# endif +#endif + +int +main () +{ +char *p = (char *) alloca (1); + if (p) return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_func_alloca_works=yes +else + ac_cv_func_alloca_works=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_alloca_works" >&5 +$as_echo "$ac_cv_func_alloca_works" >&6; } + +if test $ac_cv_func_alloca_works = yes; then + +$as_echo "#define HAVE_ALLOCA 1" >>confdefs.h + +else + # The SVR3 libPW and SVR4 libucb both contain incompatible functions +# that cause trouble. Some versions do not even contain alloca or +# contain a buggy version. If you still want to use their alloca, +# use ar to extract alloca.o from them instead of compiling alloca.c. + +ALLOCA=\${LIBOBJDIR}alloca.$ac_objext + +$as_echo "#define C_ALLOCA 1" >>confdefs.h + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether \`alloca.c' needs Cray hooks" >&5 +$as_echo_n "checking whether \`alloca.c' needs Cray hooks... " >&6; } +if ${ac_cv_os_cray+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined CRAY && ! defined CRAY2 +webecray +#else +wenotbecray +#endif + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "webecray" >/dev/null 2>&1; then : + ac_cv_os_cray=yes +else + ac_cv_os_cray=no +fi +rm -f conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_os_cray" >&5 +$as_echo "$ac_cv_os_cray" >&6; } +if test $ac_cv_os_cray = yes; then + for ac_func in _getb67 GETB67 getb67; do + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + +cat >>confdefs.h <<_ACEOF +#define CRAY_STACKSEG_END $ac_func +_ACEOF + + break +fi + + done +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking stack direction for C alloca" >&5 +$as_echo_n "checking stack direction for C alloca... " >&6; } +if ${ac_cv_c_stack_direction+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_c_stack_direction=0 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +find_stack_direction (int *addr, int depth) +{ + int dir, dummy = 0; + if (! addr) + addr = &dummy; + *addr = addr < &dummy ? 1 : addr == &dummy ? 0 : -1; + dir = depth ? find_stack_direction (addr, depth - 1) : 0; + return dir + dummy; +} + +int +main (int argc, char **argv) +{ + return find_stack_direction (0, argc + !argv + 20) < 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_c_stack_direction=1 +else + ac_cv_c_stack_direction=-1 +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_stack_direction" >&5 +$as_echo "$ac_cv_c_stack_direction" >&6; } +cat >>confdefs.h <<_ACEOF +#define STACK_DIRECTION $ac_cv_c_stack_direction +_ACEOF + + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether closedir returns void" >&5 +$as_echo_n "checking whether closedir returns void... " >&6; } +if ${ac_cv_func_closedir_void+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_closedir_void=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header_dirent> +#ifndef __cplusplus +int closedir (); +#endif + +int +main () +{ +return closedir (opendir (".")) != 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_closedir_void=no +else + ac_cv_func_closedir_void=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_closedir_void" >&5 +$as_echo "$ac_cv_func_closedir_void" >&6; } +if test $ac_cv_func_closedir_void = yes; then + +$as_echo "#define CLOSEDIR_VOID 1" >>confdefs.h + +fi + +for ac_header in unistd.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "unistd.h" "ac_cv_header_unistd_h" "$ac_includes_default" +if test "x$ac_cv_header_unistd_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_UNISTD_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working chown" >&5 +$as_echo_n "checking for working chown... " >&6; } +if ${ac_cv_func_chown_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_chown_works=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +#include <fcntl.h> + +int +main () +{ + char *f = "conftest.chown"; + struct stat before, after; + + if (creat (f, 0600) < 0) + return 1; + if (stat (f, &before) < 0) + return 1; + if (chown (f, (uid_t) -1, (gid_t) -1) == -1) + return 1; + if (stat (f, &after) < 0) + return 1; + return ! (before.st_uid == after.st_uid && before.st_gid == after.st_gid); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_chown_works=yes +else + ac_cv_func_chown_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +rm -f conftest.chown + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_chown_works" >&5 +$as_echo "$ac_cv_func_chown_works" >&6; } +if test $ac_cv_func_chown_works = yes; then + +$as_echo "#define HAVE_CHOWN 1" >>confdefs.h + +fi + +for ac_header in vfork.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "vfork.h" "ac_cv_header_vfork_h" "$ac_includes_default" +if test "x$ac_cv_header_vfork_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_VFORK_H 1 +_ACEOF + +fi + +done + +for ac_func in fork vfork +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + +if test "x$ac_cv_func_fork" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working fork" >&5 +$as_echo_n "checking for working fork... " >&6; } +if ${ac_cv_func_fork_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_fork_works=cross +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ + + /* By Ruediger Kuhlmann. */ + return fork () < 0; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_fork_works=yes +else + ac_cv_func_fork_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_fork_works" >&5 +$as_echo "$ac_cv_func_fork_works" >&6; } + +else + ac_cv_func_fork_works=$ac_cv_func_fork +fi +if test "x$ac_cv_func_fork_works" = xcross; then + case $host in + *-*-amigaos* | *-*-msdosdjgpp*) + # Override, as these systems have only a dummy fork() stub + ac_cv_func_fork_works=no + ;; + *) + ac_cv_func_fork_works=yes + ;; + esac + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&5 +$as_echo "$as_me: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&2;} +fi +ac_cv_func_vfork_works=$ac_cv_func_vfork +if test "x$ac_cv_func_vfork" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working vfork" >&5 +$as_echo_n "checking for working vfork... " >&6; } +if ${ac_cv_func_vfork_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_vfork_works=cross +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Thanks to Paul Eggert for this test. */ +$ac_includes_default +#include <sys/wait.h> +#ifdef HAVE_VFORK_H +# include <vfork.h> +#endif +/* On some sparc systems, changes by the child to local and incoming + argument registers are propagated back to the parent. The compiler + is told about this with #include <vfork.h>, but some compilers + (e.g. gcc -O) don't grok <vfork.h>. Test for this by using a + static variable whose address is put into a register that is + clobbered by the vfork. */ +static void +#ifdef __cplusplus +sparc_address_test (int arg) +# else +sparc_address_test (arg) int arg; +#endif +{ + static pid_t child; + if (!child) { + child = vfork (); + if (child < 0) { + perror ("vfork"); + _exit(2); + } + if (!child) { + arg = getpid(); + write(-1, "", 0); + _exit (arg); + } + } +} + +int +main () +{ + pid_t parent = getpid (); + pid_t child; + + sparc_address_test (0); + + child = vfork (); + + if (child == 0) { + /* Here is another test for sparc vfork register problems. This + test uses lots of local variables, at least as many local + variables as main has allocated so far including compiler + temporaries. 4 locals are enough for gcc 1.40.3 on a Solaris + 4.1.3 sparc, but we use 8 to be safe. A buggy compiler should + reuse the register of parent for one of the local variables, + since it will think that parent can't possibly be used any more + in this routine. Assigning to the local variable will thus + munge parent in the parent process. */ + pid_t + p = getpid(), p1 = getpid(), p2 = getpid(), p3 = getpid(), + p4 = getpid(), p5 = getpid(), p6 = getpid(), p7 = getpid(); + /* Convince the compiler that p..p7 are live; otherwise, it might + use the same hardware register for all 8 local variables. */ + if (p != p1 || p != p2 || p != p3 || p != p4 + || p != p5 || p != p6 || p != p7) + _exit(1); + + /* On some systems (e.g. IRIX 3.3), vfork doesn't separate parent + from child file descriptors. If the child closes a descriptor + before it execs or exits, this munges the parent's descriptor + as well. Test for this by closing stdout in the child. */ + _exit(close(fileno(stdout)) != 0); + } else { + int status; + struct stat st; + + while (wait(&status) != child) + ; + return ( + /* Was there some problem with vforking? */ + child < 0 + + /* Did the child fail? (This shouldn't happen.) */ + || status + + /* Did the vfork/compiler bug occur? */ + || parent != getpid() + + /* Did the file descriptor bug occur? */ + || fstat(fileno(stdout), &st) != 0 + ); + } +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_vfork_works=yes +else + ac_cv_func_vfork_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vfork_works" >&5 +$as_echo "$ac_cv_func_vfork_works" >&6; } + +fi; +if test "x$ac_cv_func_fork_works" = xcross; then + ac_cv_func_vfork_works=$ac_cv_func_vfork + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&5 +$as_echo "$as_me: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&2;} +fi + +if test "x$ac_cv_func_vfork_works" = xyes; then + +$as_echo "#define HAVE_WORKING_VFORK 1" >>confdefs.h + +else + +$as_echo "#define vfork fork" >>confdefs.h + +fi +if test "x$ac_cv_func_fork_works" = xyes; then + +$as_echo "#define HAVE_WORKING_FORK 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether lstat correctly handles trailing slash" >&5 +$as_echo_n "checking whether lstat correctly handles trailing slash... " >&6; } +if ${ac_cv_func_lstat_dereferences_slashed_symlink+:} false; then : + $as_echo_n "(cached) " >&6 +else + rm -f conftest.sym conftest.file +echo >conftest.file +if test "$as_ln_s" = "ln -s" && ln -s conftest.file conftest.sym; then + if test "$cross_compiling" = yes; then : + ac_cv_func_lstat_dereferences_slashed_symlink=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +struct stat sbuf; + /* Linux will dereference the symlink and fail, as required by POSIX. + That is better in the sense that it means we will not + have to compile and use the lstat wrapper. */ + return lstat ("conftest.sym/", &sbuf) == 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_lstat_dereferences_slashed_symlink=yes +else + ac_cv_func_lstat_dereferences_slashed_symlink=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +else + # If the `ln -s' command failed, then we probably don't even + # have an lstat function. + ac_cv_func_lstat_dereferences_slashed_symlink=no +fi +rm -f conftest.sym conftest.file + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 +$as_echo "$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } + +test $ac_cv_func_lstat_dereferences_slashed_symlink = yes && + +cat >>confdefs.h <<_ACEOF +#define LSTAT_FOLLOWS_SLASHED_SYMLINK 1 +_ACEOF + + +if test "x$ac_cv_func_lstat_dereferences_slashed_symlink" = xno; then + case " $LIBOBJS " in + *" lstat.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS lstat.$ac_objext" + ;; +esac + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether lstat accepts an empty string" >&5 +$as_echo_n "checking whether lstat accepts an empty string... " >&6; } +if ${ac_cv_func_lstat_empty_string_bug+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_lstat_empty_string_bug=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +struct stat sbuf; + return lstat ("", &sbuf) == 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_lstat_empty_string_bug=no +else + ac_cv_func_lstat_empty_string_bug=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_lstat_empty_string_bug" >&5 +$as_echo "$ac_cv_func_lstat_empty_string_bug" >&6; } +if test $ac_cv_func_lstat_empty_string_bug = yes; then + case " $LIBOBJS " in + *" lstat.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS lstat.$ac_objext" + ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define HAVE_LSTAT_EMPTY_STRING_BUG 1 +_ACEOF + +fi + +for ac_header in stdlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STDLIB_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 +$as_echo_n "checking for GNU libc compatible malloc... " >&6; } +if ${ac_cv_func_malloc_0_nonnull+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_malloc_0_nonnull=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined STDC_HEADERS || defined HAVE_STDLIB_H +# include <stdlib.h> +#else +char *malloc (); +#endif + +int +main () +{ +return ! malloc (0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_malloc_0_nonnull=yes +else + ac_cv_func_malloc_0_nonnull=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 +$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } +if test $ac_cv_func_malloc_0_nonnull = yes; then : + +$as_echo "#define HAVE_MALLOC 1" >>confdefs.h + +else + $as_echo "#define HAVE_MALLOC 0" >>confdefs.h + + case " $LIBOBJS " in + *" malloc.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS malloc.$ac_objext" + ;; +esac + + +$as_echo "#define malloc rpl_malloc" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working memcmp" >&5 +$as_echo_n "checking for working memcmp... " >&6; } +if ${ac_cv_func_memcmp_working+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_memcmp_working=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ + + /* Some versions of memcmp are not 8-bit clean. */ + char c0 = '\100', c1 = '\200', c2 = '\201'; + if (memcmp(&c0, &c2, 1) >= 0 || memcmp(&c1, &c2, 1) >= 0) + return 1; + + /* The Next x86 OpenStep bug shows up only when comparing 16 bytes + or more and with at least one buffer not starting on a 4-byte boundary. + William Lewis provided this test program. */ + { + char foo[21]; + char bar[21]; + int i; + for (i = 0; i < 4; i++) + { + char *a = foo + i; + char *b = bar + i; + strcpy (a, "--------01111111"); + strcpy (b, "--------10000000"); + if (memcmp (a, b, 16) >= 0) + return 1; + } + return 0; + } + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_memcmp_working=yes +else + ac_cv_func_memcmp_working=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_memcmp_working" >&5 +$as_echo "$ac_cv_func_memcmp_working" >&6; } +test $ac_cv_func_memcmp_working = no && case " $LIBOBJS " in + *" memcmp.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS memcmp.$ac_objext" + ;; +esac + + + + + + for ac_header in $ac_header_list +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + + + + + + + for ac_func in $ac_func_list +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working mktime" >&5 +$as_echo_n "checking for working mktime... " >&6; } +if ${ac_cv_func_working_mktime+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_working_mktime=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Test program from Paul Eggert and Tony Leneis. */ +#ifdef TIME_WITH_SYS_TIME +# include <sys/time.h> +# include <time.h> +#else +# ifdef HAVE_SYS_TIME_H +# include <sys/time.h> +# else +# include <time.h> +# endif +#endif + +#include <limits.h> +#include <stdlib.h> + +#ifdef HAVE_UNISTD_H +# include <unistd.h> +#endif + +#ifndef HAVE_ALARM +# define alarm(X) /* empty */ +#endif + +/* Work around redefinition to rpl_putenv by other config tests. */ +#undef putenv + +static time_t time_t_max; +static time_t time_t_min; + +/* Values we'll use to set the TZ environment variable. */ +static const char *tz_strings[] = { + (const char *) 0, "TZ=GMT0", "TZ=JST-9", + "TZ=EST+3EDT+2,M10.1.0/00:00:00,M2.3.0/00:00:00" +}; +#define N_STRINGS (sizeof (tz_strings) / sizeof (tz_strings[0])) + +/* Return 0 if mktime fails to convert a date in the spring-forward gap. + Based on a problem report from Andreas Jaeger. */ +static int +spring_forward_gap () +{ + /* glibc (up to about 1998-10-07) failed this test. */ + struct tm tm; + + /* Use the portable POSIX.1 specification "TZ=PST8PDT,M4.1.0,M10.5.0" + instead of "TZ=America/Vancouver" in order to detect the bug even + on systems that don't support the Olson extension, or don't have the + full zoneinfo tables installed. */ + putenv ((char*) "TZ=PST8PDT,M4.1.0,M10.5.0"); + + tm.tm_year = 98; + tm.tm_mon = 3; + tm.tm_mday = 5; + tm.tm_hour = 2; + tm.tm_min = 0; + tm.tm_sec = 0; + tm.tm_isdst = -1; + return mktime (&tm) != (time_t) -1; +} + +static int +mktime_test1 (time_t now) +{ + struct tm *lt; + return ! (lt = localtime (&now)) || mktime (lt) == now; +} + +static int +mktime_test (time_t now) +{ + return (mktime_test1 (now) + && mktime_test1 ((time_t) (time_t_max - now)) + && mktime_test1 ((time_t) (time_t_min + now))); +} + +static int +irix_6_4_bug () +{ + /* Based on code from Ariel Faigon. */ + struct tm tm; + tm.tm_year = 96; + tm.tm_mon = 3; + tm.tm_mday = 0; + tm.tm_hour = 0; + tm.tm_min = 0; + tm.tm_sec = 0; + tm.tm_isdst = -1; + mktime (&tm); + return tm.tm_mon == 2 && tm.tm_mday == 31; +} + +static int +bigtime_test (int j) +{ + struct tm tm; + time_t now; + tm.tm_year = tm.tm_mon = tm.tm_mday = tm.tm_hour = tm.tm_min = tm.tm_sec = j; + now = mktime (&tm); + if (now != (time_t) -1) + { + struct tm *lt = localtime (&now); + if (! (lt + && lt->tm_year == tm.tm_year + && lt->tm_mon == tm.tm_mon + && lt->tm_mday == tm.tm_mday + && lt->tm_hour == tm.tm_hour + && lt->tm_min == tm.tm_min + && lt->tm_sec == tm.tm_sec + && lt->tm_yday == tm.tm_yday + && lt->tm_wday == tm.tm_wday + && ((lt->tm_isdst < 0 ? -1 : 0 < lt->tm_isdst) + == (tm.tm_isdst < 0 ? -1 : 0 < tm.tm_isdst)))) + return 0; + } + return 1; +} + +static int +year_2050_test () +{ + /* The correct answer for 2050-02-01 00:00:00 in Pacific time, + ignoring leap seconds. */ + unsigned long int answer = 2527315200UL; + + struct tm tm; + time_t t; + tm.tm_year = 2050 - 1900; + tm.tm_mon = 2 - 1; + tm.tm_mday = 1; + tm.tm_hour = tm.tm_min = tm.tm_sec = 0; + tm.tm_isdst = -1; + + /* Use the portable POSIX.1 specification "TZ=PST8PDT,M4.1.0,M10.5.0" + instead of "TZ=America/Vancouver" in order to detect the bug even + on systems that don't support the Olson extension, or don't have the + full zoneinfo tables installed. */ + putenv ((char*) "TZ=PST8PDT,M4.1.0,M10.5.0"); + + t = mktime (&tm); + + /* Check that the result is either a failure, or close enough + to the correct answer that we can assume the discrepancy is + due to leap seconds. */ + return (t == (time_t) -1 + || (0 < t && answer - 120 <= t && t <= answer + 120)); +} + +int +main () +{ + time_t t, delta; + int i, j; + + /* This test makes some buggy mktime implementations loop. + Give up after 60 seconds; a mktime slower than that + isn't worth using anyway. */ + alarm (60); + + for (;;) + { + t = (time_t_max << 1) + 1; + if (t <= time_t_max) + break; + time_t_max = t; + } + time_t_min = - ((time_t) ~ (time_t) 0 == (time_t) -1) - time_t_max; + + delta = time_t_max / 997; /* a suitable prime number */ + for (i = 0; i < N_STRINGS; i++) + { + if (tz_strings[i]) + putenv ((char*) tz_strings[i]); + + for (t = 0; t <= time_t_max - delta; t += delta) + if (! mktime_test (t)) + return 1; + if (! (mktime_test ((time_t) 1) + && mktime_test ((time_t) (60 * 60)) + && mktime_test ((time_t) (60 * 60 * 24)))) + return 1; + + for (j = 1; ; j <<= 1) + if (! bigtime_test (j)) + return 1; + else if (INT_MAX / 2 < j) + break; + if (! bigtime_test (INT_MAX)) + return 1; + } + return ! (irix_6_4_bug () && spring_forward_gap () && year_2050_test ()); +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_working_mktime=yes +else + ac_cv_func_working_mktime=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_working_mktime" >&5 +$as_echo "$ac_cv_func_working_mktime" >&6; } +if test $ac_cv_func_working_mktime = no; then + case " $LIBOBJS " in + *" mktime.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS mktime.$ac_objext" + ;; +esac + +fi + + + + + + +for ac_func in getpagesize +do : + ac_fn_c_check_func "$LINENO" "getpagesize" "ac_cv_func_getpagesize" +if test "x$ac_cv_func_getpagesize" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETPAGESIZE 1 +_ACEOF + +fi +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working mmap" >&5 +$as_echo_n "checking for working mmap... " >&6; } +if ${ac_cv_func_mmap_fixed_mapped+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_mmap_fixed_mapped=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +/* malloc might have been renamed as rpl_malloc. */ +#undef malloc + +/* Thanks to Mike Haertel and Jim Avera for this test. + Here is a matrix of mmap possibilities: + mmap private not fixed + mmap private fixed at somewhere currently unmapped + mmap private fixed at somewhere already mapped + mmap shared not fixed + mmap shared fixed at somewhere currently unmapped + mmap shared fixed at somewhere already mapped + For private mappings, we should verify that changes cannot be read() + back from the file, nor mmap's back from the file at a different + address. (There have been systems where private was not correctly + implemented like the infamous i386 svr4.0, and systems where the + VM page cache was not coherent with the file system buffer cache + like early versions of FreeBSD and possibly contemporary NetBSD.) + For shared mappings, we should conversely verify that changes get + propagated back to all the places they're supposed to be. + + Grep wants private fixed already mapped. + The main things grep needs to know about mmap are: + * does it exist and is it safe to write into the mmap'd area + * how to use it (BSD variants) */ + +#include <fcntl.h> +#include <sys/mman.h> + +#if !defined STDC_HEADERS && !defined HAVE_STDLIB_H +char *malloc (); +#endif + +/* This mess was copied from the GNU getpagesize.h. */ +#ifndef HAVE_GETPAGESIZE +# ifdef _SC_PAGESIZE +# define getpagesize() sysconf(_SC_PAGESIZE) +# else /* no _SC_PAGESIZE */ +# ifdef HAVE_SYS_PARAM_H +# include <sys/param.h> +# ifdef EXEC_PAGESIZE +# define getpagesize() EXEC_PAGESIZE +# else /* no EXEC_PAGESIZE */ +# ifdef NBPG +# define getpagesize() NBPG * CLSIZE +# ifndef CLSIZE +# define CLSIZE 1 +# endif /* no CLSIZE */ +# else /* no NBPG */ +# ifdef NBPC +# define getpagesize() NBPC +# else /* no NBPC */ +# ifdef PAGESIZE +# define getpagesize() PAGESIZE +# endif /* PAGESIZE */ +# endif /* no NBPC */ +# endif /* no NBPG */ +# endif /* no EXEC_PAGESIZE */ +# else /* no HAVE_SYS_PARAM_H */ +# define getpagesize() 8192 /* punt totally */ +# endif /* no HAVE_SYS_PARAM_H */ +# endif /* no _SC_PAGESIZE */ + +#endif /* no HAVE_GETPAGESIZE */ + +int +main () +{ + char *data, *data2, *data3; + const char *cdata2; + int i, pagesize; + int fd, fd2; + + pagesize = getpagesize (); + + /* First, make a file with some known garbage in it. */ + data = (char *) malloc (pagesize); + if (!data) + return 1; + for (i = 0; i < pagesize; ++i) + *(data + i) = rand (); + umask (0); + fd = creat ("conftest.mmap", 0600); + if (fd < 0) + return 2; + if (write (fd, data, pagesize) != pagesize) + return 3; + close (fd); + + /* Next, check that the tail of a page is zero-filled. File must have + non-zero length, otherwise we risk SIGBUS for entire page. */ + fd2 = open ("conftest.txt", O_RDWR | O_CREAT | O_TRUNC, 0600); + if (fd2 < 0) + return 4; + cdata2 = ""; + if (write (fd2, cdata2, 1) != 1) + return 5; + data2 = (char *) mmap (0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd2, 0L); + if (data2 == MAP_FAILED) + return 6; + for (i = 0; i < pagesize; ++i) + if (*(data2 + i)) + return 7; + close (fd2); + if (munmap (data2, pagesize)) + return 8; + + /* Next, try to mmap the file at a fixed address which already has + something else allocated at it. If we can, also make sure that + we see the same garbage. */ + fd = open ("conftest.mmap", O_RDWR); + if (fd < 0) + return 9; + if (data2 != mmap (data2, pagesize, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED, fd, 0L)) + return 10; + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data2 + i)) + return 11; + + /* Finally, make sure that changes to the mapped area do not + percolate back to the file as seen by read(). (This is a bug on + some variants of i386 svr4.0.) */ + for (i = 0; i < pagesize; ++i) + *(data2 + i) = *(data2 + i) + 1; + data3 = (char *) malloc (pagesize); + if (!data3) + return 12; + if (read (fd, data3, pagesize) != pagesize) + return 13; + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data3 + i)) + return 14; + close (fd); + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_mmap_fixed_mapped=yes +else + ac_cv_func_mmap_fixed_mapped=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_mmap_fixed_mapped" >&5 +$as_echo "$ac_cv_func_mmap_fixed_mapped" >&6; } +if test $ac_cv_func_mmap_fixed_mapped = yes; then + +$as_echo "#define HAVE_MMAP 1" >>confdefs.h + +fi +rm -f conftest.mmap conftest.txt + +for ac_header in stdlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STDLIB_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible realloc" >&5 +$as_echo_n "checking for GNU libc compatible realloc... " >&6; } +if ${ac_cv_func_realloc_0_nonnull+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_realloc_0_nonnull=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined STDC_HEADERS || defined HAVE_STDLIB_H +# include <stdlib.h> +#else +char *realloc (); +#endif + +int +main () +{ +return ! realloc (0, 0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_realloc_0_nonnull=yes +else + ac_cv_func_realloc_0_nonnull=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_realloc_0_nonnull" >&5 +$as_echo "$ac_cv_func_realloc_0_nonnull" >&6; } +if test $ac_cv_func_realloc_0_nonnull = yes; then : + +$as_echo "#define HAVE_REALLOC 1" >>confdefs.h + +else + $as_echo "#define HAVE_REALLOC 0" >>confdefs.h + + case " $LIBOBJS " in + *" realloc.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS realloc.$ac_objext" + ;; +esac + + +$as_echo "#define realloc rpl_realloc" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stat accepts an empty string" >&5 +$as_echo_n "checking whether stat accepts an empty string... " >&6; } +if ${ac_cv_func_stat_empty_string_bug+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_stat_empty_string_bug=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +struct stat sbuf; + return stat ("", &sbuf) == 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_stat_empty_string_bug=no +else + ac_cv_func_stat_empty_string_bug=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_stat_empty_string_bug" >&5 +$as_echo "$ac_cv_func_stat_empty_string_bug" >&6; } +if test $ac_cv_func_stat_empty_string_bug = yes; then + case " $LIBOBJS " in + *" stat.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS stat.$ac_objext" + ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define HAVE_STAT_EMPTY_STRING_BUG 1 +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working strtod" >&5 +$as_echo_n "checking for working strtod... " >&6; } +if ${ac_cv_func_strtod+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_strtod=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +$ac_includes_default +#ifndef strtod +double strtod (); +#endif +int +main() +{ + { + /* Some versions of Linux strtod mis-parse strings with leading '+'. */ + char *string = " +69"; + char *term; + double value; + value = strtod (string, &term); + if (value != 69 || term != (string + 4)) + return 1; + } + + { + /* Under Solaris 2.4, strtod returns the wrong value for the + terminating character under some conditions. */ + char *string = "NaN"; + char *term; + strtod (string, &term); + if (term != string && *(term - 1) == 0) + return 1; + } + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_strtod=yes +else + ac_cv_func_strtod=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strtod" >&5 +$as_echo "$ac_cv_func_strtod" >&6; } +if test $ac_cv_func_strtod = no; then + case " $LIBOBJS " in + *" strtod.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS strtod.$ac_objext" + ;; +esac + +ac_fn_c_check_func "$LINENO" "pow" "ac_cv_func_pow" +if test "x$ac_cv_func_pow" = xyes; then : + +fi + +if test $ac_cv_func_pow = no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pow in -lm" >&5 +$as_echo_n "checking for pow in -lm... " >&6; } +if ${ac_cv_lib_m_pow+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lm $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pow (); +int +main () +{ +return pow (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_m_pow=yes +else + ac_cv_lib_m_pow=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_pow" >&5 +$as_echo "$ac_cv_lib_m_pow" >&6; } +if test "x$ac_cv_lib_m_pow" = xyes; then : + POW_LIB=-lm +else + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cannot find library containing definition of pow" >&5 +$as_echo "$as_me: WARNING: cannot find library containing definition of pow" >&2;} +fi + +fi + +fi + +for ac_func in vprintf +do : + ac_fn_c_check_func "$LINENO" "vprintf" "ac_cv_func_vprintf" +if test "x$ac_cv_func_vprintf" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_VPRINTF 1 +_ACEOF + +ac_fn_c_check_func "$LINENO" "_doprnt" "ac_cv_func__doprnt" +if test "x$ac_cv_func__doprnt" = xyes; then : + +$as_echo "#define HAVE_DOPRNT 1" >>confdefs.h + +fi + +fi +done + + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable dependency tracking" >&5 +$as_echo_n "checking whether to enable dependency tracking... " >&6; } +# Check whether --enable-dependency-tracking was given. +if test "${enable_dependency_tracking+set}" = set; then : + enableval=$enable_dependency_tracking; USE_TRACKING=$enableval +else + USE_TRACKING=yes +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $USE_TRACKING" >&5 +$as_echo "$USE_TRACKING" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to use static linking" >&5 +$as_echo_n "checking whether to use static linking... " >&6; } +# Check whether --enable-static_link was given. +if test "${enable_static_link+set}" = set; then : + enableval=$enable_static_link; STATIC_LINK=$enableval +else + STATIC_LINK=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $STATIC_LINK" >&5 +$as_echo "$STATIC_LINK" >&6; } + +################################################################################ + + + ac_save_CFLAGS=$CFLAGS + CFLAGS=-pie + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -pie flag" >&5 +$as_echo_n "checking whether $CC accepts -pie flag... " >&6; } +if ${ac_cv_flag_HAVE_PIE+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_flag_HAVE_PIE=yes +else + ac_cv_flag_HAVE_PIE=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_flag_HAVE_PIE" >&5 +$as_echo "$ac_cv_flag_HAVE_PIE" >&6; } + CFLAGS=$ac_save_CFLAGS + HAVE_PIE=$ac_cv_flag_HAVE_PIE + if test "HAVE_PIE" = yes; then + : + else + : + fi + + + + + ac_save_LDFLAGS=$LDFLAGS + LDFLAGS=-Wl,-z,relro,-z,now + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Wl,-z,relro,-z,now ld flags" >&5 +$as_echo_n "checking whether $CC accepts -Wl,-z,relro,-z,now ld flags... " >&6; } +if ${ac_cv_flag_HAVE_FULL_RELRO+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_flag_HAVE_FULL_RELRO=yes +else + ac_cv_flag_HAVE_FULL_RELRO=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_flag_HAVE_FULL_RELRO" >&5 +$as_echo "$ac_cv_flag_HAVE_FULL_RELRO" >&6; } + LDFLAGS=$ac_save_LDFLAGS + HAVE_FULL_RELRO=$ac_cv_flag_HAVE_FULL_RELRO + if test "HAVE_FULL_RELRO" = yes; then + : + else + : + fi + + + +################################################################################ + +if test "$prefix" = NONE; then + datarootdir=${ac_default_prefix}/share +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking file owner" >&5 +$as_echo_n "checking file owner... " >&6; } + +# Check whether --with-user was given. +if test "${with_user+set}" = set; then : + withval=$with_user; OWNER=$withval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $OWNER" >&5 +$as_echo "$OWNER" >&6; } +test -n "$OWNER" && INSTALL="$INSTALL -o $OWNER" + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking group owner" >&5 +$as_echo_n "checking group owner... " >&6; } + +# Check whether --with-group was given. +if test "${with_group+set}" = set; then : + withval=$with_group; GROUP=$withval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $GROUP" >&5 +$as_echo "$GROUP" >&6; } +test -n "$GROUP" && INSTALL="$INSTALL -g $GROUP" + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking device node uid" >&5 +$as_echo_n "checking device node uid... " >&6; } + + +# Check whether --with-device-uid was given. +if test "${with_device_uid+set}" = set; then : + withval=$with_device_uid; DM_DEVICE_UID=$withval +else + DM_DEVICE_UID=0 +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DM_DEVICE_UID" >&5 +$as_echo "$DM_DEVICE_UID" >&6; } + +cat >>confdefs.h <<_ACEOF +#define DM_DEVICE_UID $DM_DEVICE_UID +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking device node gid" >&5 +$as_echo_n "checking device node gid... " >&6; } + + +# Check whether --with-device-gid was given. +if test "${with_device_gid+set}" = set; then : + withval=$with_device_gid; DM_DEVICE_GID=$withval +else + DM_DEVICE_GID=0 +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DM_DEVICE_GID" >&5 +$as_echo "$DM_DEVICE_GID" >&6; } + +cat >>confdefs.h <<_ACEOF +#define DM_DEVICE_GID $DM_DEVICE_GID +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking device node mode" >&5 +$as_echo_n "checking device node mode... " >&6; } + + +# Check whether --with-device-mode was given. +if test "${with_device_mode+set}" = set; then : + withval=$with_device_mode; DM_DEVICE_MODE=$withval +else + DM_DEVICE_MODE=0600 +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DM_DEVICE_MODE" >&5 +$as_echo "$DM_DEVICE_MODE" >&6; } + +cat >>confdefs.h <<_ACEOF +#define DM_DEVICE_MODE $DM_DEVICE_MODE +_ACEOF + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking when to create device nodes" >&5 +$as_echo_n "checking when to create device nodes... " >&6; } + +# Check whether --with-device-nodes-on was given. +if test "${with_device_nodes_on+set}" = set; then : + withval=$with_device_nodes_on; ADD_NODE=$withval +else + ADD_NODE=resume +fi + +case "$ADD_NODE" in + resume) add_on=DM_ADD_NODE_ON_RESUME;; + create) add_on=DM_ADD_NODE_ON_CREATE;; + *) as_fn_error $? "--with-device-nodes-on parameter invalid" "$LINENO" 5;; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: on $ADD_NODE" >&5 +$as_echo "on $ADD_NODE" >&6; } + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_DM_ADD_NODE $add_on +_ACEOF + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking default name mangling" >&5 +$as_echo_n "checking default name mangling... " >&6; } + +# Check whether --with-default-name-mangling was given. +if test "${with_default_name_mangling+set}" = set; then : + withval=$with_default_name_mangling; MANGLING=$withval +else + MANGLING=auto +fi + +case "$MANGLING" in + auto) mangling=DM_STRING_MANGLING_AUTO;; + none|disabled) mangling=DM_STRING_MANGLING_NONE;; + hex) mangling=DM_STRING_MANGLING_HEX;; + *) as_fn_error $? "--with-default-name-mangling parameter invalid" "$LINENO" 5;; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANGLING" >&5 +$as_echo "$MANGLING" >&6; } + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_DM_NAME_MANGLING $mangling +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable lvm1 fallback" >&5 +$as_echo_n "checking whether to enable lvm1 fallback... " >&6; } +# Check whether --enable-lvm1_fallback was given. +if test "${enable_lvm1_fallback+set}" = set; then : + enableval=$enable_lvm1_fallback; LVM1_FALLBACK=$enableval +else + LVM1_FALLBACK=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LVM1_FALLBACK" >&5 +$as_echo "$LVM1_FALLBACK" >&6; } + +if test "$LVM1_FALLBACK" = yes; then + DEFAULT_FALLBACK_TO_LVM1=1 + +$as_echo "#define LVM1_FALLBACK 1" >>confdefs.h + +else + DEFAULT_FALLBACK_TO_LVM1=0 +fi + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_FALLBACK_TO_LVM1 $DEFAULT_FALLBACK_TO_LVM1 +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include support for lvm1 metadata" >&5 +$as_echo_n "checking whether to include support for lvm1 metadata... " >&6; } + +# Check whether --with-lvm1 was given. +if test "${with_lvm1+set}" = set; then : + withval=$with_lvm1; LVM1=$withval +else + LVM1=internal +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LVM1" >&5 +$as_echo "$LVM1" >&6; } + +case "$LVM1" in + none|shared) ;; + internal) +$as_echo "#define LVM1_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-lvm1 parameter invalid" "$LINENO" 5 ;; +esac + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include support for GFS pool metadata" >&5 +$as_echo_n "checking whether to include support for GFS pool metadata... " >&6; } + +# Check whether --with-pool was given. +if test "${with_pool+set}" = set; then : + withval=$with_pool; POOL=$withval +else + POOL=internal +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $POOL" >&5 +$as_echo "$POOL" >&6; } + +case "$POOL" in + none|shared) ;; + internal) +$as_echo "#define POOL_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-pool parameter invalid" "$LINENO" 5 +esac + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include support for cluster locking" >&5 +$as_echo_n "checking whether to include support for cluster locking... " >&6; } + +# Check whether --with-cluster was given. +if test "${with_cluster+set}" = set; then : + withval=$with_cluster; CLUSTER=$withval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CLUSTER" >&5 +$as_echo "$CLUSTER" >&6; } + +case "$CLUSTER" in + none|shared) ;; + internal) +$as_echo "#define CLUSTER_LOCKING_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-cluster parameter invalid" "$LINENO" 5 ;; +esac + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include snapshots" >&5 +$as_echo_n "checking whether to include snapshots... " >&6; } + +# Check whether --with-snapshots was given. +if test "${with_snapshots+set}" = set; then : + withval=$with_snapshots; SNAPSHOTS=$withval +else + SNAPSHOTS=internal +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SNAPSHOTS" >&5 +$as_echo "$SNAPSHOTS" >&6; } + +case "$SNAPSHOTS" in + none|shared) ;; + internal) +$as_echo "#define SNAPSHOT_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-snapshots parameter invalid" "$LINENO" 5 ;; +esac + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include mirrors" >&5 +$as_echo_n "checking whether to include mirrors... " >&6; } + +# Check whether --with-mirrors was given. +if test "${with_mirrors+set}" = set; then : + withval=$with_mirrors; MIRRORS=$withval +else + MIRRORS=internal +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MIRRORS" >&5 +$as_echo "$MIRRORS" >&6; } + +case "$MIRRORS" in + none|shared) ;; + internal) +$as_echo "#define MIRRORED_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-mirrors parameter invalid" "$LINENO" 5 ;; +esac + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include raid" >&5 +$as_echo_n "checking whether to include raid... " >&6; } + +# Check whether --with-raid was given. +if test "${with_raid+set}" = set; then : + withval=$with_raid; RAID=$withval +else + RAID=internal +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $RAID" >&5 +$as_echo "$RAID" >&6; } + + +# Check whether --with-default-mirror-segtype was given. +if test "${with_default_mirror_segtype+set}" = set; then : + withval=$with_default_mirror_segtype; DEFAULT_MIRROR_SEGTYPE=$withval +else + DEFAULT_MIRROR_SEGTYPE="raid1" +fi + + +# Check whether --with-default-raid10-segtype was given. +if test "${with_default_raid10_segtype+set}" = set; then : + withval=$with_default_raid10_segtype; DEFAULT_RAID10_SEGTYPE=$withval +else + DEFAULT_RAID10_SEGTYPE="raid10" +fi + +case "$RAID" in + none) test "$DEFAULT_MIRROR_SEGTYPE" = "raid1" && DEFAULT_MIRROR_SEGTYPE="mirror" + test "$DEFAULT_RAID10_SEGTYPE" = "raid10" && DEFAULT_RAID10_SEGTYPE="mirror" ;; + shared) ;; + internal) +$as_echo "#define RAID_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-raid parameter invalid" "$LINENO" 5 ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_MIRROR_SEGTYPE "$DEFAULT_MIRROR_SEGTYPE" +_ACEOF + + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_RAID10_SEGTYPE "$DEFAULT_RAID10_SEGTYPE" +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include replicators" >&5 +$as_echo_n "checking whether to include replicators... " >&6; } + +# Check whether --with-replicators was given. +if test "${with_replicators+set}" = set; then : + withval=$with_replicators; REPLICATORS=$withval +else + REPLICATORS=none +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $REPLICATORS" >&5 +$as_echo "$REPLICATORS" >&6; } + +case "$REPLICATORS" in + none|shared) ;; + internal) +$as_echo "#define REPLICATOR_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-replicators parameter invalid ($REPLICATORS)" "$LINENO" 5 ;; +esac + + + +# Check whether --with-default-sparse-segtype was given. +if test "${with_default_sparse_segtype+set}" = set; then : + withval=$with_default_sparse_segtype; DEFAULT_SPARSE_SEGTYPE=$withval +else + DEFAULT_SPARSE_SEGTYPE="thin" +fi + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include thin provisioning" >&5 +$as_echo_n "checking whether to include thin provisioning... " >&6; } + +# Check whether --with-thin was given. +if test "${with_thin+set}" = set; then : + withval=$with_thin; THIN=$withval +else + THIN=internal +fi + + +# Check whether --with-thin-check was given. +if test "${with_thin_check+set}" = set; then : + withval=$with_thin_check; THIN_CHECK_CMD=$withval +else + THIN_CHECK_CMD="autodetect" +fi + + +# Check whether --with-thin-dump was given. +if test "${with_thin_dump+set}" = set; then : + withval=$with_thin_dump; THIN_DUMP_CMD=$withval +else + THIN_DUMP_CMD="autodetect" +fi + + +# Check whether --with-thin-repair was given. +if test "${with_thin_repair+set}" = set; then : + withval=$with_thin_repair; THIN_REPAIR_CMD=$withval +else + THIN_REPAIR_CMD="autodetect" +fi + + +# Check whether --with-thin-restore was given. +if test "${with_thin_restore+set}" = set; then : + withval=$with_thin_restore; THIN_RESTORE_CMD=$withval +else + THIN_RESTORE_CMD="autodetect" +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $THIN" >&5 +$as_echo "$THIN" >&6; } + +case "$THIN" in + none) test "$DEFAULT_SPARSE_SEGTYPE" = "thin" && DEFAULT_SPARSE_SEGTYPE="snapshot" ;; + shared) ;; + internal) +$as_echo "#define THIN_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-thin parameter invalid ($THIN)" "$LINENO" 5 ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_SPARSE_SEGTYPE "$DEFAULT_SPARSE_SEGTYPE" +_ACEOF + + +# Check whether --enable-thin_check_needs_check was given. +if test "${enable_thin_check_needs_check+set}" = set; then : + enableval=$enable_thin_check_needs_check; THIN_CHECK_NEEDS_CHECK=$enableval +else + THIN_CHECK_NEEDS_CHECK=yes +fi + + +# Test if necessary thin tools are available +# if not - use plain defaults and warn user +case "$THIN" in + internal|shared) + # Empty means a config way to ignore thin checking + if test "$THIN_CHECK_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}thin_check", so it can be a program name with args. +set dummy ${ac_tool_prefix}thin_check; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_THIN_CHECK_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $THIN_CHECK_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_THIN_CHECK_CMD="$THIN_CHECK_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_THIN_CHECK_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +THIN_CHECK_CMD=$ac_cv_path_THIN_CHECK_CMD +if test -n "$THIN_CHECK_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $THIN_CHECK_CMD" >&5 +$as_echo "$THIN_CHECK_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_THIN_CHECK_CMD"; then + ac_pt_THIN_CHECK_CMD=$THIN_CHECK_CMD + # Extract the first word of "thin_check", so it can be a program name with args. +set dummy thin_check; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_THIN_CHECK_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_THIN_CHECK_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_THIN_CHECK_CMD="$ac_pt_THIN_CHECK_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_THIN_CHECK_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_THIN_CHECK_CMD=$ac_cv_path_ac_pt_THIN_CHECK_CMD +if test -n "$ac_pt_THIN_CHECK_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_THIN_CHECK_CMD" >&5 +$as_echo "$ac_pt_THIN_CHECK_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_THIN_CHECK_CMD" = x; then + THIN_CHECK_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + THIN_CHECK_CMD=$ac_pt_THIN_CHECK_CMD + fi +else + THIN_CHECK_CMD="$ac_cv_path_THIN_CHECK_CMD" +fi + + if test -z "$THIN_CHECK_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: thin_check not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: thin_check not found in path $PATH" >&2;} + THIN_CHECK_CMD=/usr/sbin/thin_check + THIN_CONFIGURE_WARN=y + fi + fi + if test "$THIN_CHECK_NEEDS_CHECK" = yes; then + THIN_CHECK_VSN=`"$THIN_CHECK_CMD" -V 2>/dev/null` + THIN_CHECK_VSN_MAJOR=`echo "$THIN_CHECK_VSN" | $AWK -F '.' '{print $1}'` + THIN_CHECK_VSN_MINOR=`echo "$THIN_CHECK_VSN" | $AWK -F '.' '{print $2}'` + + if test -z "$THIN_CHECK_VSN_MAJOR" -o -z "$THIN_CHECK_VSN_MINOR"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $THIN_CHECK_CMD: Bad version \"$THIN_CHECK_VSN\" found" >&5 +$as_echo "$as_me: WARNING: $THIN_CHECK_CMD: Bad version \"$THIN_CHECK_VSN\" found" >&2;} + THIN_CHECK_VERSION_WARN=y + THIN_CHECK_NEEDS_CHECK=no + elif test "$THIN_CHECK_VSN_MAJOR" -eq 0 -a "$THIN_CHECK_VSN_MINOR" -lt 3; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $THIN_CHECK_CMD: Old version \"$THIN_CHECK_VSN\" found" >&5 +$as_echo "$as_me: WARNING: $THIN_CHECK_CMD: Old version \"$THIN_CHECK_VSN\" found" >&2;} + THIN_CHECK_VERSION_WARN=y + THIN_CHECK_NEEDS_CHECK=no + fi + fi + # Empty means a config way to ignore thin dumping + if test "$THIN_DUMP_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}thin_dump", so it can be a program name with args. +set dummy ${ac_tool_prefix}thin_dump; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_THIN_DUMP_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $THIN_DUMP_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_THIN_DUMP_CMD="$THIN_DUMP_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_THIN_DUMP_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +THIN_DUMP_CMD=$ac_cv_path_THIN_DUMP_CMD +if test -n "$THIN_DUMP_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $THIN_DUMP_CMD" >&5 +$as_echo "$THIN_DUMP_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_THIN_DUMP_CMD"; then + ac_pt_THIN_DUMP_CMD=$THIN_DUMP_CMD + # Extract the first word of "thin_dump", so it can be a program name with args. +set dummy thin_dump; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_THIN_DUMP_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_THIN_DUMP_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_THIN_DUMP_CMD="$ac_pt_THIN_DUMP_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_THIN_DUMP_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_THIN_DUMP_CMD=$ac_cv_path_ac_pt_THIN_DUMP_CMD +if test -n "$ac_pt_THIN_DUMP_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_THIN_DUMP_CMD" >&5 +$as_echo "$ac_pt_THIN_DUMP_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_THIN_DUMP_CMD" = x; then + THIN_DUMP_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + THIN_DUMP_CMD=$ac_pt_THIN_DUMP_CMD + fi +else + THIN_DUMP_CMD="$ac_cv_path_THIN_DUMP_CMD" +fi + + test -z "$THIN_DUMP_CMD" && { + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: thin_dump not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: thin_dump not found in path $PATH" >&2;} + THIN_DUMP_CMD=/usr/sbin/thin_dump + THIN_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore thin repairing + if test "$THIN_REPAIR_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}thin_repair", so it can be a program name with args. +set dummy ${ac_tool_prefix}thin_repair; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_THIN_REPAIR_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $THIN_REPAIR_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_THIN_REPAIR_CMD="$THIN_REPAIR_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_THIN_REPAIR_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +THIN_REPAIR_CMD=$ac_cv_path_THIN_REPAIR_CMD +if test -n "$THIN_REPAIR_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $THIN_REPAIR_CMD" >&5 +$as_echo "$THIN_REPAIR_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_THIN_REPAIR_CMD"; then + ac_pt_THIN_REPAIR_CMD=$THIN_REPAIR_CMD + # Extract the first word of "thin_repair", so it can be a program name with args. +set dummy thin_repair; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_THIN_REPAIR_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_THIN_REPAIR_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_THIN_REPAIR_CMD="$ac_pt_THIN_REPAIR_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_THIN_REPAIR_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_THIN_REPAIR_CMD=$ac_cv_path_ac_pt_THIN_REPAIR_CMD +if test -n "$ac_pt_THIN_REPAIR_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_THIN_REPAIR_CMD" >&5 +$as_echo "$ac_pt_THIN_REPAIR_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_THIN_REPAIR_CMD" = x; then + THIN_REPAIR_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + THIN_REPAIR_CMD=$ac_pt_THIN_REPAIR_CMD + fi +else + THIN_REPAIR_CMD="$ac_cv_path_THIN_REPAIR_CMD" +fi + + test -z "$THIN_REPAIR_CMD" && { + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: thin_repair not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: thin_repair not found in path $PATH" >&2;} + THIN_REPAIR_CMD=/usr/sbin/thin_repair + THIN_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore thin restoring + if test "$THIN_RESTORE_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}thin_restore", so it can be a program name with args. +set dummy ${ac_tool_prefix}thin_restore; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_THIN_RESTORE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $THIN_RESTORE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_THIN_RESTORE_CMD="$THIN_RESTORE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_THIN_RESTORE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +THIN_RESTORE_CMD=$ac_cv_path_THIN_RESTORE_CMD +if test -n "$THIN_RESTORE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $THIN_RESTORE_CMD" >&5 +$as_echo "$THIN_RESTORE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_THIN_RESTORE_CMD"; then + ac_pt_THIN_RESTORE_CMD=$THIN_RESTORE_CMD + # Extract the first word of "thin_restore", so it can be a program name with args. +set dummy thin_restore; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_THIN_RESTORE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_THIN_RESTORE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_THIN_RESTORE_CMD="$ac_pt_THIN_RESTORE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_THIN_RESTORE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_THIN_RESTORE_CMD=$ac_cv_path_ac_pt_THIN_RESTORE_CMD +if test -n "$ac_pt_THIN_RESTORE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_THIN_RESTORE_CMD" >&5 +$as_echo "$ac_pt_THIN_RESTORE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_THIN_RESTORE_CMD" = x; then + THIN_RESTORE_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + THIN_RESTORE_CMD=$ac_pt_THIN_RESTORE_CMD + fi +else + THIN_RESTORE_CMD="$ac_cv_path_THIN_RESTORE_CMD" +fi + + test -z "$THIN_RESTORE_CMD" && { + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: thin_restore not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: thin_restore not found in path $PATH" >&2;} + THIN_RESTORE_CMD=/usr/sbin/thin_restore + THIN_CONFIGURE_WARN=y + } + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether thin_check supports the needs-check flag" >&5 +$as_echo_n "checking whether thin_check supports the needs-check flag... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $THIN_CHECK_NEEDS_CHECK" >&5 +$as_echo "$THIN_CHECK_NEEDS_CHECK" >&6; } + if test "$THIN_CHECK_NEEDS_CHECK" = yes; then + +$as_echo "#define THIN_CHECK_NEEDS_CHECK 1" >>confdefs.h + + fi + + ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define THIN_CHECK_CMD "$THIN_CHECK_CMD" +_ACEOF + + + +cat >>confdefs.h <<_ACEOF +#define THIN_DUMP_CMD "$THIN_DUMP_CMD" +_ACEOF + + + +cat >>confdefs.h <<_ACEOF +#define THIN_REPAIR_CMD "$THIN_REPAIR_CMD" +_ACEOF + + + +cat >>confdefs.h <<_ACEOF +#define THIN_RESTORE_CMD "$THIN_RESTORE_CMD" +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include cache" >&5 +$as_echo_n "checking whether to include cache... " >&6; } + +# Check whether --with-cache was given. +if test "${with_cache+set}" = set; then : + withval=$with_cache; CACHE=$withval +else + CACHE="internal" +fi + + +# Check whether --with-cache-check was given. +if test "${with_cache_check+set}" = set; then : + withval=$with_cache_check; CACHE_CHECK_CMD=$withval +else + CACHE_CHECK_CMD="autodetect" +fi + + +# Check whether --with-cache-dump was given. +if test "${with_cache_dump+set}" = set; then : + withval=$with_cache_dump; CACHE_DUMP_CMD=$withval +else + CACHE_DUMP_CMD="autodetect" +fi + + +# Check whether --with-cache-repair was given. +if test "${with_cache_repair+set}" = set; then : + withval=$with_cache_repair; CACHE_REPAIR_CMD=$withval +else + CACHE_REPAIR_CMD="autodetect" +fi + + +# Check whether --with-cache-restore was given. +if test "${with_cache_restore+set}" = set; then : + withval=$with_cache_restore; CACHE_RESTORE_CMD=$withval +else + CACHE_RESTORE_CMD="autodetect" +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CACHE" >&5 +$as_echo "$CACHE" >&6; } + +case "$CACHE" in + none|shared) ;; + internal) +$as_echo "#define CACHE_INTERNAL 1" >>confdefs.h + ;; + *) as_fn_error $? "--with-cache parameter invalid" "$LINENO" 5 ;; +esac + +# Check whether --enable-cache_check_needs_check was given. +if test "${enable_cache_check_needs_check+set}" = set; then : + enableval=$enable_cache_check_needs_check; CACHE_CHECK_NEEDS_CHECK=$enableval +else + CACHE_CHECK_NEEDS_CHECK=yes +fi + + +# Test if necessary cache tools are available +# if not - use plain defaults and warn user +case "$CACHE" in + internal|shared) + # Empty means a config way to ignore cache checking + if test "$CACHE_CHECK_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cache_check", so it can be a program name with args. +set dummy ${ac_tool_prefix}cache_check; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_CACHE_CHECK_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $CACHE_CHECK_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_CACHE_CHECK_CMD="$CACHE_CHECK_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_CACHE_CHECK_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CACHE_CHECK_CMD=$ac_cv_path_CACHE_CHECK_CMD +if test -n "$CACHE_CHECK_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CACHE_CHECK_CMD" >&5 +$as_echo "$CACHE_CHECK_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_CACHE_CHECK_CMD"; then + ac_pt_CACHE_CHECK_CMD=$CACHE_CHECK_CMD + # Extract the first word of "cache_check", so it can be a program name with args. +set dummy cache_check; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_CACHE_CHECK_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_CACHE_CHECK_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_CACHE_CHECK_CMD="$ac_pt_CACHE_CHECK_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_CACHE_CHECK_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_CACHE_CHECK_CMD=$ac_cv_path_ac_pt_CACHE_CHECK_CMD +if test -n "$ac_pt_CACHE_CHECK_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_CACHE_CHECK_CMD" >&5 +$as_echo "$ac_pt_CACHE_CHECK_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_CACHE_CHECK_CMD" = x; then + CACHE_CHECK_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CACHE_CHECK_CMD=$ac_pt_CACHE_CHECK_CMD + fi +else + CACHE_CHECK_CMD="$ac_cv_path_CACHE_CHECK_CMD" +fi + + if test -z "$CACHE_CHECK_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache_check not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: cache_check not found in path $PATH" >&2;} + CACHE_CHECK_CMD=/usr/sbin/cache_check + CACHE_CONFIGURE_WARN=y + fi + fi + if test "$CACHE_CHECK_NEEDS_CHECK" = yes; then + $CACHE_CHECK_CMD -V 2>/dev/null >conftest.tmp + read -r CACHE_CHECK_VSN < conftest.tmp + IFS=.- read -r CACHE_CHECK_VSN_MAJOR CACHE_CHECK_VSN_MINOR CACHE_CHECK_VSN_PATCH LEFTOVER < conftest.tmp + rm -f conftest.tmp + + # Require version >= 0.5.4 for --clear-needs-check-flag + if test -z "$CACHE_CHECK_VSN_MAJOR" \ + || test -z "$CACHE_CHECK_VSN_MINOR" \ + || test -z "$CACHE_CHECK_VSN_PATCH"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $CACHE_CHECK_CMD: Bad version \"$CACHE_CHECK_VSN\" found" >&5 +$as_echo "$as_me: WARNING: $CACHE_CHECK_CMD: Bad version \"$CACHE_CHECK_VSN\" found" >&2;} + CACHE_CHECK_VERSION_WARN=y + CACHE_CHECK_NEEDS_CHECK=no + elif test "$CACHE_CHECK_VSN_MAJOR" -eq 0 ; then + if test "$CACHE_CHECK_VSN_MINOR" -lt 5 \ + || test "$CACHE_CHECK_VSN_MINOR" -eq 5 -a "$CACHE_CHECK_VSN_PATCH" -lt 4; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $CACHE_CHECK_CMD: Old version \"$CACHE_CHECK_VSN\" found" >&5 +$as_echo "$as_me: WARNING: $CACHE_CHECK_CMD: Old version \"$CACHE_CHECK_VSN\" found" >&2;} + CACHE_CHECK_VERSION_WARN=y + CACHE_CHECK_NEEDS_CHECK=no + fi + fi + fi + # Empty means a config way to ignore cache dumping + if test "$CACHE_DUMP_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cache_dump", so it can be a program name with args. +set dummy ${ac_tool_prefix}cache_dump; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_CACHE_DUMP_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $CACHE_DUMP_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_CACHE_DUMP_CMD="$CACHE_DUMP_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_CACHE_DUMP_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CACHE_DUMP_CMD=$ac_cv_path_CACHE_DUMP_CMD +if test -n "$CACHE_DUMP_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CACHE_DUMP_CMD" >&5 +$as_echo "$CACHE_DUMP_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_CACHE_DUMP_CMD"; then + ac_pt_CACHE_DUMP_CMD=$CACHE_DUMP_CMD + # Extract the first word of "cache_dump", so it can be a program name with args. +set dummy cache_dump; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_CACHE_DUMP_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_CACHE_DUMP_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_CACHE_DUMP_CMD="$ac_pt_CACHE_DUMP_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_CACHE_DUMP_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_CACHE_DUMP_CMD=$ac_cv_path_ac_pt_CACHE_DUMP_CMD +if test -n "$ac_pt_CACHE_DUMP_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_CACHE_DUMP_CMD" >&5 +$as_echo "$ac_pt_CACHE_DUMP_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_CACHE_DUMP_CMD" = x; then + CACHE_DUMP_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CACHE_DUMP_CMD=$ac_pt_CACHE_DUMP_CMD + fi +else + CACHE_DUMP_CMD="$ac_cv_path_CACHE_DUMP_CMD" +fi + + test -z "$CACHE_DUMP_CMD" && { + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache_dump not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: cache_dump not found in path $PATH" >&2;} + CACHE_DUMP_CMD=/usr/sbin/cache_dump + CACHE_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore cache repairing + if test "$CACHE_REPAIR_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cache_repair", so it can be a program name with args. +set dummy ${ac_tool_prefix}cache_repair; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_CACHE_REPAIR_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $CACHE_REPAIR_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_CACHE_REPAIR_CMD="$CACHE_REPAIR_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_CACHE_REPAIR_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CACHE_REPAIR_CMD=$ac_cv_path_CACHE_REPAIR_CMD +if test -n "$CACHE_REPAIR_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CACHE_REPAIR_CMD" >&5 +$as_echo "$CACHE_REPAIR_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_CACHE_REPAIR_CMD"; then + ac_pt_CACHE_REPAIR_CMD=$CACHE_REPAIR_CMD + # Extract the first word of "cache_repair", so it can be a program name with args. +set dummy cache_repair; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_CACHE_REPAIR_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_CACHE_REPAIR_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_CACHE_REPAIR_CMD="$ac_pt_CACHE_REPAIR_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_CACHE_REPAIR_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_CACHE_REPAIR_CMD=$ac_cv_path_ac_pt_CACHE_REPAIR_CMD +if test -n "$ac_pt_CACHE_REPAIR_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_CACHE_REPAIR_CMD" >&5 +$as_echo "$ac_pt_CACHE_REPAIR_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_CACHE_REPAIR_CMD" = x; then + CACHE_REPAIR_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CACHE_REPAIR_CMD=$ac_pt_CACHE_REPAIR_CMD + fi +else + CACHE_REPAIR_CMD="$ac_cv_path_CACHE_REPAIR_CMD" +fi + + test -z "$CACHE_REPAIR_CMD" && { + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache_repair not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: cache_repair not found in path $PATH" >&2;} + CACHE_REPAIR_CMD=/usr/sbin/cache_repair + CACHE_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore cache restoring + if test "$CACHE_RESTORE_CMD" = "autodetect"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cache_restore", so it can be a program name with args. +set dummy ${ac_tool_prefix}cache_restore; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_CACHE_RESTORE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $CACHE_RESTORE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_CACHE_RESTORE_CMD="$CACHE_RESTORE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_CACHE_RESTORE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +CACHE_RESTORE_CMD=$ac_cv_path_CACHE_RESTORE_CMD +if test -n "$CACHE_RESTORE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CACHE_RESTORE_CMD" >&5 +$as_echo "$CACHE_RESTORE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_CACHE_RESTORE_CMD"; then + ac_pt_CACHE_RESTORE_CMD=$CACHE_RESTORE_CMD + # Extract the first word of "cache_restore", so it can be a program name with args. +set dummy cache_restore; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_CACHE_RESTORE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_CACHE_RESTORE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_CACHE_RESTORE_CMD="$ac_pt_CACHE_RESTORE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_CACHE_RESTORE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_CACHE_RESTORE_CMD=$ac_cv_path_ac_pt_CACHE_RESTORE_CMD +if test -n "$ac_pt_CACHE_RESTORE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_CACHE_RESTORE_CMD" >&5 +$as_echo "$ac_pt_CACHE_RESTORE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_CACHE_RESTORE_CMD" = x; then + CACHE_RESTORE_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CACHE_RESTORE_CMD=$ac_pt_CACHE_RESTORE_CMD + fi +else + CACHE_RESTORE_CMD="$ac_cv_path_CACHE_RESTORE_CMD" +fi + + test -z "$CACHE_RESTORE_CMD" && { + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache_restore not found in path $PATH" >&5 +$as_echo "$as_me: WARNING: cache_restore not found in path $PATH" >&2;} + CACHE_RESTORE_CMD=/usr/sbin/cache_restore + CACHE_CONFIGURE_WARN=y + } + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cache_check supports the needs-check flag" >&5 +$as_echo_n "checking whether cache_check supports the needs-check flag... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CACHE_CHECK_NEEDS_CHECK" >&5 +$as_echo "$CACHE_CHECK_NEEDS_CHECK" >&6; } + if test "$CACHE_CHECK_NEEDS_CHECK" = yes; then + +$as_echo "#define CACHE_CHECK_NEEDS_CHECK 1" >>confdefs.h + + fi + ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define CACHE_CHECK_CMD "$CACHE_CHECK_CMD" +_ACEOF + + + +cat >>confdefs.h <<_ACEOF +#define CACHE_DUMP_CMD "$CACHE_DUMP_CMD" +_ACEOF + + + +cat >>confdefs.h <<_ACEOF +#define CACHE_REPAIR_CMD "$CACHE_REPAIR_CMD" +_ACEOF + + + +cat >>confdefs.h <<_ACEOF +#define CACHE_RESTORE_CMD "$CACHE_RESTORE_CMD" +_ACEOF + + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable readline" >&5 +$as_echo_n "checking whether to enable readline... " >&6; } +# Check whether --enable-readline was given. +if test "${enable_readline+set}" = set; then : + enableval=$enable_readline; READLINE=$enableval +else + READLINE=maybe +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $READLINE" >&5 +$as_echo "$READLINE" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable realtime support" >&5 +$as_echo_n "checking whether to enable realtime support... " >&6; } +# Check whether --enable-realtime was given. +if test "${enable_realtime+set}" = set; then : + enableval=$enable_realtime; REALTIME=$enableval +else + REALTIME=yes +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $REALTIME" >&5 +$as_echo "$REALTIME" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable OCF resource agents" >&5 +$as_echo_n "checking whether to enable OCF resource agents... " >&6; } +# Check whether --enable-ocf was given. +if test "${enable_ocf+set}" = set; then : + enableval=$enable_ocf; OCF=$enableval +else + OCF=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $OCF" >&5 +$as_echo "$OCF" >&6; } + +# Check whether --with-ocfdir was given. +if test "${with_ocfdir+set}" = set; then : + withval=$with_ocfdir; OCFDIR=$withval +else + OCFDIR='${prefix}/lib/ocf/resource.d/lvm2' +fi + + +################################################################################ +pkg_config_init() { + if test "$PKGCONFIG_INIT" != 1; then + + + + + + + +if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PKG_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKG_CONFIG=$ac_cv_path_PKG_CONFIG +if test -n "$PKG_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5 +$as_echo "$PKG_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKG_CONFIG"; then + ac_pt_PKG_CONFIG=$PKG_CONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG +if test -n "$ac_pt_PKG_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5 +$as_echo "$ac_pt_PKG_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_PKG_CONFIG" = x; then + PKG_CONFIG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKG_CONFIG=$ac_pt_PKG_CONFIG + fi +else + PKG_CONFIG="$ac_cv_path_PKG_CONFIG" +fi + +fi +if test -n "$PKG_CONFIG"; then + _pkg_min_version=0.9.0 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5 +$as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; } + if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + PKG_CONFIG="" + fi +fi + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for PKGCONFIGINIT" >&5 +$as_echo_n "checking for PKGCONFIGINIT... " >&6; } + +if test -n "$PKGCONFIGINIT_CFLAGS"; then + pkg_cv_PKGCONFIGINIT_CFLAGS="$PKGCONFIGINIT_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"pkgconfiginit\""; } >&5 + ($PKG_CONFIG --exists --print-errors "pkgconfiginit") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_PKGCONFIGINIT_CFLAGS=`$PKG_CONFIG --cflags "pkgconfiginit" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$PKGCONFIGINIT_LIBS"; then + pkg_cv_PKGCONFIGINIT_LIBS="$PKGCONFIGINIT_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"pkgconfiginit\""; } >&5 + ($PKG_CONFIG --exists --print-errors "pkgconfiginit") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_PKGCONFIGINIT_LIBS=`$PKG_CONFIG --libs "pkgconfiginit" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + PKGCONFIGINIT_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "pkgconfiginit" 2>&1` + else + PKGCONFIGINIT_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "pkgconfiginit" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$PKGCONFIGINIT_PKG_ERRORS" >&5 + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: pkg-config initialized" >&5 +$as_echo "pkg-config initialized" >&6; } +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: pkg-config initialized" >&5 +$as_echo "pkg-config initialized" >&6; } +else + PKGCONFIGINIT_CFLAGS=$pkg_cv_PKGCONFIGINIT_CFLAGS + PKGCONFIGINIT_LIBS=$pkg_cv_PKGCONFIGINIT_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + +fi + PKGCONFIG_INIT=1 + fi +} + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for default run directory" >&5 +$as_echo_n "checking for default run directory... " >&6; } +RUN_DIR="/run" +test -d "/run" || RUN_DIR="/var/run" +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $RUN_DIR" >&5 +$as_echo "$RUN_DIR" >&6; } + + +# Check whether --with-default-pid-dir was given. +if test "${with_default_pid_dir+set}" = set; then : + withval=$with_default_pid_dir; DEFAULT_PID_DIR="$withval" +else + DEFAULT_PID_DIR=$RUN_DIR +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_PID_DIR "$DEFAULT_PID_DIR" +_ACEOF + + + + +# Check whether --with-default-dm-run-dir was given. +if test "${with_default_dm_run_dir+set}" = set; then : + withval=$with_default_dm_run_dir; DEFAULT_DM_RUN_DIR="$withval" +else + DEFAULT_DM_RUN_DIR=$RUN_DIR +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_DM_RUN_DIR "$DEFAULT_DM_RUN_DIR" +_ACEOF + + + + +# Check whether --with-default-run-dir was given. +if test "${with_default_run_dir+set}" = set; then : + withval=$with_default_run_dir; DEFAULT_RUN_DIR="$withval" +else + DEFAULT_RUN_DIR="$RUN_DIR/lvm" +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_RUN_DIR "$DEFAULT_RUN_DIR" +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build cluster LVM daemon" >&5 +$as_echo_n "checking whether to build cluster LVM daemon... " >&6; } + +# Check whether --with-clvmd was given. +if test "${with_clvmd+set}" = set; then : + withval=$with_clvmd; CLVMD=$withval +else + CLVMD=none +fi + +test "$CLVMD" = yes && CLVMD=all +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CLVMD" >&5 +$as_echo "$CLVMD" >&6; } + +test "$CLVMD" != none -a "$CLUSTER" = none && CLUSTER=internal + +test "$CLVMD" != none && pkg_config_init + +CLVMD_CMANAGERS="" +CLVMD_NEEDS_QDISKD=no + +if [ `expr x"$CLVMD" : '.*gulm.*'` != 0 ]; then + as_fn_error $? "Since version 2.02.87 GULM locking is no longer supported." "$LINENO" 5; +fi +if [ `expr x"$CLVMD" : '.*cman.*'` != 0 ]; then + BUILDCMAN=yes + CLVMD_CMANAGERS="$CLVMD_CMANAGERS cman" + CLVMD_NEEDS_QDISKD=yes +fi +if [ `expr x"$CLVMD" : '.*corosync.*'` != 0 ]; then + BUILDCOROSYNC=yes + CLVMD_CMANAGERS="$CLVMD_CMANAGERS corosync" +fi +if [ `expr x"$CLVMD" : '.*openais.*'` != 0 ]; then + BUILDOPENAIS=yes + CLVMD_CMANAGERS="$CLVMD_CMANAGERS openais" +fi +test "$CLVMD_NEEDS_QDISKD" != no && CLVMD_CMANAGERS="$CLVMD_CMANAGERS qdiskd" + +soft_bailout() { + NOTFOUND=1 +} + +hard_bailout() { + as_fn_error $? "bailing out" "$LINENO" 5 +} + +if test "$CLVMD" = all; then + bailout=soft_bailout + BUILDCMAN=yes + BUILDCOROSYNC=yes + BUILDOPENAIS=yes +else + bailout=hard_bailout +fi + +check_lib_no_libs() { + lib_no_libs_arg1=$1 + shift + lib_no_libs_arg2=$1 + shift + lib_no_libs_args=$@ + as_ac_Lib=`$as_echo "ac_cv_lib_$lib_no_libs_arg1''_$lib_no_libs_arg2" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $lib_no_libs_arg2 in -l$lib_no_libs_arg1" >&5 +$as_echo_n "checking for $lib_no_libs_arg2 in -l$lib_no_libs_arg1... " >&6; } +if eval \${$as_ac_Lib+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-l$lib_no_libs_arg1 $lib_no_libs_args $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $lib_no_libs_arg2 (); +int +main () +{ +return $lib_no_libs_arg2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$as_ac_Lib=yes" +else + eval "$as_ac_Lib=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +eval ac_res=\$$as_ac_Lib + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +if eval test \"x\$"$as_ac_Lib"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_LIB$lib_no_libs_arg1" | $as_tr_cpp` 1 +_ACEOF + + LIBS="-l$lib_no_libs_arg1 $LIBS" + +else + $bailout +fi + + LIBS=$ac_check_lib_save_LIBS +} + +if test "$BUILDCMAN" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for CMAN" >&5 +$as_echo_n "checking for CMAN... " >&6; } + +if test -n "$CMAN_CFLAGS"; then + pkg_cv_CMAN_CFLAGS="$CMAN_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcman\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcman") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CMAN_CFLAGS=`$PKG_CONFIG --cflags "libcman" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$CMAN_LIBS"; then + pkg_cv_CMAN_LIBS="$CMAN_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcman\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcman") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CMAN_LIBS=`$PKG_CONFIG --libs "libcman" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + CMAN_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libcman" 2>&1` + else + CMAN_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libcman" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$CMAN_PKG_ERRORS" >&5 + + NOTFOUND=0 + for ac_header in libcman.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "libcman.h" "ac_cv_header_libcman_h" "$ac_includes_default" +if test "x$ac_cv_header_libcman_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBCMAN_H 1 +_ACEOF + +else + $bailout +fi + +done + + check_lib_no_libs cman cman_init + if test $NOTFOUND = 0; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no pkg for libcman, using -lcman" >&5 +$as_echo "no pkg for libcman, using -lcman" >&6; } + CMAN_LIBS="-lcman" + HAVE_CMAN=yes + fi +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + NOTFOUND=0 + for ac_header in libcman.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "libcman.h" "ac_cv_header_libcman_h" "$ac_includes_default" +if test "x$ac_cv_header_libcman_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBCMAN_H 1 +_ACEOF + +else + $bailout +fi + +done + + check_lib_no_libs cman cman_init + if test $NOTFOUND = 0; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no pkg for libcman, using -lcman" >&5 +$as_echo "no pkg for libcman, using -lcman" >&6; } + CMAN_LIBS="-lcman" + HAVE_CMAN=yes + fi +else + CMAN_CFLAGS=$pkg_cv_CMAN_CFLAGS + CMAN_LIBS=$pkg_cv_CMAN_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_CMAN=yes +fi + CHECKCONFDB=yes + CHECKDLM=yes +fi + +if test "$BUILDCOROSYNC" = yes -o "$BUILDOPENAIS" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for COROSYNC" >&5 +$as_echo_n "checking for COROSYNC... " >&6; } + +if test -n "$COROSYNC_CFLAGS"; then + pkg_cv_COROSYNC_CFLAGS="$COROSYNC_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"corosync\""; } >&5 + ($PKG_CONFIG --exists --print-errors "corosync") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_COROSYNC_CFLAGS=`$PKG_CONFIG --cflags "corosync" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$COROSYNC_LIBS"; then + pkg_cv_COROSYNC_LIBS="$COROSYNC_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"corosync\""; } >&5 + ($PKG_CONFIG --exists --print-errors "corosync") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_COROSYNC_LIBS=`$PKG_CONFIG --libs "corosync" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + COROSYNC_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "corosync" 2>&1` + else + COROSYNC_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "corosync" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$COROSYNC_PKG_ERRORS" >&5 + + $bailout +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + $bailout +else + COROSYNC_CFLAGS=$pkg_cv_COROSYNC_CFLAGS + COROSYNC_LIBS=$pkg_cv_COROSYNC_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_COROSYNC=yes +fi + CHECKCONFDB=yes + CHECKCMAP=yes +fi + +if test "$BUILDCOROSYNC" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for QUORUM" >&5 +$as_echo_n "checking for QUORUM... " >&6; } + +if test -n "$QUORUM_CFLAGS"; then + pkg_cv_QUORUM_CFLAGS="$QUORUM_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libquorum\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libquorum") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_QUORUM_CFLAGS=`$PKG_CONFIG --cflags "libquorum" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$QUORUM_LIBS"; then + pkg_cv_QUORUM_LIBS="$QUORUM_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libquorum\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libquorum") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_QUORUM_LIBS=`$PKG_CONFIG --libs "libquorum" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + QUORUM_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libquorum" 2>&1` + else + QUORUM_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libquorum" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$QUORUM_PKG_ERRORS" >&5 + + $bailout +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + $bailout +else + QUORUM_CFLAGS=$pkg_cv_QUORUM_CFLAGS + QUORUM_LIBS=$pkg_cv_QUORUM_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_QUORUM=yes +fi + CHECKCPG=yes + CHECKDLM=yes +fi + +if test "$BUILDOPENAIS" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SALCK" >&5 +$as_echo_n "checking for SALCK... " >&6; } + +if test -n "$SALCK_CFLAGS"; then + pkg_cv_SALCK_CFLAGS="$SALCK_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libSaLck\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libSaLck") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_SALCK_CFLAGS=`$PKG_CONFIG --cflags "libSaLck" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$SALCK_LIBS"; then + pkg_cv_SALCK_LIBS="$SALCK_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libSaLck\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libSaLck") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_SALCK_LIBS=`$PKG_CONFIG --libs "libSaLck" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + SALCK_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libSaLck" 2>&1` + else + SALCK_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libSaLck" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$SALCK_PKG_ERRORS" >&5 + + $bailout +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + $bailout +else + SALCK_CFLAGS=$pkg_cv_SALCK_CFLAGS + SALCK_LIBS=$pkg_cv_SALCK_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_SALCK=yes +fi + CHECKCPG=yes +fi + + + +if test "$CHECKCONFDB" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for CONFDB" >&5 +$as_echo_n "checking for CONFDB... " >&6; } + +if test -n "$CONFDB_CFLAGS"; then + pkg_cv_CONFDB_CFLAGS="$CONFDB_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libconfdb\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libconfdb") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CONFDB_CFLAGS=`$PKG_CONFIG --cflags "libconfdb" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$CONFDB_LIBS"; then + pkg_cv_CONFDB_LIBS="$CONFDB_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libconfdb\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libconfdb") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CONFDB_LIBS=`$PKG_CONFIG --libs "libconfdb" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + CONFDB_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libconfdb" 2>&1` + else + CONFDB_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libconfdb" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$CONFDB_PKG_ERRORS" >&5 + + HAVE_CONFDB=no +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + HAVE_CONFDB=no +else + CONFDB_CFLAGS=$pkg_cv_CONFDB_CFLAGS + CONFDB_LIBS=$pkg_cv_CONFDB_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_CONFDB=yes +fi + + for ac_header in corosync/confdb.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "corosync/confdb.h" "ac_cv_header_corosync_confdb_h" "$ac_includes_default" +if test "x$ac_cv_header_corosync_confdb_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_COROSYNC_CONFDB_H 1 +_ACEOF + HAVE_CONFDB_H=yes +else + HAVE_CONFDB_H=no +fi + +done + + + if test "$HAVE_CONFDB" != yes -a "$HAVE_CONFDB_H" = yes; then + check_lib_no_libs confdb confdb_initialize + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no pkg for confdb, using -lconfdb" >&5 +$as_echo "no pkg for confdb, using -lconfdb" >&6; } + CONFDB_LIBS="-lconfdb" + HAVE_CONFDB=yes + fi +fi + + +if test "$CHECKCMAP" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for CMAP" >&5 +$as_echo_n "checking for CMAP... " >&6; } + +if test -n "$CMAP_CFLAGS"; then + pkg_cv_CMAP_CFLAGS="$CMAP_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcmap\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcmap") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CMAP_CFLAGS=`$PKG_CONFIG --cflags "libcmap" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$CMAP_LIBS"; then + pkg_cv_CMAP_LIBS="$CMAP_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcmap\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcmap") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CMAP_LIBS=`$PKG_CONFIG --libs "libcmap" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + CMAP_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libcmap" 2>&1` + else + CMAP_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libcmap" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$CMAP_PKG_ERRORS" >&5 + + HAVE_CMAP=no +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + HAVE_CMAP=no +else + CMAP_CFLAGS=$pkg_cv_CMAP_CFLAGS + CMAP_LIBS=$pkg_cv_CMAP_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_CMAP=yes +fi + + for ac_header in corosync/cmap.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "corosync/cmap.h" "ac_cv_header_corosync_cmap_h" "$ac_includes_default" +if test "x$ac_cv_header_corosync_cmap_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_COROSYNC_CMAP_H 1 +_ACEOF + HAVE_CMAP_H=yes +else + HAVE_CMAP_H=no +fi + +done + + + if test "$HAVE_CMAP" != yes -a "$HAVE_CMAP_H" = yes; then + check_lib_no_libs cmap cmap_initialize + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no pkg for cmap, using -lcmap" >&5 +$as_echo "no pkg for cmap, using -lcmap" >&6; } + CMAP_LIBS="-lcmap" + HAVE_CMAP=yes + fi +fi + +if test "$BUILDCOROSYNC" = yes -a \ + "$HAVE_CMAP" != yes -a "$HAVE_CONFDB" != yes -a "$CLVMD" != all; then + as_fn_error $? "bailing out... cmap (corosync >= 2.0) or confdb (corosync < 2.0) library is required" "$LINENO" 5 +fi + +if test "$CHECKCPG" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for CPG" >&5 +$as_echo_n "checking for CPG... " >&6; } + +if test -n "$CPG_CFLAGS"; then + pkg_cv_CPG_CFLAGS="$CPG_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcpg\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcpg") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CPG_CFLAGS=`$PKG_CONFIG --cflags "libcpg" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$CPG_LIBS"; then + pkg_cv_CPG_LIBS="$CPG_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcpg\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcpg") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CPG_LIBS=`$PKG_CONFIG --libs "libcpg" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + CPG_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libcpg" 2>&1` + else + CPG_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libcpg" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$CPG_PKG_ERRORS" >&5 + + $bailout +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + $bailout +else + CPG_CFLAGS=$pkg_cv_CPG_CFLAGS + CPG_LIBS=$pkg_cv_CPG_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_CPG=yes +fi +fi + +if test "$CHECKDLM" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for DLM" >&5 +$as_echo_n "checking for DLM... " >&6; } + +if test -n "$DLM_CFLAGS"; then + pkg_cv_DLM_CFLAGS="$DLM_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libdlm\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libdlm") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_DLM_CFLAGS=`$PKG_CONFIG --cflags "libdlm" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$DLM_LIBS"; then + pkg_cv_DLM_LIBS="$DLM_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libdlm\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libdlm") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_DLM_LIBS=`$PKG_CONFIG --libs "libdlm" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + DLM_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libdlm" 2>&1` + else + DLM_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libdlm" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$DLM_PKG_ERRORS" >&5 + + NOTFOUND=0 + for ac_header in libdlm.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "libdlm.h" "ac_cv_header_libdlm_h" "$ac_includes_default" +if test "x$ac_cv_header_libdlm_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDLM_H 1 +_ACEOF + +else + $bailout +fi + +done + + check_lib_no_libs dlm dlm_lock -lpthread + if test $NOTFOUND = 0; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no pkg for libdlm, using -ldlm" >&5 +$as_echo "no pkg for libdlm, using -ldlm" >&6; } + DLM_LIBS="-ldlm -lpthread" + HAVE_DLM=yes + fi +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + NOTFOUND=0 + for ac_header in libdlm.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "libdlm.h" "ac_cv_header_libdlm_h" "$ac_includes_default" +if test "x$ac_cv_header_libdlm_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDLM_H 1 +_ACEOF + +else + $bailout +fi + +done + + check_lib_no_libs dlm dlm_lock -lpthread + if test $NOTFOUND = 0; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no pkg for libdlm, using -ldlm" >&5 +$as_echo "no pkg for libdlm, using -ldlm" >&6; } + DLM_LIBS="-ldlm -lpthread" + HAVE_DLM=yes + fi +else + DLM_CFLAGS=$pkg_cv_DLM_CFLAGS + DLM_LIBS=$pkg_cv_DLM_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_DLM=yes +fi +fi + +if test "$CLVMD" = all; then + CLVMD=none + CLVMD_CMANAGERS="" + CLVMD_NEEDS_QDISKD=no + if test "$HAVE_CMAN" = yes -a \ + "$HAVE_DLM" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: Enabling clvmd cman cluster manager" >&5 +$as_echo "Enabling clvmd cman cluster manager" >&6; } + CLVMD="$CLVMD,cman" + CLVMD_CMANAGERS="$CLVMD_CMANAGERS cman" + CLVMD_NEEDS_QDISKD=yes + fi + if test "$HAVE_COROSYNC" = yes -a \ + "$HAVE_QUORUM" = yes -a \ + "$HAVE_CPG" = yes -a \ + "$HAVE_DLM" = yes; then + if test "$HAVE_CONFDB" = yes -o "$HAVE_CMAP" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: Enabling clvmd corosync cluster manager" >&5 +$as_echo "Enabling clvmd corosync cluster manager" >&6; } + CLVMD="$CLVMD,corosync" + CLVMD_CMANAGERS="$CLVMD_CMANAGERS corosync" + fi + fi + if test "$HAVE_COROSYNC" = yes -a \ + "$HAVE_CPG" = yes -a \ + "$HAVE_SALCK" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: Enabling clvmd openais cluster manager" >&5 +$as_echo "Enabling clvmd openais cluster manager" >&6; } + CLVMD="$CLVMD,openais" + CLVMD_CMANAGERS="$CLVMD_CMANAGERS openais" + fi + test "$CLVMD_NEEDS_QDISKD" != no && CLVMD_CMANAGERS="$CLVMD_CMANAGERS qdiskd" + test "$CLVMD" = none && { $as_echo "$as_me:${as_lineno-$LINENO}: result: Disabling clvmd build. No cluster manager detected." >&5 +$as_echo "Disabling clvmd build. No cluster manager detected." >&6; } +fi + +if [ `expr x"$CLVMD" : '.*corosync.*'` != 0 ]; then + test "$HAVE_CMAP" = yes && CLVMD_CMANAGERS="$CLVMD_CMANAGERS dlm" +fi + +################################################################################ +if test "$CLVMD" != none; then + +# Check whether --with-clvmd-pidfile was given. +if test "${with_clvmd_pidfile+set}" = set; then : + withval=$with_clvmd_pidfile; CLVMD_PIDFILE=$withval +else + CLVMD_PIDFILE="$DEFAULT_PID_DIR/clvmd.pid" +fi + + +cat >>confdefs.h <<_ACEOF +#define CLVMD_PIDFILE "$CLVMD_PIDFILE" +_ACEOF + +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build cluster mirror log daemon" >&5 +$as_echo_n "checking whether to build cluster mirror log daemon... " >&6; } +# Check whether --enable-cmirrord was given. +if test "${enable_cmirrord+set}" = set; then : + enableval=$enable_cmirrord; CMIRRORD=$enableval +else + CMIRRORD=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CMIRRORD" >&5 +$as_echo "$CMIRRORD" >&6; } + +BUILD_CMIRRORD=$CMIRRORD + +################################################################################ +if test "$BUILD_CMIRRORD" = yes; then + +# Check whether --with-cmirrord-pidfile was given. +if test "${with_cmirrord_pidfile+set}" = set; then : + withval=$with_cmirrord_pidfile; CMIRRORD_PIDFILE=$withval +else + CMIRRORD_PIDFILE="$DEFAULT_PID_DIR/cmirrord.pid" +fi + + +cat >>confdefs.h <<_ACEOF +#define CMIRRORD_PIDFILE "$CMIRRORD_PIDFILE" +_ACEOF + +fi + +################################################################################ +if [ "$BUILD_CMIRRORD" = yes ]; then + pkg_config_init + + +$as_echo "#define CMIRROR_HAS_CHECKPOINT 1" >>confdefs.h + + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SACKPT" >&5 +$as_echo_n "checking for SACKPT... " >&6; } + +if test -n "$SACKPT_CFLAGS"; then + pkg_cv_SACKPT_CFLAGS="$SACKPT_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libSaCkpt\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libSaCkpt") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_SACKPT_CFLAGS=`$PKG_CONFIG --cflags "libSaCkpt" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$SACKPT_LIBS"; then + pkg_cv_SACKPT_LIBS="$SACKPT_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libSaCkpt\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libSaCkpt") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_SACKPT_LIBS=`$PKG_CONFIG --libs "libSaCkpt" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + SACKPT_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libSaCkpt" 2>&1` + else + SACKPT_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libSaCkpt" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$SACKPT_PKG_ERRORS" >&5 + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no libSaCkpt, compiling without it" >&5 +$as_echo "no libSaCkpt, compiling without it" >&6; } + +$as_echo "#define CMIRROR_HAS_CHECKPOINT 0" >>confdefs.h + +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no libSaCkpt, compiling without it" >&5 +$as_echo "no libSaCkpt, compiling without it" >&6; } + +$as_echo "#define CMIRROR_HAS_CHECKPOINT 0" >>confdefs.h + +else + SACKPT_CFLAGS=$pkg_cv_SACKPT_CFLAGS + SACKPT_LIBS=$pkg_cv_SACKPT_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_SACKPT=yes +fi + + if test "$HAVE_CPG" != yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for CPG" >&5 +$as_echo_n "checking for CPG... " >&6; } + +if test -n "$CPG_CFLAGS"; then + pkg_cv_CPG_CFLAGS="$CPG_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcpg\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcpg") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CPG_CFLAGS=`$PKG_CONFIG --cflags "libcpg" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$CPG_LIBS"; then + pkg_cv_CPG_LIBS="$CPG_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libcpg\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libcpg") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CPG_LIBS=`$PKG_CONFIG --libs "libcpg" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + CPG_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libcpg" 2>&1` + else + CPG_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libcpg" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$CPG_PKG_ERRORS" >&5 + + as_fn_error $? "Package requirements (libcpg) were not met: + +$CPG_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +Alternatively, you may set the environment variables CPG_CFLAGS +and CPG_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details." "$LINENO" 5 +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +Alternatively, you may set the environment variables CPG_CFLAGS +and CPG_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details. + +To get pkg-config, see <http://pkg-config.freedesktop.org/>. +See \`config.log' for more details" "$LINENO" 5; } +else + CPG_CFLAGS=$pkg_cv_CPG_CFLAGS + CPG_LIBS=$pkg_cv_CPG_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + +fi + fi +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable debugging" >&5 +$as_echo_n "checking whether to enable debugging... " >&6; } +# Check whether --enable-debug was given. +if test "${enable_debug+set}" = set; then : + enableval=$enable_debug; DEBUG=$enableval +else + DEBUG=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DEBUG" >&5 +$as_echo "$DEBUG" >&6; } + +if test "$DEBUG" = yes; then + COPTIMISE_FLAG= +else + CSCOPE_CMD= +fi + + + + ac_save_CFLAGS=$CFLAGS + CFLAGS=-Wjump-misses-init + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Wjump-misses-init flag" >&5 +$as_echo_n "checking whether $CC accepts -Wjump-misses-init flag... " >&6; } +if ${ac_cv_flag_HAVE_WJUMP+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_flag_HAVE_WJUMP=yes +else + ac_cv_flag_HAVE_WJUMP=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_flag_HAVE_WJUMP" >&5 +$as_echo "$ac_cv_flag_HAVE_WJUMP" >&6; } + CFLAGS=$ac_save_CFLAGS + HAVE_WJUMP=$ac_cv_flag_HAVE_WJUMP + if test "HAVE_WJUMP" = yes; then + : + else + : + fi + + + + + ac_save_CFLAGS=$CFLAGS + CFLAGS=-Wclobbered + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Wclobbered flag" >&5 +$as_echo_n "checking whether $CC accepts -Wclobbered flag... " >&6; } +if ${ac_cv_flag_HAVE_WCLOBBERED+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_flag_HAVE_WCLOBBERED=yes +else + ac_cv_flag_HAVE_WCLOBBERED=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_flag_HAVE_WCLOBBERED" >&5 +$as_echo "$ac_cv_flag_HAVE_WCLOBBERED" >&6; } + CFLAGS=$ac_save_CFLAGS + HAVE_WCLOBBERED=$ac_cv_flag_HAVE_WCLOBBERED + if test "HAVE_WCLOBBERED" = yes; then + : + else + : + fi + + + + + ac_save_CFLAGS=$CFLAGS + CFLAGS=-Wsync-nand + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Wsync-nand flag" >&5 +$as_echo_n "checking whether $CC accepts -Wsync-nand flag... " >&6; } +if ${ac_cv_flag_HAVE_WSYNCNAND+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_flag_HAVE_WSYNCNAND=yes +else + ac_cv_flag_HAVE_WSYNCNAND=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_flag_HAVE_WSYNCNAND" >&5 +$as_echo "$ac_cv_flag_HAVE_WSYNCNAND" >&6; } + CFLAGS=$ac_save_CFLAGS + HAVE_WSYNCNAND=$ac_cv_flag_HAVE_WSYNCNAND + if test "HAVE_WSYNCNAND" = yes; then + : + else + : + fi + + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C optimisation flag" >&5 +$as_echo_n "checking for C optimisation flag... " >&6; } + +# Check whether --with-optimisation was given. +if test "${with_optimisation+set}" = set; then : + withval=$with_optimisation; COPTIMISE_FLAG=$withval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $COPTIMISE_FLAG" >&5 +$as_echo "$COPTIMISE_FLAG" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to gather gcov profiling data" >&5 +$as_echo_n "checking whether to gather gcov profiling data... " >&6; } +# Check whether --enable-profiling was given. +if test "${enable_profiling+set}" = set; then : + enableval=$enable_profiling; PROFILING=$enableval +else + PROFILING=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $PROFILING" >&5 +$as_echo "$PROFILING" >&6; } + +if test "$PROFILING" = yes; then + COPTIMISE_FLAG="$COPTIMISE_FLAG -fprofile-arcs -ftest-coverage" + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}lcov", so it can be a program name with args. +set dummy ${ac_tool_prefix}lcov; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_LCOV+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $LCOV in + [\\/]* | ?:[\\/]*) + ac_cv_path_LCOV="$LCOV" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_LCOV="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +LCOV=$ac_cv_path_LCOV +if test -n "$LCOV"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LCOV" >&5 +$as_echo "$LCOV" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_LCOV"; then + ac_pt_LCOV=$LCOV + # Extract the first word of "lcov", so it can be a program name with args. +set dummy lcov; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_LCOV+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_LCOV in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_LCOV="$ac_pt_LCOV" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_LCOV="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_LCOV=$ac_cv_path_ac_pt_LCOV +if test -n "$ac_pt_LCOV"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_LCOV" >&5 +$as_echo "$ac_pt_LCOV" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_LCOV" = x; then + LCOV="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + LCOV=$ac_pt_LCOV + fi +else + LCOV="$ac_cv_path_LCOV" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}genhtml", so it can be a program name with args. +set dummy ${ac_tool_prefix}genhtml; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_GENHTML+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $GENHTML in + [\\/]* | ?:[\\/]*) + ac_cv_path_GENHTML="$GENHTML" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_GENHTML="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +GENHTML=$ac_cv_path_GENHTML +if test -n "$GENHTML"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GENHTML" >&5 +$as_echo "$GENHTML" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_GENHTML"; then + ac_pt_GENHTML=$GENHTML + # Extract the first word of "genhtml", so it can be a program name with args. +set dummy genhtml; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_GENHTML+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_GENHTML in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_GENHTML="$ac_pt_GENHTML" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_GENHTML="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_GENHTML=$ac_cv_path_ac_pt_GENHTML +if test -n "$ac_pt_GENHTML"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_GENHTML" >&5 +$as_echo "$ac_pt_GENHTML" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_GENHTML" = x; then + GENHTML="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + GENHTML=$ac_pt_GENHTML + fi +else + GENHTML="$ac_cv_path_GENHTML" +fi + + test -z "$LCOV" -o -z "$GENHTML" && as_fn_error $? "lcov and genhtml are required for profiling" "$LINENO" 5 + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}genpng", so it can be a program name with args. +set dummy ${ac_tool_prefix}genpng; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_GENPNG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $GENPNG in + [\\/]* | ?:[\\/]*) + ac_cv_path_GENPNG="$GENPNG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_GENPNG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +GENPNG=$ac_cv_path_GENPNG +if test -n "$GENPNG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GENPNG" >&5 +$as_echo "$GENPNG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_GENPNG"; then + ac_pt_GENPNG=$GENPNG + # Extract the first word of "genpng", so it can be a program name with args. +set dummy genpng; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_GENPNG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_GENPNG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_GENPNG="$ac_pt_GENPNG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_GENPNG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_GENPNG=$ac_cv_path_ac_pt_GENPNG +if test -n "$ac_pt_GENPNG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_GENPNG" >&5 +$as_echo "$ac_pt_GENPNG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_GENPNG" = x; then + GENPNG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + GENPNG=$ac_pt_GENPNG + fi +else + GENPNG="$ac_cv_path_GENPNG" +fi + + if test -n "$GENPNG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $GENPNG has all required modules" >&5 +$as_echo_n "checking whether $GENPNG has all required modules... " >&6; } + if "$GENPNG" --help > /dev/null 2>&1 ; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 +$as_echo "ok" >&6; } + GENHTML="$GENHTML --frames" + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5 +$as_echo "not supported" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: GD.pm perl module is not installed" >&5 +$as_echo "$as_me: WARNING: GD.pm perl module is not installed" >&2;} + GENPNG= + fi + fi +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable unit testing" >&5 +$as_echo_n "checking whether to enable unit testing... " >&6; } +# Check whether --enable-testing was given. +if test "${enable_testing+set}" = set; then : + enableval=$enable_testing; TESTING=$enableval +else + TESTING=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $TESTING" >&5 +$as_echo "$TESTING" >&6; } + +if test "$TESTING" = yes; then + pkg_config_init + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for CUNIT" >&5 +$as_echo_n "checking for CUNIT... " >&6; } + +if test -n "$CUNIT_CFLAGS"; then + pkg_cv_CUNIT_CFLAGS="$CUNIT_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"cunit >= 2.0\""; } >&5 + ($PKG_CONFIG --exists --print-errors "cunit >= 2.0") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CUNIT_CFLAGS=`$PKG_CONFIG --cflags "cunit >= 2.0" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$CUNIT_LIBS"; then + pkg_cv_CUNIT_LIBS="$CUNIT_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"cunit >= 2.0\""; } >&5 + ($PKG_CONFIG --exists --print-errors "cunit >= 2.0") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_CUNIT_LIBS=`$PKG_CONFIG --libs "cunit >= 2.0" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + CUNIT_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "cunit >= 2.0" 2>&1` + else + CUNIT_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "cunit >= 2.0" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$CUNIT_PKG_ERRORS" >&5 + + as_fn_error $? "Package requirements (cunit >= 2.0) were not met: + +$CUNIT_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +Alternatively, you may set the environment variables CUNIT_CFLAGS +and CUNIT_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details." "$LINENO" 5 +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +Alternatively, you may set the environment variables CUNIT_CFLAGS +and CUNIT_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details. + +To get pkg-config, see <http://pkg-config.freedesktop.org/>. +See \`config.log' for more details" "$LINENO" 5; } +else + CUNIT_CFLAGS=$pkg_cv_CUNIT_CFLAGS + CUNIT_LIBS=$pkg_cv_CUNIT_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + +fi +fi + +################################################################################ +TESTSUITE_DATA='${datarootdir}/lvm2-testsuite' +# double eval needed ${datarootdir} -> ${prefix}/share -> real path + +cat >>confdefs.h <<_ACEOF +#define TESTSUITE_DATA "$(eval echo $(eval echo $TESTSUITE_DATA))" +_ACEOF + + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable valgrind awareness of pools" >&5 +$as_echo_n "checking whether to enable valgrind awareness of pools... " >&6; } +# Check whether --enable-valgrind_pool was given. +if test "${enable_valgrind_pool+set}" = set; then : + enableval=$enable_valgrind_pool; VALGRIND_POOL=$enableval +else + VALGRIND_POOL=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $VALGRIND_POOL" >&5 +$as_echo "$VALGRIND_POOL" >&6; } + +pkg_config_init + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for VALGRIND" >&5 +$as_echo_n "checking for VALGRIND... " >&6; } + +if test -n "$VALGRIND_CFLAGS"; then + pkg_cv_VALGRIND_CFLAGS="$VALGRIND_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"valgrind\""; } >&5 + ($PKG_CONFIG --exists --print-errors "valgrind") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_VALGRIND_CFLAGS=`$PKG_CONFIG --cflags "valgrind" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$VALGRIND_LIBS"; then + pkg_cv_VALGRIND_LIBS="$VALGRIND_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"valgrind\""; } >&5 + ($PKG_CONFIG --exists --print-errors "valgrind") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_VALGRIND_LIBS=`$PKG_CONFIG --libs "valgrind" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + VALGRIND_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "valgrind" 2>&1` + else + VALGRIND_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "valgrind" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$VALGRIND_PKG_ERRORS" >&5 + + if test x$VALGRIND_POOL = xyes; then as_fn_error $? "bailing out" "$LINENO" 5; fi +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + if test x$VALGRIND_POOL = xyes; then as_fn_error $? "bailing out" "$LINENO" 5; fi +else + VALGRIND_CFLAGS=$pkg_cv_VALGRIND_CFLAGS + VALGRIND_LIBS=$pkg_cv_VALGRIND_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_VALGRIND=yes +fi + + +if test x$HAVE_VALGRIND = xyes; then + +$as_echo "#define HAVE_VALGRIND 1" >>confdefs.h + +fi + +if test x$VALGRIND_POOL = xyes; then + +$as_echo "#define VALGRIND_POOL 1" >>confdefs.h + +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to use device-mapper" >&5 +$as_echo_n "checking whether to use device-mapper... " >&6; } +# Check whether --enable-devmapper was given. +if test "${enable_devmapper+set}" = set; then : + enableval=$enable_devmapper; DEVMAPPER=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DEVMAPPER" >&5 +$as_echo "$DEVMAPPER" >&6; } + +if test "$DEVMAPPER" = yes; then + +$as_echo "#define DEVMAPPER_SUPPORT 1" >>confdefs.h + +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build LVMetaD" >&5 +$as_echo_n "checking whether to build LVMetaD... " >&6; } +# Check whether --enable-lvmetad was given. +if test "${enable_lvmetad+set}" = set; then : + enableval=$enable_lvmetad; LVMETAD=$enableval +fi + +test -n "$LVMETAD" && BUILD_LVMETAD=$LVMETAD +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $BUILD_LVMETAD" >&5 +$as_echo "$BUILD_LVMETAD" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build lvmpolld" >&5 +$as_echo_n "checking whether to build lvmpolld... " >&6; } +# Check whether --enable-lvmpolld was given. +if test "${enable_lvmpolld+set}" = set; then : + enableval=$enable_lvmpolld; LVMPOLLD=$enableval +fi + +test -n "$LVMPOLLD" && BUILD_LVMPOLLD=$LVMPOLLD +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $BUILD_LVMPOLLD" >&5 +$as_echo "$BUILD_LVMPOLLD" >&6; } + +################################################################################ +BUILD_LVMLOCKD=no + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build lockdsanlock" >&5 +$as_echo_n "checking whether to build lockdsanlock... " >&6; } +# Check whether --enable-lockd-sanlock was given. +if test "${enable_lockd_sanlock+set}" = set; then : + enableval=$enable_lockd_sanlock; LOCKDSANLOCK=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LOCKDSANLOCK" >&5 +$as_echo "$LOCKDSANLOCK" >&6; } + +BUILD_LOCKDSANLOCK=$LOCKDSANLOCK + +if test "$BUILD_LOCKDSANLOCK" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for LOCKD_SANLOCK" >&5 +$as_echo_n "checking for LOCKD_SANLOCK... " >&6; } + +if test -n "$LOCKD_SANLOCK_CFLAGS"; then + pkg_cv_LOCKD_SANLOCK_CFLAGS="$LOCKD_SANLOCK_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libsanlock_client >= 3.3.0\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libsanlock_client >= 3.3.0") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_LOCKD_SANLOCK_CFLAGS=`$PKG_CONFIG --cflags "libsanlock_client >= 3.3.0" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$LOCKD_SANLOCK_LIBS"; then + pkg_cv_LOCKD_SANLOCK_LIBS="$LOCKD_SANLOCK_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libsanlock_client >= 3.3.0\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libsanlock_client >= 3.3.0") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_LOCKD_SANLOCK_LIBS=`$PKG_CONFIG --libs "libsanlock_client >= 3.3.0" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + LOCKD_SANLOCK_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libsanlock_client >= 3.3.0" 2>&1` + else + LOCKD_SANLOCK_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libsanlock_client >= 3.3.0" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$LOCKD_SANLOCK_PKG_ERRORS" >&5 + + $bailout +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + $bailout +else + LOCKD_SANLOCK_CFLAGS=$pkg_cv_LOCKD_SANLOCK_CFLAGS + LOCKD_SANLOCK_LIBS=$pkg_cv_LOCKD_SANLOCK_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_LOCKD_SANLOCK=yes +fi + +$as_echo "#define LOCKDSANLOCK_SUPPORT 1" >>confdefs.h + + BUILD_LVMLOCKD=yes +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build lockddlm" >&5 +$as_echo_n "checking whether to build lockddlm... " >&6; } +# Check whether --enable-lockd-dlm was given. +if test "${enable_lockd_dlm+set}" = set; then : + enableval=$enable_lockd_dlm; LOCKDDLM=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LOCKDDLM" >&5 +$as_echo "$LOCKDDLM" >&6; } + +BUILD_LOCKDDLM=$LOCKDDLM + +if test "$BUILD_LOCKDDLM" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for LOCKD_DLM" >&5 +$as_echo_n "checking for LOCKD_DLM... " >&6; } + +if test -n "$LOCKD_DLM_CFLAGS"; then + pkg_cv_LOCKD_DLM_CFLAGS="$LOCKD_DLM_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libdlm\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libdlm") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_LOCKD_DLM_CFLAGS=`$PKG_CONFIG --cflags "libdlm" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$LOCKD_DLM_LIBS"; then + pkg_cv_LOCKD_DLM_LIBS="$LOCKD_DLM_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libdlm\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libdlm") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_LOCKD_DLM_LIBS=`$PKG_CONFIG --libs "libdlm" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + LOCKD_DLM_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libdlm" 2>&1` + else + LOCKD_DLM_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libdlm" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$LOCKD_DLM_PKG_ERRORS" >&5 + + $bailout +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + $bailout +else + LOCKD_DLM_CFLAGS=$pkg_cv_LOCKD_DLM_CFLAGS + LOCKD_DLM_LIBS=$pkg_cv_LOCKD_DLM_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_LOCKD_DLM=yes +fi + +$as_echo "#define LOCKDDLM_SUPPORT 1" >>confdefs.h + + BUILD_LVMLOCKD=yes +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build lvmlockd" >&5 +$as_echo_n "checking whether to build lvmlockd... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $BUILD_LVMLOCKD" >&5 +$as_echo "$BUILD_LVMLOCKD" >&6; } + +if test "$BUILD_LVMLOCKD" = yes; then + if test "$LVMPOLLD" = no; then : + as_fn_error $? "cannot build lvmlockd with --disable-lvmpolld." "$LINENO" 5 +fi + if test "$LVMETAD" = no; then : + as_fn_error $? "cannot build lvmlockd with --disable-lvmetad." "$LINENO" 5 +fi + if test "$BUILD_LVMPOLLD" = no; then : + BUILD_LVMPOLLD=yes; { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Enabling lvmpolld - required by lvmlockd." >&5 +$as_echo "$as_me: WARNING: Enabling lvmpolld - required by lvmlockd." >&2;} +fi + if test "$BUILD_LVMETAD" = no; then : + BUILD_LVMETAD=yes; { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Enabling lvmetad - required by lvmlockd." >&5 +$as_echo "$as_me: WARNING: Enabling lvmetad - required by lvmlockd." >&2;} +fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking defaults for use_lvmlockd" >&5 +$as_echo_n "checking defaults for use_lvmlockd... " >&6; } + # Check whether --enable-use_lvmlockd was given. +if test "${enable_use_lvmlockd+set}" = set; then : + enableval=$enable_use_lvmlockd; case ${enableval} in + yes) DEFAULT_USE_LVMLOCKD=1 ;; + *) DEFAULT_USE_LVMLOCKD=0 ;; + esac +else + DEFAULT_USE_LVMLOCKD=1 +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DEFAULT_USE_LVMLOCKD" >&5 +$as_echo "$DEFAULT_USE_LVMLOCKD" >&6; } + +$as_echo "#define LVMLOCKD_SUPPORT 1" >>confdefs.h + + + +# Check whether --with-lvmlockd-pidfile was given. +if test "${with_lvmlockd_pidfile+set}" = set; then : + withval=$with_lvmlockd_pidfile; LVMLOCKD_PIDFILE=$withval +else + LVMLOCKD_PIDFILE="$DEFAULT_PID_DIR/lvmlockd.pid" +fi + + +cat >>confdefs.h <<_ACEOF +#define LVMLOCKD_PIDFILE "$LVMLOCKD_PIDFILE" +_ACEOF + +else + DEFAULT_USE_LVMLOCKD=0 +fi + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_USE_LVMLOCKD $DEFAULT_USE_LVMLOCKD +_ACEOF + + +################################################################################ +if test "$BUILD_LVMETAD" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking defaults for use_lvmetad" >&5 +$as_echo_n "checking defaults for use_lvmetad... " >&6; } + # Check whether --enable-use_lvmetad was given. +if test "${enable_use_lvmetad+set}" = set; then : + enableval=$enable_use_lvmetad; case ${enableval} in + yes) DEFAULT_USE_LVMETAD=1 ;; + *) DEFAULT_USE_LVMETAD=0 ;; + esac +else + DEFAULT_USE_LVMETAD=1 +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DEFAULT_USE_LVMETAD" >&5 +$as_echo "$DEFAULT_USE_LVMETAD" >&6; } + +$as_echo "#define LVMETAD_SUPPORT 1" >>confdefs.h + + + +# Check whether --with-lvmetad-pidfile was given. +if test "${with_lvmetad_pidfile+set}" = set; then : + withval=$with_lvmetad_pidfile; LVMETAD_PIDFILE=$withval +else + LVMETAD_PIDFILE="$DEFAULT_PID_DIR/lvmetad.pid" +fi + + +cat >>confdefs.h <<_ACEOF +#define LVMETAD_PIDFILE "$LVMETAD_PIDFILE" +_ACEOF + +else + DEFAULT_USE_LVMETAD=0 +fi + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_USE_LVMETAD $DEFAULT_USE_LVMETAD +_ACEOF + + +################################################################################ +if test "$BUILD_LVMPOLLD" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking defaults for use_lvmpolld" >&5 +$as_echo_n "checking defaults for use_lvmpolld... " >&6; } + # Check whether --enable-use_lvmpolld was given. +if test "${enable_use_lvmpolld+set}" = set; then : + enableval=$enable_use_lvmpolld; case ${enableval} in + yes) DEFAULT_USE_LVMPOLLD=1 ;; + *) DEFAULT_USE_LVMPOLLD=0 ;; + esac +else + DEFAULT_USE_LVMPOLLD=1 +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DEFAULT_USE_LVMPOLLD" >&5 +$as_echo "$DEFAULT_USE_LVMPOLLD" >&6; } + +$as_echo "#define LVMPOLLD_SUPPORT 1" >>confdefs.h + + + +# Check whether --with-lvmpolld-pidfile was given. +if test "${with_lvmpolld_pidfile+set}" = set; then : + withval=$with_lvmpolld_pidfile; LVMPOLLD_PIDFILE=$withval +else + LVMPOLLD_PIDFILE="$DEFAULT_PID_DIR/lvmpolld.pid" +fi + + +cat >>confdefs.h <<_ACEOF +#define LVMPOLLD_PIDFILE "$LVMPOLLD_PIDFILE" +_ACEOF + +else + DEFAULT_USE_LVMPOLLD=0 +fi + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_USE_LVMPOLLD $DEFAULT_USE_LVMPOLLD +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build notifydbus" >&5 +$as_echo_n "checking whether to build notifydbus... " >&6; } +# Check whether --enable-notify-dbus was given. +if test "${enable_notify_dbus+set}" = set; then : + enableval=$enable_notify_dbus; NOTIFYDBUS=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $NOTIFYDBUS" >&5 +$as_echo "$NOTIFYDBUS" >&6; } + +BUILD_NOTIFYDBUS=$NOTIFYDBUS + +if test "$BUILD_NOTIFYDBUS" = yes; then + +$as_echo "#define NOTIFYDBUS_SUPPORT 1" >>confdefs.h + + LIBS="-lsystemd $LIBS" +fi + +################################################################################ +if test "$BUILD_NOTIFYDBUS" = yes; then + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for NOTIFY_DBUS" >&5 +$as_echo_n "checking for NOTIFY_DBUS... " >&6; } + +if test -n "$NOTIFY_DBUS_CFLAGS"; then + pkg_cv_NOTIFY_DBUS_CFLAGS="$NOTIFY_DBUS_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"systemd >= 221\""; } >&5 + ($PKG_CONFIG --exists --print-errors "systemd >= 221") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_NOTIFY_DBUS_CFLAGS=`$PKG_CONFIG --cflags "systemd >= 221" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$NOTIFY_DBUS_LIBS"; then + pkg_cv_NOTIFY_DBUS_LIBS="$NOTIFY_DBUS_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"systemd >= 221\""; } >&5 + ($PKG_CONFIG --exists --print-errors "systemd >= 221") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_NOTIFY_DBUS_LIBS=`$PKG_CONFIG --libs "systemd >= 221" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + NOTIFY_DBUS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "systemd >= 221" 2>&1` + else + NOTIFY_DBUS_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "systemd >= 221" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$NOTIFY_DBUS_PKG_ERRORS" >&5 + + $bailout +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + $bailout +else + NOTIFY_DBUS_CFLAGS=$pkg_cv_NOTIFY_DBUS_CFLAGS + NOTIFY_DBUS_LIBS=$pkg_cv_NOTIFY_DBUS_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + HAVE_NOTIFY_DBUS=yes +fi +fi + +################################################################################ + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable libblkid detection of signatures when wiping" >&5 +$as_echo_n "checking whether to enable libblkid detection of signatures when wiping... " >&6; } +# Check whether --enable-blkid_wiping was given. +if test "${enable_blkid_wiping+set}" = set; then : + enableval=$enable_blkid_wiping; BLKID_WIPING=$enableval +else + BLKID_WIPING=maybe +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $BLKID_WIPING" >&5 +$as_echo "$BLKID_WIPING" >&6; } + +if test "$BLKID_WIPING" != no; then + pkg_config_init + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BLKID" >&5 +$as_echo_n "checking for BLKID... " >&6; } + +if test -n "$BLKID_CFLAGS"; then + pkg_cv_BLKID_CFLAGS="$BLKID_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"blkid >= 2.24\""; } >&5 + ($PKG_CONFIG --exists --print-errors "blkid >= 2.24") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_BLKID_CFLAGS=`$PKG_CONFIG --cflags "blkid >= 2.24" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$BLKID_LIBS"; then + pkg_cv_BLKID_LIBS="$BLKID_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"blkid >= 2.24\""; } >&5 + ($PKG_CONFIG --exists --print-errors "blkid >= 2.24") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_BLKID_LIBS=`$PKG_CONFIG --libs "blkid >= 2.24" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + BLKID_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "blkid >= 2.24" 2>&1` + else + BLKID_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "blkid >= 2.24" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$BLKID_PKG_ERRORS" >&5 + + if test "$BLKID_WIPING" = maybe; then + BLKID_WIPING=no + else + as_fn_error $? "bailing out... blkid library >= 2.24 is required" "$LINENO" 5 + fi +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + if test "$BLKID_WIPING" = maybe; then + BLKID_WIPING=no + else + as_fn_error $? "bailing out... blkid library >= 2.24 is required" "$LINENO" 5 + fi +else + BLKID_CFLAGS=$pkg_cv_BLKID_CFLAGS + BLKID_LIBS=$pkg_cv_BLKID_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + test "$BLKID_WIPING" = maybe && BLKID_WIPING=yes +fi + if test "$BLKID_WIPING" = yes; then + BLKID_PC="blkid" + DEFAULT_USE_BLKID_WIPING=1 + +$as_echo "#define BLKID_WIPING_SUPPORT 1" >>confdefs.h + + else + DEFAULT_USE_BLKID_WIPING=0 + fi +else + DEFAULT_USE_BLKID_WIPING=0 +fi + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_USE_BLKID_WIPING $DEFAULT_USE_BLKID_WIPING +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to use udev-systemd protocol for jobs in background" >&5 +$as_echo_n "checking whether to use udev-systemd protocol for jobs in background... " >&6; } +# Check whether --enable-udev-systemd-background-jobs was given. +if test "${enable_udev_systemd_background_jobs+set}" = set; then : + enableval=$enable_udev_systemd_background_jobs; UDEV_SYSTEMD_BACKGROUND_JOBS=$enableval +else + UDEV_SYSTEMD_BACKGROUND_JOBS=maybe +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $UDEV_SYSTEMD_BACKGROUND_JOBS" >&5 +$as_echo "$UDEV_SYSTEMD_BACKGROUND_JOBS" >&6; } + +if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" != no; then + pkg_config_init + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SYSTEMD" >&5 +$as_echo_n "checking for SYSTEMD... " >&6; } + +if test -n "$SYSTEMD_CFLAGS"; then + pkg_cv_SYSTEMD_CFLAGS="$SYSTEMD_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"systemd >= 205\""; } >&5 + ($PKG_CONFIG --exists --print-errors "systemd >= 205") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_SYSTEMD_CFLAGS=`$PKG_CONFIG --cflags "systemd >= 205" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$SYSTEMD_LIBS"; then + pkg_cv_SYSTEMD_LIBS="$SYSTEMD_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"systemd >= 205\""; } >&5 + ($PKG_CONFIG --exists --print-errors "systemd >= 205") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_SYSTEMD_LIBS=`$PKG_CONFIG --libs "systemd >= 205" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + SYSTEMD_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "systemd >= 205" 2>&1` + else + SYSTEMD_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "systemd >= 205" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$SYSTEMD_PKG_ERRORS" >&5 + + if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" = maybe; then + UDEV_SYSTEMD_BACKGROUND_JOBS=no + else + as_fn_error $? "bailing out... systemd >= 205 is required" "$LINENO" 5 + fi +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" = maybe; then + UDEV_SYSTEMD_BACKGROUND_JOBS=no + else + as_fn_error $? "bailing out... systemd >= 205 is required" "$LINENO" 5 + fi +else + SYSTEMD_CFLAGS=$pkg_cv_SYSTEMD_CFLAGS + SYSTEMD_LIBS=$pkg_cv_SYSTEMD_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + test "$UDEV_SYSTEMD_BACKGROUND_JOBS" = maybe && UDEV_SYSTEMD_BACKGROUND_JOBS=yes +fi +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable synchronisation with udev processing" >&5 +$as_echo_n "checking whether to enable synchronisation with udev processing... " >&6; } +# Check whether --enable-udev_sync was given. +if test "${enable_udev_sync+set}" = set; then : + enableval=$enable_udev_sync; UDEV_SYNC=$enableval +else + UDEV_SYNC=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $UDEV_SYNC" >&5 +$as_echo "$UDEV_SYNC" >&6; } + +if test "$UDEV_SYNC" = yes; then + pkg_config_init + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for UDEV" >&5 +$as_echo_n "checking for UDEV... " >&6; } + +if test -n "$UDEV_CFLAGS"; then + pkg_cv_UDEV_CFLAGS="$UDEV_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libudev >= 143\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libudev >= 143") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_UDEV_CFLAGS=`$PKG_CONFIG --cflags "libudev >= 143" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$UDEV_LIBS"; then + pkg_cv_UDEV_LIBS="$UDEV_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libudev >= 143\""; } >&5 + ($PKG_CONFIG --exists --print-errors "libudev >= 143") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_UDEV_LIBS=`$PKG_CONFIG --libs "libudev >= 143" 2>/dev/null` + test "x$?" != "x0" && pkg_failed=yes +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + UDEV_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libudev >= 143" 2>&1` + else + UDEV_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libudev >= 143" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$UDEV_PKG_ERRORS" >&5 + + as_fn_error $? "Package requirements (libudev >= 143) were not met: + +$UDEV_PKG_ERRORS + +Consider adjusting the PKG_CONFIG_PATH environment variable if you +installed software in a non-standard prefix. + +Alternatively, you may set the environment variables UDEV_CFLAGS +and UDEV_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details." "$LINENO" 5 +elif test $pkg_failed = untried; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it +is in your PATH or set the PKG_CONFIG environment variable to the full +path to pkg-config. + +Alternatively, you may set the environment variables UDEV_CFLAGS +and UDEV_LIBS to avoid the need to call pkg-config. +See the pkg-config man page for more details. + +To get pkg-config, see <http://pkg-config.freedesktop.org/>. +See \`config.log' for more details" "$LINENO" 5; } +else + UDEV_CFLAGS=$pkg_cv_UDEV_CFLAGS + UDEV_LIBS=$pkg_cv_UDEV_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + UDEV_PC="libudev" +fi + +$as_echo "#define UDEV_SYNC_SUPPORT 1" >>confdefs.h + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for udev_device_get_is_initialized in -ludev" >&5 +$as_echo_n "checking for udev_device_get_is_initialized in -ludev... " >&6; } +if ${ac_cv_lib_udev_udev_device_get_is_initialized+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ludev $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char udev_device_get_is_initialized (); +int +main () +{ +return udev_device_get_is_initialized (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_udev_udev_device_get_is_initialized=yes +else + ac_cv_lib_udev_udev_device_get_is_initialized=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_udev_udev_device_get_is_initialized" >&5 +$as_echo "$ac_cv_lib_udev_udev_device_get_is_initialized" >&6; } +if test "x$ac_cv_lib_udev_udev_device_get_is_initialized" = xyes; then : + +$as_echo "#define HAVE_LIBUDEV_UDEV_DEVICE_GET_IS_INITIALIZED 1" >>confdefs.h + +fi + + LIBS=$ac_check_lib_save_LIBS +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable installation of udev rules required for synchronisation" >&5 +$as_echo_n "checking whether to enable installation of udev rules required for synchronisation... " >&6; } +# Check whether --enable-udev_rules was given. +if test "${enable_udev_rules+set}" = set; then : + enableval=$enable_udev_rules; UDEV_RULES=$enableval +else + UDEV_RULES=$UDEV_SYNC +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $UDEV_RULES" >&5 +$as_echo "$UDEV_RULES" >&6; } + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable executable path detection in udev rules" >&5 +$as_echo_n "checking whether to enable executable path detection in udev rules... " >&6; } +# Check whether --enable-udev_rule_exec_detection was given. +if test "${enable_udev_rule_exec_detection+set}" = set; then : + enableval=$enable_udev_rule_exec_detection; UDEV_RULE_EXEC_DETECTION=$enableval +else + UDEV_RULE_EXEC_DETECTION=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $UDEV_RULE_EXEC_DETECTION" >&5 +$as_echo "$UDEV_RULE_EXEC_DETECTION" >&6; } + +if test "$UDEV_RULE" != no ; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether udev supports built-in blkid" >&5 +$as_echo_n "checking whether udev supports built-in blkid... " >&6; } + pkg_config_init + if $("$PKG_CONFIG" --atleast-version=176 libudev); then + UDEV_HAS_BUILTIN_BLKID=yes + else + UDEV_HAS_BUILTIN_BLKID=no + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $UDEV_HAS_BUILTIN_BLKID" >&5 +$as_echo "$UDEV_HAS_BUILTIN_BLKID" >&6; } +fi + +################################################################################ +# Check whether --enable-compat was given. +if test "${enable_compat+set}" = set; then : + enableval=$enable_compat; DM_COMPAT=$enableval +else + DM_COMPAT=no +fi + + +if test "$DM_COMPAT" = yes; then : + +$as_echo "#define DM_COMPAT 1" >>confdefs.h + + as_fn_error $? "--enable-compat is not currently supported. +Since device-mapper version 1.02.66, only one version (4) of the device-mapper +ioctl protocol is supported." "$LINENO" 5 +fi + +################################################################################ +# Check whether --enable-units-compat was given. +if test "${enable_units_compat+set}" = set; then : + enableval=$enable_units_compat; UNITS_COMPAT=$enableval +else + UNITS_COMPAT=no +fi + + +if test "$UNITS_COMPAT" = yes; then + +$as_echo "#define DEFAULT_SI_UNIT_CONSISTENCY 0" >>confdefs.h + +fi + +################################################################################ +# Check whether --enable-ioctl was given. +if test "${enable_ioctl+set}" = set; then : + enableval=$enable_ioctl; DM_IOCTLS=$enableval +fi + +if test "$DM_IOCTLS" = yes; then : + +$as_echo "#define DM_IOCTLS 1" >>confdefs.h + +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable O_DIRECT" >&5 +$as_echo_n "checking whether to enable O_DIRECT... " >&6; } +# Check whether --enable-o_direct was given. +if test "${enable_o_direct+set}" = set; then : + enableval=$enable_o_direct; ODIRECT=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ODIRECT" >&5 +$as_echo "$ODIRECT" >&6; } + +if test "$ODIRECT" = yes; then + +$as_echo "#define O_DIRECT_SUPPORT 1" >>confdefs.h + +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build liblvm2app.so application library" >&5 +$as_echo_n "checking whether to build liblvm2app.so application library... " >&6; } +# Check whether --enable-applib was given. +if test "${enable_applib+set}" = set; then : + enableval=$enable_applib; APPLIB=$enableval +else + APPLIB=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $APPLIB" >&5 +$as_echo "$APPLIB" >&6; } + +test "$APPLIB" = yes \ + && LVM2APP_LIB=-llvm2app \ + || LVM2APP_LIB= + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to compile liblvm2cmd.so" >&5 +$as_echo_n "checking whether to compile liblvm2cmd.so... " >&6; } +# Check whether --enable-cmdlib was given. +if test "${enable_cmdlib+set}" = set; then : + enableval=$enable_cmdlib; CMDLIB=$enableval +else + CMDLIB=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CMDLIB" >&5 +$as_echo "$CMDLIB" >&6; } + +test "$CMDLIB" = yes \ + && LVM2CMD_LIB=-llvm2cmd \ + || LVM2CMD_LIB= + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to include Python D-Bus support" >&5 +$as_echo_n "checking whether to include Python D-Bus support... " >&6; } +# Check whether --enable-dbus-service was given. +if test "${enable_dbus_service+set}" = set; then : + enableval=$enable_dbus_service; BUILD_LVMDBUSD=$enableval +else + BUILD_LVMDBUSD=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $BUILD_LVMDBUSD" >&5 +$as_echo "$BUILD_LVMDBUSD" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build Python wrapper for liblvm2app.so" >&5 +$as_echo_n "checking whether to build Python wrapper for liblvm2app.so... " >&6; } +# Check whether --enable-python_bindings was given. +if test "${enable_python_bindings+set}" = set; then : + enableval=$enable_python_bindings; PYTHON_BINDINGS=$enableval +else + PYTHON_BINDINGS=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON_BINDINGS" >&5 +$as_echo "$PYTHON_BINDINGS" >&6; } + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build Python2 wrapper for liblvm2app.so" >&5 +$as_echo_n "checking whether to build Python2 wrapper for liblvm2app.so... " >&6; } +# Check whether --enable-python2_bindings was given. +if test "${enable_python2_bindings+set}" = set; then : + enableval=$enable_python2_bindings; PYTHON2_BINDINGS=$enableval +else + PYTHON2_BINDINGS=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON2_BINDINGS" >&5 +$as_echo "$PYTHON2_BINDINGS" >&6; } + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build Python3 wrapper for liblvm2app.so" >&5 +$as_echo_n "checking whether to build Python3 wrapper for liblvm2app.so... " >&6; } +# Check whether --enable-python3_bindings was given. +if test "${enable_python3_bindings+set}" = set; then : + enableval=$enable_python3_bindings; PYTHON3_BINDINGS=$enableval +else + PYTHON3_BINDINGS=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON3_BINDINGS" >&5 +$as_echo "$PYTHON3_BINDINGS" >&6; } + +if test "$PYTHON_BINDINGS" = yes; then + as_fn_error $? "--enable-python-bindings is replaced by --enable-python2-bindings and --enable-python3-bindings" "$LINENO" 5 +fi + +if test "$PYTHON2_BINDINGS" = yes; then + + + + + + + if test -n "$PYTHON"; then + # If the user set $PYTHON, use it and don't search something else. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $PYTHON version is >= 2" >&5 +$as_echo_n "checking whether $PYTHON version is >= 2... " >&6; } + prog="import sys +# split strings by '.' and convert to numeric. Append some zeros +# because we need at least 4 digits for the hex conversion. +# map returns an iterator in Python 3.0 and a list in 2.x +minver = list(map(int, '2'.split('.'))) + [0, 0, 0] +minverhex = 0 +# xrange is not present in Python 3.0 and range returns an iterator +for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[i] +sys.exit(sys.hexversion < minverhex)" + if { echo "$as_me:$LINENO: $PYTHON -c "$prog"" >&5 + ($PYTHON -c "$prog") >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + as_fn_error $? "Python interpreter is too old" "$LINENO" 5 +fi + am_display_PYTHON=$PYTHON + else + # Otherwise, try each interpreter until we find one that satisfies + # VERSION. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a Python interpreter with version >= 2" >&5 +$as_echo_n "checking for a Python interpreter with version >= 2... " >&6; } +if ${am_cv_pathless_PYTHON+:} false; then : + $as_echo_n "(cached) " >&6 +else + + for am_cv_pathless_PYTHON in python python2 python3 python3.3 python3.2 python3.1 python3.0 python2.7 python2.6 python2.5 python2.4 python2.3 python2.2 python2.1 python2.0 none; do + test "$am_cv_pathless_PYTHON" = none && break + prog="import sys +# split strings by '.' and convert to numeric. Append some zeros +# because we need at least 4 digits for the hex conversion. +# map returns an iterator in Python 3.0 and a list in 2.x +minver = list(map(int, '2'.split('.'))) + [0, 0, 0] +minverhex = 0 +# xrange is not present in Python 3.0 and range returns an iterator +for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[i] +sys.exit(sys.hexversion < minverhex)" + if { echo "$as_me:$LINENO: $am_cv_pathless_PYTHON -c "$prog"" >&5 + ($am_cv_pathless_PYTHON -c "$prog") >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then : + break +fi + done +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_pathless_PYTHON" >&5 +$as_echo "$am_cv_pathless_PYTHON" >&6; } + # Set $PYTHON to the absolute path of $am_cv_pathless_PYTHON. + if test "$am_cv_pathless_PYTHON" = none; then + PYTHON=: + else + # Extract the first word of "$am_cv_pathless_PYTHON", so it can be a program name with args. +set dummy $am_cv_pathless_PYTHON; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON="$PYTHON" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PYTHON="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PYTHON=$ac_cv_path_PYTHON +if test -n "$PYTHON"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5 +$as_echo "$PYTHON" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi + am_display_PYTHON=$am_cv_pathless_PYTHON + fi + + + if test "$PYTHON" = :; then + as_fn_error $? "no suitable Python interpreter found" "$LINENO" 5 + else + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON version" >&5 +$as_echo_n "checking for $am_display_PYTHON version... " >&6; } +if ${am_cv_python_version+:} false; then : + $as_echo_n "(cached) " >&6 +else + am_cv_python_version=`$PYTHON -c "import sys; sys.stdout.write(sys.version[:3])"` +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_version" >&5 +$as_echo "$am_cv_python_version" >&6; } + PYTHON_VERSION=$am_cv_python_version + + + + PYTHON_PREFIX='${prefix}' + + PYTHON_EXEC_PREFIX='${exec_prefix}' + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON platform" >&5 +$as_echo_n "checking for $am_display_PYTHON platform... " >&6; } +if ${am_cv_python_platform+:} false; then : + $as_echo_n "(cached) " >&6 +else + am_cv_python_platform=`$PYTHON -c "import sys; sys.stdout.write(sys.platform)"` +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_platform" >&5 +$as_echo "$am_cv_python_platform" >&6; } + PYTHON_PLATFORM=$am_cv_python_platform + + + # Just factor out some code duplication. + am_python_setup_sysconfig="\ +import sys +# Prefer sysconfig over distutils.sysconfig, for better compatibility +# with python 3.x. See automake bug#10227. +try: + import sysconfig +except ImportError: + can_use_sysconfig = 0 +else: + can_use_sysconfig = 1 +# Can't use sysconfig in CPython 2.7, since it's broken in virtualenvs: +# <https://github.com/pypa/virtualenv/issues/118> +try: + from platform import python_implementation + if python_implementation() == 'CPython' and sys.version[:3] == '2.7': + can_use_sysconfig = 0 +except ImportError: + pass" + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON script directory" >&5 +$as_echo_n "checking for $am_display_PYTHON script directory... " >&6; } +if ${am_cv_python_pythondir+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$prefix" = xNONE + then + am_py_prefix=$ac_default_prefix + else + am_py_prefix=$prefix + fi + am_cv_python_pythondir=`$PYTHON -c " +$am_python_setup_sysconfig +if can_use_sysconfig: + sitedir = sysconfig.get_path('purelib', vars={'base':'$am_py_prefix'}) +else: + from distutils import sysconfig + sitedir = sysconfig.get_python_lib(0, 0, prefix='$am_py_prefix') +sys.stdout.write(sitedir)"` + case $am_cv_python_pythondir in + $am_py_prefix*) + am__strip_prefix=`echo "$am_py_prefix" | sed 's|.|.|g'` + am_cv_python_pythondir=`echo "$am_cv_python_pythondir" | sed "s,^$am__strip_prefix,$PYTHON_PREFIX,"` + ;; + *) + case $am_py_prefix in + /usr|/System*) ;; + *) + am_cv_python_pythondir=$PYTHON_PREFIX/lib/python$PYTHON_VERSION/site-packages + ;; + esac + ;; + esac + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_pythondir" >&5 +$as_echo "$am_cv_python_pythondir" >&6; } + pythondir=$am_cv_python_pythondir + + + + pkgpythondir=\${pythondir}/$PACKAGE + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON extension module directory" >&5 +$as_echo_n "checking for $am_display_PYTHON extension module directory... " >&6; } +if ${am_cv_python_pyexecdir+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$exec_prefix" = xNONE + then + am_py_exec_prefix=$am_py_prefix + else + am_py_exec_prefix=$exec_prefix + fi + am_cv_python_pyexecdir=`$PYTHON -c " +$am_python_setup_sysconfig +if can_use_sysconfig: + sitedir = sysconfig.get_path('platlib', vars={'platbase':'$am_py_prefix'}) +else: + from distutils import sysconfig + sitedir = sysconfig.get_python_lib(1, 0, prefix='$am_py_prefix') +sys.stdout.write(sitedir)"` + case $am_cv_python_pyexecdir in + $am_py_exec_prefix*) + am__strip_prefix=`echo "$am_py_exec_prefix" | sed 's|.|.|g'` + am_cv_python_pyexecdir=`echo "$am_cv_python_pyexecdir" | sed "s,^$am__strip_prefix,$PYTHON_EXEC_PREFIX,"` + ;; + *) + case $am_py_exec_prefix in + /usr|/System*) ;; + *) + am_cv_python_pyexecdir=$PYTHON_EXEC_PREFIX/lib/python$PYTHON_VERSION/site-packages + ;; + esac + ;; + esac + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_pyexecdir" >&5 +$as_echo "$am_cv_python_pyexecdir" >&6; } + pyexecdir=$am_cv_python_pyexecdir + + + + pkgpyexecdir=\${pyexecdir}/$PACKAGE + + + + fi + + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}python2", so it can be a program name with args. +set dummy ${ac_tool_prefix}python2; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON2+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON2 in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON2="$PYTHON2" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PYTHON2="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PYTHON2=$ac_cv_path_PYTHON2 +if test -n "$PYTHON2"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON2" >&5 +$as_echo "$PYTHON2" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PYTHON2"; then + ac_pt_PYTHON2=$PYTHON2 + # Extract the first word of "python2", so it can be a program name with args. +set dummy python2; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_PYTHON2+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PYTHON2 in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PYTHON2="$ac_pt_PYTHON2" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PYTHON2="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PYTHON2=$ac_cv_path_ac_pt_PYTHON2 +if test -n "$ac_pt_PYTHON2"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PYTHON2" >&5 +$as_echo "$ac_pt_PYTHON2" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_PYTHON2" = x; then + PYTHON2="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PYTHON2=$ac_pt_PYTHON2 + fi +else + PYTHON2="$ac_cv_path_PYTHON2" +fi + + test -z "$PYTHON2" && as_fn_error $? "python2 is required for --enable-python2_bindings but cannot be found" "$LINENO" 5 + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}python2-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}python2-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON2_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON2_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON2_CONFIG="$PYTHON2_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PYTHON2_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PYTHON2_CONFIG=$ac_cv_path_PYTHON2_CONFIG +if test -n "$PYTHON2_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON2_CONFIG" >&5 +$as_echo "$PYTHON2_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PYTHON2_CONFIG"; then + ac_pt_PYTHON2_CONFIG=$PYTHON2_CONFIG + # Extract the first word of "python2-config", so it can be a program name with args. +set dummy python2-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_PYTHON2_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PYTHON2_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PYTHON2_CONFIG="$ac_pt_PYTHON2_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PYTHON2_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PYTHON2_CONFIG=$ac_cv_path_ac_pt_PYTHON2_CONFIG +if test -n "$ac_pt_PYTHON2_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PYTHON2_CONFIG" >&5 +$as_echo "$ac_pt_PYTHON2_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_PYTHON2_CONFIG" = x; then + PYTHON2_CONFIG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PYTHON2_CONFIG=$ac_pt_PYTHON2_CONFIG + fi +else + PYTHON2_CONFIG="$ac_cv_path_PYTHON2_CONFIG" +fi + + test -z "$PYTHON2_CONFIG" && if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}python-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}python-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON2_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON2_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON2_CONFIG="$PYTHON2_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PYTHON2_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PYTHON2_CONFIG=$ac_cv_path_PYTHON2_CONFIG +if test -n "$PYTHON2_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON2_CONFIG" >&5 +$as_echo "$PYTHON2_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PYTHON2_CONFIG"; then + ac_pt_PYTHON2_CONFIG=$PYTHON2_CONFIG + # Extract the first word of "python-config", so it can be a program name with args. +set dummy python-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_PYTHON2_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PYTHON2_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PYTHON2_CONFIG="$ac_pt_PYTHON2_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PYTHON2_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PYTHON2_CONFIG=$ac_cv_path_ac_pt_PYTHON2_CONFIG +if test -n "$ac_pt_PYTHON2_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PYTHON2_CONFIG" >&5 +$as_echo "$ac_pt_PYTHON2_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_PYTHON2_CONFIG" = x; then + PYTHON2_CONFIG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PYTHON2_CONFIG=$ac_pt_PYTHON2_CONFIG + fi +else + PYTHON2_CONFIG="$ac_cv_path_PYTHON2_CONFIG" +fi + + test -z "$PYTHON2_CONFIG" && as_fn_error $? "python headers are required for --enable-python2_bindings but cannot be found" "$LINENO" 5 + PYTHON2_INCDIRS=`"$PYTHON2_CONFIG" --includes` + PYTHON2_LIBDIRS=`"$PYTHON2_CONFIG" --libs` + PYTHON2DIR=$pythondir + PYTHON_BINDINGS=yes +fi + +if test "$PYTHON3_BINDINGS" = yes -o "$BUILD_LVMDBUSD" = yes; then + unset PYTHON PYTHON_CONFIG + unset am_cv_pathless_PYTHON ac_cv_path_PYTHON am_cv_python_platform + unset am_cv_python_pythondir am_cv_python_version am_cv_python_pyexecdir + unset ac_cv_path_PYTHON_CONFIG ac_cv_path_ac_pt_PYTHON_CONFIG + + + + + + + if test -n "$PYTHON"; then + # If the user set $PYTHON, use it and don't search something else. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $PYTHON version is >= 3" >&5 +$as_echo_n "checking whether $PYTHON version is >= 3... " >&6; } + prog="import sys +# split strings by '.' and convert to numeric. Append some zeros +# because we need at least 4 digits for the hex conversion. +# map returns an iterator in Python 3.0 and a list in 2.x +minver = list(map(int, '3'.split('.'))) + [0, 0, 0] +minverhex = 0 +# xrange is not present in Python 3.0 and range returns an iterator +for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[i] +sys.exit(sys.hexversion < minverhex)" + if { echo "$as_me:$LINENO: $PYTHON -c "$prog"" >&5 + ($PYTHON -c "$prog") >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + as_fn_error $? "Python interpreter is too old" "$LINENO" 5 +fi + am_display_PYTHON=$PYTHON + else + # Otherwise, try each interpreter until we find one that satisfies + # VERSION. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a Python interpreter with version >= 3" >&5 +$as_echo_n "checking for a Python interpreter with version >= 3... " >&6; } +if ${am_cv_pathless_PYTHON+:} false; then : + $as_echo_n "(cached) " >&6 +else + + for am_cv_pathless_PYTHON in python python2 python3 python3.3 python3.2 python3.1 python3.0 python2.7 python2.6 python2.5 python2.4 python2.3 python2.2 python2.1 python2.0 none; do + test "$am_cv_pathless_PYTHON" = none && break + prog="import sys +# split strings by '.' and convert to numeric. Append some zeros +# because we need at least 4 digits for the hex conversion. +# map returns an iterator in Python 3.0 and a list in 2.x +minver = list(map(int, '3'.split('.'))) + [0, 0, 0] +minverhex = 0 +# xrange is not present in Python 3.0 and range returns an iterator +for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[i] +sys.exit(sys.hexversion < minverhex)" + if { echo "$as_me:$LINENO: $am_cv_pathless_PYTHON -c "$prog"" >&5 + ($am_cv_pathless_PYTHON -c "$prog") >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then : + break +fi + done +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_pathless_PYTHON" >&5 +$as_echo "$am_cv_pathless_PYTHON" >&6; } + # Set $PYTHON to the absolute path of $am_cv_pathless_PYTHON. + if test "$am_cv_pathless_PYTHON" = none; then + PYTHON=: + else + # Extract the first word of "$am_cv_pathless_PYTHON", so it can be a program name with args. +set dummy $am_cv_pathless_PYTHON; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON="$PYTHON" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PYTHON="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PYTHON=$ac_cv_path_PYTHON +if test -n "$PYTHON"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5 +$as_echo "$PYTHON" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi + am_display_PYTHON=$am_cv_pathless_PYTHON + fi + + + if test "$PYTHON" = :; then + as_fn_error $? "no suitable Python interpreter found" "$LINENO" 5 + else + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON version" >&5 +$as_echo_n "checking for $am_display_PYTHON version... " >&6; } +if ${am_cv_python_version+:} false; then : + $as_echo_n "(cached) " >&6 +else + am_cv_python_version=`$PYTHON -c "import sys; sys.stdout.write(sys.version[:3])"` +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_version" >&5 +$as_echo "$am_cv_python_version" >&6; } + PYTHON_VERSION=$am_cv_python_version + + + + PYTHON_PREFIX='${prefix}' + + PYTHON_EXEC_PREFIX='${exec_prefix}' + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON platform" >&5 +$as_echo_n "checking for $am_display_PYTHON platform... " >&6; } +if ${am_cv_python_platform+:} false; then : + $as_echo_n "(cached) " >&6 +else + am_cv_python_platform=`$PYTHON -c "import sys; sys.stdout.write(sys.platform)"` +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_platform" >&5 +$as_echo "$am_cv_python_platform" >&6; } + PYTHON_PLATFORM=$am_cv_python_platform + + + # Just factor out some code duplication. + am_python_setup_sysconfig="\ +import sys +# Prefer sysconfig over distutils.sysconfig, for better compatibility +# with python 3.x. See automake bug#10227. +try: + import sysconfig +except ImportError: + can_use_sysconfig = 0 +else: + can_use_sysconfig = 1 +# Can't use sysconfig in CPython 2.7, since it's broken in virtualenvs: +# <https://github.com/pypa/virtualenv/issues/118> +try: + from platform import python_implementation + if python_implementation() == 'CPython' and sys.version[:3] == '2.7': + can_use_sysconfig = 0 +except ImportError: + pass" + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON script directory" >&5 +$as_echo_n "checking for $am_display_PYTHON script directory... " >&6; } +if ${am_cv_python_pythondir+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$prefix" = xNONE + then + am_py_prefix=$ac_default_prefix + else + am_py_prefix=$prefix + fi + am_cv_python_pythondir=`$PYTHON -c " +$am_python_setup_sysconfig +if can_use_sysconfig: + sitedir = sysconfig.get_path('purelib', vars={'base':'$am_py_prefix'}) +else: + from distutils import sysconfig + sitedir = sysconfig.get_python_lib(0, 0, prefix='$am_py_prefix') +sys.stdout.write(sitedir)"` + case $am_cv_python_pythondir in + $am_py_prefix*) + am__strip_prefix=`echo "$am_py_prefix" | sed 's|.|.|g'` + am_cv_python_pythondir=`echo "$am_cv_python_pythondir" | sed "s,^$am__strip_prefix,$PYTHON_PREFIX,"` + ;; + *) + case $am_py_prefix in + /usr|/System*) ;; + *) + am_cv_python_pythondir=$PYTHON_PREFIX/lib/python$PYTHON_VERSION/site-packages + ;; + esac + ;; + esac + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_pythondir" >&5 +$as_echo "$am_cv_python_pythondir" >&6; } + pythondir=$am_cv_python_pythondir + + + + pkgpythondir=\${pythondir}/$PACKAGE + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $am_display_PYTHON extension module directory" >&5 +$as_echo_n "checking for $am_display_PYTHON extension module directory... " >&6; } +if ${am_cv_python_pyexecdir+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$exec_prefix" = xNONE + then + am_py_exec_prefix=$am_py_prefix + else + am_py_exec_prefix=$exec_prefix + fi + am_cv_python_pyexecdir=`$PYTHON -c " +$am_python_setup_sysconfig +if can_use_sysconfig: + sitedir = sysconfig.get_path('platlib', vars={'platbase':'$am_py_prefix'}) +else: + from distutils import sysconfig + sitedir = sysconfig.get_python_lib(1, 0, prefix='$am_py_prefix') +sys.stdout.write(sitedir)"` + case $am_cv_python_pyexecdir in + $am_py_exec_prefix*) + am__strip_prefix=`echo "$am_py_exec_prefix" | sed 's|.|.|g'` + am_cv_python_pyexecdir=`echo "$am_cv_python_pyexecdir" | sed "s,^$am__strip_prefix,$PYTHON_EXEC_PREFIX,"` + ;; + *) + case $am_py_exec_prefix in + /usr|/System*) ;; + *) + am_cv_python_pyexecdir=$PYTHON_EXEC_PREFIX/lib/python$PYTHON_VERSION/site-packages + ;; + esac + ;; + esac + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_python_pyexecdir" >&5 +$as_echo "$am_cv_python_pyexecdir" >&6; } + pyexecdir=$am_cv_python_pyexecdir + + + + pkgpyexecdir=\${pyexecdir}/$PACKAGE + + + + fi + + + PYTHON3=$PYTHON + test -z "$PYTHON3" && as_fn_error $? "python3 is required for --enable-python3_bindings or --enable-dbus-service but cannot be found" "$LINENO" 5 + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}python3-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}python3-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON3_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON3_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON3_CONFIG="$PYTHON3_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PYTHON3_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PYTHON3_CONFIG=$ac_cv_path_PYTHON3_CONFIG +if test -n "$PYTHON3_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON3_CONFIG" >&5 +$as_echo "$PYTHON3_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PYTHON3_CONFIG"; then + ac_pt_PYTHON3_CONFIG=$PYTHON3_CONFIG + # Extract the first word of "python3-config", so it can be a program name with args. +set dummy python3-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_PYTHON3_CONFIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PYTHON3_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PYTHON3_CONFIG="$ac_pt_PYTHON3_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_PYTHON3_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PYTHON3_CONFIG=$ac_cv_path_ac_pt_PYTHON3_CONFIG +if test -n "$ac_pt_PYTHON3_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PYTHON3_CONFIG" >&5 +$as_echo "$ac_pt_PYTHON3_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_PYTHON3_CONFIG" = x; then + PYTHON3_CONFIG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PYTHON3_CONFIG=$ac_pt_PYTHON3_CONFIG + fi +else + PYTHON3_CONFIG="$ac_cv_path_PYTHON3_CONFIG" +fi + + test -z "$PYTHON3_CONFIG" && as_fn_error $? "python3 headers are required for --enable-python3_bindings or --enable-dbus-service but cannot be found" "$LINENO" 5 + PYTHON3_INCDIRS=`"$PYTHON3_CONFIG" --includes` + PYTHON3_LIBDIRS=`"$PYTHON3_CONFIG" --libs` + PYTHON3DIR=$pythondir + PYTHON_BINDINGS=yes +fi + +if test "$BUILD_LVMDBUSD" = yes; then + # To get this macro, install autoconf-archive package then run autoreconf + + if test -z $PYTHON; + then + if test -z "python3"; + then + PYTHON="python3" + else + PYTHON="python3" + fi + fi + PYTHON_NAME=`basename $PYTHON` + { $as_echo "$as_me:${as_lineno-$LINENO}: checking $PYTHON_NAME module: pyudev" >&5 +$as_echo_n "checking $PYTHON_NAME module: pyudev... " >&6; } + $PYTHON -c "import pyudev" 2>/dev/null + if test $? -eq 0; + then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + eval HAVE_PYMOD_PYUDEV=yes + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + eval HAVE_PYMOD_PYUDEV=no + # + if test -n "Required" + then + as_fn_error $? "failed to find required module pyudev" "$LINENO" 5 + exit 1 + fi + fi + + + if test -z $PYTHON; + then + if test -z "python3"; + then + PYTHON="python3" + else + PYTHON="python3" + fi + fi + PYTHON_NAME=`basename $PYTHON` + { $as_echo "$as_me:${as_lineno-$LINENO}: checking $PYTHON_NAME module: dbus" >&5 +$as_echo_n "checking $PYTHON_NAME module: dbus... " >&6; } + $PYTHON -c "import dbus" 2>/dev/null + if test $? -eq 0; + then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + eval HAVE_PYMOD_DBUS=yes + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + eval HAVE_PYMOD_DBUS=no + # + if test -n "Required" + then + as_fn_error $? "failed to find required module dbus" "$LINENO" 5 + exit 1 + fi + fi + +fi + +if test "$PYTHON_BINDINGS" = yes -o "$PYTHON2_BINDINGS" = yes -o "$PYTHON3_BINDINGS" = yes; then + test "$APPLIB" != yes && as_fn_error $? "Python_bindings require --enable-applib" "$LINENO" 5 +fi + +################################################################################ +# Check whether --enable-pkgconfig was given. +if test "${enable_pkgconfig+set}" = set; then : + enableval=$enable_pkgconfig; PKGCONFIG=$enableval +else + PKGCONFIG=no +fi + + +################################################################################ +# Check whether --enable-write_install was given. +if test "${enable_write_install+set}" = set; then : + enableval=$enable_write_install; WRITE_INSTALL=$enableval +else + WRITE_INSTALL=no +fi + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to install fsadm" >&5 +$as_echo_n "checking whether to install fsadm... " >&6; } +# Check whether --enable-fsadm was given. +if test "${enable_fsadm+set}" = set; then : + enableval=$enable_fsadm; FSADM=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $FSADM" >&5 +$as_echo "$FSADM" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to install blkdeactivate" >&5 +$as_echo_n "checking whether to install blkdeactivate... " >&6; } +# Check whether --enable-blkdeactivate was given. +if test "${enable_blkdeactivate+set}" = set; then : + enableval=$enable_blkdeactivate; BLKDEACTIVATE=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $BLKDEACTIVATE" >&5 +$as_echo "$BLKDEACTIVATE" >&6; } + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to use dmeventd" >&5 +$as_echo_n "checking whether to use dmeventd... " >&6; } +# Check whether --enable-dmeventd was given. +if test "${enable_dmeventd+set}" = set; then : + enableval=$enable_dmeventd; DMEVENTD=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DMEVENTD" >&5 +$as_echo "$DMEVENTD" >&6; } + +BUILD_DMEVENTD=$DMEVENTD + +if test "$DMEVENTD" = yes; then + if test "$MIRRORS" != internal; then + as_fn_error $? "--enable-dmeventd currently requires --with-mirrors=internal" "$LINENO" 5 + fi + if test "$CMDLIB" = no; then + as_fn_error $? "--enable-dmeventd requires --enable-cmdlib to be used as well" "$LINENO" 5 + fi + + +$as_echo "#define DMEVENTD 1" >>confdefs.h + +fi + +################################################################################ + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getline in -lc" >&5 +$as_echo_n "checking for getline in -lc... " >&6; } +if ${ac_cv_lib_c_getline+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char getline (); +int +main () +{ +return getline (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_getline=yes +else + ac_cv_lib_c_getline=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_getline" >&5 +$as_echo "$ac_cv_lib_c_getline" >&6; } +if test "x$ac_cv_lib_c_getline" = xyes; then : + +$as_echo "#define HAVE_GETLINE 1" >>confdefs.h + +fi + + +################################################################################ + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for canonicalize_file_name in -lc" >&5 +$as_echo_n "checking for canonicalize_file_name in -lc... " >&6; } +if ${ac_cv_lib_c_canonicalize_file_name+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char canonicalize_file_name (); +int +main () +{ +return canonicalize_file_name (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_canonicalize_file_name=yes +else + ac_cv_lib_c_canonicalize_file_name=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_canonicalize_file_name" >&5 +$as_echo "$ac_cv_lib_c_canonicalize_file_name" >&6; } +if test "x$ac_cv_lib_c_canonicalize_file_name" = xyes; then : + +$as_echo "#define HAVE_CANONICALIZE_FILE_NAME 1" >>confdefs.h + +fi + + +################################################################################ +test "$exec_prefix" = NONE -a "$prefix" = NONE && exec_prefix="" + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if ${ac_cv_lib_dl_dlopen+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dl_dlopen=yes +else + ac_cv_lib_dl_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = xyes; then : + +$as_echo "#define HAVE_LIBDL 1" >>confdefs.h + + DL_LIBS="-ldl" + HAVE_LIBDL=yes +else + DL_LIBS= + HAVE_LIBDL=no +fi + + +################################################################################ +if [ \( "$LVM1" = shared -o "$POOL" = shared -o "$CLUSTER" = shared \ + -o "$SNAPSHOTS" = shared -o "$MIRRORS" = shared \ + -o "$RAID" = shared -o "$CACHE" = shared \ + \) -a "$STATIC_LINK" = yes ]; then + as_fn_error $? "Features cannot be 'shared' when building statically" "$LINENO" 5 +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for log10 in -lm" >&5 +$as_echo_n "checking for log10 in -lm... " >&6; } +if ${ac_cv_lib_m_log10+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lm $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char log10 (); +int +main () +{ +return log10 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_m_log10=yes +else + ac_cv_lib_m_log10=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_log10" >&5 +$as_echo "$ac_cv_lib_m_log10" >&6; } +if test "x$ac_cv_lib_m_log10" = xyes; then : + M_LIBS="-lm" +else + hard_bailout +fi + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_lock in -lpthread" >&5 +$as_echo_n "checking for pthread_mutex_lock in -lpthread... " >&6; } +if ${ac_cv_lib_pthread_pthread_mutex_lock+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pthread_mutex_lock (); +int +main () +{ +return pthread_mutex_lock (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pthread_pthread_mutex_lock=yes +else + ac_cv_lib_pthread_pthread_mutex_lock=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_mutex_lock" >&5 +$as_echo "$ac_cv_lib_pthread_pthread_mutex_lock" >&6; } +if test "x$ac_cv_lib_pthread_pthread_mutex_lock" = xyes; then : + PTHREAD_LIBS="-lpthread" +else + hard_bailout +fi + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable selinux support" >&5 +$as_echo_n "checking whether to enable selinux support... " >&6; } +# Check whether --enable-selinux was given. +if test "${enable_selinux+set}" = set; then : + enableval=$enable_selinux; SELINUX=$enableval +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SELINUX" >&5 +$as_echo "$SELINUX" >&6; } + +################################################################################ +if test "$SELINUX" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sepol_check_context in -lsepol" >&5 +$as_echo_n "checking for sepol_check_context in -lsepol... " >&6; } +if ${ac_cv_lib_sepol_sepol_check_context+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsepol $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char sepol_check_context (); +int +main () +{ +return sepol_check_context (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_sepol_sepol_check_context=yes +else + ac_cv_lib_sepol_sepol_check_context=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sepol_sepol_check_context" >&5 +$as_echo "$ac_cv_lib_sepol_sepol_check_context" >&6; } +if test "x$ac_cv_lib_sepol_sepol_check_context" = xyes; then : + + +$as_echo "#define HAVE_SEPOL 1" >>confdefs.h + + SELINUX_LIBS="-lsepol" +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for is_selinux_enabled in -lselinux" >&5 +$as_echo_n "checking for is_selinux_enabled in -lselinux... " >&6; } +if ${ac_cv_lib_selinux_is_selinux_enabled+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lselinux $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char is_selinux_enabled (); +int +main () +{ +return is_selinux_enabled (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_selinux_is_selinux_enabled=yes +else + ac_cv_lib_selinux_is_selinux_enabled=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_selinux_is_selinux_enabled" >&5 +$as_echo "$ac_cv_lib_selinux_is_selinux_enabled" >&6; } +if test "x$ac_cv_lib_selinux_is_selinux_enabled" = xyes; then : + + for ac_header in selinux/selinux.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "selinux/selinux.h" "ac_cv_header_selinux_selinux_h" "$ac_includes_default" +if test "x$ac_cv_header_selinux_selinux_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SELINUX_SELINUX_H 1 +_ACEOF + +else + hard_bailout +fi + +done + + for ac_header in selinux/label.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "selinux/label.h" "ac_cv_header_selinux_label_h" "$ac_includes_default" +if test "x$ac_cv_header_selinux_label_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SELINUX_LABEL_H 1 +_ACEOF + +fi + +done + + +$as_echo "#define HAVE_SELINUX 1" >>confdefs.h + + SELINUX_LIBS="-lselinux $SELINUX_LIBS" + SELINUX_PC="libselinux" + HAVE_SELINUX=yes +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Disabling selinux" >&5 +$as_echo "$as_me: WARNING: Disabling selinux" >&2;} + SELINUX_LIBS= + SELINUX_PC= + HAVE_SELINUX=no +fi + +fi + +################################################################################ +if test "$REALTIME" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_gettime in -lrt" >&5 +$as_echo_n "checking for clock_gettime in -lrt... " >&6; } +if ${ac_cv_lib_rt_clock_gettime+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lrt $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char clock_gettime (); +int +main () +{ +return clock_gettime (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_rt_clock_gettime=yes +else + ac_cv_lib_rt_clock_gettime=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rt_clock_gettime" >&5 +$as_echo "$ac_cv_lib_rt_clock_gettime" >&6; } +if test "x$ac_cv_lib_rt_clock_gettime" = xyes; then : + HAVE_REALTIME=yes +else + HAVE_REALTIME=no +fi + + + if test "$HAVE_REALTIME" = yes; then + +$as_echo "#define HAVE_REALTIME 1" >>confdefs.h + + LIBS="-lrt $LIBS" + RT_LIB="-lrt" + else + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Disabling realtime clock" >&5 +$as_echo "$as_me: WARNING: Disabling realtime clock" >&2;} + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct stat has st_ctim." >&5 +$as_echo_n "checking for struct stat has st_ctim.... " >&6; } +if ${ac_cv_stat_st_ctim+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <sys/stat.h> +long bar(void) { struct stat s; return (long)(s.st_ctim.tv_sec + s.st_ctim.tv_nsec);} + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_stat_st_ctim=yes +else + ac_cv_stat_st_ctim=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_stat_st_ctim" >&5 +$as_echo "$ac_cv_stat_st_ctim" >&6; } + +if test $ac_cv_stat_st_ctim = yes; then : + +$as_echo "#define HAVE_STAT_ST_CTIM 1" >>confdefs.h + +fi + +################################################################################ +for ac_header in getopt.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "getopt.h" "ac_cv_header_getopt_h" "$ac_includes_default" +if test "x$ac_cv_header_getopt_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETOPT_H 1 +_ACEOF + +$as_echo "#define HAVE_GETOPTLONG 1" >>confdefs.h + +fi + +done + + +################################################################################ +if test "$READLINE" != no; then + lvm_saved_libs=$LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing tgetent" >&5 +$as_echo_n "checking for library containing tgetent... " >&6; } +if ${ac_cv_search_tgetent+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char tgetent (); +int +main () +{ +return tgetent (); + ; + return 0; +} +_ACEOF +for ac_lib in '' tinfo ncurses curses termcap termlib; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_tgetent=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_tgetent+:} false; then : + break +fi +done +if ${ac_cv_search_tgetent+:} false; then : + +else + ac_cv_search_tgetent=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_tgetent" >&5 +$as_echo "$ac_cv_search_tgetent" >&6; } +ac_res=$ac_cv_search_tgetent +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + READLINE_LIBS=$ac_cv_search_tgetent +else + + if test "$READLINE" = yes; then + as_fn_error $? "termcap could not be found which is required for the +--enable-readline option (which is enabled by default). Either disable readline +support with --disable-readline or download and install termcap from: + ftp.gnu.org/gnu/termcap +Note: if you are using precompiled packages you will also need the development + package as well (which may be called termcap-devel or something similar). +Note: (n)curses also seems to work as a substitute for termcap. This was + not found either - but you could try installing that as well." "$LINENO" 5 + fi +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for readline in -lreadline" >&5 +$as_echo_n "checking for readline in -lreadline... " >&6; } +if ${ac_cv_lib_readline_readline+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lreadline $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char readline (); +int +main () +{ +return readline (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_readline_readline=yes +else + ac_cv_lib_readline_readline=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_readline" >&5 +$as_echo "$ac_cv_lib_readline_readline" >&6; } +if test "x$ac_cv_lib_readline_readline" = xyes; then : + + +$as_echo "#define READLINE_SUPPORT 1" >>confdefs.h + + LIBS=$lvm_saved_libs + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_line_buffer in -lreadline" >&5 +$as_echo_n "checking for rl_line_buffer in -lreadline... " >&6; } +if ${ac_cv_lib_readline_rl_line_buffer+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lreadline $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char rl_line_buffer (); +int +main () +{ +return rl_line_buffer (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_readline_rl_line_buffer=yes +else + ac_cv_lib_readline_rl_line_buffer=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_line_buffer" >&5 +$as_echo "$ac_cv_lib_readline_rl_line_buffer" >&6; } +if test "x$ac_cv_lib_readline_rl_line_buffer" = xyes; then : + READLINE_LIBS="-lreadline" +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: linking -lreadline with $READLINE_LIBS needed" >&5 +$as_echo "linking -lreadline with $READLINE_LIBS needed" >&6; } + READLINE_LIBS="-lreadline $READLINE_LIBS" + +fi + +else + + READLINE_LIBS= + if test "$READLINE" = yes; then + as_fn_error $? "GNU Readline could not be found which is required for the +--enable-readline option (which is enabled by default). Either disable readline +support with --disable-readline or download and install readline from: + ftp.gnu.org/gnu/readline +Note: if you are using precompiled packages you will also need the development +package as well (which may be called readline-devel or something similar)." "$LINENO" 5 + fi +fi + + LIBS="$READLINE_LIBS $lvm_saved_libs" + for ac_func in rl_completion_matches +do : + ac_fn_c_check_func "$LINENO" "rl_completion_matches" "ac_cv_func_rl_completion_matches" +if test "x$ac_cv_func_rl_completion_matches" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_RL_COMPLETION_MATCHES 1 +_ACEOF + +fi +done + + LIBS=$lvm_saved_libs +fi + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable internationalisation" >&5 +$as_echo_n "checking whether to enable internationalisation... " >&6; } +# Check whether --enable-nls was given. +if test "${enable_nls+set}" = set; then : + enableval=$enable_nls; INTL=$enableval +else + INTL=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INTL" >&5 +$as_echo "$INTL" >&6; } + +if test "$INTL" = yes; then +# FIXME - Move this - can be device-mapper too + INTL_PACKAGE="lvm2" + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}msgfmt", so it can be a program name with args. +set dummy ${ac_tool_prefix}msgfmt; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_MSGFMT+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $MSGFMT in + [\\/]* | ?:[\\/]*) + ac_cv_path_MSGFMT="$MSGFMT" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_MSGFMT="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +MSGFMT=$ac_cv_path_MSGFMT +if test -n "$MSGFMT"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSGFMT" >&5 +$as_echo "$MSGFMT" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_MSGFMT"; then + ac_pt_MSGFMT=$MSGFMT + # Extract the first word of "msgfmt", so it can be a program name with args. +set dummy msgfmt; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_MSGFMT+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_MSGFMT in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_MSGFMT="$ac_pt_MSGFMT" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_MSGFMT="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_MSGFMT=$ac_cv_path_ac_pt_MSGFMT +if test -n "$ac_pt_MSGFMT"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_MSGFMT" >&5 +$as_echo "$ac_pt_MSGFMT" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_MSGFMT" = x; then + MSGFMT="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + MSGFMT=$ac_pt_MSGFMT + fi +else + MSGFMT="$ac_cv_path_MSGFMT" +fi + + + if test -z "$MSGFMT"; then : + as_fn_error $? "msgfmt not found in path $PATH" "$LINENO" 5 +fi + + +# Check whether --with-localedir was given. +if test "${with_localedir+set}" = set; then : + withval=$with_localedir; localedir=$withval +else + localedir=${localedir-'${datarootdir}/locale'} +fi + + +cat >>confdefs.h <<_ACEOF +#define INTL_PACKAGE "$INTL_PACKAGE" +_ACEOF + + # double eval needed ${datarootdir} -> ${prefix}/share -> real path + +cat >>confdefs.h <<_ACEOF +#define LOCALEDIR "$(eval echo $(eval echo $localedir))" +_ACEOF + +fi + +################################################################################ + +# Check whether --with-confdir was given. +if test "${with_confdir+set}" = set; then : + withval=$with_confdir; CONFDIR=$withval +else + CONFDIR='/etc' +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_ETC_DIR "$CONFDIR" +_ACEOF + + + +# Check whether --with-staticdir was given. +if test "${with_staticdir+set}" = set; then : + withval=$with_staticdir; STATICDIR=$withval +else + STATICDIR='${exec_prefix}/sbin' +fi + + + +# Check whether --with-usrlibdir was given. +if test "${with_usrlibdir+set}" = set; then : + withval=$with_usrlibdir; usrlibdir=$withval +else + usrlibdir='${prefix}/lib' +fi + + + +# Check whether --with-usrsbindir was given. +if test "${with_usrsbindir+set}" = set; then : + withval=$with_usrsbindir; usrsbindir=$withval +else + usrsbindir='${prefix}/sbin' +fi + + +################################################################################ + +# Check whether --with-udev_prefix was given. +if test "${with_udev_prefix+set}" = set; then : + withval=$with_udev_prefix; udev_prefix=$withval +else + udev_prefix='${exec_prefix}' +fi + + + +# Check whether --with-udevdir was given. +if test "${with_udevdir+set}" = set; then : + withval=$with_udevdir; udevdir=$withval +else + udevdir='${udev_prefix}/lib/udev/rules.d' +fi + + +################################################################################ + +# Check whether --with-systemdsystemunitdir was given. +if test "${with_systemdsystemunitdir+set}" = set; then : + withval=$with_systemdsystemunitdir; systemdsystemunitdir=$withval +else + pkg_config_init + pkg_systemdsystemunitdir=$("$PKG_CONFIG" --variable=systemdsystemunitdir systemd) +fi + + +test -n "$pkg_systemdsystemunitdir" && systemdsystemunitdir=$pkg_systemdsystemunitdir +test -z "$systemdsystemunitdir" && systemdsystemunitdir='${exec_prefix}/lib/systemd/system'; + +systemdutildir=$("$PKG_CONFIG" --variable=systemdutildir systemd) +test -z "$systemdutildir" && systemdutildir='${exec_prefix}/lib/systemd'; + +################################################################################ + +# Check whether --with-tmpfilesdir was given. +if test "${with_tmpfilesdir+set}" = set; then : + withval=$with_tmpfilesdir; tmpfilesdir=$withval +else + tmpfilesdir='${prefix}/lib/tmpfiles.d' +fi + +################################################################################ +if test "$READLINE" = yes; then + for ac_header in readline/readline.h readline/history.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else + hard_bailout +fi + +done + +fi + +if test "$BUILD_CMIRRORD" = yes; then + for ac_func in atexit +do : + ac_fn_c_check_func "$LINENO" "atexit" "ac_cv_func_atexit" +if test "x$ac_cv_func_atexit" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_ATEXIT 1 +_ACEOF + +else + hard_bailout +fi +done + +fi + +if test "$BUILD_LVMLOCKD" = yes; then + for ac_func in clock_gettime strtoull +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +else + hard_bailout +fi +done + +fi + +if test "$BUILD_LVMPOLLD" = yes; then + for ac_func in strpbrk +do : + ac_fn_c_check_func "$LINENO" "strpbrk" "ac_cv_func_strpbrk" +if test "x$ac_cv_func_strpbrk" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STRPBRK 1 +_ACEOF + +else + hard_bailout +fi +done + + ac_fn_c_check_decl "$LINENO" "strerror_r" "ac_cv_have_decl_strerror_r" "$ac_includes_default" +if test "x$ac_cv_have_decl_strerror_r" = xyes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi + +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_STRERROR_R $ac_have_decl +_ACEOF + +for ac_func in strerror_r +do : + ac_fn_c_check_func "$LINENO" "strerror_r" "ac_cv_func_strerror_r" +if test "x$ac_cv_func_strerror_r" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STRERROR_R 1 +_ACEOF + +fi +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether strerror_r returns char *" >&5 +$as_echo_n "checking whether strerror_r returns char *... " >&6; } +if ${ac_cv_func_strerror_r_char_p+:} false; then : + $as_echo_n "(cached) " >&6 +else + + ac_cv_func_strerror_r_char_p=no + if test $ac_cv_have_decl_strerror_r = yes; then + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ + + char buf[100]; + char x = *strerror_r (0, buf, sizeof buf); + char *p = strerror_r (0, buf, sizeof buf); + return !p || x; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_func_strerror_r_char_p=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + else + # strerror_r is not declared. Choose between + # systems that have relatively inaccessible declarations for the + # function. BeOS and DEC UNIX 4.0 fall in this category, but the + # former has a strerror_r that returns char*, while the latter + # has a strerror_r that returns `int'. + # This test should segfault on the DEC system. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + extern char *strerror_r (); +int +main () +{ +char buf[100]; + char x = *strerror_r (0, buf, sizeof buf); + return ! isalpha (x); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_strerror_r_char_p=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strerror_r_char_p" >&5 +$as_echo "$ac_cv_func_strerror_r_char_p" >&6; } +if test $ac_cv_func_strerror_r_char_p = yes; then + +$as_echo "#define STRERROR_R_CHAR_P 1" >>confdefs.h + +fi + +fi + +if test "$CLVMD" != none; then + for ac_header in mntent.h netdb.h netinet/in.h pthread.h search.h sys/mount.h sys/socket.h sys/uio.h sys/un.h utmpx.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else + as_fn_error $? "bailing out" "$LINENO" 5 +fi + +done + + for ac_func in dup2 getmntent memmove select socket +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +else + hard_bailout +fi +done + + # getmntent is in the standard C library on UNICOS, in -lsun on Irix 4, +# -lseq on Dynix/PTX, -lgen on Unixware. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing getmntent" >&5 +$as_echo_n "checking for library containing getmntent... " >&6; } +if ${ac_cv_search_getmntent+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char getmntent (); +int +main () +{ +return getmntent (); + ; + return 0; +} +_ACEOF +for ac_lib in '' sun seq gen; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_getmntent=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_getmntent+:} false; then : + break +fi +done +if ${ac_cv_search_getmntent+:} false; then : + +else + ac_cv_search_getmntent=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_getmntent" >&5 +$as_echo "$ac_cv_search_getmntent" >&6; } +ac_res=$ac_cv_search_getmntent +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + ac_cv_func_getmntent=yes + +$as_echo "#define HAVE_GETMNTENT 1" >>confdefs.h + +else + ac_cv_func_getmntent=no +fi + + + for ac_header in sys/select.h sys/socket.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking types of arguments for select" >&5 +$as_echo_n "checking types of arguments for select... " >&6; } +if ${ac_cv_func_select_args+:} false; then : + $as_echo_n "(cached) " >&6 +else + for ac_arg234 in 'fd_set *' 'int *' 'void *'; do + for ac_arg1 in 'int' 'size_t' 'unsigned long int' 'unsigned int'; do + for ac_arg5 in 'struct timeval *' 'const struct timeval *'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +#ifdef HAVE_SYS_SELECT_H +# include <sys/select.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +# include <sys/socket.h> +#endif + +int +main () +{ +extern int select ($ac_arg1, + $ac_arg234, $ac_arg234, $ac_arg234, + $ac_arg5); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_func_select_args="$ac_arg1,$ac_arg234,$ac_arg5"; break 3 +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done + done +done +# Provide a safe default value. +: "${ac_cv_func_select_args=int,int *,struct timeval *}" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_select_args" >&5 +$as_echo "$ac_cv_func_select_args" >&6; } +ac_save_IFS=$IFS; IFS=',' +set dummy `echo "$ac_cv_func_select_args" | sed 's/\*/\*/g'` +IFS=$ac_save_IFS +shift + +cat >>confdefs.h <<_ACEOF +#define SELECT_TYPE_ARG1 $1 +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define SELECT_TYPE_ARG234 ($2) +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define SELECT_TYPE_ARG5 ($3) +_ACEOF + +rm -f conftest* + +fi + +if test "$CLUSTER" != none; then + for ac_header in sys/socket.h sys/un.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else + hard_bailout +fi + +done + + for ac_func in socket +do : + ac_fn_c_check_func "$LINENO" "socket" "ac_cv_func_socket" +if test "x$ac_cv_func_socket" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SOCKET 1 +_ACEOF + +else + hard_bailout +fi +done + +fi + +if test "$DMEVENTD" = yes; then + for ac_header in arpa/inet.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "arpa/inet.h" "ac_cv_header_arpa_inet_h" "$ac_includes_default" +if test "x$ac_cv_header_arpa_inet_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_ARPA_INET_H 1 +_ACEOF + +else + hard_bailout +fi + +done + +fi + +if test "$HAVE_LIBDL" = yes; then + for ac_header in dlfcn.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default" +if test "x$ac_cv_header_dlfcn_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DLFCN_H 1 +_ACEOF + +else + hard_bailout +fi + +done + +fi + +if test "$INTL" = yes; then + for ac_header in libintl.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "libintl.h" "ac_cv_header_libintl_h" "$ac_includes_default" +if test "x$ac_cv_header_libintl_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBINTL_H 1 +_ACEOF + +else + hard_bailout +fi + +done + +fi + +if test "$UDEV_SYNC" = yes; then + for ac_header in sys/ipc.h sys/sem.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +else + hard_bailout +fi + +done + +fi + +################################################################################ +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}modprobe", so it can be a program name with args. +set dummy ${ac_tool_prefix}modprobe; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_MODPROBE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $MODPROBE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_MODPROBE_CMD="$MODPROBE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_MODPROBE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +MODPROBE_CMD=$ac_cv_path_MODPROBE_CMD +if test -n "$MODPROBE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MODPROBE_CMD" >&5 +$as_echo "$MODPROBE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_MODPROBE_CMD"; then + ac_pt_MODPROBE_CMD=$MODPROBE_CMD + # Extract the first word of "modprobe", so it can be a program name with args. +set dummy modprobe; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ac_pt_MODPROBE_CMD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_MODPROBE_CMD in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_MODPROBE_CMD="$ac_pt_MODPROBE_CMD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ac_pt_MODPROBE_CMD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_MODPROBE_CMD=$ac_cv_path_ac_pt_MODPROBE_CMD +if test -n "$ac_pt_MODPROBE_CMD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_MODPROBE_CMD" >&5 +$as_echo "$ac_pt_MODPROBE_CMD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_MODPROBE_CMD" = x; then + MODPROBE_CMD="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + MODPROBE_CMD=$ac_pt_MODPROBE_CMD + fi +else + MODPROBE_CMD="$ac_cv_path_MODPROBE_CMD" +fi + + +if test -n "$MODPROBE_CMD"; then + +cat >>confdefs.h <<_ACEOF +#define MODPROBE_CMD "$MODPROBE_CMD" +_ACEOF + +fi + + +lvm_exec_prefix=$exec_prefix +test "$lvm_exec_prefix" = NONE && lvm_exec_prefix=$prefix +test "$lvm_exec_prefix" = NONE && lvm_exec_prefix=$ac_default_prefix +LVM_PATH="$lvm_exec_prefix/sbin/lvm" + +cat >>confdefs.h <<_ACEOF +#define LVM_PATH "$LVM_PATH" +_ACEOF + + +clvmd_prefix=$ac_default_prefix +test "$prefix" != NONE && clvmd_prefix=$prefix +CLVMD_PATH="$clvmd_prefix/sbin/clvmd" + +cat >>confdefs.h <<_ACEOF +#define CLVMD_PATH "$CLVMD_PATH" +_ACEOF + + +################################################################################ +if test "$BUILD_DMEVENTD" = yes; then + +# Check whether --with-dmeventd-pidfile was given. +if test "${with_dmeventd_pidfile+set}" = set; then : + withval=$with_dmeventd_pidfile; DMEVENTD_PIDFILE=$withval +else + DMEVENTD_PIDFILE="$DEFAULT_PID_DIR/dmeventd.pid" +fi + + +cat >>confdefs.h <<_ACEOF +#define DMEVENTD_PIDFILE "$DMEVENTD_PIDFILE" +_ACEOF + +fi + +if test "$BUILD_DMEVENTD" = yes; then + +# Check whether --with-dmeventd-path was given. +if test "${with_dmeventd_path+set}" = set; then : + withval=$with_dmeventd_path; DMEVENTD_PATH=$withval +else + DMEVENTD_PATH="$lvm_exec_prefix/sbin/dmeventd" +fi + + +cat >>confdefs.h <<_ACEOF +#define DMEVENTD_PATH "$DMEVENTD_PATH" +_ACEOF + +fi + +################################################################################ + +# Check whether --with-default-system-dir was given. +if test "${with_default_system_dir+set}" = set; then : + withval=$with_default_system_dir; DEFAULT_SYS_DIR=$withval +else + DEFAULT_SYS_DIR="/etc/lvm" +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_SYS_DIR "$DEFAULT_SYS_DIR" +_ACEOF + + + +# Check whether --with-default-profile-subdir was given. +if test "${with_default_profile_subdir+set}" = set; then : + withval=$with_default_profile_subdir; DEFAULT_PROFILE_SUBDIR=$withval +else + DEFAULT_PROFILE_SUBDIR=profile +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_PROFILE_SUBDIR "$DEFAULT_PROFILE_SUBDIR" +_ACEOF + + + +# Check whether --with-default-archive-subdir was given. +if test "${with_default_archive_subdir+set}" = set; then : + withval=$with_default_archive_subdir; DEFAULT_ARCHIVE_SUBDIR=$withval +else + DEFAULT_ARCHIVE_SUBDIR=archive +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_ARCHIVE_SUBDIR "$DEFAULT_ARCHIVE_SUBDIR" +_ACEOF + + + +# Check whether --with-default-backup-subdir was given. +if test "${with_default_backup_subdir+set}" = set; then : + withval=$with_default_backup_subdir; DEFAULT_BACKUP_SUBDIR=$withval +else + DEFAULT_BACKUP_SUBDIR=backup +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_BACKUP_SUBDIR "$DEFAULT_BACKUP_SUBDIR" +_ACEOF + + + +# Check whether --with-default-cache-subdir was given. +if test "${with_default_cache_subdir+set}" = set; then : + withval=$with_default_cache_subdir; DEFAULT_CACHE_SUBDIR=$withval +else + DEFAULT_CACHE_SUBDIR=cache +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_CACHE_SUBDIR "$DEFAULT_CACHE_SUBDIR" +_ACEOF + + + +# Check whether --with-default-locking-dir was given. +if test "${with_default_locking_dir+set}" = set; then : + withval=$with_default_locking_dir; DEFAULT_LOCK_DIR=$withval +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for default lock directory" >&5 +$as_echo_n "checking for default lock directory... " >&6; } + DEFAULT_LOCK_DIR="$RUN_DIR/lock/lvm" + test -d "$RUN_DIR/lock" || DEFAULT_LOCK_DIR="/var/lock/lvm" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DEFAULT_LOCK_DIR" >&5 +$as_echo "$DEFAULT_LOCK_DIR" >&6; } +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_LOCK_DIR "$DEFAULT_LOCK_DIR" +_ACEOF + + +################################################################################ + +# Check whether --with-default-data-alignment was given. +if test "${with_default_data_alignment+set}" = set; then : + withval=$with_default_data_alignment; DEFAULT_DATA_ALIGNMENT=$withval +else + DEFAULT_DATA_ALIGNMENT=1 +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_DATA_ALIGNMENT $DEFAULT_DATA_ALIGNMENT +_ACEOF + + +################################################################################ +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for kernel interface choice" >&5 +$as_echo_n "checking for kernel interface choice... " >&6; } + +# Check whether --with-interface was given. +if test "${with_interface+set}" = set; then : + withval=$with_interface; interface=$withval +else + interface=ioctl +fi + +test "$interface" != ioctl && as_fn_error $? "--with-interface=ioctl required. fs no longer supported." "$LINENO" 5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $interface" >&5 +$as_echo "$interface" >&6; } + +################################################################################ +read DM_LIB_VERSION < "$srcdir"/VERSION_DM 2>/dev/null || DM_LIB_VERSION=Unknown + +cat >>confdefs.h <<_ACEOF +#define DM_LIB_VERSION "$DM_LIB_VERSION" +_ACEOF + + +DM_LIB_PATCHLEVEL=`cat "$srcdir"/VERSION_DM | $AWK -F '[-. ]' '{printf "%s.%s.%s",$1,$2,$3}'` + +read VER < "$srcdir"/VERSION 2>/dev/null || VER=Unknown + +LVM_VERSION=\"$VER\" +LVM_RELEASE_DATE="\"`echo $VER | $SED 's/.* (//;s/).*//'`\"" +VER=`echo "$VER" | $AWK '{print $1}'` +LVM_RELEASE="\"`echo "$VER" | $AWK -F '-' '{print $2}'`\"" +VER=`echo "$VER" | $AWK -F '-' '{print $1}'` +LVM_MAJOR=`echo "$VER" | $AWK -F '.' '{print $1}'` +LVM_MINOR=`echo "$VER" | $AWK -F '.' '{print $2}'` +LVM_PATCHLEVEL=`echo "$VER" | $AWK -F '[(.]' '{print $3}'` +LVM_LIBAPI=`echo "$VER" | $AWK -F '[()]' '{print $2}'` + +################################################################################ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +################################################################################ +ac_config_files="$ac_config_files Makefile make.tmpl daemons/Makefile daemons/clvmd/Makefile daemons/cmirrord/Makefile daemons/dmeventd/Makefile daemons/dmeventd/libdevmapper-event.pc daemons/dmeventd/plugins/Makefile daemons/dmeventd/plugins/lvm2/Makefile daemons/dmeventd/plugins/raid/Makefile daemons/dmeventd/plugins/mirror/Makefile daemons/dmeventd/plugins/snapshot/Makefile daemons/dmeventd/plugins/thin/Makefile daemons/lvmdbusd/Makefile daemons/lvmdbusd/path.py daemons/lvmetad/Makefile daemons/lvmpolld/Makefile daemons/lvmlockd/Makefile conf/Makefile conf/example.conf conf/lvmlocal.conf conf/command_profile_template.profile conf/metadata_profile_template.profile include/.symlinks include/Makefile lib/Makefile lib/format1/Makefile lib/format_pool/Makefile lib/locking/Makefile lib/mirror/Makefile lib/replicator/Makefile include/lvm-version.h lib/raid/Makefile lib/snapshot/Makefile lib/thin/Makefile lib/cache_segtype/Makefile libdaemon/Makefile libdaemon/client/Makefile libdaemon/server/Makefile libdm/Makefile libdm/libdevmapper.pc liblvm/Makefile liblvm/liblvm2app.pc man/Makefile po/Makefile python/Makefile python/setup.py scripts/blkdeactivate.sh scripts/blk_availability_init_red_hat scripts/blk_availability_systemd_red_hat.service scripts/clvmd_init_red_hat scripts/cmirrord_init_red_hat scripts/com.redhat.lvmdbus1.service scripts/dm_event_systemd_red_hat.service scripts/dm_event_systemd_red_hat.socket scripts/lvm2_cluster_activation_red_hat.sh scripts/lvm2_cluster_activation_systemd_red_hat.service scripts/lvm2_clvmd_systemd_red_hat.service scripts/lvm2_cmirrord_systemd_red_hat.service scripts/lvm2_lvmdbusd_systemd_red_hat.service scripts/lvm2_lvmetad_init_red_hat scripts/lvm2_lvmetad_systemd_red_hat.service scripts/lvm2_lvmetad_systemd_red_hat.socket scripts/lvm2_lvmpolld_init_red_hat scripts/lvm2_lvmpolld_systemd_red_hat.service scripts/lvm2_lvmpolld_systemd_red_hat.socket scripts/lvm2_lvmlockd_systemd_red_hat.service scripts/lvm2_lvmlocking_systemd_red_hat.service scripts/lvm2_monitoring_init_red_hat scripts/lvm2_monitoring_systemd_red_hat.service scripts/lvm2_pvscan_systemd_red_hat@.service scripts/lvm2_tmpfiles_red_hat.conf scripts/Makefile test/Makefile test/api/Makefile test/unit/Makefile tools/Makefile udev/Makefile unit-tests/datastruct/Makefile unit-tests/regex/Makefile unit-tests/mm/Makefile" + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + if test "x$cache_file" != "x/dev/null"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by $as_me, which was +generated by GNU Autoconf 2.69. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Report bugs to the package provider." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" +ac_cs_version="\\ +config.status +configured by $0, generated by GNU Autoconf 2.69, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2012 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +MKDIR_P='$MKDIR_P' +AWK='$AWK' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "include/configure.h") CONFIG_HEADERS="$CONFIG_HEADERS include/configure.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "make.tmpl") CONFIG_FILES="$CONFIG_FILES make.tmpl" ;; + "daemons/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/Makefile" ;; + "daemons/clvmd/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/clvmd/Makefile" ;; + "daemons/cmirrord/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/cmirrord/Makefile" ;; + "daemons/dmeventd/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/Makefile" ;; + "daemons/dmeventd/libdevmapper-event.pc") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/libdevmapper-event.pc" ;; + "daemons/dmeventd/plugins/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/plugins/Makefile" ;; + "daemons/dmeventd/plugins/lvm2/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/plugins/lvm2/Makefile" ;; + "daemons/dmeventd/plugins/raid/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/plugins/raid/Makefile" ;; + "daemons/dmeventd/plugins/mirror/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/plugins/mirror/Makefile" ;; + "daemons/dmeventd/plugins/snapshot/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/plugins/snapshot/Makefile" ;; + "daemons/dmeventd/plugins/thin/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/dmeventd/plugins/thin/Makefile" ;; + "daemons/lvmdbusd/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/lvmdbusd/Makefile" ;; + "daemons/lvmdbusd/path.py") CONFIG_FILES="$CONFIG_FILES daemons/lvmdbusd/path.py" ;; + "daemons/lvmetad/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/lvmetad/Makefile" ;; + "daemons/lvmpolld/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/lvmpolld/Makefile" ;; + "daemons/lvmlockd/Makefile") CONFIG_FILES="$CONFIG_FILES daemons/lvmlockd/Makefile" ;; + "conf/Makefile") CONFIG_FILES="$CONFIG_FILES conf/Makefile" ;; + "conf/example.conf") CONFIG_FILES="$CONFIG_FILES conf/example.conf" ;; + "conf/lvmlocal.conf") CONFIG_FILES="$CONFIG_FILES conf/lvmlocal.conf" ;; + "conf/command_profile_template.profile") CONFIG_FILES="$CONFIG_FILES conf/command_profile_template.profile" ;; + "conf/metadata_profile_template.profile") CONFIG_FILES="$CONFIG_FILES conf/metadata_profile_template.profile" ;; + "include/.symlinks") CONFIG_FILES="$CONFIG_FILES include/.symlinks" ;; + "include/Makefile") CONFIG_FILES="$CONFIG_FILES include/Makefile" ;; + "lib/Makefile") CONFIG_FILES="$CONFIG_FILES lib/Makefile" ;; + "lib/format1/Makefile") CONFIG_FILES="$CONFIG_FILES lib/format1/Makefile" ;; + "lib/format_pool/Makefile") CONFIG_FILES="$CONFIG_FILES lib/format_pool/Makefile" ;; + "lib/locking/Makefile") CONFIG_FILES="$CONFIG_FILES lib/locking/Makefile" ;; + "lib/mirror/Makefile") CONFIG_FILES="$CONFIG_FILES lib/mirror/Makefile" ;; + "lib/replicator/Makefile") CONFIG_FILES="$CONFIG_FILES lib/replicator/Makefile" ;; + "include/lvm-version.h") CONFIG_FILES="$CONFIG_FILES include/lvm-version.h" ;; + "lib/raid/Makefile") CONFIG_FILES="$CONFIG_FILES lib/raid/Makefile" ;; + "lib/snapshot/Makefile") CONFIG_FILES="$CONFIG_FILES lib/snapshot/Makefile" ;; + "lib/thin/Makefile") CONFIG_FILES="$CONFIG_FILES lib/thin/Makefile" ;; + "lib/cache_segtype/Makefile") CONFIG_FILES="$CONFIG_FILES lib/cache_segtype/Makefile" ;; + "libdaemon/Makefile") CONFIG_FILES="$CONFIG_FILES libdaemon/Makefile" ;; + "libdaemon/client/Makefile") CONFIG_FILES="$CONFIG_FILES libdaemon/client/Makefile" ;; + "libdaemon/server/Makefile") CONFIG_FILES="$CONFIG_FILES libdaemon/server/Makefile" ;; + "libdm/Makefile") CONFIG_FILES="$CONFIG_FILES libdm/Makefile" ;; + "libdm/libdevmapper.pc") CONFIG_FILES="$CONFIG_FILES libdm/libdevmapper.pc" ;; + "liblvm/Makefile") CONFIG_FILES="$CONFIG_FILES liblvm/Makefile" ;; + "liblvm/liblvm2app.pc") CONFIG_FILES="$CONFIG_FILES liblvm/liblvm2app.pc" ;; + "man/Makefile") CONFIG_FILES="$CONFIG_FILES man/Makefile" ;; + "po/Makefile") CONFIG_FILES="$CONFIG_FILES po/Makefile" ;; + "python/Makefile") CONFIG_FILES="$CONFIG_FILES python/Makefile" ;; + "python/setup.py") CONFIG_FILES="$CONFIG_FILES python/setup.py" ;; + "scripts/blkdeactivate.sh") CONFIG_FILES="$CONFIG_FILES scripts/blkdeactivate.sh" ;; + "scripts/blk_availability_init_red_hat") CONFIG_FILES="$CONFIG_FILES scripts/blk_availability_init_red_hat" ;; + "scripts/blk_availability_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/blk_availability_systemd_red_hat.service" ;; + "scripts/clvmd_init_red_hat") CONFIG_FILES="$CONFIG_FILES scripts/clvmd_init_red_hat" ;; + "scripts/cmirrord_init_red_hat") CONFIG_FILES="$CONFIG_FILES scripts/cmirrord_init_red_hat" ;; + "scripts/com.redhat.lvmdbus1.service") CONFIG_FILES="$CONFIG_FILES scripts/com.redhat.lvmdbus1.service" ;; + "scripts/dm_event_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/dm_event_systemd_red_hat.service" ;; + "scripts/dm_event_systemd_red_hat.socket") CONFIG_FILES="$CONFIG_FILES scripts/dm_event_systemd_red_hat.socket" ;; + "scripts/lvm2_cluster_activation_red_hat.sh") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_cluster_activation_red_hat.sh" ;; + "scripts/lvm2_cluster_activation_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_cluster_activation_systemd_red_hat.service" ;; + "scripts/lvm2_clvmd_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_clvmd_systemd_red_hat.service" ;; + "scripts/lvm2_cmirrord_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_cmirrord_systemd_red_hat.service" ;; + "scripts/lvm2_lvmdbusd_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmdbusd_systemd_red_hat.service" ;; + "scripts/lvm2_lvmetad_init_red_hat") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmetad_init_red_hat" ;; + "scripts/lvm2_lvmetad_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmetad_systemd_red_hat.service" ;; + "scripts/lvm2_lvmetad_systemd_red_hat.socket") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmetad_systemd_red_hat.socket" ;; + "scripts/lvm2_lvmpolld_init_red_hat") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmpolld_init_red_hat" ;; + "scripts/lvm2_lvmpolld_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmpolld_systemd_red_hat.service" ;; + "scripts/lvm2_lvmpolld_systemd_red_hat.socket") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmpolld_systemd_red_hat.socket" ;; + "scripts/lvm2_lvmlockd_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmlockd_systemd_red_hat.service" ;; + "scripts/lvm2_lvmlocking_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_lvmlocking_systemd_red_hat.service" ;; + "scripts/lvm2_monitoring_init_red_hat") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_monitoring_init_red_hat" ;; + "scripts/lvm2_monitoring_systemd_red_hat.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_monitoring_systemd_red_hat.service" ;; + "scripts/lvm2_pvscan_systemd_red_hat@.service") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_pvscan_systemd_red_hat@.service" ;; + "scripts/lvm2_tmpfiles_red_hat.conf") CONFIG_FILES="$CONFIG_FILES scripts/lvm2_tmpfiles_red_hat.conf" ;; + "scripts/Makefile") CONFIG_FILES="$CONFIG_FILES scripts/Makefile" ;; + "test/Makefile") CONFIG_FILES="$CONFIG_FILES test/Makefile" ;; + "test/api/Makefile") CONFIG_FILES="$CONFIG_FILES test/api/Makefile" ;; + "test/unit/Makefile") CONFIG_FILES="$CONFIG_FILES test/unit/Makefile" ;; + "tools/Makefile") CONFIG_FILES="$CONFIG_FILES tools/Makefile" ;; + "udev/Makefile") CONFIG_FILES="$CONFIG_FILES udev/Makefile" ;; + "unit-tests/datastruct/Makefile") CONFIG_FILES="$CONFIG_FILES unit-tests/datastruct/Makefile" ;; + "unit-tests/regex/Makefile") CONFIG_FILES="$CONFIG_FILES unit-tests/regex/Makefile" ;; + "unit-tests/mm/Makefile") CONFIG_FILES="$CONFIG_FILES unit-tests/mm/Makefile" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' <conf$$subs.awk | sed ' +/^[^""]/{ + N + s/\n// +} +' >>$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' <confdefs.h | sed ' +s/'"$ac_delim"'/"\\\ +"/g' >>$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac + ac_MKDIR_P=$MKDIR_P + case $MKDIR_P in + [\\/$]* | ?:[\\/]* ) ;; + */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; + esac +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +s&@MKDIR_P@&$ac_MKDIR_P&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi + ;; + + + esac + +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + + +if test -n "$THIN_CONFIGURE_WARN"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Support for thin provisioning is limited since some thin provisioning tools are missing!" >&5 +$as_echo "$as_me: WARNING: Support for thin provisioning is limited since some thin provisioning tools are missing!" >&2;} +fi + +if test -n "$THIN_CHECK_VERSION_WARN"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You should also install thin_check vsn 0.3.2 (or later) to use lvm2 thin provisioning" >&5 +$as_echo "$as_me: WARNING: You should also install thin_check vsn 0.3.2 (or later) to use lvm2 thin provisioning" >&2;} +fi + +if test -n "$CACHE_CONFIGURE_WARN"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Support for cache is limited since some cache tools are missing!" >&5 +$as_echo "$as_me: WARNING: Support for cache is limited since some cache tools are missing!" >&2;} +fi + +if test "$ODIRECT" != yes; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: O_DIRECT disabled: low-memory pvmove may lock up" >&5 +$as_echo "$as_me: WARNING: O_DIRECT disabled: low-memory pvmove may lock up" >&2;} +fi
diff --git a/configure.h b/configure.h new file mode 100644 index 0000000..d7649ab --- /dev/null +++ b/configure.h
@@ -0,0 +1,15 @@ +#ifndef CONFIGURE_H +#define CONFIGURE_H + +#include <sys/ioctl.h> + +#define DEFAULT_DM_ADD_NODE DM_ADD_NODE_ON_CREATE +#define DEFAULT_DM_NAME_MANGLING DM_STRING_MANGLING_NONE +#define DM_LIB_VERSION "1.02.131 (2016-07-15)" +#define DM_DEVICE_UID 0 +#define DM_DEVICE_GID 0 +#define DM_DEVICE_MODE 0600 +#define DM_IOCTLS 1 +#define HAVE_GETOPTLONG + +#endif // CONFIGURE_H
diff --git a/configure.in b/configure.in new file mode 100644 index 0000000..33b5c76 --- /dev/null +++ b/configure.in
@@ -0,0 +1,2238 @@ +############################################################################### +## Copyright (C) 2000-2004 Sistina Software, Inc. All rights reserved. +## Copyright (C) 2004-2016 Red Hat, Inc. All rights reserved. +## +## This copyrighted material is made available to anyone wishing to use, +## modify, copy, or redistribute it subject to the terms and conditions +## of the GNU General Public License v.2. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software Foundation, +## Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +################################################################################ + +AC_PREREQ(2.69) +################################################################################ +dnl -- Process this file with autoconf to produce a configure script. +AC_INIT +AC_CONFIG_SRCDIR([lib/device/dev-cache.h]) +AC_CONFIG_HEADERS([include/configure.h]) + +################################################################################ +dnl -- Setup the directory where autoconf has auxilary files +AC_CONFIG_AUX_DIR(autoconf) + +################################################################################ +dnl -- Get system type +AC_CANONICAL_TARGET([]) + +AS_IF([test -z "$CFLAGS"], [COPTIMISE_FLAG="-O2"]) +case "$host_os" in + linux*) + CLDFLAGS="$CLDFLAGS -Wl,--version-script,.export.sym" + ELDFLAGS="-Wl,--export-dynamic" + # FIXME Generate list and use --dynamic-list=.dlopen.sym + CLDWHOLEARCHIVE="-Wl,-whole-archive" + CLDNOWHOLEARCHIVE="-Wl,-no-whole-archive" + LDDEPS="$LDDEPS .export.sym" + LIB_SUFFIX=so + DEVMAPPER=yes + BUILD_LVMETAD=no + BUILD_LVMPOLLD=no + LOCKDSANLOCK=no + LOCKDDLM=no + ODIRECT=yes + DM_IOCTLS=yes + SELINUX=yes + CLUSTER=internal + FSADM=yes + BLKDEACTIVATE=yes + ;; + darwin*) + CFLAGS="$CFLAGS -no-cpp-precomp -fno-common" + CLDFLAGS="$CLDFLAGS" + ELDFLAGS= + CLDWHOLEARCHIVE="-all_load" + CLDNOWHOLEARCHIVE= + LIB_SUFFIX=dylib + DEVMAPPER=yes + ODIRECT=no + DM_IOCTLS=no + SELINUX=no + CLUSTER=none + FSADM=no + BLKDEACTIVATE=no + ;; +esac + +################################################################################ +dnl -- Checks for programs. +AC_PROG_SED +AC_PROG_AWK +save_CFLAGS=$CFLAGS +save_CXXFLAGS=$CXXFLAGS +AC_PROG_CC +AC_PROG_CXX +CFLAGS=$save_CFLAGS +CXXFLAGS=$save_CXXFLAGS + +dnl probably no longer needed in 2008, but... +AC_PROG_GCC_TRADITIONAL +AC_PROG_INSTALL +AC_PROG_LN_S +AC_PROG_MAKE_SET +AC_PROG_MKDIR_P +AC_PROG_RANLIB +AC_PATH_TOOL(CFLOW_CMD, cflow) +AC_PATH_TOOL(CSCOPE_CMD, cscope) +AC_PATH_TOOL(CHMOD, chmod) + +################################################################################ +dnl -- Check for header files. +AC_HEADER_DIRENT +AC_HEADER_MAJOR +AC_HEADER_STDBOOL +AC_HEADER_STDC +AC_HEADER_SYS_WAIT +AC_HEADER_TIME + +AC_CHECK_HEADERS([assert.h ctype.h dirent.h errno.h fcntl.h float.h \ + getopt.h inttypes.h langinfo.h libgen.h limits.h locale.h paths.h \ + signal.h stdarg.h stddef.h stdio.h stdlib.h string.h sys/file.h \ + sys/ioctl.h syslog.h sys/mman.h sys/param.h sys/resource.h sys/stat.h \ + sys/time.h sys/types.h sys/utsname.h sys/wait.h time.h \ + unistd.h], , [AC_MSG_ERROR(bailing out)]) + +AC_CHECK_HEADERS(termios.h sys/statvfs.h sys/timerfd.h linux/magic.h linux/fiemap.h) + +case "$host_os" in + linux*) + AC_CHECK_HEADERS(asm/byteorder.h linux/fs.h malloc.h,,AC_MSG_ERROR(bailing out)) ;; + darwin*) + AC_CHECK_HEADERS(machine/endian.h sys/disk.h,,AC_MSG_ERROR(bailing out)) ;; +esac + +################################################################################ +dnl -- Check for typedefs, structures, and compiler characteristics. +AC_C_CONST +AC_C_INLINE +AC_CHECK_MEMBERS([struct stat.st_rdev]) +AC_CHECK_TYPES([ptrdiff_t]) +AC_STRUCT_TM +AC_TYPE_OFF_T +AC_TYPE_PID_T +AC_TYPE_SIGNAL +AC_TYPE_SIZE_T +AC_TYPE_MODE_T +AC_TYPE_INT8_T +AC_TYPE_INT16_T +AC_TYPE_INT32_T +AC_TYPE_INT64_T +AC_TYPE_SSIZE_T +AC_TYPE_UID_T +AC_TYPE_UINT8_T +AC_TYPE_UINT16_T +AC_TYPE_UINT32_T +AC_TYPE_UINT64_T + +################################################################################ +dnl -- Check for functions +AC_CHECK_FUNCS([ftruncate gethostname getpagesize gettimeofday localtime_r \ + memchr memset mkdir mkfifo munmap nl_langinfo realpath rmdir setenv \ + setlocale strcasecmp strchr strcspn strdup strerror strncasecmp strndup \ + strrchr strspn strstr strtol strtoul uname], , [AC_MSG_ERROR(bailing out)]) +AC_FUNC_ALLOCA +AC_FUNC_CLOSEDIR_VOID +AC_FUNC_CHOWN +AC_FUNC_FORK +AC_FUNC_LSTAT +AC_FUNC_MALLOC +AC_FUNC_MEMCMP +AC_FUNC_MKTIME +AC_FUNC_MMAP +AC_FUNC_REALLOC +AC_FUNC_STAT +AC_FUNC_STRTOD +AC_FUNC_VPRINTF + +################################################################################ +dnl -- Disable dependency tracking +AC_MSG_CHECKING(whether to enable dependency tracking) +AC_ARG_ENABLE(dependency-tracking, + AC_HELP_STRING([--disable-dependency-tracking], + [speeds up one-time build.]), + USE_TRACKING=$enableval, USE_TRACKING=yes) +AC_MSG_RESULT($USE_TRACKING) + +################################################################################ +dnl -- Enables statically-linked tools +AC_MSG_CHECKING(whether to use static linking) +AC_ARG_ENABLE(static_link, + AC_HELP_STRING([--enable-static_link], + [use this to link the tools to their libraries + statically (default is dynamic linking]), + STATIC_LINK=$enableval, STATIC_LINK=no) +AC_MSG_RESULT($STATIC_LINK) + +################################################################################ +dnl -- Check if compiler/linker supports PIE and RELRO +AC_TRY_CCFLAG([-pie], [HAVE_PIE], [], []) +AC_SUBST(HAVE_PIE) +AC_TRY_LDFLAGS([-Wl,-z,relro,-z,now], [HAVE_FULL_RELRO], [], []) +AC_SUBST(HAVE_FULL_RELRO) + +################################################################################ +dnl -- Prefix is /usr by default, the exec_prefix default is setup later +AC_PREFIX_DEFAULT(/usr) +if test "$prefix" = NONE; then + datarootdir=${ac_default_prefix}/share +fi + +################################################################################ +dnl -- Setup the ownership of the files +AC_MSG_CHECKING(file owner) +AC_ARG_WITH(user, + AC_HELP_STRING([--with-user=USER], + [set the owner of installed files [USER=]]), + OWNER=$withval) +AC_MSG_RESULT($OWNER) +test -n "$OWNER" && INSTALL="$INSTALL -o $OWNER" + +################################################################################ +dnl -- Setup the group ownership of the files +AC_MSG_CHECKING(group owner) +AC_ARG_WITH(group, + AC_HELP_STRING([--with-group=GROUP], + [set the group owner of installed files [GROUP=]]), + GROUP=$withval) +AC_MSG_RESULT($GROUP) +test -n "$GROUP" && INSTALL="$INSTALL -g $GROUP" + +################################################################################ +dnl -- Setup device node ownership +AC_MSG_CHECKING(device node uid) + +AC_ARG_WITH(device-uid, + AC_HELP_STRING([--with-device-uid=UID], + [set the owner used for new device nodes [UID=0]]), + DM_DEVICE_UID=$withval, DM_DEVICE_UID=0) +AC_MSG_RESULT($DM_DEVICE_UID) +AC_DEFINE_UNQUOTED([DM_DEVICE_UID], [$DM_DEVICE_UID], [Define default owner for device node]) + +################################################################################ +dnl -- Setup device group ownership +AC_MSG_CHECKING(device node gid) + +AC_ARG_WITH(device-gid, + AC_HELP_STRING([--with-device-gid=GID], + [set the group used for new device nodes [GID=0]]), + DM_DEVICE_GID=$withval, DM_DEVICE_GID=0) +AC_MSG_RESULT($DM_DEVICE_GID) +AC_DEFINE_UNQUOTED([DM_DEVICE_GID], [$DM_DEVICE_GID], [Define default group for device node]) + +################################################################################ +dnl -- Setup device mode +AC_MSG_CHECKING(device node mode) + +AC_ARG_WITH(device-mode, + AC_HELP_STRING([--with-device-mode=MODE], + [set the mode used for new device nodes [MODE=0600]]), + DM_DEVICE_MODE=$withval, DM_DEVICE_MODE=0600) +AC_MSG_RESULT($DM_DEVICE_MODE) +AC_DEFINE_UNQUOTED([DM_DEVICE_MODE], [$DM_DEVICE_MODE], [Define default mode for device node]) + +AC_MSG_CHECKING(when to create device nodes) +AC_ARG_WITH(device-nodes-on, + AC_HELP_STRING([--with-device-nodes-on=ON], + [create nodes on resume or create [ON=resume]]), + ADD_NODE=$withval, ADD_NODE=resume) +case "$ADD_NODE" in + resume) add_on=DM_ADD_NODE_ON_RESUME;; + create) add_on=DM_ADD_NODE_ON_CREATE;; + *) AC_MSG_ERROR([--with-device-nodes-on parameter invalid]);; +esac +AC_MSG_RESULT(on $ADD_NODE) +AC_DEFINE_UNQUOTED([DEFAULT_DM_ADD_NODE], $add_on, [Define default node creation behavior with dmsetup create]) + +AC_MSG_CHECKING(default name mangling) +AC_ARG_WITH(default-name-mangling, + AC_HELP_STRING([--with-default-name-mangling=MANGLING], + [default name mangling: auto/none/hex [auto]]), + MANGLING=$withval, MANGLING=auto) +case "$MANGLING" in + auto) mangling=DM_STRING_MANGLING_AUTO;; + none|disabled) mangling=DM_STRING_MANGLING_NONE;; + hex) mangling=DM_STRING_MANGLING_HEX;; + *) AC_MSG_ERROR([--with-default-name-mangling parameter invalid]);; +esac +AC_MSG_RESULT($MANGLING) +AC_DEFINE_UNQUOTED([DEFAULT_DM_NAME_MANGLING], $mangling, [Define default name mangling behaviour]) + +################################################################################ +dnl -- LVM1 tool fallback option +AC_MSG_CHECKING(whether to enable lvm1 fallback) +AC_ARG_ENABLE(lvm1_fallback, + AC_HELP_STRING([--enable-lvm1_fallback], + [use this to fall back and use LVM1 binaries if + device-mapper is missing from the kernel]), + LVM1_FALLBACK=$enableval, LVM1_FALLBACK=no) +AC_MSG_RESULT($LVM1_FALLBACK) + +if test "$LVM1_FALLBACK" = yes; then + DEFAULT_FALLBACK_TO_LVM1=1 + AC_DEFINE([LVM1_FALLBACK], 1, [Define to 1 if 'lvm' should fall back to using LVM1 binaries if device-mapper is missing from the kernel]) +else + DEFAULT_FALLBACK_TO_LVM1=0 +fi +AC_DEFINE_UNQUOTED(DEFAULT_FALLBACK_TO_LVM1, [$DEFAULT_FALLBACK_TO_LVM1], + [Fall back to LVM1 by default if device-mapper is missing from the kernel.]) + +################################################################################ +dnl -- format1 inclusion type +AC_MSG_CHECKING(whether to include support for lvm1 metadata) +AC_ARG_WITH(lvm1, + AC_HELP_STRING([--with-lvm1=TYPE], + [LVM1 metadata support: internal/shared/none [internal]]), + LVM1=$withval, LVM1=internal) + +AC_MSG_RESULT($LVM1) + +case "$LVM1" in + none|shared) ;; + internal) AC_DEFINE([LVM1_INTERNAL], 1, + [Define to 1 to include built-in support for LVM1 metadata.]) ;; + *) AC_MSG_ERROR([--with-lvm1 parameter invalid]) ;; +esac + +################################################################################ +dnl -- format_pool inclusion type +AC_MSG_CHECKING(whether to include support for GFS pool metadata) +AC_ARG_WITH(pool, + AC_HELP_STRING([--with-pool=TYPE], + [GFS pool read-only support: internal/shared/none [internal]]), + POOL=$withval, POOL=internal) +AC_MSG_RESULT($POOL) + +case "$POOL" in + none|shared) ;; + internal) AC_DEFINE([POOL_INTERNAL], 1, + [Define to 1 to include built-in support for GFS pool metadata.]) ;; + *) AC_MSG_ERROR([--with-pool parameter invalid]) +esac + +################################################################################ +dnl -- cluster_locking inclusion type +AC_MSG_CHECKING(whether to include support for cluster locking) +AC_ARG_WITH(cluster, + AC_HELP_STRING([--with-cluster=TYPE], + [cluster LVM locking support: internal/shared/none [internal]]), + CLUSTER=$withval) +AC_MSG_RESULT($CLUSTER) + +case "$CLUSTER" in + none|shared) ;; + internal) AC_DEFINE([CLUSTER_LOCKING_INTERNAL], 1, + [Define to 1 to include built-in support for clustered LVM locking.]) ;; + *) AC_MSG_ERROR([--with-cluster parameter invalid]) ;; +esac + +################################################################################ +dnl -- snapshots inclusion type +AC_MSG_CHECKING(whether to include snapshots) +AC_ARG_WITH(snapshots, + AC_HELP_STRING([--with-snapshots=TYPE], + [snapshot support: internal/shared/none [internal]]), + SNAPSHOTS=$withval, SNAPSHOTS=internal) +AC_MSG_RESULT($SNAPSHOTS) + +case "$SNAPSHOTS" in + none|shared) ;; + internal) AC_DEFINE([SNAPSHOT_INTERNAL], 1, + [Define to 1 to include built-in support for snapshots.]) ;; + *) AC_MSG_ERROR([--with-snapshots parameter invalid]) ;; +esac + +################################################################################ +dnl -- mirrors inclusion type +AC_MSG_CHECKING(whether to include mirrors) +AC_ARG_WITH(mirrors, + AC_HELP_STRING([--with-mirrors=TYPE], + [mirror support: internal/shared/none [internal]]), + MIRRORS=$withval, MIRRORS=internal) +AC_MSG_RESULT($MIRRORS) + +case "$MIRRORS" in + none|shared) ;; + internal) AC_DEFINE([MIRRORED_INTERNAL], 1, + [Define to 1 to include built-in support for mirrors.]) ;; + *) AC_MSG_ERROR([--with-mirrors parameter invalid]) ;; +esac + +################################################################################ +dnl -- raid inclusion type +AC_MSG_CHECKING(whether to include raid) +AC_ARG_WITH(raid, + AC_HELP_STRING([--with-raid=TYPE], + [raid support: internal/shared/none [internal]]), + RAID=$withval, RAID=internal) +AC_MSG_RESULT($RAID) + +AC_ARG_WITH(default-mirror-segtype, + AC_HELP_STRING([--with-default-mirror-segtype=TYPE], + [default mirror segtype: raid1/mirror [raid1]]), + DEFAULT_MIRROR_SEGTYPE=$withval, DEFAULT_MIRROR_SEGTYPE="raid1") +AC_ARG_WITH(default-raid10-segtype, + AC_HELP_STRING([--with-default-raid10-segtype=TYPE], + [default mirror segtype: raid10/mirror [raid10]]), + DEFAULT_RAID10_SEGTYPE=$withval, DEFAULT_RAID10_SEGTYPE="raid10") +case "$RAID" in + none) test "$DEFAULT_MIRROR_SEGTYPE" = "raid1" && DEFAULT_MIRROR_SEGTYPE="mirror" + test "$DEFAULT_RAID10_SEGTYPE" = "raid10" && DEFAULT_RAID10_SEGTYPE="mirror" ;; + shared) ;; + internal) AC_DEFINE([RAID_INTERNAL], 1, + [Define to 1 to include built-in support for raid.]) ;; + *) AC_MSG_ERROR([--with-raid parameter invalid]) ;; +esac + +AC_DEFINE_UNQUOTED([DEFAULT_MIRROR_SEGTYPE], ["$DEFAULT_MIRROR_SEGTYPE"], + [Default segtype used for mirror volumes.]) + +AC_DEFINE_UNQUOTED([DEFAULT_RAID10_SEGTYPE], ["$DEFAULT_RAID10_SEGTYPE"], + [Default segtype used for raid10 volumes.]) + +################################################################################ +dnl -- asynchronous volume replicator inclusion type +AC_MSG_CHECKING(whether to include replicators) +AC_ARG_WITH(replicators, + AC_HELP_STRING([--with-replicators=TYPE], + [replicator support: internal/shared/none [none]]), + REPLICATORS=$withval, REPLICATORS=none) +AC_MSG_RESULT($REPLICATORS) + +case "$REPLICATORS" in + none|shared) ;; + internal) AC_DEFINE([REPLICATOR_INTERNAL], 1, + [Define to 1 to include built-in support for replicators.]) ;; + *) AC_MSG_ERROR([--with-replicators parameter invalid ($REPLICATORS)]) ;; +esac + + +AC_ARG_WITH(default-sparse-segtype, + AC_HELP_STRING([--with-default-sparse-segtype=TYPE], + [default sparse segtype: thin/snapshot [thin]]), + DEFAULT_SPARSE_SEGTYPE=$withval, DEFAULT_SPARSE_SEGTYPE="thin") + +################################################################################ +dnl -- thin provisioning +AC_MSG_CHECKING(whether to include thin provisioning) +AC_ARG_WITH(thin, + AC_HELP_STRING([--with-thin=TYPE], + [thin provisioning support: internal/shared/none [internal]]), + THIN=$withval, THIN=internal) +AC_ARG_WITH(thin-check, + AC_HELP_STRING([--with-thin-check=PATH], + [thin_check tool: [autodetect]]), + THIN_CHECK_CMD=$withval, THIN_CHECK_CMD="autodetect") +AC_ARG_WITH(thin-dump, + AC_HELP_STRING([--with-thin-dump=PATH], + [thin_dump tool: [autodetect]]), + THIN_DUMP_CMD=$withval, THIN_DUMP_CMD="autodetect") +AC_ARG_WITH(thin-repair, + AC_HELP_STRING([--with-thin-repair=PATH], + [thin_repair tool: [autodetect]]), + THIN_REPAIR_CMD=$withval, THIN_REPAIR_CMD="autodetect") +AC_ARG_WITH(thin-restore, + AC_HELP_STRING([--with-thin-restore=PATH], + [thin_restore tool: [autodetect]]), + THIN_RESTORE_CMD=$withval, THIN_RESTORE_CMD="autodetect") + +AC_MSG_RESULT($THIN) + +case "$THIN" in + none) test "$DEFAULT_SPARSE_SEGTYPE" = "thin" && DEFAULT_SPARSE_SEGTYPE="snapshot" ;; + shared) ;; + internal) AC_DEFINE([THIN_INTERNAL], 1, + [Define to 1 to include built-in support for thin provisioning.]) ;; + *) AC_MSG_ERROR([--with-thin parameter invalid ($THIN)]) ;; +esac + +AC_DEFINE_UNQUOTED([DEFAULT_SPARSE_SEGTYPE], ["$DEFAULT_SPARSE_SEGTYPE"], + [Default segtype used for sparse volumes.]) + +dnl -- thin_check needs-check flag +AC_ARG_ENABLE(thin_check_needs_check, + AC_HELP_STRING([--disable-thin_check_needs_check], + [required if thin_check version is < 0.3.0]), + THIN_CHECK_NEEDS_CHECK=$enableval, THIN_CHECK_NEEDS_CHECK=yes) + +# Test if necessary thin tools are available +# if not - use plain defaults and warn user +case "$THIN" in + internal|shared) + # Empty means a config way to ignore thin checking + if test "$THIN_CHECK_CMD" = "autodetect"; then + AC_PATH_TOOL(THIN_CHECK_CMD, thin_check) + if test -z "$THIN_CHECK_CMD"; then + AC_MSG_WARN([thin_check not found in path $PATH]) + THIN_CHECK_CMD=/usr/sbin/thin_check + THIN_CONFIGURE_WARN=y + fi + fi + if test "$THIN_CHECK_NEEDS_CHECK" = yes; then + THIN_CHECK_VSN=`"$THIN_CHECK_CMD" -V 2>/dev/null` + THIN_CHECK_VSN_MAJOR=`echo "$THIN_CHECK_VSN" | $AWK -F '.' '{print $1}'` + THIN_CHECK_VSN_MINOR=`echo "$THIN_CHECK_VSN" | $AWK -F '.' '{print $2}'` + + if test -z "$THIN_CHECK_VSN_MAJOR" -o -z "$THIN_CHECK_VSN_MINOR"; then + AC_MSG_WARN([$THIN_CHECK_CMD: Bad version "$THIN_CHECK_VSN" found]) + THIN_CHECK_VERSION_WARN=y + THIN_CHECK_NEEDS_CHECK=no + elif test "$THIN_CHECK_VSN_MAJOR" -eq 0 -a "$THIN_CHECK_VSN_MINOR" -lt 3; then + AC_MSG_WARN([$THIN_CHECK_CMD: Old version "$THIN_CHECK_VSN" found]) + THIN_CHECK_VERSION_WARN=y + THIN_CHECK_NEEDS_CHECK=no + fi + fi + # Empty means a config way to ignore thin dumping + if test "$THIN_DUMP_CMD" = "autodetect"; then + AC_PATH_TOOL(THIN_DUMP_CMD, thin_dump) + test -z "$THIN_DUMP_CMD" && { + AC_MSG_WARN(thin_dump not found in path $PATH) + THIN_DUMP_CMD=/usr/sbin/thin_dump + THIN_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore thin repairing + if test "$THIN_REPAIR_CMD" = "autodetect"; then + AC_PATH_TOOL(THIN_REPAIR_CMD, thin_repair) + test -z "$THIN_REPAIR_CMD" && { + AC_MSG_WARN(thin_repair not found in path $PATH) + THIN_REPAIR_CMD=/usr/sbin/thin_repair + THIN_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore thin restoring + if test "$THIN_RESTORE_CMD" = "autodetect"; then + AC_PATH_TOOL(THIN_RESTORE_CMD, thin_restore) + test -z "$THIN_RESTORE_CMD" && { + AC_MSG_WARN(thin_restore not found in path $PATH) + THIN_RESTORE_CMD=/usr/sbin/thin_restore + THIN_CONFIGURE_WARN=y + } + fi + + AC_MSG_CHECKING([whether thin_check supports the needs-check flag]) + AC_MSG_RESULT([$THIN_CHECK_NEEDS_CHECK]) + if test "$THIN_CHECK_NEEDS_CHECK" = yes; then + AC_DEFINE([THIN_CHECK_NEEDS_CHECK], 1, [Define to 1 if the external 'thin_check' tool requires the --clear-needs-check-flag option]) + fi + + ;; +esac + +AC_DEFINE_UNQUOTED([THIN_CHECK_CMD], ["$THIN_CHECK_CMD"], + [The path to 'thin_check', if available.]) + +AC_DEFINE_UNQUOTED([THIN_DUMP_CMD], ["$THIN_DUMP_CMD"], + [The path to 'thin_dump', if available.]) + +AC_DEFINE_UNQUOTED([THIN_REPAIR_CMD], ["$THIN_REPAIR_CMD"], + [The path to 'thin_repair', if available.]) + +AC_DEFINE_UNQUOTED([THIN_RESTORE_CMD], ["$THIN_RESTORE_CMD"], + [The path to 'thin_restore', if available.]) + +################################################################################ +dnl -- cache inclusion type +AC_MSG_CHECKING(whether to include cache) +AC_ARG_WITH(cache, + AC_HELP_STRING([--with-cache=TYPE], + [cache support: internal/shared/none [internal]]), + CACHE=$withval, CACHE="internal") +AC_ARG_WITH(cache-check, + AC_HELP_STRING([--with-cache-check=PATH], + [cache_check tool: [autodetect]]), + CACHE_CHECK_CMD=$withval, CACHE_CHECK_CMD="autodetect") +AC_ARG_WITH(cache-dump, + AC_HELP_STRING([--with-cache-dump=PATH], + [cache_dump tool: [autodetect]]), + CACHE_DUMP_CMD=$withval, CACHE_DUMP_CMD="autodetect") +AC_ARG_WITH(cache-repair, + AC_HELP_STRING([--with-cache-repair=PATH], + [cache_repair tool: [autodetect]]), + CACHE_REPAIR_CMD=$withval, CACHE_REPAIR_CMD="autodetect") +AC_ARG_WITH(cache-restore, + AC_HELP_STRING([--with-cache-restore=PATH], + [cache_restore tool: [autodetect]]), + CACHE_RESTORE_CMD=$withval, CACHE_RESTORE_CMD="autodetect") +AC_MSG_RESULT($CACHE) + +case "$CACHE" in + none|shared) ;; + internal) AC_DEFINE([CACHE_INTERNAL], 1, [Define to 1 to include built-in support for cache.]) ;; + *) AC_MSG_ERROR([--with-cache parameter invalid]) ;; +esac + +dnl -- cache_check needs-check flag +AC_ARG_ENABLE(cache_check_needs_check, + AC_HELP_STRING([--disable-cache_check_needs_check], + [required if cache_check version is < 0.5]), + CACHE_CHECK_NEEDS_CHECK=$enableval, CACHE_CHECK_NEEDS_CHECK=yes) + +# Test if necessary cache tools are available +# if not - use plain defaults and warn user +case "$CACHE" in + internal|shared) + # Empty means a config way to ignore cache checking + if test "$CACHE_CHECK_CMD" = "autodetect"; then + AC_PATH_TOOL(CACHE_CHECK_CMD, cache_check) + if test -z "$CACHE_CHECK_CMD"; then + AC_MSG_WARN([cache_check not found in path $PATH]) + CACHE_CHECK_CMD=/usr/sbin/cache_check + CACHE_CONFIGURE_WARN=y + fi + fi + if test "$CACHE_CHECK_NEEDS_CHECK" = yes; then + $CACHE_CHECK_CMD -V 2>/dev/null >conftest.tmp + read -r CACHE_CHECK_VSN < conftest.tmp + IFS=.- read -r CACHE_CHECK_VSN_MAJOR CACHE_CHECK_VSN_MINOR CACHE_CHECK_VSN_PATCH LEFTOVER < conftest.tmp + rm -f conftest.tmp + + # Require version >= 0.5.4 for --clear-needs-check-flag + if test -z "$CACHE_CHECK_VSN_MAJOR" \ + || test -z "$CACHE_CHECK_VSN_MINOR" \ + || test -z "$CACHE_CHECK_VSN_PATCH"; then + AC_MSG_WARN([$CACHE_CHECK_CMD: Bad version "$CACHE_CHECK_VSN" found]) + CACHE_CHECK_VERSION_WARN=y + CACHE_CHECK_NEEDS_CHECK=no + elif test "$CACHE_CHECK_VSN_MAJOR" -eq 0 ; then + if test "$CACHE_CHECK_VSN_MINOR" -lt 5 \ + || test "$CACHE_CHECK_VSN_MINOR" -eq 5 -a "$CACHE_CHECK_VSN_PATCH" -lt 4; then + AC_MSG_WARN([$CACHE_CHECK_CMD: Old version "$CACHE_CHECK_VSN" found]) + CACHE_CHECK_VERSION_WARN=y + CACHE_CHECK_NEEDS_CHECK=no + fi + fi + fi + # Empty means a config way to ignore cache dumping + if test "$CACHE_DUMP_CMD" = "autodetect"; then + AC_PATH_TOOL(CACHE_DUMP_CMD, cache_dump) + test -z "$CACHE_DUMP_CMD" && { + AC_MSG_WARN(cache_dump not found in path $PATH) + CACHE_DUMP_CMD=/usr/sbin/cache_dump + CACHE_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore cache repairing + if test "$CACHE_REPAIR_CMD" = "autodetect"; then + AC_PATH_TOOL(CACHE_REPAIR_CMD, cache_repair) + test -z "$CACHE_REPAIR_CMD" && { + AC_MSG_WARN(cache_repair not found in path $PATH) + CACHE_REPAIR_CMD=/usr/sbin/cache_repair + CACHE_CONFIGURE_WARN=y + } + fi + # Empty means a config way to ignore cache restoring + if test "$CACHE_RESTORE_CMD" = "autodetect"; then + AC_PATH_TOOL(CACHE_RESTORE_CMD, cache_restore) + test -z "$CACHE_RESTORE_CMD" && { + AC_MSG_WARN(cache_restore not found in path $PATH) + CACHE_RESTORE_CMD=/usr/sbin/cache_restore + CACHE_CONFIGURE_WARN=y + } + fi + + AC_MSG_CHECKING([whether cache_check supports the needs-check flag]) + AC_MSG_RESULT([$CACHE_CHECK_NEEDS_CHECK]) + if test "$CACHE_CHECK_NEEDS_CHECK" = yes; then + AC_DEFINE([CACHE_CHECK_NEEDS_CHECK], 1, [Define to 1 if the external 'cache_check' tool requires the --clear-needs-check-flag option]) + fi + ;; +esac + +AC_DEFINE_UNQUOTED([CACHE_CHECK_CMD], ["$CACHE_CHECK_CMD"], + [The path to 'cache_check', if available.]) + +AC_DEFINE_UNQUOTED([CACHE_DUMP_CMD], ["$CACHE_DUMP_CMD"], + [The path to 'cache_dump', if available.]) + +AC_DEFINE_UNQUOTED([CACHE_REPAIR_CMD], ["$CACHE_REPAIR_CMD"], + [The path to 'cache_repair', if available.]) + +AC_DEFINE_UNQUOTED([CACHE_RESTORE_CMD], ["$CACHE_RESTORE_CMD"], + [The path to 'cache_restore', if available.]) + + +################################################################################ +dnl -- Disable readline +AC_MSG_CHECKING(whether to enable readline) +AC_ARG_ENABLE([readline], + AC_HELP_STRING([--disable-readline], [disable readline support]), + READLINE=$enableval, READLINE=maybe) +AC_MSG_RESULT($READLINE) + +################################################################################ +dnl -- Disable realtime clock support +AC_MSG_CHECKING(whether to enable realtime support) +AC_ARG_ENABLE(realtime, + AC_HELP_STRING([--disable-realtime], [disable realtime clock support]), + REALTIME=$enableval, REALTIME=yes) +AC_MSG_RESULT($REALTIME) + +################################################################################ +dnl -- disable OCF resource agents +AC_MSG_CHECKING(whether to enable OCF resource agents) +AC_ARG_ENABLE(ocf, + AC_HELP_STRING([--enable-ocf], + [enable Open Cluster Framework (OCF) compliant resource agents]), + OCF=$enableval, OCF=no) +AC_MSG_RESULT($OCF) +AC_ARG_WITH(ocfdir, + AC_HELP_STRING([--with-ocfdir=DIR], + [install OCF files in [PREFIX/lib/ocf/resource.d/lvm2]]), + OCFDIR=$withval, OCFDIR='${prefix}/lib/ocf/resource.d/lvm2') + +################################################################################ +dnl -- Init pkg-config with dummy invokation: +dnl -- this is required because PKG_CHECK_MODULES macro is expanded +dnl -- to initialize the pkg-config environment only at the first invokation, +dnl -- that would be conditional in this configure.in. +pkg_config_init() { + if test "$PKGCONFIG_INIT" != 1; then + PKG_CHECK_MODULES(PKGCONFIGINIT, pkgconfiginit, [], + [AC_MSG_RESULT([pkg-config initialized])]) + PKGCONFIG_INIT=1 + fi +} + +################################################################################ +AC_MSG_CHECKING(for default run directory) +RUN_DIR="/run" +test -d "/run" || RUN_DIR="/var/run" +AC_MSG_RESULT($RUN_DIR) +dnl -- Set up pidfile and run directory +AH_TEMPLATE(DEFAULT_PID_DIR) +AC_ARG_WITH(default-pid-dir, + AC_HELP_STRING([--with-default-pid-dir=PID_DIR], + [Default directory to keep PID files in. [autodetect]]), + DEFAULT_PID_DIR="$withval", DEFAULT_PID_DIR=$RUN_DIR) +AC_DEFINE_UNQUOTED(DEFAULT_PID_DIR, ["$DEFAULT_PID_DIR"], + [Default directory to keep PID files in.]) + +AH_TEMPLATE(DEFAULT_DM_RUN_DIR, [Name of default DM run directory.]) +AC_ARG_WITH(default-dm-run-dir, + AC_HELP_STRING([--with-default-dm-run-dir=DM_RUN_DIR], + [ Default DM run directory. [autodetect]]), + DEFAULT_DM_RUN_DIR="$withval", DEFAULT_DM_RUN_DIR=$RUN_DIR) +AC_DEFINE_UNQUOTED(DEFAULT_DM_RUN_DIR, ["$DEFAULT_DM_RUN_DIR"], + [Default DM run directory.]) + +AH_TEMPLATE(DEFAULT_RUN_DIR, [Name of default LVM run directory.]) +AC_ARG_WITH(default-run-dir, + AC_HELP_STRING([--with-default-run-dir=RUN_DIR], + [Default LVM run directory. [autodetect_run_dir/lvm]]), + DEFAULT_RUN_DIR="$withval", DEFAULT_RUN_DIR="$RUN_DIR/lvm") +AC_DEFINE_UNQUOTED(DEFAULT_RUN_DIR, ["$DEFAULT_RUN_DIR"], + [Default LVM run directory.]) + +################################################################################ +dnl -- Build cluster LVM daemon +AC_MSG_CHECKING(whether to build cluster LVM daemon) +AC_ARG_WITH(clvmd, + [ --with-clvmd=TYPE build cluster LVM Daemon + The following cluster manager combinations are valid: + * cman (RHEL5 or equivalent) + * cman,corosync,openais (or selection of them) + * singlenode (localhost only) + * all (autodetect) + * none (disable build) + [[none]]], + CLVMD=$withval, CLVMD=none) +test "$CLVMD" = yes && CLVMD=all +AC_MSG_RESULT($CLVMD) + +dnl -- If clvmd enabled without cluster locking, automagically include it +test "$CLVMD" != none -a "$CLUSTER" = none && CLUSTER=internal + +dnl -- init pkgconfig if required +test "$CLVMD" != none && pkg_config_init + +dnl -- Express clvmd init script Required-Start / Required-Stop +CLVMD_CMANAGERS="" +dnl -- On RHEL4/RHEL5, qdiskd is started from a separate init script. +dnl -- Enable if we are build for cman. +CLVMD_NEEDS_QDISKD=no + +dnl -- define build types +if [[ `expr x"$CLVMD" : '.*gulm.*'` != 0 ]]; then + AC_MSG_ERROR([Since version 2.02.87 GULM locking is no longer supported.]); +fi +if [[ `expr x"$CLVMD" : '.*cman.*'` != 0 ]]; then + BUILDCMAN=yes + CLVMD_CMANAGERS="$CLVMD_CMANAGERS cman" + CLVMD_NEEDS_QDISKD=yes +fi +if [[ `expr x"$CLVMD" : '.*corosync.*'` != 0 ]]; then + BUILDCOROSYNC=yes + CLVMD_CMANAGERS="$CLVMD_CMANAGERS corosync" +fi +if [[ `expr x"$CLVMD" : '.*openais.*'` != 0 ]]; then + BUILDOPENAIS=yes + CLVMD_CMANAGERS="$CLVMD_CMANAGERS openais" +fi +test "$CLVMD_NEEDS_QDISKD" != no && CLVMD_CMANAGERS="$CLVMD_CMANAGERS qdiskd" + +dnl -- define a soft bailout if we are autodetecting +soft_bailout() { + NOTFOUND=1 +} + +hard_bailout() { + AC_MSG_ERROR([bailing out]) +} + +dnl -- if clvmd=all then set soft_bailout (we do not want to error) +dnl -- and set all builds to yes. We need to do this here +dnl -- to skip the openais|corosync sanity check above. +if test "$CLVMD" = all; then + bailout=soft_bailout + BUILDCMAN=yes + BUILDCOROSYNC=yes + BUILDOPENAIS=yes +else + bailout=hard_bailout +fi + +dnl -- helper macro to check libs without adding them to LIBS +check_lib_no_libs() { + lib_no_libs_arg1=$1 + shift + lib_no_libs_arg2=$1 + shift + lib_no_libs_args=$@ + AC_CHECK_LIB([$lib_no_libs_arg1], + [$lib_no_libs_arg2],, + [$bailout], + [$lib_no_libs_args]) + LIBS=$ac_check_lib_save_LIBS +} + +dnl -- Look for cman libraries if required. +if test "$BUILDCMAN" = yes; then + PKG_CHECK_MODULES(CMAN, libcman, [HAVE_CMAN=yes], + [NOTFOUND=0 + AC_CHECK_HEADERS(libcman.h,,$bailout) + check_lib_no_libs cman cman_init + if test $NOTFOUND = 0; then + AC_MSG_RESULT([no pkg for libcman, using -lcman]) + CMAN_LIBS="-lcman" + HAVE_CMAN=yes + fi]) + CHECKCONFDB=yes + CHECKDLM=yes +fi + +dnl -- Look for corosync that is required also for openais build +dnl -- only enough recent version of corosync ship pkg-config files. +dnl -- We can safely rely on that to detect the correct bits. +if test "$BUILDCOROSYNC" = yes -o "$BUILDOPENAIS" = yes; then + PKG_CHECK_MODULES(COROSYNC, corosync, [HAVE_COROSYNC=yes], $bailout) + CHECKCONFDB=yes + CHECKCMAP=yes +fi + +dnl -- Look for corosync libraries if required. +if test "$BUILDCOROSYNC" = yes; then + PKG_CHECK_MODULES(QUORUM, libquorum, [HAVE_QUORUM=yes], $bailout) + CHECKCPG=yes + CHECKDLM=yes +fi + +dnl -- Look for openais libraries if required. +if test "$BUILDOPENAIS" = yes; then + PKG_CHECK_MODULES(SALCK, libSaLck, [HAVE_SALCK=yes], $bailout) + CHECKCPG=yes +fi + +dnl -- Below are checks for libraries common to more than one build. + +dnl -- Check confdb library. +dnl -- mandatory for corosync < 2.0 build. +dnl -- optional for openais/cman build. + +if test "$CHECKCONFDB" = yes; then + PKG_CHECK_MODULES(CONFDB, libconfdb, + [HAVE_CONFDB=yes], [HAVE_CONFDB=no]) + + AC_CHECK_HEADERS([corosync/confdb.h], + [HAVE_CONFDB_H=yes], [HAVE_CONFDB_H=no]) + + if test "$HAVE_CONFDB" != yes -a "$HAVE_CONFDB_H" = yes; then + check_lib_no_libs confdb confdb_initialize + AC_MSG_RESULT([no pkg for confdb, using -lconfdb]) + CONFDB_LIBS="-lconfdb" + HAVE_CONFDB=yes + fi +fi + +dnl -- Check cmap library +dnl -- mandatory for corosync >= 2.0 build. + +if test "$CHECKCMAP" = yes; then + PKG_CHECK_MODULES(CMAP, libcmap, + [HAVE_CMAP=yes], [HAVE_CMAP=no]) + + AC_CHECK_HEADERS([corosync/cmap.h], + [HAVE_CMAP_H=yes], [HAVE_CMAP_H=no]) + + if test "$HAVE_CMAP" != yes -a "$HAVE_CMAP_H" = yes; then + check_lib_no_libs cmap cmap_initialize + AC_MSG_RESULT([no pkg for cmap, using -lcmap]) + CMAP_LIBS="-lcmap" + HAVE_CMAP=yes + fi +fi + +if test "$BUILDCOROSYNC" = yes -a \ + "$HAVE_CMAP" != yes -a "$HAVE_CONFDB" != yes -a "$CLVMD" != all; then + AC_MSG_ERROR([bailing out... cmap (corosync >= 2.0) or confdb (corosync < 2.0) library is required]) +fi + +dnl -- Check cpg library. +if test "$CHECKCPG" = yes; then + PKG_CHECK_MODULES(CPG, libcpg, [HAVE_CPG=yes], [$bailout]) +fi + +dnl -- Check dlm library. +if test "$CHECKDLM" = yes; then + PKG_CHECK_MODULES(DLM, libdlm, [HAVE_DLM=yes], + [NOTFOUND=0 + AC_CHECK_HEADERS(libdlm.h,,[$bailout]) + check_lib_no_libs dlm dlm_lock -lpthread + if test $NOTFOUND = 0; then + AC_MSG_RESULT([no pkg for libdlm, using -ldlm]) + DLM_LIBS="-ldlm -lpthread" + HAVE_DLM=yes + fi]) +fi + +dnl -- If we are autodetecting, we need to re-create +dnl -- the depedencies checks and set a proper CLVMD, +dnl -- together with init script Required-Start/Stop entries. +if test "$CLVMD" = all; then + CLVMD=none + CLVMD_CMANAGERS="" + CLVMD_NEEDS_QDISKD=no + if test "$HAVE_CMAN" = yes -a \ + "$HAVE_DLM" = yes; then + AC_MSG_RESULT([Enabling clvmd cman cluster manager]) + CLVMD="$CLVMD,cman" + CLVMD_CMANAGERS="$CLVMD_CMANAGERS cman" + CLVMD_NEEDS_QDISKD=yes + fi + if test "$HAVE_COROSYNC" = yes -a \ + "$HAVE_QUORUM" = yes -a \ + "$HAVE_CPG" = yes -a \ + "$HAVE_DLM" = yes; then + if test "$HAVE_CONFDB" = yes -o "$HAVE_CMAP" = yes; then + AC_MSG_RESULT([Enabling clvmd corosync cluster manager]) + CLVMD="$CLVMD,corosync" + CLVMD_CMANAGERS="$CLVMD_CMANAGERS corosync" + fi + fi + if test "$HAVE_COROSYNC" = yes -a \ + "$HAVE_CPG" = yes -a \ + "$HAVE_SALCK" = yes; then + AC_MSG_RESULT([Enabling clvmd openais cluster manager]) + CLVMD="$CLVMD,openais" + CLVMD_CMANAGERS="$CLVMD_CMANAGERS openais" + fi + test "$CLVMD_NEEDS_QDISKD" != no && CLVMD_CMANAGERS="$CLVMD_CMANAGERS qdiskd" + test "$CLVMD" = none && AC_MSG_RESULT([Disabling clvmd build. No cluster manager detected.]) +fi + +dnl -- Fixup CLVMD_CMANAGERS with new corosync +dnl -- clvmd built with corosync >= 2.0 needs dlm (either init or systemd service) +dnl -- to be started. +if [[ `expr x"$CLVMD" : '.*corosync.*'` != 0 ]]; then + test "$HAVE_CMAP" = yes && CLVMD_CMANAGERS="$CLVMD_CMANAGERS dlm" +fi + +################################################################################ +dnl -- clvmd pidfile +if test "$CLVMD" != none; then + AC_ARG_WITH(clvmd-pidfile, + AC_HELP_STRING([--with-clvmd-pidfile=PATH], + [clvmd pidfile [PID_DIR/clvmd.pid]]), + CLVMD_PIDFILE=$withval, + CLVMD_PIDFILE="$DEFAULT_PID_DIR/clvmd.pid") + AC_DEFINE_UNQUOTED(CLVMD_PIDFILE, ["$CLVMD_PIDFILE"], + [Path to clvmd pidfile.]) +fi + +################################################################################ +dnl -- Build cluster mirror log daemon +AC_MSG_CHECKING(whether to build cluster mirror log daemon) +AC_ARG_ENABLE(cmirrord, + AC_HELP_STRING([--enable-cmirrord], + [enable the cluster mirror log daemon]), + CMIRRORD=$enableval, CMIRRORD=no) +AC_MSG_RESULT($CMIRRORD) + +BUILD_CMIRRORD=$CMIRRORD + +################################################################################ +dnl -- cmirrord pidfile +if test "$BUILD_CMIRRORD" = yes; then + AC_ARG_WITH(cmirrord-pidfile, + AC_HELP_STRING([--with-cmirrord-pidfile=PATH], + [cmirrord pidfile [PID_DIR/cmirrord.pid]]), + CMIRRORD_PIDFILE=$withval, + CMIRRORD_PIDFILE="$DEFAULT_PID_DIR/cmirrord.pid") + AC_DEFINE_UNQUOTED(CMIRRORD_PIDFILE, ["$CMIRRORD_PIDFILE"], + [Path to cmirrord pidfile.]) +fi + +################################################################################ +dnl -- Look for corosync libraries if required. +if [[ "$BUILD_CMIRRORD" = yes ]]; then + pkg_config_init + + AC_DEFINE([CMIRROR_HAS_CHECKPOINT], 1, [Define to 1 to include libSaCkpt.]) + PKG_CHECK_MODULES(SACKPT, libSaCkpt, [HAVE_SACKPT=yes], + [AC_MSG_RESULT([no libSaCkpt, compiling without it]) + AC_DEFINE([CMIRROR_HAS_CHECKPOINT], 0, [Define to 0 to exclude libSaCkpt.])]) + + if test "$HAVE_CPG" != yes; then + PKG_CHECK_MODULES(CPG, libcpg) + fi +fi + +################################################################################ +dnl -- Enable debugging +AC_MSG_CHECKING(whether to enable debugging) +AC_ARG_ENABLE(debug, AC_HELP_STRING([--enable-debug], [enable debugging]), + DEBUG=$enableval, DEBUG=no) +AC_MSG_RESULT($DEBUG) + +dnl -- Normally turn off optimisation for debug builds +if test "$DEBUG" = yes; then + COPTIMISE_FLAG= +else + CSCOPE_CMD= +fi + +dnl -- Check if compiler supports -Wjump-misses-init +AC_TRY_CCFLAG([-Wjump-misses-init], [HAVE_WJUMP], [], []) +AC_SUBST(HAVE_WJUMP) +AC_TRY_CCFLAG([-Wclobbered], [HAVE_WCLOBBERED], [], []) +AC_SUBST(HAVE_WCLOBBERED) +AC_TRY_CCFLAG([-Wsync-nand], [HAVE_WSYNCNAND], [], []) +AC_SUBST(HAVE_WSYNCNAND) + +################################################################################ +dnl -- Override optimisation +AC_MSG_CHECKING(for C optimisation flag) +AC_ARG_WITH(optimisation, + AC_HELP_STRING([--with-optimisation=OPT], + [C optimisation flag [OPT=-O2]]), + COPTIMISE_FLAG=$withval) +AC_MSG_RESULT($COPTIMISE_FLAG) + +################################################################################ +dnl -- Enable profiling +AC_MSG_CHECKING(whether to gather gcov profiling data) +AC_ARG_ENABLE(profiling, + AC_HELP_STRING([--enable-profiling], + [gather gcov profiling data]), + PROFILING=$enableval, PROFILING=no) +AC_MSG_RESULT($PROFILING) + +if test "$PROFILING" = yes; then + COPTIMISE_FLAG="$COPTIMISE_FLAG -fprofile-arcs -ftest-coverage" + AC_PATH_TOOL(LCOV, lcov) + AC_PATH_TOOL(GENHTML, genhtml) + test -z "$LCOV" -o -z "$GENHTML" && AC_MSG_ERROR([lcov and genhtml are required for profiling]) + AC_PATH_TOOL(GENPNG, genpng) + if test -n "$GENPNG"; then + AC_MSG_CHECKING([whether $GENPNG has all required modules]) + if "$GENPNG" --help > /dev/null 2>&1 ; then + AC_MSG_RESULT(ok) + GENHTML="$GENHTML --frames" + else + AC_MSG_RESULT([not supported]) + AC_MSG_WARN([GD.pm perl module is not installed]) + GENPNG= + fi + fi +fi + +################################################################################ +dnl -- Enable testing +AC_MSG_CHECKING(whether to enable unit testing) +AC_ARG_ENABLE(testing, + AC_HELP_STRING([--enable-testing], + [enable testing targets in the makefile]), + TESTING=$enableval, TESTING=no) +AC_MSG_RESULT($TESTING) + +if test "$TESTING" = yes; then + pkg_config_init + PKG_CHECK_MODULES(CUNIT, cunit >= 2.0) +fi + +################################################################################ +dnl -- Set LVM2 testsuite data +TESTSUITE_DATA='${datarootdir}/lvm2-testsuite' +# double eval needed ${datarootdir} -> ${prefix}/share -> real path +AC_DEFINE_UNQUOTED(TESTSUITE_DATA, ["$(eval echo $(eval echo $TESTSUITE_DATA))"], [Path to testsuite data]) + + +################################################################################ +dnl -- Enable valgrind awareness of memory pools +AC_MSG_CHECKING(whether to enable valgrind awareness of pools) +AC_ARG_ENABLE(valgrind_pool, + AC_HELP_STRING([--enable-valgrind-pool], + [enable valgrind awareness of pools]), + VALGRIND_POOL=$enableval, VALGRIND_POOL=no) +AC_MSG_RESULT($VALGRIND_POOL) + +pkg_config_init +PKG_CHECK_MODULES(VALGRIND, valgrind, [HAVE_VALGRIND=yes], [if test x$VALGRIND_POOL = xyes; then AC_MSG_ERROR(bailing out); fi]) +AC_SUBST(VALGRIND_CFLAGS) + +if test x$HAVE_VALGRIND = xyes; then + AC_DEFINE([HAVE_VALGRIND], 1, [valgrind.h found]) +fi + +if test x$VALGRIND_POOL = xyes; then + AC_DEFINE([VALGRIND_POOL], 1, [Enable a valgrind aware build of pool]) +fi + +################################################################################ +dnl -- Disable devmapper +AC_MSG_CHECKING(whether to use device-mapper) +AC_ARG_ENABLE(devmapper, + AC_HELP_STRING([--disable-devmapper], + [disable LVM2 device-mapper interaction]), + DEVMAPPER=$enableval) +AC_MSG_RESULT($DEVMAPPER) + +if test "$DEVMAPPER" = yes; then + AC_DEFINE([DEVMAPPER_SUPPORT], 1, [Define to 1 to enable LVM2 device-mapper interaction.]) +fi + +################################################################################ +dnl -- Build lvmetad +AC_MSG_CHECKING(whether to build LVMetaD) +AC_ARG_ENABLE(lvmetad, + AC_HELP_STRING([--enable-lvmetad], + [enable the LVM Metadata Daemon]), + LVMETAD=$enableval) +test -n "$LVMETAD" && BUILD_LVMETAD=$LVMETAD +AC_MSG_RESULT($BUILD_LVMETAD) + +################################################################################ +dnl -- Build lvmpolld +AC_MSG_CHECKING(whether to build lvmpolld) +AC_ARG_ENABLE(lvmpolld, + AC_HELP_STRING([--enable-lvmpolld], + [enable the LVM Polling Daemon]), + LVMPOLLD=$enableval) +test -n "$LVMPOLLD" && BUILD_LVMPOLLD=$LVMPOLLD +AC_MSG_RESULT($BUILD_LVMPOLLD) + +################################################################################ +BUILD_LVMLOCKD=no + +dnl -- Build lockdsanlock +AC_MSG_CHECKING(whether to build lockdsanlock) +AC_ARG_ENABLE(lockd-sanlock, + AC_HELP_STRING([--enable-lockd-sanlock], + [enable the LVM lock daemon using sanlock]), + LOCKDSANLOCK=$enableval) +AC_MSG_RESULT($LOCKDSANLOCK) + +BUILD_LOCKDSANLOCK=$LOCKDSANLOCK + +dnl -- Look for sanlock libraries +if test "$BUILD_LOCKDSANLOCK" = yes; then + PKG_CHECK_MODULES(LOCKD_SANLOCK, libsanlock_client >= 3.3.0, [HAVE_LOCKD_SANLOCK=yes], $bailout) + AC_DEFINE([LOCKDSANLOCK_SUPPORT], 1, [Define to 1 to include code that uses lvmlockd sanlock option.]) + BUILD_LVMLOCKD=yes +fi + +################################################################################ +dnl -- Build lockddlm +AC_MSG_CHECKING(whether to build lockddlm) +AC_ARG_ENABLE(lockd-dlm, + AC_HELP_STRING([--enable-lockd-dlm], + [enable the LVM lock daemon using dlm]), + LOCKDDLM=$enableval) +AC_MSG_RESULT($LOCKDDLM) + +BUILD_LOCKDDLM=$LOCKDDLM + +dnl -- Look for dlm libraries +if test "$BUILD_LOCKDDLM" = yes; then + PKG_CHECK_MODULES(LOCKD_DLM, libdlm, [HAVE_LOCKD_DLM=yes], $bailout) + AC_DEFINE([LOCKDDLM_SUPPORT], 1, [Define to 1 to include code that uses lvmlockd dlm option.]) + BUILD_LVMLOCKD=yes +fi + +################################################################################ +dnl -- Build lvmlockd +AC_MSG_CHECKING(whether to build lvmlockd) +AC_MSG_RESULT($BUILD_LVMLOCKD) + +if test "$BUILD_LVMLOCKD" = yes; then + AS_IF([test "$LVMPOLLD" = no], [AC_MSG_ERROR([cannot build lvmlockd with --disable-lvmpolld.])]) + AS_IF([test "$LVMETAD" = no], [AC_MSG_ERROR([cannot build lvmlockd with --disable-lvmetad.])]) + AS_IF([test "$BUILD_LVMPOLLD" = no], [BUILD_LVMPOLLD=yes; AC_MSG_WARN([Enabling lvmpolld - required by lvmlockd.])]) + AS_IF([test "$BUILD_LVMETAD" = no], [BUILD_LVMETAD=yes; AC_MSG_WARN([Enabling lvmetad - required by lvmlockd.])]) + AC_MSG_CHECKING([defaults for use_lvmlockd]) + AC_ARG_ENABLE(use_lvmlockd, + AC_HELP_STRING([--disable-use-lvmlockd], + [disable usage of LVM lock daemon]), + [case ${enableval} in + yes) DEFAULT_USE_LVMLOCKD=1 ;; + *) DEFAULT_USE_LVMLOCKD=0 ;; + esac], DEFAULT_USE_LVMLOCKD=1) + AC_MSG_RESULT($DEFAULT_USE_LVMLOCKD) + AC_DEFINE([LVMLOCKD_SUPPORT], 1, [Define to 1 to include code that uses lvmlockd.]) + + AC_ARG_WITH(lvmlockd-pidfile, + AC_HELP_STRING([--with-lvmlockd-pidfile=PATH], + [lvmlockd pidfile [PID_DIR/lvmlockd.pid]]), + LVMLOCKD_PIDFILE=$withval, + LVMLOCKD_PIDFILE="$DEFAULT_PID_DIR/lvmlockd.pid") + AC_DEFINE_UNQUOTED(LVMLOCKD_PIDFILE, ["$LVMLOCKD_PIDFILE"], + [Path to lvmlockd pidfile.]) +else + DEFAULT_USE_LVMLOCKD=0 +fi +AC_DEFINE_UNQUOTED(DEFAULT_USE_LVMLOCKD, [$DEFAULT_USE_LVMLOCKD], + [Use lvmlockd by default.]) + +################################################################################ +dnl -- Check lvmetad +if test "$BUILD_LVMETAD" = yes; then + AC_MSG_CHECKING([defaults for use_lvmetad]) + AC_ARG_ENABLE(use_lvmetad, + AC_HELP_STRING([--disable-use-lvmetad], + [disable usage of LVM Metadata Daemon]), + [case ${enableval} in + yes) DEFAULT_USE_LVMETAD=1 ;; + *) DEFAULT_USE_LVMETAD=0 ;; + esac], DEFAULT_USE_LVMETAD=1) + AC_MSG_RESULT($DEFAULT_USE_LVMETAD) + AC_DEFINE([LVMETAD_SUPPORT], 1, [Define to 1 to include code that uses lvmetad.]) + + AC_ARG_WITH(lvmetad-pidfile, + AC_HELP_STRING([--with-lvmetad-pidfile=PATH], + [lvmetad pidfile [PID_DIR/lvmetad.pid]]), + LVMETAD_PIDFILE=$withval, + LVMETAD_PIDFILE="$DEFAULT_PID_DIR/lvmetad.pid") + AC_DEFINE_UNQUOTED(LVMETAD_PIDFILE, ["$LVMETAD_PIDFILE"], + [Path to lvmetad pidfile.]) +else + DEFAULT_USE_LVMETAD=0 +fi +AC_DEFINE_UNQUOTED(DEFAULT_USE_LVMETAD, [$DEFAULT_USE_LVMETAD], + [Use lvmetad by default.]) + +################################################################################ +dnl -- Check lvmpolld +if test "$BUILD_LVMPOLLD" = yes; then + AC_MSG_CHECKING([defaults for use_lvmpolld]) + AC_ARG_ENABLE(use_lvmpolld, + AC_HELP_STRING([--disable-use-lvmpolld], + [disable usage of LVM Poll Daemon]), + [case ${enableval} in + yes) DEFAULT_USE_LVMPOLLD=1 ;; + *) DEFAULT_USE_LVMPOLLD=0 ;; + esac], DEFAULT_USE_LVMPOLLD=1) + AC_MSG_RESULT($DEFAULT_USE_LVMPOLLD) + AC_DEFINE([LVMPOLLD_SUPPORT], 1, [Define to 1 to include code that uses lvmpolld.]) + + AC_ARG_WITH(lvmpolld-pidfile, + AC_HELP_STRING([--with-lvmpolld-pidfile=PATH], + [lvmpolld pidfile [PID_DIR/lvmpolld.pid]]), + LVMPOLLD_PIDFILE=$withval, + LVMPOLLD_PIDFILE="$DEFAULT_PID_DIR/lvmpolld.pid") + AC_DEFINE_UNQUOTED(LVMPOLLD_PIDFILE, ["$LVMPOLLD_PIDFILE"], + [Path to lvmpolld pidfile.]) +else + DEFAULT_USE_LVMPOLLD=0 +fi +AC_DEFINE_UNQUOTED(DEFAULT_USE_LVMPOLLD, [$DEFAULT_USE_LVMPOLLD], + [Use lvmpolld by default.]) + +################################################################################ +dnl -- Build notifydbus +AC_MSG_CHECKING(whether to build notifydbus) +AC_ARG_ENABLE(notify-dbus, + AC_HELP_STRING([--enable-notify-dbus], + [enable LVM notification using dbus]), + NOTIFYDBUS=$enableval) +AC_MSG_RESULT($NOTIFYDBUS) + +BUILD_NOTIFYDBUS=$NOTIFYDBUS + +if test "$BUILD_NOTIFYDBUS" = yes; then + AC_DEFINE([NOTIFYDBUS_SUPPORT], 1, [Define to 1 to include code that uses dbus notification.]) + LIBS="-lsystemd $LIBS" +fi + +################################################################################ +dnl -- Look for dbus libraries +if test "$BUILD_NOTIFYDBUS" = yes; then + PKG_CHECK_MODULES(NOTIFY_DBUS, systemd >= 221, [HAVE_NOTIFY_DBUS=yes], $bailout) +fi + +################################################################################ + +dnl -- Enable blkid wiping functionality +AC_MSG_CHECKING(whether to enable libblkid detection of signatures when wiping) +AC_ARG_ENABLE(blkid_wiping, + AC_HELP_STRING([--disable-blkid_wiping], + [disable libblkid detection of signatures when wiping and use native code instead]), + BLKID_WIPING=$enableval, BLKID_WIPING=maybe) +AC_MSG_RESULT($BLKID_WIPING) + +if test "$BLKID_WIPING" != no; then + pkg_config_init + PKG_CHECK_MODULES(BLKID, blkid >= 2.24, + [test "$BLKID_WIPING" = maybe && BLKID_WIPING=yes], + [if test "$BLKID_WIPING" = maybe; then + BLKID_WIPING=no + else + AC_MSG_ERROR([bailing out... blkid library >= 2.24 is required]) + fi]) + if test "$BLKID_WIPING" = yes; then + BLKID_PC="blkid" + DEFAULT_USE_BLKID_WIPING=1 + AC_DEFINE([BLKID_WIPING_SUPPORT], 1, [Define to 1 to use libblkid detection of signatures when wiping.]) + else + DEFAULT_USE_BLKID_WIPING=0 + fi +else + DEFAULT_USE_BLKID_WIPING=0 +fi +AC_DEFINE_UNQUOTED(DEFAULT_USE_BLKID_WIPING, [$DEFAULT_USE_BLKID_WIPING], + [Use blkid wiping by default.]) + +################################################################################ +dnl -- Enable udev-systemd protocol to instantiate a service for background jobs +dnl -- Requires systemd version 205 at least (including support for systemd-run) +AC_MSG_CHECKING(whether to use udev-systemd protocol for jobs in background) +AC_ARG_ENABLE(udev-systemd-background-jobs, + AC_HELP_STRING([--disable-udev-systemd-background-jobs], + [disable udev-systemd protocol to instantiate a service for background job]), + UDEV_SYSTEMD_BACKGROUND_JOBS=$enableval, + UDEV_SYSTEMD_BACKGROUND_JOBS=maybe) +AC_MSG_RESULT($UDEV_SYSTEMD_BACKGROUND_JOBS) + +if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" != no; then + pkg_config_init + PKG_CHECK_MODULES(SYSTEMD, systemd >= 205, + [test "$UDEV_SYSTEMD_BACKGROUND_JOBS" = maybe && UDEV_SYSTEMD_BACKGROUND_JOBS=yes], + [if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" = maybe; then + UDEV_SYSTEMD_BACKGROUND_JOBS=no + else + AC_MSG_ERROR([bailing out... systemd >= 205 is required]) + fi]) +fi + +################################################################################ +dnl -- Enable udev synchronisation +AC_MSG_CHECKING(whether to enable synchronisation with udev processing) +AC_ARG_ENABLE(udev_sync, + AC_HELP_STRING([--enable-udev_sync], + [enable synchronisation with udev processing]), + UDEV_SYNC=$enableval, UDEV_SYNC=no) +AC_MSG_RESULT($UDEV_SYNC) + +if test "$UDEV_SYNC" = yes; then + pkg_config_init + PKG_CHECK_MODULES(UDEV, libudev >= 143, [UDEV_PC="libudev"]) + AC_DEFINE([UDEV_SYNC_SUPPORT], 1, [Define to 1 to enable synchronisation with udev processing.]) + + AC_CHECK_LIB(udev, udev_device_get_is_initialized, AC_DEFINE([HAVE_LIBUDEV_UDEV_DEVICE_GET_IS_INITIALIZED], 1, + [Define to 1 if udev_device_get_is_initialized is available.])) + LIBS=$ac_check_lib_save_LIBS +fi + +dnl -- Enable udev rules +AC_MSG_CHECKING(whether to enable installation of udev rules required for synchronisation) +AC_ARG_ENABLE(udev_rules, + AC_HELP_STRING([--enable-udev_rules], + [install rule files needed for udev synchronisation]), + UDEV_RULES=$enableval, UDEV_RULES=$UDEV_SYNC) +AC_MSG_RESULT($UDEV_RULES) + +AC_MSG_CHECKING(whether to enable executable path detection in udev rules) +AC_ARG_ENABLE(udev_rule_exec_detection, + AC_HELP_STRING([--enable-udev-rule-exec-detection], + [enable executable path detection in udev rules]), + UDEV_RULE_EXEC_DETECTION=$enableval, UDEV_RULE_EXEC_DETECTION=no) +AC_MSG_RESULT($UDEV_RULE_EXEC_DETECTION) + +dnl -- Check support for built-in blkid against target udev version +if test "$UDEV_RULE" != no ; then + AC_MSG_CHECKING(whether udev supports built-in blkid) + pkg_config_init + if $("$PKG_CONFIG" --atleast-version=176 libudev); then + UDEV_HAS_BUILTIN_BLKID=yes + else + UDEV_HAS_BUILTIN_BLKID=no + fi + AC_MSG_RESULT($UDEV_HAS_BUILTIN_BLKID) +fi + +################################################################################ +dnl -- Compatibility mode +AC_ARG_ENABLE(compat, + AC_HELP_STRING([--enable-compat], + [enable support for old device-mapper versions]), + DM_COMPAT=$enableval, DM_COMPAT=no) + +AS_IF([test "$DM_COMPAT" = yes], + [AC_DEFINE([DM_COMPAT], 1, [Define to enable compat protocol]) + AC_MSG_ERROR([--enable-compat is not currently supported. +Since device-mapper version 1.02.66, only one version (4) of the device-mapper +ioctl protocol is supported.])]) + +################################################################################ +dnl -- Compatible units suffix mode +AC_ARG_ENABLE(units-compat, + AC_HELP_STRING([--enable-units-compat], + [enable output compatibility with old versions that + that do not use KiB-style unit suffixes]), + UNITS_COMPAT=$enableval, UNITS_COMPAT=no) + +if test "$UNITS_COMPAT" = yes; then + AC_DEFINE([DEFAULT_SI_UNIT_CONSISTENCY], 0, [Define to 0 to reinstate the pre-2.02.54 handling of unit suffixes.]) +fi + +################################################################################ +dnl -- Disable ioctl +AC_ARG_ENABLE(ioctl, + AC_HELP_STRING([--disable-ioctl], + [disable ioctl calls to device-mapper in the kernel]), + DM_IOCTLS=$enableval) +AS_IF([test "$DM_IOCTLS" = yes], + [AC_DEFINE([DM_IOCTLS], 1, [Define to enable ioctls calls to kernel])]) + +################################################################################ +dnl -- Disable O_DIRECT +AC_MSG_CHECKING(whether to enable O_DIRECT) +AC_ARG_ENABLE(o_direct, + AC_HELP_STRING([--disable-o_direct], [disable O_DIRECT]), + ODIRECT=$enableval) +AC_MSG_RESULT($ODIRECT) + +if test "$ODIRECT" = yes; then + AC_DEFINE([O_DIRECT_SUPPORT], 1, [Define to 1 to enable O_DIRECT support.]) +fi + +################################################################################ +dnl -- Enable liblvm2app.so +AC_MSG_CHECKING(whether to build liblvm2app.so application library) +AC_ARG_ENABLE(applib, + AC_HELP_STRING([--enable-applib], [build application library]), + APPLIB=$enableval, APPLIB=no) +AC_MSG_RESULT($APPLIB) +AC_SUBST([LVM2APP_LIB]) +test "$APPLIB" = yes \ + && LVM2APP_LIB=-llvm2app \ + || LVM2APP_LIB= + +################################################################################ +dnl -- Enable cmdlib +AC_MSG_CHECKING(whether to compile liblvm2cmd.so) +AC_ARG_ENABLE(cmdlib, + AC_HELP_STRING([--enable-cmdlib], [build shared command library]), + CMDLIB=$enableval, CMDLIB=no) +AC_MSG_RESULT($CMDLIB) +AC_SUBST([LVM2CMD_LIB]) +test "$CMDLIB" = yes \ + && LVM2CMD_LIB=-llvm2cmd \ + || LVM2CMD_LIB= + +################################################################################ +dnl -- Enable D-Bus service +AC_MSG_CHECKING(whether to include Python D-Bus support) +AC_ARG_ENABLE(dbus-service, + AC_HELP_STRING([--enable-dbus-service], [install D-Bus support]), + BUILD_LVMDBUSD=$enableval, BUILD_LVMDBUSD=no) +AC_MSG_RESULT($BUILD_LVMDBUSD) + +################################################################################ +dnl -- Enable Python liblvm2app bindings +AC_MSG_CHECKING(whether to build Python wrapper for liblvm2app.so) +AC_ARG_ENABLE(python_bindings, + AC_HELP_STRING([--enable-python_bindings], [build default Python applib bindings]), + PYTHON_BINDINGS=$enableval, PYTHON_BINDINGS=no) +AC_MSG_RESULT($PYTHON_BINDINGS) + +AC_MSG_CHECKING(whether to build Python2 wrapper for liblvm2app.so) +AC_ARG_ENABLE(python2_bindings, + AC_HELP_STRING([--enable-python2_bindings], [build Python2 applib bindings]), + PYTHON2_BINDINGS=$enableval, PYTHON2_BINDINGS=no) +AC_MSG_RESULT($PYTHON2_BINDINGS) + + +AC_MSG_CHECKING(whether to build Python3 wrapper for liblvm2app.so) +AC_ARG_ENABLE(python3_bindings, + AC_HELP_STRING([--enable-python3_bindings], [build Python3 applib bindings]), + PYTHON3_BINDINGS=$enableval, PYTHON3_BINDINGS=no) +AC_MSG_RESULT($PYTHON3_BINDINGS) + +if test "$PYTHON_BINDINGS" = yes; then + AC_MSG_ERROR([--enable-python-bindings is replaced by --enable-python2-bindings and --enable-python3-bindings]) +fi + +if test "$PYTHON2_BINDINGS" = yes; then + AM_PATH_PYTHON([2]) + AC_PATH_TOOL(PYTHON2, python2) + test -z "$PYTHON2" && AC_MSG_ERROR([python2 is required for --enable-python2_bindings but cannot be found]) + AC_PATH_TOOL(PYTHON2_CONFIG, python2-config) + test -z "$PYTHON2_CONFIG" && AC_PATH_TOOL(PYTHON2_CONFIG, python-config) + test -z "$PYTHON2_CONFIG" && AC_MSG_ERROR([python headers are required for --enable-python2_bindings but cannot be found]) + PYTHON2_INCDIRS=`"$PYTHON2_CONFIG" --includes` + PYTHON2_LIBDIRS=`"$PYTHON2_CONFIG" --libs` + PYTHON2DIR=$pythondir + PYTHON_BINDINGS=yes +fi + +if test "$PYTHON3_BINDINGS" = yes -o "$BUILD_LVMDBUSD" = yes; then + unset PYTHON PYTHON_CONFIG + unset am_cv_pathless_PYTHON ac_cv_path_PYTHON am_cv_python_platform + unset am_cv_python_pythondir am_cv_python_version am_cv_python_pyexecdir + unset ac_cv_path_PYTHON_CONFIG ac_cv_path_ac_pt_PYTHON_CONFIG + AM_PATH_PYTHON([3]) + PYTHON3=$PYTHON + test -z "$PYTHON3" && AC_MSG_ERROR([python3 is required for --enable-python3_bindings or --enable-dbus-service but cannot be found]) + AC_PATH_TOOL(PYTHON3_CONFIG, python3-config) + test -z "$PYTHON3_CONFIG" && AC_MSG_ERROR([python3 headers are required for --enable-python3_bindings or --enable-dbus-service but cannot be found]) + PYTHON3_INCDIRS=`"$PYTHON3_CONFIG" --includes` + PYTHON3_LIBDIRS=`"$PYTHON3_CONFIG" --libs` + PYTHON3DIR=$pythondir + PYTHON_BINDINGS=yes +fi + +if test "$BUILD_LVMDBUSD" = yes; then + # To get this macro, install autoconf-archive package then run autoreconf + AC_PYTHON_MODULE([pyudev], [Required], python3) + AC_PYTHON_MODULE([dbus], [Required], python3) +fi + +if test "$PYTHON_BINDINGS" = yes -o "$PYTHON2_BINDINGS" = yes -o "$PYTHON3_BINDINGS" = yes; then + test "$APPLIB" != yes && AC_MSG_ERROR([Python_bindings require --enable-applib]) +fi + +################################################################################ +dnl -- Enable pkg-config +AC_ARG_ENABLE(pkgconfig, + AC_HELP_STRING([--enable-pkgconfig], [install pkgconfig support]), + PKGCONFIG=$enableval, PKGCONFIG=no) + +################################################################################ +dnl -- Enable installation of writable files by user +AC_ARG_ENABLE(write_install, + AC_HELP_STRING([--enable-write_install], + [install user writable files]), + WRITE_INSTALL=$enableval, WRITE_INSTALL=no) + +################################################################################ +dnl -- Enable fsadm +AC_MSG_CHECKING(whether to install fsadm) +AC_ARG_ENABLE(fsadm, AC_HELP_STRING([--disable-fsadm], [disable fsadm]), + FSADM=$enableval) +AC_MSG_RESULT($FSADM) + +################################################################################ +dnl -- Enable blkdeactivate +AC_MSG_CHECKING(whether to install blkdeactivate) +AC_ARG_ENABLE(blkdeactivate, AC_HELP_STRING([--disable-blkdeactivate], [disable blkdeactivate]), + BLKDEACTIVATE=$enableval) +AC_MSG_RESULT($BLKDEACTIVATE) + +################################################################################ +dnl -- enable dmeventd handling +AC_MSG_CHECKING(whether to use dmeventd) +AC_ARG_ENABLE(dmeventd, AC_HELP_STRING([--enable-dmeventd], + [enable the device-mapper event daemon]), + DMEVENTD=$enableval) +AC_MSG_RESULT($DMEVENTD) + +BUILD_DMEVENTD=$DMEVENTD + +dnl -- dmeventd currently requires internal mirror support +if test "$DMEVENTD" = yes; then + if test "$MIRRORS" != internal; then + AC_MSG_ERROR([--enable-dmeventd currently requires --with-mirrors=internal]) + fi + if test "$CMDLIB" = no; then + AC_MSG_ERROR([--enable-dmeventd requires --enable-cmdlib to be used as well]) + fi + + AC_DEFINE([DMEVENTD], 1, [Define to 1 to enable the device-mapper event daemon.]) +fi + +################################################################################ +dnl -- getline included in recent libc + +AC_CHECK_LIB(c, getline, AC_DEFINE([HAVE_GETLINE], 1, + [Define to 1 if getline is available.])) + +################################################################################ +dnl -- canonicalize_file_name included in recent libc + +AC_CHECK_LIB(c, canonicalize_file_name, + AC_DEFINE([HAVE_CANONICALIZE_FILE_NAME], 1, + [Define to 1 if canonicalize_file_name is available.])) + +################################################################################ +dnl -- Clear default exec_prefix - install into /sbin rather than /usr/sbin +test "$exec_prefix" = NONE -a "$prefix" = NONE && exec_prefix="" + +################################################################################ +dnl -- Check for dlopen +AC_CHECK_LIB(dl, dlopen, + [AC_DEFINE([HAVE_LIBDL], 1, [Define to 1 if dynamic libraries are available.]) + DL_LIBS="-ldl" + HAVE_LIBDL=yes], + [DL_LIBS= + HAVE_LIBDL=no ]) + +################################################################################ +dnl -- Check for shared/static conflicts +if [[ \( "$LVM1" = shared -o "$POOL" = shared -o "$CLUSTER" = shared \ + -o "$SNAPSHOTS" = shared -o "$MIRRORS" = shared \ + -o "$RAID" = shared -o "$CACHE" = shared \ + \) -a "$STATIC_LINK" = yes ]]; then + AC_MSG_ERROR([Features cannot be 'shared' when building statically]) +fi + +################################################################################ +AC_CHECK_LIB(m, log10, + [M_LIBS="-lm"], hard_bailout) + +################################################################################ +AC_CHECK_LIB([pthread], [pthread_mutex_lock], + [PTHREAD_LIBS="-lpthread"], hard_bailout) + +################################################################################ +dnl -- Disable selinux +AC_MSG_CHECKING(whether to enable selinux support) +AC_ARG_ENABLE(selinux, + AC_HELP_STRING([--disable-selinux], [disable selinux support]), + SELINUX=$enableval) +AC_MSG_RESULT($SELINUX) + +################################################################################ +dnl -- Check for selinux +if test "$SELINUX" = yes; then + AC_CHECK_LIB([sepol], [sepol_check_context], [ + AC_DEFINE([HAVE_SEPOL], 1, [Define to 1 if sepol_check_context is available.]) + SELINUX_LIBS="-lsepol"]) + + AC_CHECK_LIB([selinux], [is_selinux_enabled], [ + AC_CHECK_HEADERS([selinux/selinux.h],, hard_bailout) + AC_CHECK_HEADERS([selinux/label.h]) + AC_DEFINE([HAVE_SELINUX], 1, [Define to 1 to include support for selinux.]) + SELINUX_LIBS="-lselinux $SELINUX_LIBS" + SELINUX_PC="libselinux" + HAVE_SELINUX=yes ], [ + AC_MSG_WARN(Disabling selinux) + SELINUX_LIBS= + SELINUX_PC= + HAVE_SELINUX=no ]) +fi + +################################################################################ +dnl -- Check for realtime clock support +if test "$REALTIME" = yes; then + AC_CHECK_LIB(rt, clock_gettime, HAVE_REALTIME=yes, HAVE_REALTIME=no) + + if test "$HAVE_REALTIME" = yes; then + AC_DEFINE([HAVE_REALTIME], 1, [Define to 1 to include support for realtime clock.]) + LIBS="-lrt $LIBS" + RT_LIB="-lrt" + else + AC_MSG_WARN(Disabling realtime clock) + fi +fi + +dnl Check if the system has struct stat st_ctim. +AC_CACHE_CHECK([for struct stat has st_ctim.], + [ac_cv_stat_st_ctim], + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM( +[#include <sys/stat.h> +long bar(void) { struct stat s; return (long)(s.st_ctim.tv_sec + s.st_ctim.tv_nsec);}] + )], [ac_cv_stat_st_ctim=yes], [ac_cv_stat_st_ctim=no])]) + +AC_IF_YES(ac_cv_stat_st_ctim, + AC_DEFINE(HAVE_STAT_ST_CTIM, 1, + [Define if struct stat has a field st_ctim with timespec for ctime])) + +################################################################################ +dnl -- Check for getopt +AC_CHECK_HEADERS(getopt.h, AC_DEFINE([HAVE_GETOPTLONG], 1, [Define to 1 if getopt_long is available.])) + +################################################################################ +dnl -- Check for readline (Shamelessly copied from parted 1.4.17) +if test "$READLINE" != no; then + lvm_saved_libs=$LIBS + AC_SEARCH_LIBS([tgetent], [tinfo ncurses curses termcap termlib], + READLINE_LIBS=$ac_cv_search_tgetent, [ + if test "$READLINE" = yes; then + AC_MSG_ERROR( +[termcap could not be found which is required for the +--enable-readline option (which is enabled by default). Either disable readline +support with --disable-readline or download and install termcap from: + ftp.gnu.org/gnu/termcap +Note: if you are using precompiled packages you will also need the development + package as well (which may be called termcap-devel or something similar). +Note: (n)curses also seems to work as a substitute for termcap. This was + not found either - but you could try installing that as well.]) + fi]) + dnl -- Old systems may need extra termcap dependency explicitly in LIBS + AC_CHECK_LIB([readline], [readline], [ + AC_DEFINE([READLINE_SUPPORT], 1, + [Define to 1 to include the LVM readline shell.]) + dnl -- Try only with -lreadline and check for different symbol + LIBS=$lvm_saved_libs + AC_CHECK_LIB([readline], [rl_line_buffer], + [ READLINE_LIBS="-lreadline" ], [ + AC_MSG_RESULT([linking -lreadline with $READLINE_LIBS needed]) + READLINE_LIBS="-lreadline $READLINE_LIBS" + ]) ], [ + READLINE_LIBS= + if test "$READLINE" = yes; then + AC_MSG_ERROR( +[GNU Readline could not be found which is required for the +--enable-readline option (which is enabled by default). Either disable readline +support with --disable-readline or download and install readline from: + ftp.gnu.org/gnu/readline +Note: if you are using precompiled packages you will also need the development +package as well (which may be called readline-devel or something similar).]) + fi ]) + LIBS="$READLINE_LIBS $lvm_saved_libs" + AC_CHECK_FUNCS([rl_completion_matches]) + LIBS=$lvm_saved_libs +fi + +################################################################################ +dnl -- Internationalisation stuff +AC_MSG_CHECKING(whether to enable internationalisation) +AC_ARG_ENABLE(nls, + AC_HELP_STRING([--enable-nls], [enable Native Language Support]), + INTL=$enableval, INTL=no) +AC_MSG_RESULT($INTL) + +if test "$INTL" = yes; then +# FIXME - Move this - can be device-mapper too + INTL_PACKAGE="lvm2" + AC_PATH_TOOL(MSGFMT, msgfmt) + + AS_IF([test -z "$MSGFMT"], [AC_MSG_ERROR([msgfmt not found in path $PATH])]) + + AC_ARG_WITH(localedir, + AC_HELP_STRING([--with-localedir=DIR], + [locale-dependent data [DATAROOTDIR/locale]]), + localedir=$withval, localedir=${localedir-'${datarootdir}/locale'}) + AC_DEFINE_UNQUOTED([INTL_PACKAGE], ["$INTL_PACKAGE"], [Internalization package]) + # double eval needed ${datarootdir} -> ${prefix}/share -> real path + AC_DEFINE_UNQUOTED([LOCALEDIR], ["$(eval echo $(eval echo $localedir))"], [Locale-dependent data]) +fi + +################################################################################ +dnl -- FIXME: need to switch to regular option here --sysconfdir +AC_ARG_WITH(confdir, + AC_HELP_STRING([--with-confdir=DIR], + [configuration files in DIR [/etc]]), + CONFDIR=$withval, CONFDIR='/etc') +AC_DEFINE_UNQUOTED(DEFAULT_ETC_DIR, ["$CONFDIR"], + [Default system configuration directory.]) + +AC_ARG_WITH(staticdir, + AC_HELP_STRING([--with-staticdir=DIR], + [static binaries in DIR [EPREFIX/sbin]]), + STATICDIR=$withval, STATICDIR='${exec_prefix}/sbin') + +AC_ARG_WITH(usrlibdir, + AC_HELP_STRING([--with-usrlibdir=DIR], + [usrlib in DIR [PREFIX/lib]]), + usrlibdir=$withval, usrlibdir='${prefix}/lib') + +AC_ARG_WITH(usrsbindir, + AC_HELP_STRING([--with-usrsbindir=DIR], + [usrsbin executables in DIR [PREFIX/sbin]]), + usrsbindir=$withval, usrsbindir='${prefix}/sbin') + +################################################################################ +AC_ARG_WITH(udev_prefix, + AC_HELP_STRING([--with-udev-prefix=UPREFIX], + [install udev rule files in UPREFIX [EPREFIX]]), + udev_prefix=$withval, udev_prefix='${exec_prefix}') + +AC_ARG_WITH(udevdir, + AC_HELP_STRING([--with-udevdir=DIR], + [udev rules in DIR [UPREFIX/lib/udev/rules.d]]), + udevdir=$withval, udevdir='${udev_prefix}/lib/udev/rules.d') + +################################################################################ +dnl -- Get the systemd system unit dir value from pkg_config automatically if value not given explicitly. +dnl -- This follows the recommendation for systemd integration best practices mentioned in daemon(7) manpage. +AC_ARG_WITH(systemdsystemunitdir, + AC_HELP_STRING([--with-systemdsystemunitdir=DIR], + [systemd service files in DIR]), + systemdsystemunitdir=$withval, + pkg_config_init + pkg_systemdsystemunitdir=$("$PKG_CONFIG" --variable=systemdsystemunitdir systemd)) + +test -n "$pkg_systemdsystemunitdir" && systemdsystemunitdir=$pkg_systemdsystemunitdir +test -z "$systemdsystemunitdir" && systemdsystemunitdir='${exec_prefix}/lib/systemd/system'; + +systemdutildir=$("$PKG_CONFIG" --variable=systemdutildir systemd) +test -z "$systemdutildir" && systemdutildir='${exec_prefix}/lib/systemd'; + +################################################################################ +AC_ARG_WITH(tmpfilesdir, + AC_HELP_STRING([--with-tmpfilesdir=DIR], + [install configuration files for management of volatile files and directories in DIR [PREFIX/lib/tmpfiles.d]]), + tmpfilesdir=$withval, tmpfilesdir='${prefix}/lib/tmpfiles.d') +################################################################################ +dnl -- Ensure additional headers required +if test "$READLINE" = yes; then + AC_CHECK_HEADERS(readline/readline.h readline/history.h,,hard_bailout) +fi + +if test "$BUILD_CMIRRORD" = yes; then + AC_CHECK_FUNCS(atexit,,hard_bailout) +fi + +if test "$BUILD_LVMLOCKD" = yes; then + AC_CHECK_FUNCS(clock_gettime strtoull,,hard_bailout) +fi + +if test "$BUILD_LVMPOLLD" = yes; then + AC_CHECK_FUNCS(strpbrk,,hard_bailout) + AC_FUNC_STRERROR_R +fi + +if test "$CLVMD" != none; then + AC_CHECK_HEADERS(mntent.h netdb.h netinet/in.h pthread.h search.h sys/mount.h sys/socket.h sys/uio.h sys/un.h utmpx.h,,AC_MSG_ERROR(bailing out)) + AC_CHECK_FUNCS(dup2 getmntent memmove select socket,,hard_bailout) + AC_FUNC_GETMNTENT + AC_FUNC_SELECT_ARGTYPES +fi + +if test "$CLUSTER" != none; then + AC_CHECK_HEADERS(sys/socket.h sys/un.h,,hard_bailout) + AC_CHECK_FUNCS(socket,,hard_bailout) +fi + +if test "$DMEVENTD" = yes; then + AC_CHECK_HEADERS(arpa/inet.h,,hard_bailout) +fi + +if test "$HAVE_LIBDL" = yes; then + AC_CHECK_HEADERS(dlfcn.h,,hard_bailout) +fi + +if test "$INTL" = yes; then + AC_CHECK_HEADERS(libintl.h,,hard_bailout) +fi + +if test "$UDEV_SYNC" = yes; then + AC_CHECK_HEADERS(sys/ipc.h sys/sem.h,,hard_bailout) +fi + +################################################################################ +AC_PATH_TOOL(MODPROBE_CMD, modprobe) + +if test -n "$MODPROBE_CMD"; then + AC_DEFINE_UNQUOTED([MODPROBE_CMD], ["$MODPROBE_CMD"], [The path to 'modprobe', if available.]) +fi + + +lvm_exec_prefix=$exec_prefix +test "$lvm_exec_prefix" = NONE && lvm_exec_prefix=$prefix +test "$lvm_exec_prefix" = NONE && lvm_exec_prefix=$ac_default_prefix +LVM_PATH="$lvm_exec_prefix/sbin/lvm" +AC_DEFINE_UNQUOTED(LVM_PATH, ["$LVM_PATH"], [Path to lvm binary.]) + +clvmd_prefix=$ac_default_prefix +test "$prefix" != NONE && clvmd_prefix=$prefix +CLVMD_PATH="$clvmd_prefix/sbin/clvmd" +AC_DEFINE_UNQUOTED(CLVMD_PATH, ["$CLVMD_PATH"], [Path to clvmd binary.]) + +################################################################################ +dnl -- dmeventd pidfile and executable path +if test "$BUILD_DMEVENTD" = yes; then + AC_ARG_WITH(dmeventd-pidfile, + AC_HELP_STRING([--with-dmeventd-pidfile=PATH], + [dmeventd pidfile [PID_DIR/dmeventd.pid]]), + DMEVENTD_PIDFILE=$withval, + DMEVENTD_PIDFILE="$DEFAULT_PID_DIR/dmeventd.pid") + AC_DEFINE_UNQUOTED(DMEVENTD_PIDFILE, ["$DMEVENTD_PIDFILE"], + [Path to dmeventd pidfile.]) +fi + +if test "$BUILD_DMEVENTD" = yes; then + AC_ARG_WITH(dmeventd-path, + AC_HELP_STRING([--with-dmeventd-path=PATH], + [dmeventd path [EPREFIX/sbin/dmeventd]]), + DMEVENTD_PATH=$withval, + DMEVENTD_PATH="$lvm_exec_prefix/sbin/dmeventd") + AC_DEFINE_UNQUOTED(DMEVENTD_PATH, ["$DMEVENTD_PATH"], + [Path to dmeventd binary.]) +fi + +################################################################################ +dnl -- various defaults +dnl -- FIXME: need to switch to regular option here --sysconfdir +AC_ARG_WITH(default-system-dir, + AC_HELP_STRING([--with-default-system-dir=DIR], + [default LVM system directory [/etc/lvm]]), + DEFAULT_SYS_DIR=$withval, DEFAULT_SYS_DIR="/etc/lvm") +AC_DEFINE_UNQUOTED(DEFAULT_SYS_DIR, ["$DEFAULT_SYS_DIR"], + [Path to LVM system directory.]) + +AC_ARG_WITH(default-profile-subdir, + AC_HELP_STRING([--with-default-profile-subdir=SUBDIR], + [default configuration profile subdir [profile]]), + DEFAULT_PROFILE_SUBDIR=$withval, DEFAULT_PROFILE_SUBDIR=profile) +AC_DEFINE_UNQUOTED(DEFAULT_PROFILE_SUBDIR, ["$DEFAULT_PROFILE_SUBDIR"], + [Name of default configuration profile subdirectory.]) + +AC_ARG_WITH(default-archive-subdir, + AC_HELP_STRING([--with-default-archive-subdir=SUBDIR], + [default metadata archive subdir [archive]]), + DEFAULT_ARCHIVE_SUBDIR=$withval, DEFAULT_ARCHIVE_SUBDIR=archive) +AC_DEFINE_UNQUOTED(DEFAULT_ARCHIVE_SUBDIR, ["$DEFAULT_ARCHIVE_SUBDIR"], + [Name of default metadata archive subdirectory.]) + +AC_ARG_WITH(default-backup-subdir, + AC_HELP_STRING([--with-default-backup-subdir=SUBDIR], + [default metadata backup subdir [backup]]), + DEFAULT_BACKUP_SUBDIR=$withval, DEFAULT_BACKUP_SUBDIR=backup) +AC_DEFINE_UNQUOTED(DEFAULT_BACKUP_SUBDIR, ["$DEFAULT_BACKUP_SUBDIR"], + [Name of default metadata backup subdirectory.]) + +AC_ARG_WITH(default-cache-subdir, + AC_HELP_STRING([--with-default-cache-subdir=SUBDIR], + [default metadata cache subdir [cache]]), + DEFAULT_CACHE_SUBDIR=$withval, DEFAULT_CACHE_SUBDIR=cache) +AC_DEFINE_UNQUOTED(DEFAULT_CACHE_SUBDIR, ["$DEFAULT_CACHE_SUBDIR"], + [Name of default metadata cache subdirectory.]) + +AC_ARG_WITH(default-locking-dir, + AC_HELP_STRING([--with-default-locking-dir=DIR], + [default locking directory [autodetect_lock_dir/lvm]]), + DEFAULT_LOCK_DIR=$withval, + [AC_MSG_CHECKING(for default lock directory) + DEFAULT_LOCK_DIR="$RUN_DIR/lock/lvm" + test -d "$RUN_DIR/lock" || DEFAULT_LOCK_DIR="/var/lock/lvm" + AC_MSG_RESULT($DEFAULT_LOCK_DIR)]) +AC_DEFINE_UNQUOTED(DEFAULT_LOCK_DIR, ["$DEFAULT_LOCK_DIR"], + [Name of default locking directory.]) + +################################################################################ +dnl -- Setup default data alignment +AC_ARG_WITH(default-data-alignment, + AC_HELP_STRING([--with-default-data-alignment=NUM], + [set the default data alignment in MiB [1]]), + DEFAULT_DATA_ALIGNMENT=$withval, DEFAULT_DATA_ALIGNMENT=1) +AC_DEFINE_UNQUOTED(DEFAULT_DATA_ALIGNMENT, [$DEFAULT_DATA_ALIGNMENT], + [Default data alignment.]) + +################################################################################ +dnl -- which kernel interface to use (ioctl only) +AC_MSG_CHECKING(for kernel interface choice) +AC_ARG_WITH(interface, + AC_HELP_STRING([--with-interface=IFACE], + [choose kernel interface (ioctl) [ioctl]]), + interface=$withval, interface=ioctl) +test "$interface" != ioctl && AC_MSG_ERROR([--with-interface=ioctl required. fs no longer supported.]) +AC_MSG_RESULT($interface) + +################################################################################ +read DM_LIB_VERSION < "$srcdir"/VERSION_DM 2>/dev/null || DM_LIB_VERSION=Unknown +AC_DEFINE_UNQUOTED(DM_LIB_VERSION, "$DM_LIB_VERSION", [Library version]) + +DM_LIB_PATCHLEVEL=`cat "$srcdir"/VERSION_DM | $AWK -F '[[-. ]]' '{printf "%s.%s.%s",$1,$2,$3}'` + +read VER < "$srcdir"/VERSION 2>/dev/null || VER=Unknown + +LVM_VERSION=\"$VER\" +LVM_RELEASE_DATE="\"`echo $VER | $SED 's/.* (//;s/).*//'`\"" +VER=`echo "$VER" | $AWK '{print $1}'` +LVM_RELEASE="\"`echo "$VER" | $AWK -F '-' '{print $2}'`\"" +VER=`echo "$VER" | $AWK -F '-' '{print $1}'` +LVM_MAJOR=`echo "$VER" | $AWK -F '.' '{print $1}'` +LVM_MINOR=`echo "$VER" | $AWK -F '.' '{print $2}'` +LVM_PATCHLEVEL=`echo "$VER" | $AWK -F '[[(.]]' '{print $3}'` +LVM_LIBAPI=`echo "$VER" | $AWK -F '[[()]]' '{print $2}'` + +################################################################################ +AC_SUBST(APPLIB) +AC_SUBST(AWK) +AC_SUBST(BLKID_PC) +AC_SUBST(BUILD_CMIRRORD) +AC_SUBST(BUILD_DMEVENTD) +AC_SUBST(BUILD_LVMDBUSD) +AC_SUBST(BUILD_LVMETAD) +AC_SUBST(BUILD_LVMPOLLD) +AC_SUBST(BUILD_LVMLOCKD) +AC_SUBST(BUILD_LOCKDSANLOCK) +AC_SUBST(BUILD_LOCKDDLM) +AC_SUBST(BUILD_NOTIFYDBUS) +AC_SUBST(CACHE) +AC_SUBST(CFLAGS) +AC_SUBST(CFLOW_CMD) +AC_SUBST(CHMOD) +AC_SUBST(CLDFLAGS) +AC_SUBST(CLDNOWHOLEARCHIVE) +AC_SUBST(CLDWHOLEARCHIVE) +AC_SUBST(CLUSTER) +AC_SUBST(CLVMD) +AC_SUBST(CLVMD_CMANAGERS) +AC_SUBST(CLVMD_PATH) +AC_SUBST(CMAN_CFLAGS) +AC_SUBST(CMAN_LIBS) +AC_SUBST(CMAP_CFLAGS) +AC_SUBST(CMAP_LIBS) +AC_SUBST(CMDLIB) +AC_SUBST(CONFDB_CFLAGS) +AC_SUBST(CONFDB_LIBS) +AC_SUBST(CONFDIR) +AC_SUBST(COPTIMISE_FLAG) +AC_SUBST(CPG_CFLAGS) +AC_SUBST(CPG_LIBS) +AC_SUBST(CSCOPE_CMD) +AC_SUBST(DEBUG) +AC_SUBST(DEFAULT_ARCHIVE_SUBDIR) +AC_SUBST(DEFAULT_BACKUP_SUBDIR) +AC_SUBST(DEFAULT_CACHE_SUBDIR) +AC_SUBST(DEFAULT_DATA_ALIGNMENT) +AC_SUBST(DEFAULT_DM_RUN_DIR) +AC_SUBST(DEFAULT_LOCK_DIR) +AC_SUBST(DEFAULT_FALLBACK_TO_LVM1) +AC_SUBST(DEFAULT_MIRROR_SEGTYPE) +AC_SUBST(DEFAULT_PID_DIR) +AC_SUBST(DEFAULT_PROFILE_SUBDIR) +AC_SUBST(DEFAULT_RAID10_SEGTYPE) +AC_SUBST(DEFAULT_RUN_DIR) +AC_SUBST(DEFAULT_SPARSE_SEGTYPE) +AC_SUBST(DEFAULT_SYS_DIR) +AC_SUBST(DEFAULT_USE_BLKID_WIPING) +AC_SUBST(DEFAULT_USE_LVMETAD) +AC_SUBST(DEFAULT_USE_LVMPOLLD) +AC_SUBST(DEFAULT_USE_LVMLOCKD) +AC_SUBST(DEVMAPPER) +AC_SUBST(DLM_CFLAGS) +AC_SUBST(DLM_LIBS) +AC_SUBST(DL_LIBS) +AC_SUBST(DMEVENTD) +AC_SUBST(DMEVENTD_PATH) +AC_SUBST(DM_LIB_PATCHLEVEL) +AC_SUBST(ELDFLAGS) +AC_SUBST(FSADM) +AC_SUBST(BLKDEACTIVATE) +AC_SUBST(HAVE_LIBDL) +AC_SUBST(HAVE_REALTIME) +AC_SUBST(HAVE_VALGRIND) +AC_SUBST(INTL) +AC_SUBST(JOBS) +AC_SUBST(LDDEPS) +AC_SUBST(LIBS) +AC_SUBST(LIB_SUFFIX) +AC_SUBST(LVM1) +AC_SUBST(LVM1_FALLBACK) +AC_SUBST(LVM_VERSION) +AC_SUBST(LVM_LIBAPI) +AC_SUBST(LVM_MAJOR) +AC_SUBST(LVM_MINOR) +AC_SUBST(LVM_PATCHLEVEL) +AC_SUBST(LVM_PATH) +AC_SUBST(LVM_RELEASE) +AC_SUBST(LVM_RELEASE_DATE) +AC_SUBST(localedir) +AC_SUBST(MANGLING) +AC_SUBST(MIRRORS) +AC_SUBST(MSGFMT) +AC_SUBST(OCF) +AC_SUBST(OCFDIR) +AC_SUBST(PKGCONFIG) +AC_SUBST(POOL) +AC_SUBST(M_LIBS) +AC_SUBST(PTHREAD_LIBS) +AC_SUBST(PYTHON2) +AC_SUBST(PYTHON3) +AC_SUBST(PYTHON_BINDINGS) +AC_SUBST(PYTHON2_BINDINGS) +AC_SUBST(PYTHON3_BINDINGS) +AC_SUBST(PYTHON2_INCDIRS) +AC_SUBST(PYTHON3_INCDIRS) +AC_SUBST(PYTHON2_LIBDIRS) +AC_SUBST(PYTHON3_LIBDIRS) +AC_SUBST(PYTHON2DIR) +AC_SUBST(PYTHON3DIR) +AC_SUBST(QUORUM_CFLAGS) +AC_SUBST(QUORUM_LIBS) +AC_SUBST(RAID) +AC_SUBST(RT_LIB) +AC_SUBST(READLINE_LIBS) +AC_SUBST(REPLICATORS) +AC_SUBST(SACKPT_CFLAGS) +AC_SUBST(SACKPT_LIBS) +AC_SUBST(SALCK_CFLAGS) +AC_SUBST(SALCK_LIBS) +AC_SUBST(SELINUX_LIBS) +AC_SUBST(SELINUX_PC) +AC_SUBST(SNAPSHOTS) +AC_SUBST(STATICDIR) +AC_SUBST(STATIC_LINK) +AC_SUBST(TESTING) +AC_SUBST(TESTSUITE_DATA) +AC_SUBST(THIN) +AC_SUBST(THIN_CHECK_CMD) +AC_SUBST(THIN_DUMP_CMD) +AC_SUBST(THIN_REPAIR_CMD) +AC_SUBST(THIN_RESTORE_CMD) +AC_SUBST(CACHE_CHECK_CMD) +AC_SUBST(CACHE_DUMP_CMD) +AC_SUBST(CACHE_REPAIR_CMD) +AC_SUBST(CACHE_RESTORE_CMD) +AC_SUBST(UDEV_PC) +AC_SUBST(UDEV_RULES) +AC_SUBST(UDEV_SYNC) +AC_SUBST(UDEV_SYSTEMD_BACKGROUND_JOBS) +AC_SUBST(UDEV_RULE_EXEC_DETECTION) +AC_SUBST(UDEV_HAS_BUILTIN_BLKID) +AC_SUBST(USE_TRACKING) +AC_SUBST(VALGRIND_POOL) +AC_SUBST(WRITE_INSTALL) +AC_SUBST(DMEVENTD_PIDFILE) +AC_SUBST(LVMETAD_PIDFILE) +AC_SUBST(LVMPOLLD_PIDFILE) +AC_SUBST(LVMLOCKD_PIDFILE) +AC_SUBST(CLVMD_PIDFILE) +AC_SUBST(CMIRRORD_PIDFILE) +AC_SUBST(interface) +AC_SUBST(kerneldir) +AC_SUBST(missingkernel) +AC_SUBST(kernelvsn) +AC_SUBST(tmpdir) +AC_SUBST(udev_prefix) +AC_SUBST(udevdir) +AC_SUBST(systemdsystemunitdir) +AC_SUBST(systemdutildir) +AC_SUBST(tmpfilesdir) +AC_SUBST(usrlibdir) +AC_SUBST(usrsbindir) + +################################################################################ +dnl -- First and last lines should not contain files to generate in order to +dnl -- keep utility scripts running properly +AC_CONFIG_FILES([ +Makefile +make.tmpl +daemons/Makefile +daemons/clvmd/Makefile +daemons/cmirrord/Makefile +daemons/dmeventd/Makefile +daemons/dmeventd/libdevmapper-event.pc +daemons/dmeventd/plugins/Makefile +daemons/dmeventd/plugins/lvm2/Makefile +daemons/dmeventd/plugins/raid/Makefile +daemons/dmeventd/plugins/mirror/Makefile +daemons/dmeventd/plugins/snapshot/Makefile +daemons/dmeventd/plugins/thin/Makefile +daemons/lvmdbusd/Makefile +daemons/lvmdbusd/path.py +daemons/lvmetad/Makefile +daemons/lvmpolld/Makefile +daemons/lvmlockd/Makefile +conf/Makefile +conf/example.conf +conf/lvmlocal.conf +conf/command_profile_template.profile +conf/metadata_profile_template.profile +include/.symlinks +include/Makefile +lib/Makefile +lib/format1/Makefile +lib/format_pool/Makefile +lib/locking/Makefile +lib/mirror/Makefile +lib/replicator/Makefile +include/lvm-version.h +lib/raid/Makefile +lib/snapshot/Makefile +lib/thin/Makefile +lib/cache_segtype/Makefile +libdaemon/Makefile +libdaemon/client/Makefile +libdaemon/server/Makefile +libdm/Makefile +libdm/libdevmapper.pc +liblvm/Makefile +liblvm/liblvm2app.pc +man/Makefile +po/Makefile +python/Makefile +python/setup.py +scripts/blkdeactivate.sh +scripts/blk_availability_init_red_hat +scripts/blk_availability_systemd_red_hat.service +scripts/clvmd_init_red_hat +scripts/cmirrord_init_red_hat +scripts/com.redhat.lvmdbus1.service +scripts/dm_event_systemd_red_hat.service +scripts/dm_event_systemd_red_hat.socket +scripts/lvm2_cluster_activation_red_hat.sh +scripts/lvm2_cluster_activation_systemd_red_hat.service +scripts/lvm2_clvmd_systemd_red_hat.service +scripts/lvm2_cmirrord_systemd_red_hat.service +scripts/lvm2_lvmdbusd_systemd_red_hat.service +scripts/lvm2_lvmetad_init_red_hat +scripts/lvm2_lvmetad_systemd_red_hat.service +scripts/lvm2_lvmetad_systemd_red_hat.socket +scripts/lvm2_lvmpolld_init_red_hat +scripts/lvm2_lvmpolld_systemd_red_hat.service +scripts/lvm2_lvmpolld_systemd_red_hat.socket +scripts/lvm2_lvmlockd_systemd_red_hat.service +scripts/lvm2_lvmlocking_systemd_red_hat.service +scripts/lvm2_monitoring_init_red_hat +scripts/lvm2_monitoring_systemd_red_hat.service +scripts/lvm2_pvscan_systemd_red_hat@.service +scripts/lvm2_tmpfiles_red_hat.conf +scripts/Makefile +test/Makefile +test/api/Makefile +test/unit/Makefile +tools/Makefile +udev/Makefile +unit-tests/datastruct/Makefile +unit-tests/regex/Makefile +unit-tests/mm/Makefile +]) +AC_OUTPUT + +AS_IF([test -n "$THIN_CONFIGURE_WARN"], + [AC_MSG_WARN([Support for thin provisioning is limited since some thin provisioning tools are missing!])]) + +AS_IF([test -n "$THIN_CHECK_VERSION_WARN"], + [AC_MSG_WARN([You should also install thin_check vsn 0.3.2 (or later) to use lvm2 thin provisioning])]) + +AS_IF([test -n "$CACHE_CONFIGURE_WARN"], + [AC_MSG_WARN([Support for cache is limited since some cache tools are missing!])]) + +AS_IF([test "$ODIRECT" != yes], + [AC_MSG_WARN([O_DIRECT disabled: low-memory pvmove may lock up])])
diff --git a/coverity/coverity_model.c b/coverity/coverity_model.c new file mode 100644 index 0000000..c5a5bfb --- /dev/null +++ b/coverity/coverity_model.c
@@ -0,0 +1,122 @@ +/* + * Copyright (C) 2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * Coverity usage: + * + * translate model into xml + * cov-make-library -of coverity_model.xml coverity_model.c + * + * compile (using outdir 'cov'): + * cov-build --dir=cov make CC=gcc + * + * analyze (agressively, using 'cov') + * cov-analyze --dir cov --wait-for-license --hfa --concurrency --enable-fnptr --enable-constraint-fpp --security --all --aggressiveness-level=high --field-offset-escape --user-model-file=coverity/coverity_model.xml + * + * generate html output (to 'html' from 'cov'): + * cov-format-errors --dir cov --html-output html + */ + +struct lv_segment; +struct logical_volume; + +struct lv_segment *first_seg(const struct logical_volume *lv) +{ + return ((struct lv_segment **)lv)[0]; +} + +struct lv_segment *last_seg(const struct logical_volume *lv) +{ + return ((struct lv_segment **)lv)[0]; +} + +/* simple_memccpy() from glibc */ +void *memccpy(void *dest, const void *src, int c, size_t n) +{ + const char *s = src; + char *d = dest; + + while (n-- > 0) + if ((*d++ = *s++) == (char) c) + return d; + + return 0; +} + +/* + * 2 lines bellow needs to be placed in coverity/config/user_nodefs.h + * Not sure about any other way. + * Without them, coverity shows warning since x86 system header files + * are using inline assembly to reset fdset + */ +//#nodef FD_ZERO model_FD_ZERO +//void model_FD_ZERO(void *fdset); + +void model_FD_ZERO(void *fdset) +{ + unsigned i; + + for (i = 0; i < 1024 / 8 / sizeof(long); ++i) + ((long*)fdset)[i] = 0; +} + +/* + * Added extra pointer check to not need these models, + * for now just keep then in file + */ + +/* +struct cmd_context; +struct profile; + +const char *find_config_tree_str(struct cmd_context *cmd, int id, struct profile *profile) +{ + return "text"; +} + +const char *find_config_tree_str_allow_empty(struct cmd_context *cmd, int id, struct profile *profile) +{ + return "text"; +} +*/ + +/* + * Until fixed coverity case# 00531860: + * A FORWARD_NULL false positive on a recursive function call + * + * model also these functions: + */ +/* +const struct dm_config_node; +const struct dm_config_node *find_config_tree_array(struct cmd_context *cmd, int id, struct profile *profile) +{ + const struct dm_config_node *cn; + + return cn; +} + +const struct dm_config_node *find_config_tree_node(struct cmd_context *cmd, int id, struct profile *profile) +{ + const struct dm_config_node *cn; + + return cn; +} + +int find_config_tree_bool(struct cmd_context *cmd, int id, struct profile *profile) +{ + int b; + + return b; +} +*/
diff --git a/daemons/Makefile.in b/daemons/Makefile.in new file mode 100644 index 0000000..2d43278 --- /dev/null +++ b/daemons/Makefile.in
@@ -0,0 +1,59 @@ +# +# Copyright (C) 2004-2015 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +.PHONY: dmeventd clvmd cmirrord lvmetad lvmpolld lvmlockd + +ifneq ("@CLVMD@", "none") + SUBDIRS += clvmd +endif + +ifeq ("@BUILD_CMIRRORD@", "yes") + SUBDIRS += cmirrord +endif + +ifeq ("@BUILD_DMEVENTD@", "yes") + SUBDIRS += dmeventd +ifneq ("$(CFLOW_CMD)", "") +daemons.cflow: dmeventd.cflow +endif +endif + +ifeq ("@BUILD_LVMETAD@", "yes") + SUBDIRS += lvmetad +endif + +ifeq ("@BUILD_LVMPOLLD@", "yes") + SUBDIRS += lvmpolld +endif + +ifeq ("@BUILD_LVMLOCKD@", "yes") + SUBDIRS += lvmlockd +endif + +ifeq ("@BUILD_LVMDBUSD@", "yes") + SUBDIRS += lvmdbusd +endif + +ifeq ($(MAKECMDGOALS),distclean) + SUBDIRS = clvmd cmirrord dmeventd lvmetad lvmpolld lvmlockd lvmdbusd +endif + +include $(top_builddir)/make.tmpl + +ifeq ("@BUILD_DMEVENTD@", "yes") +device-mapper: dmeventd.device-mapper +endif
diff --git a/daemons/clvmd/.gitignore b/daemons/clvmd/.gitignore new file mode 100644 index 0000000..816032f --- /dev/null +++ b/daemons/clvmd/.gitignore
@@ -0,0 +1 @@ +clvmd
diff --git a/daemons/clvmd/Makefile.in b/daemons/clvmd/Makefile.in new file mode 100644 index 0000000..257afb2 --- /dev/null +++ b/daemons/clvmd/Makefile.in
@@ -0,0 +1,103 @@ +# +# Copyright (C) 2004 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +CMAN_LIBS = @CMAN_LIBS@ +CMAN_CFLAGS = @CMAN_CFLAGS@ +CMAP_LIBS = @CMAP_LIBS@ +CMAP_CFLAGS = @CMAP_CFLAGS@ +CONFDB_LIBS = @CONFDB_LIBS@ +CONFDB_CFLAGS = @CONFDB_CFLAGS@ +CPG_LIBS = @CPG_LIBS@ +CPG_CFLAGS = @CPG_CFLAGS@ +DLM_LIBS = @DLM_LIBS@ +DLM_CFLAGS = @DLM_CFLAGS@ +QUORUM_LIBS = @QUORUM_LIBS@ +QUORUM_CFLAGS = @QUORUM_CFLAGS@ +SALCK_LIBS = @SALCK_LIBS@ +SALCK_CFLAGS = @SALCK_CFLAGS@ + +SOURCES = \ + clvmd-command.c \ + clvmd.c \ + lvm-functions.c \ + refresh_clvmd.c + +ifneq (,$(findstring cman,, "@CLVMD@,")) + SOURCES += clvmd-cman.c + LMLIBS += $(CMAN_LIBS) $(CONFDB_LIBS) $(DLM_LIBS) + CFLAGS += $(CMAN_CFLAGS) $(CONFDB_CFLAGS) $(DLM_CFLAGS) + DEFS += -DUSE_CMAN +endif + +ifneq (,$(findstring openais,, "@CLVMD@,")) + SOURCES += clvmd-openais.c + LMLIBS += $(CONFDB_LIBS) $(CPG_LIBS) $(SALCK_LIBS) + CFLAGS += $(CONFDB_CFLAGS) $(CPG_CFLAGS) $(SALCK_CFLAGS) + DEFS += -DUSE_OPENAIS +endif + +ifneq (,$(findstring corosync,, "@CLVMD@,")) + SOURCES += clvmd-corosync.c + LMLIBS += $(CMAP_LIBS) $(CONFDB_LIBS) $(CPG_LIBS) $(DLM_LIBS) $(QUORUM_LIBS) + CFLAGS += $(CMAP_CFLAGS) $(CONFDB_CFLAGS) $(CPG_CFLAGS) $(DLM_CFLAGS) $(QUORUM_CFLAGS) + DEFS += -DUSE_COROSYNC +endif + +ifneq (,$(findstring singlenode,, "@CLVMD@,")) + SOURCES += clvmd-singlenode.c + DEFS += -DUSE_SINGLENODE +endif + +ifeq ($(MAKECMDGOALS),distclean) + SOURCES += clvmd-cman.c + SOURCES += clvmd-openais.c + SOURCES += clvmd-corosync.c + SOURCES += clvmd-singlenode.c +endif + +TARGETS = \ + clvmd + +LVMLIBS = $(LVMINTERNAL_LIBS) + +ifeq ("@DMEVENTD@", "yes") + LVMLIBS += -ldevmapper-event +endif + +include $(top_builddir)/make.tmpl + +LVMLIBS += -ldevmapper +LIBS += $(PTHREAD_LIBS) + +CFLAGS += -fno-strict-aliasing $(EXTRA_EXEC_CFLAGS) +LDFLAGS += $(EXTRA_EXEC_LDFLAGS) + +INSTALL_TARGETS = \ + install_clvmd + +clvmd: $(OBJECTS) $(top_builddir)/lib/liblvm-internal.a + $(CC) $(CFLAGS) $(LDFLAGS) -o clvmd $(OBJECTS) \ + $(LVMLIBS) $(LMLIBS) $(LIBS) + +.PHONY: install_clvmd + +install_clvmd: $(TARGETS) + $(INSTALL_PROGRAM) -D clvmd $(usrsbindir)/clvmd + +install: $(INSTALL_TARGETS) + +install_cluster: $(INSTALL_TARGETS)
diff --git a/daemons/clvmd/clvm.h b/daemons/clvmd/clvm.h new file mode 100644 index 0000000..ae0a13a --- /dev/null +++ b/daemons/clvmd/clvm.h
@@ -0,0 +1,85 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* Definitions for CLVMD server and clients */ + +/* + * The protocol spoken over the cluster and across the local socket. + */ + +#ifndef _CLVM_H +#define _CLVM_H + +#include "configure.h" +#include <inttypes.h> + +struct clvm_header { + uint8_t cmd; /* See below */ + uint8_t flags; /* See below */ + uint16_t xid; /* Transaction ID */ + uint32_t clientid; /* Only used in Daemon->Daemon comms */ + int32_t status; /* For replies, whether request succeeded */ + uint32_t arglen; /* Length of argument below. + If >1500 then it will be passed + around the cluster in the system LV */ + char node[1]; /* Actually a NUL-terminated string, node name. + If this is empty then the command is + forwarded to all cluster nodes unless + FLAG_LOCAL or FLAG_REMOTE is also set. */ + char args[1]; /* Arguments for the command follow the + node name, This member is only + valid if the node name is empty */ +} __attribute__ ((packed)); + +/* Flags */ +#define CLVMD_FLAG_LOCAL 1 /* Only do this on the local node */ +#define CLVMD_FLAG_SYSTEMLV 2 /* Data in system LV under my node name */ +#define CLVMD_FLAG_NODEERRS 4 /* Reply has errors in node-specific portion */ +#define CLVMD_FLAG_REMOTE 8 /* Do this on all nodes except for the local node */ + +/* Name of the local socket to communicate between lvm and clvmd */ +#define CLVMD_SOCKNAME DEFAULT_RUN_DIR "/clvmd.sock" + +/* Internal commands & replies */ +#define CLVMD_CMD_REPLY 1 +#define CLVMD_CMD_VERSION 2 /* Send version around cluster when we start */ +#define CLVMD_CMD_GOAWAY 3 /* Die if received this - we are running + an incompatible version */ +#define CLVMD_CMD_TEST 4 /* Just for mucking about */ + +#define CLVMD_CMD_LOCK 30 +#define CLVMD_CMD_UNLOCK 31 + +/* Lock/Unlock commands */ +#define CLVMD_CMD_LOCK_LV 50 +#define CLVMD_CMD_LOCK_VG 51 +#define CLVMD_CMD_LOCK_QUERY 52 + +/* Misc functions */ +#define CLVMD_CMD_REFRESH 40 +#define CLVMD_CMD_GET_CLUSTERNAME 41 +#define CLVMD_CMD_SET_DEBUG 42 +#define CLVMD_CMD_VG_BACKUP 43 +#define CLVMD_CMD_RESTART 44 +#define CLVMD_CMD_SYNC_NAMES 45 + +/* Used internally by some callers, but not part of the protocol.*/ +#ifndef NODE_ALL +# define NODE_ALL "*" +# define NODE_LOCAL "." +# define NODE_REMOTE "^" +#endif + +#endif
diff --git a/daemons/clvmd/clvmd-cman.c b/daemons/clvmd/clvmd-cman.c new file mode 100644 index 0000000..ece9229 --- /dev/null +++ b/daemons/clvmd/clvmd-cman.c
@@ -0,0 +1,505 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * CMAN communication layer for clvmd. + */ + +#include "clvmd-common.h" + +#include <pthread.h> + +#include "clvmd-comms.h" +#include "clvm.h" +#include "clvmd.h" +#include "lvm-functions.h" + +#include <libdlm.h> + +#include <syslog.h> + +#define LOCKSPACE_NAME "clvmd" + +struct clvmd_node +{ + struct cman_node *node; + int clvmd_up; +}; + +static int num_nodes; +static struct cman_node *nodes = NULL; +static struct cman_node this_node; +static int count_nodes; /* size of allocated nodes array */ +static struct dm_hash_table *node_updown_hash; +static dlm_lshandle_t *lockspace; +static cman_handle_t c_handle; + +static void count_clvmds_running(void); +static void get_members(void); +static int nodeid_from_csid(const char *csid); +static int name_from_nodeid(int nodeid, char *name); +static void event_callback(cman_handle_t handle, void *private, int reason, int arg); +static void data_callback(cman_handle_t handle, void *private, + char *buf, int len, uint8_t port, int nodeid); + +struct lock_wait { + pthread_cond_t cond; + pthread_mutex_t mutex; + struct dlm_lksb lksb; +}; + +static int _init_cluster(void) +{ + node_updown_hash = dm_hash_create(100); + + /* Open the cluster communication socket */ + c_handle = cman_init(NULL); + if (!c_handle) { + syslog(LOG_ERR, "Can't open cluster manager socket: %m"); + return -1; + } + DEBUGLOG("Connected to CMAN\n"); + + if (cman_start_recv_data(c_handle, data_callback, CLUSTER_PORT_CLVMD)) { + syslog(LOG_ERR, "Can't bind cluster socket: %m"); + return -1; + } + + if (cman_start_notification(c_handle, event_callback)) { + syslog(LOG_ERR, "Can't start cluster event listening"); + return -1; + } + + /* Get the cluster members list */ + get_members(); + count_clvmds_running(); + + DEBUGLOG("CMAN initialisation complete\n"); + + /* Create a lockspace for LV & VG locks to live in */ + lockspace = dlm_open_lockspace(LOCKSPACE_NAME); + if (!lockspace) { + lockspace = dlm_create_lockspace(LOCKSPACE_NAME, 0600); + if (!lockspace) { + syslog(LOG_ERR, "Unable to create DLM lockspace for CLVM: %m"); + return -1; + } + DEBUGLOG("Created DLM lockspace for CLVMD.\n"); + } else + DEBUGLOG("Opened existing DLM lockspace for CLVMD.\n"); + + dlm_ls_pthread_init(lockspace); + DEBUGLOG("DLM initialisation complete\n"); + return 0; +} + +static void _cluster_init_completed(void) +{ + clvmd_cluster_init_completed(); +} + +static int _get_main_cluster_fd(void) +{ + return cman_get_fd(c_handle); +} + +static int _get_num_nodes(void) +{ + int i; + int nnodes = 0; + + /* return number of ACTIVE nodes */ + for (i=0; i<num_nodes; i++) { + if (nodes[i].cn_member && nodes[i].cn_nodeid) + nnodes++; + } + return nnodes; +} + +/* send_message with the fd check removed */ +static int _cluster_send_message(const void *buf, int msglen, const char *csid, + const char *errtext) +{ + int nodeid = 0; + + if (csid) + memcpy(&nodeid, csid, CMAN_MAX_CSID_LEN); + + if (cman_send_data(c_handle, buf, msglen, 0, CLUSTER_PORT_CLVMD, nodeid) <= 0) + { + log_error("%s", errtext); + } + return msglen; +} + +static void _get_our_csid(char *csid) +{ + if (this_node.cn_nodeid == 0) { + cman_get_node(c_handle, 0, &this_node); + } + memcpy(csid, &this_node.cn_nodeid, CMAN_MAX_CSID_LEN); +} + +/* Call a callback routine for each node is that known (down means not running a clvmd) */ +static int _cluster_do_node_callback(struct local_client *client, + void (*callback) (struct local_client *, + const char *, + int)) +{ + int i; + int somedown = 0; + + for (i = 0; i < _get_num_nodes(); i++) { + if (nodes[i].cn_member && nodes[i].cn_nodeid) { + int up = (int)(long)dm_hash_lookup_binary(node_updown_hash, (char *)&nodes[i].cn_nodeid, sizeof(int)); + + callback(client, (char *)&nodes[i].cn_nodeid, up); + if (!up) + somedown = -1; + } + } + return somedown; +} + +/* Process OOB messages from the cluster socket */ +static void event_callback(cman_handle_t handle, void *private, int reason, int arg) +{ + char namebuf[MAX_CLUSTER_MEMBER_NAME_LEN]; + + switch (reason) { + case CMAN_REASON_PORTCLOSED: + name_from_nodeid(arg, namebuf); + log_notice("clvmd on node %s has died\n", namebuf); + DEBUGLOG("Got port closed message, removing node %s\n", namebuf); + + dm_hash_insert_binary(node_updown_hash, (char *)&arg, sizeof(int), (void *)0); + break; + + case CMAN_REASON_STATECHANGE: + DEBUGLOG("Got state change message, re-reading members list\n"); + get_members(); + break; + +#if defined(LIBCMAN_VERSION) && LIBCMAN_VERSION >= 2 + case CMAN_REASON_PORTOPENED: + /* Ignore this, wait for startup message from clvmd itself */ + break; + + case CMAN_REASON_TRY_SHUTDOWN: + DEBUGLOG("Got try shutdown, sending OK\n"); + cman_replyto_shutdown(c_handle, 1); + break; +#endif + default: + /* ERROR */ + DEBUGLOG("Got unknown event callback message: %d\n", reason); + break; + } +} + +static struct local_client *cman_client; +static int _cluster_fd_callback(struct local_client *fd, char *buf, int len, + const char *csid, + struct local_client **new_client) +{ + + /* Save this for data_callback */ + cman_client = fd; + + /* We never return a new client */ + *new_client = NULL; + + return cman_dispatch(c_handle, 0); +} + + +static void data_callback(cman_handle_t handle, void *private, + char *buf, int len, uint8_t port, int nodeid) +{ + /* Ignore looped back messages */ + if (nodeid == this_node.cn_nodeid) + return; + process_message(cman_client, buf, len, (char *)&nodeid); +} + +static void _add_up_node(const char *csid) +{ + /* It's up ! */ + int nodeid = nodeid_from_csid(csid); + + dm_hash_insert_binary(node_updown_hash, (char *)&nodeid, sizeof(int), (void *)1); + DEBUGLOG("Added new node %d to updown list\n", nodeid); +} + +static void _cluster_closedown(void) +{ + dlm_release_lockspace(LOCKSPACE_NAME, lockspace, 1); + cman_finish(c_handle); +} + +static int is_listening(int nodeid) +{ + int status; + + do { + status = cman_is_listening(c_handle, nodeid, CLUSTER_PORT_CLVMD); + if (status < 0 && errno == EBUSY) { /* Don't busywait */ + sleep(1); + errno = EBUSY; /* In case sleep trashes it */ + } + } + while (status < 0 && errno == EBUSY); + + return status; +} + +/* Populate the list of CLVMDs running. + called only at startup time */ +static void count_clvmds_running(void) +{ + int i; + + for (i = 0; i < num_nodes; i++) { + int nodeid = nodes[i].cn_nodeid; + + if (is_listening(nodeid) == 1) + dm_hash_insert_binary(node_updown_hash, (void *)&nodeid, sizeof(int), (void*)1); + else + dm_hash_insert_binary(node_updown_hash, (void *)&nodeid, sizeof(int), (void*)0); + } +} + +/* Get a list of active cluster members */ +static void get_members(void) +{ + int retnodes; + int status; + int i; + int high_nodeid = 0; + + num_nodes = cman_get_node_count(c_handle); + if (num_nodes == -1) { + log_error("Unable to get node count"); + return; + } + + /* Not enough room for new nodes list ? */ + if (num_nodes > count_nodes && nodes) { + free(nodes); + nodes = NULL; + } + + if (nodes == NULL) { + count_nodes = num_nodes + 10; /* Overallocate a little */ + nodes = malloc(count_nodes * sizeof(struct cman_node)); + if (!nodes) { + log_error("Unable to allocate nodes array\n"); + exit(5); + } + } + + status = cman_get_nodes(c_handle, count_nodes, &retnodes, nodes); + if (status < 0) { + log_error("Unable to get node details"); + exit(6); + } + + /* Get the highest nodeid */ + for (i=0; i<retnodes; i++) { + if (nodes[i].cn_nodeid > high_nodeid) + high_nodeid = nodes[i].cn_nodeid; + } +} + + +/* Convert a node name to a CSID */ +static int _csid_from_name(char *csid, const char *name) +{ + int i; + + for (i = 0; i < num_nodes; i++) { + if (strcmp(name, nodes[i].cn_name) == 0) { + memcpy(csid, &nodes[i].cn_nodeid, CMAN_MAX_CSID_LEN); + return 0; + } + } + return -1; +} + +/* Convert a CSID to a node name */ +static int _name_from_csid(const char *csid, char *name) +{ + int i; + + for (i = 0; i < num_nodes; i++) { + if (memcmp(csid, &nodes[i].cn_nodeid, CMAN_MAX_CSID_LEN) == 0) { + strcpy(name, nodes[i].cn_name); + return 0; + } + } + /* Who?? */ + strcpy(name, "Unknown"); + return -1; +} + +/* Convert a node ID to a node name */ +static int name_from_nodeid(int nodeid, char *name) +{ + int i; + + for (i = 0; i < num_nodes; i++) { + if (nodeid == nodes[i].cn_nodeid) { + strcpy(name, nodes[i].cn_name); + return 0; + } + } + /* Who?? */ + strcpy(name, "Unknown"); + return -1; +} + +/* Convert a CSID to a node ID */ +static int nodeid_from_csid(const char *csid) +{ + int nodeid; + + memcpy(&nodeid, csid, CMAN_MAX_CSID_LEN); + + return nodeid; +} + +static int _is_quorate(void) +{ + return cman_is_quorate(c_handle); +} + +static void sync_ast_routine(void *arg) +{ + struct lock_wait *lwait = arg; + + pthread_mutex_lock(&lwait->mutex); + pthread_cond_signal(&lwait->cond); + pthread_mutex_unlock(&lwait->mutex); +} + +static int _sync_lock(const char *resource, int mode, int flags, int *lockid) +{ + int status; + struct lock_wait lwait; + + if (!lockid) { + errno = EINVAL; + return -1; + } + + DEBUGLOG("sync_lock: '%s' mode:%d flags=%d\n", resource,mode,flags); + /* Conversions need the lockid in the LKSB */ + if (flags & LKF_CONVERT) + lwait.lksb.sb_lkid = *lockid; + + pthread_cond_init(&lwait.cond, NULL); + pthread_mutex_init(&lwait.mutex, NULL); + pthread_mutex_lock(&lwait.mutex); + + status = dlm_ls_lock(lockspace, + mode, + &lwait.lksb, + flags, + resource, + strlen(resource), + 0, sync_ast_routine, &lwait, NULL, NULL); + if (status) + return status; + + /* Wait for it to complete */ + pthread_cond_wait(&lwait.cond, &lwait.mutex); + pthread_mutex_unlock(&lwait.mutex); + + *lockid = lwait.lksb.sb_lkid; + + errno = lwait.lksb.sb_status; + DEBUGLOG("sync_lock: returning lkid %x\n", *lockid); + if (lwait.lksb.sb_status) + return -1; + else + return 0; +} + +static int _sync_unlock(const char *resource /* UNUSED */, int lockid) +{ + int status; + struct lock_wait lwait; + + DEBUGLOG("sync_unlock: '%s' lkid:%x\n", resource, lockid); + + pthread_cond_init(&lwait.cond, NULL); + pthread_mutex_init(&lwait.mutex, NULL); + pthread_mutex_lock(&lwait.mutex); + + status = dlm_ls_unlock(lockspace, lockid, 0, &lwait.lksb, &lwait); + + if (status) + return status; + + /* Wait for it to complete */ + pthread_cond_wait(&lwait.cond, &lwait.mutex); + pthread_mutex_unlock(&lwait.mutex); + + errno = lwait.lksb.sb_status; + if (lwait.lksb.sb_status != EUNLOCK) + return -1; + else + return 0; + +} + +static int _get_cluster_name(char *buf, int buflen) +{ + cman_cluster_t cluster_info; + int status; + + status = cman_get_cluster(c_handle, &cluster_info); + if (!status) { + strncpy(buf, cluster_info.ci_name, buflen); + } + return status; +} + +static struct cluster_ops _cluster_cman_ops = { + .name = "cman", + .cluster_init_completed = _cluster_init_completed, + .cluster_send_message = _cluster_send_message, + .name_from_csid = _name_from_csid, + .csid_from_name = _csid_from_name, + .get_num_nodes = _get_num_nodes, + .cluster_fd_callback = _cluster_fd_callback, + .get_main_cluster_fd = _get_main_cluster_fd, + .cluster_do_node_callback = _cluster_do_node_callback, + .is_quorate = _is_quorate, + .get_our_csid = _get_our_csid, + .add_up_node = _add_up_node, + .cluster_closedown = _cluster_closedown, + .get_cluster_name = _get_cluster_name, + .sync_lock = _sync_lock, + .sync_unlock = _sync_unlock, +}; + +struct cluster_ops *init_cman_cluster(void) +{ + if (!_init_cluster()) + return &_cluster_cman_ops; + else + return NULL; +}
diff --git a/daemons/clvmd/clvmd-command.c b/daemons/clvmd/clvmd-command.c new file mode 100644 index 0000000..0593f6f --- /dev/null +++ b/daemons/clvmd/clvmd-command.c
@@ -0,0 +1,414 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2011 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + + CLVMD Cluster LVM daemon command processor. + + To add commands to the daemon simply add a processor in do_command and return + and messages back in buf and the length in *retlen. The initial value of + buflen is the maximum size of the buffer. if buf is not large enough then it + may be reallocated by the functions in here to a suitable size bearing in + mind that anything larger than the passed-in size will have to be returned + using the system LV and so performance will suffer. + + The status return will be negated and passed back to the originating node. + + pre- and post- command routines are called only on the local node. The + purpose is primarily to get and release locks, though the pre- routine should + also do any other local setups required by the command (if any) and can + return a failure code that prevents the command from being distributed around + the cluster + + The pre- and post- routines are run in their own thread so can block as long + they like, do_command is run in the main clvmd thread so should not block for + too long. If the pre-command returns an error code (!=0) then the command + will not be propogated around the cluster but the post-command WILL be called + + Also note that the pre and post routine are *always* called on the local + node, even if the command to be executed was only requested to run on a + remote node. It may peek inside the client structure to check the status of + the command. + + The clients of the daemon must, naturally, understand the return messages and + codes. + + Routines in here may only READ the values in the client structure passed in + apart from client->private which they are free to do what they like with. + +*/ + +#include "clvmd-common.h" +#include "clvmd-comms.h" +#include "clvm.h" +#include "clvmd.h" +#include "lvm-globals.h" +#include "lvm-functions.h" + +#include "locking.h" + +#include <sys/utsname.h> + +extern struct cluster_ops *clops; +static int restart_clvmd(void); + +/* This is where all the real work happens: + NOTE: client will be NULL when this is executed on a remote node */ +int do_command(struct local_client *client, struct clvm_header *msg, int msglen, + char **buf, int buflen, int *retlen) +{ + char *args = msg->node + strlen(msg->node) + 1; + int arglen = msglen - sizeof(struct clvm_header) - strlen(msg->node); + int status = 0; + char *lockname; + const char *locktype; + struct utsname nodeinfo; + unsigned char lock_cmd; + unsigned char lock_flags; + + /* Do the command */ + switch (msg->cmd) { + /* Just a test message */ + case CLVMD_CMD_TEST: + if (arglen > buflen) { + char *new_buf; + buflen = arglen + 200; + new_buf = realloc(*buf, buflen); + if (new_buf == NULL) { + status = errno; + free (*buf); + } + *buf = new_buf; + } + if (*buf) { + if (uname(&nodeinfo)) + memset(&nodeinfo, 0, sizeof(nodeinfo)); + + *retlen = 1 + dm_snprintf(*buf, buflen, + "TEST from %s: %s v%s", + nodeinfo.nodename, args, + nodeinfo.release); + } + break; + + case CLVMD_CMD_LOCK_VG: + lock_cmd = args[0]; + lock_flags = args[1]; + lockname = &args[2]; + /* Check to see if the VG is in use by LVM1 */ + status = do_check_lvm1(lockname); + do_lock_vg(lock_cmd, lock_flags, lockname); + break; + + case CLVMD_CMD_LOCK_LV: + /* This is the biggie */ + lock_cmd = args[0]; + lock_flags = args[1]; + lockname = &args[2]; + status = do_lock_lv(lock_cmd, lock_flags, lockname); + /* Replace EIO with something less scary */ + if (status == EIO) { + *retlen = 1 + dm_snprintf(*buf, buflen, "%s", + get_last_lvm_error()); + return EIO; + } + break; + + case CLVMD_CMD_LOCK_QUERY: + lockname = &args[2]; + if (buflen < 3) + return EIO; + if ((locktype = do_lock_query(lockname))) + *retlen = 1 + dm_snprintf(*buf, buflen, "%s", locktype); + break; + + case CLVMD_CMD_REFRESH: + do_refresh_cache(); + break; + + case CLVMD_CMD_SYNC_NAMES: + lvm_do_fs_unlock(); + break; + + case CLVMD_CMD_SET_DEBUG: + clvmd_set_debug((debug_t) args[0]); + break; + + case CLVMD_CMD_RESTART: + status = restart_clvmd(); + break; + + case CLVMD_CMD_GET_CLUSTERNAME: + status = clops->get_cluster_name(*buf, buflen); + if (!status) + *retlen = strlen(*buf)+1; + break; + + case CLVMD_CMD_VG_BACKUP: + /* + * Do not run backup on local node, caller should do that. + */ + if (!client) + lvm_do_backup(&args[2]); + break; + + default: + /* Won't get here because command is validated in pre_command */ + break; + } + + /* Check the status of the command and return the error text */ + if (status) { + *retlen = 1 + ((*buf) ? dm_snprintf(*buf, buflen, "%s", + strerror(status)) : -1); + } + + return status; +} + +static int lock_vg(struct local_client *client) +{ + struct dm_hash_table *lock_hash; + struct clvm_header *header = + (struct clvm_header *) client->bits.localsock.cmd; + unsigned char lock_cmd; + int lock_mode; + char *args = header->node + strlen(header->node) + 1; + int lkid; + int status; + char *lockname; + + /* + * Keep a track of VG locks in our own hash table. In current + * practice there should only ever be more than two VGs locked + * if a user tries to merge lots of them at once + */ + if (!client->bits.localsock.private) { + if (!(lock_hash = dm_hash_create(3))) + return ENOMEM; + client->bits.localsock.private = (void *) lock_hash; + } else + lock_hash = (struct dm_hash_table *) client->bits.localsock.private; + + lock_cmd = args[0] & (LCK_NONBLOCK | LCK_HOLD | LCK_SCOPE_MASK | LCK_TYPE_MASK); + lock_mode = ((int) lock_cmd & LCK_TYPE_MASK); + /* lock_flags = args[1]; */ + lockname = &args[2]; + DEBUGLOG("doing PRE command LOCK_VG '%s' at %x (client=%p)\n", lockname, lock_cmd, client); + + if (lock_mode == LCK_UNLOCK) { + if (!(lkid = (int) (long) dm_hash_lookup(lock_hash, lockname))) + return EINVAL; + + if ((status = sync_unlock(lockname, lkid))) + status = errno; + else + dm_hash_remove(lock_hash, lockname); + } else { + /* Read locks need to be PR; other modes get passed through */ + if (lock_mode == LCK_READ) + lock_mode = LCK_PREAD; + + if ((status = sync_lock(lockname, lock_mode, (lock_cmd & LCK_NONBLOCK) ? LCKF_NOQUEUE : 0, &lkid))) + status = errno; + else if (!dm_hash_insert(lock_hash, lockname, (void *) (long) lkid)) + return ENOMEM; + } + + return status; +} + + +/* Pre-command is a good place to get locks that are needed only for the duration + of the commands around the cluster (don't forget to free them in post-command), + and to sanity check the command arguments */ +int do_pre_command(struct local_client *client) +{ + struct clvm_header *header = + (struct clvm_header *) client->bits.localsock.cmd; + unsigned char lock_cmd; + unsigned char lock_flags; + char *args = header->node + strlen(header->node) + 1; + int lockid = 0; + int status = 0; + char *lockname; + + switch (header->cmd) { + case CLVMD_CMD_TEST: + status = sync_lock("CLVMD_TEST", LCK_EXCL, 0, &lockid); + client->bits.localsock.private = (void *)(long)lockid; + break; + + case CLVMD_CMD_LOCK_VG: + lockname = &args[2]; + /* We take out a real lock unless LCK_CACHE was set */ + if (!strncmp(lockname, "V_", 2) || + !strncmp(lockname, "P_#", 3)) + status = lock_vg(client); + break; + + case CLVMD_CMD_LOCK_LV: + lock_cmd = args[0]; + lock_flags = args[1]; + lockname = &args[2]; + status = pre_lock_lv(lock_cmd, lock_flags, lockname); + break; + + case CLVMD_CMD_REFRESH: + case CLVMD_CMD_GET_CLUSTERNAME: + case CLVMD_CMD_SET_DEBUG: + case CLVMD_CMD_VG_BACKUP: + case CLVMD_CMD_SYNC_NAMES: + case CLVMD_CMD_LOCK_QUERY: + case CLVMD_CMD_RESTART: + break; + + default: + log_error("Unknown command %d received\n", header->cmd); + status = EINVAL; + } + return status; +} + +/* Note that the post-command routine is called even if the pre-command or the real command + failed */ +int do_post_command(struct local_client *client) +{ + struct clvm_header *header = + (struct clvm_header *) client->bits.localsock.cmd; + int status = 0; + unsigned char lock_cmd; + unsigned char lock_flags; + char *args = header->node + strlen(header->node) + 1; + char *lockname; + + switch (header->cmd) { + case CLVMD_CMD_TEST: + status = sync_unlock("CLVMD_TEST", (int) (long) client->bits.localsock.private); + client->bits.localsock.private = NULL; + break; + + case CLVMD_CMD_LOCK_LV: + lock_cmd = args[0]; + lock_flags = args[1]; + lockname = &args[2]; + status = post_lock_lv(lock_cmd, lock_flags, lockname); + break; + + default: + /* Nothing to do here */ + break; + } + return status; +} + + +/* Called when the client is about to be deleted */ +void cmd_client_cleanup(struct local_client *client) +{ + struct dm_hash_node *v; + struct dm_hash_table *lock_hash; + int lkid; + char *lockname; + + DEBUGLOG("Client thread cleanup (%p)\n", client); + if (!client->bits.localsock.private) + return; + + lock_hash = (struct dm_hash_table *)client->bits.localsock.private; + + dm_hash_iterate(v, lock_hash) { + lkid = (int)(long)dm_hash_get_data(lock_hash, v); + lockname = dm_hash_get_key(lock_hash, v); + DEBUGLOG("Cleanup (%p): Unlocking lock %s %x\n", client, lockname, lkid); + (void) sync_unlock(lockname, lkid); + } + + dm_hash_destroy(lock_hash); + client->bits.localsock.private = NULL; +} + +static int restart_clvmd(void) +{ + const char **argv; + char *lv_name; + int argc = 0, max_locks = 0; + struct dm_hash_node *hn = NULL; + char debug_arg[16]; + const char *clvmd = getenv("LVM_CLVMD_BINARY") ? : CLVMD_PATH; + + DEBUGLOG("clvmd restart requested\n"); + + /* Count exclusively-open LVs */ + do { + hn = get_next_excl_lock(hn, &lv_name); + if (lv_name) { + max_locks++; + if (!*lv_name) + break; /* FIXME: Is this error ? */ + } + } while (hn); + + /* clvmd + locks (-E uuid) + debug (-d X) + NULL */ + if (!(argv = malloc((max_locks * 2 + 6) * sizeof(*argv)))) + goto_out; + + /* + * Build the command-line + */ + argv[argc++] = "clvmd"; + + /* Propagate debug options */ + if (clvmd_get_debug()) { + if (dm_snprintf(debug_arg, sizeof(debug_arg), "-d%u", clvmd_get_debug()) < 0) + goto_out; + argv[argc++] = debug_arg; + } + + /* Propagate foreground options */ + if (clvmd_get_foreground()) + argv[argc++] = "-f"; + + argv[argc++] = "-I"; + argv[argc++] = clops->name; + + /* Now add the exclusively-open LVs */ + hn = NULL; + do { + hn = get_next_excl_lock(hn, &lv_name); + if (lv_name) { + if (!*lv_name) + break; /* FIXME: Is this error ? */ + argv[argc++] = "-E"; + argv[argc++] = lv_name; + DEBUGLOG("excl lock: %s\n", lv_name); + } + } while (hn); + argv[argc] = NULL; + + /* Exec new clvmd */ + DEBUGLOG("--- Restarting %s ---\n", clvmd); + for (argc = 1; argv[argc]; argc++) DEBUGLOG("--- %d: %s\n", argc, argv[argc]); + + /* NOTE: This will fail when downgrading! */ + execvp(clvmd, (char **)argv); +out: + /* We failed */ + DEBUGLOG("Restart of clvmd failed.\n"); + + free(argv); + + return EIO; +}
diff --git a/daemons/clvmd/clvmd-common.h b/daemons/clvmd/clvmd-common.h new file mode 100644 index 0000000..3be0e1d --- /dev/null +++ b/daemons/clvmd/clvmd-common.h
@@ -0,0 +1,27 @@ +/* + * Copyright (C) 2010 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * This file must be included first by every clvmd source file. + */ +#ifndef _LVM_CLVMD_COMMON_H +#define _LVM_CLVMD_COMMON_H + +#define _REENTRANT + +#include "tool.h" + +#include "lvm-logging.h" + +#endif
diff --git a/daemons/clvmd/clvmd-comms.h b/daemons/clvmd/clvmd-comms.h new file mode 100644 index 0000000..f94077c --- /dev/null +++ b/daemons/clvmd/clvmd-comms.h
@@ -0,0 +1,119 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2011 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * Abstraction layer for clvmd cluster communications + */ + +#ifndef _CLVMD_COMMS_H +#define _CLVMD_COMMS_H + +struct local_client; + +struct cluster_ops { + const char *name; + void (*cluster_init_completed) (void); + + int (*cluster_send_message) (const void *buf, int msglen, + const char *csid, + const char *errtext); + int (*name_from_csid) (const char *csid, char *name); + int (*csid_from_name) (char *csid, const char *name); + int (*get_num_nodes) (void); + int (*cluster_fd_callback) (struct local_client *fd, char *buf, int len, + const char *csid, + struct local_client **new_client); + int (*get_main_cluster_fd) (void); /* gets accept FD or cman cluster socket */ + int (*cluster_do_node_callback) (struct local_client *client, + void (*callback) (struct local_client *, + const char *csid, + int node_up)); + int (*is_quorate) (void); + + void (*get_our_csid) (char *csid); + void (*add_up_node) (const char *csid); + void (*reread_config) (void); + void (*cluster_closedown) (void); + + int (*get_cluster_name)(char *buf, int buflen); + + int (*sync_lock) (const char *resource, int mode, + int flags, int *lockid); + int (*sync_unlock) (const char *resource, int lockid); + +}; + +#ifdef USE_CMAN +# include <netinet/in.h> +# include "libcman.h" +# define CMAN_MAX_CSID_LEN 4 +# ifndef MAX_CSID_LEN +# define MAX_CSID_LEN CMAN_MAX_CSID_LEN +# endif +# undef MAX_CLUSTER_MEMBER_NAME_LEN +# define MAX_CLUSTER_MEMBER_NAME_LEN CMAN_MAX_NODENAME_LEN +# define CMAN_MAX_CLUSTER_MESSAGE 1500 +# define CLUSTER_PORT_CLVMD 11 +struct cluster_ops *init_cman_cluster(void); +#endif + +#ifdef USE_OPENAIS +# include <openais/saAis.h> +# include <corosync/totem/totem.h> +# define OPENAIS_CSID_LEN (sizeof(int)) +# define OPENAIS_MAX_CLUSTER_MESSAGE MESSAGE_SIZE_MAX +# define OPENAIS_MAX_CLUSTER_MEMBER_NAME_LEN SA_MAX_NAME_LENGTH +# ifndef MAX_CLUSTER_MEMBER_NAME_LEN +# define MAX_CLUSTER_MEMBER_NAME_LEN SA_MAX_NAME_LENGTH +# endif +# ifndef CMAN_MAX_CLUSTER_MESSAGE +# define CMAN_MAX_CLUSTER_MESSAGE MESSAGE_SIZE_MAX +# endif +# ifndef MAX_CSID_LEN +# define MAX_CSID_LEN sizeof(int) +# endif +struct cluster_ops *init_openais_cluster(void); +#endif + +#ifdef USE_COROSYNC +# include <corosync/corotypes.h> +# define COROSYNC_CSID_LEN (sizeof(int)) +# define COROSYNC_MAX_CLUSTER_MESSAGE 65535 +# define COROSYNC_MAX_CLUSTER_MEMBER_NAME_LEN CS_MAX_NAME_LENGTH +# ifndef MAX_CLUSTER_MEMBER_NAME_LEN +# define MAX_CLUSTER_MEMBER_NAME_LEN CS_MAX_NAME_LENGTH +# endif +# ifndef CMAN_MAX_CLUSTER_MESSAGE +# define CMAN_MAX_CLUSTER_MESSAGE 65535 +# endif +# ifndef MAX_CSID_LEN +# define MAX_CSID_LEN sizeof(int) +# endif +struct cluster_ops *init_corosync_cluster(void); +#endif + +#ifdef USE_SINGLENODE +# define SINGLENODE_CSID_LEN (sizeof(int)) +# ifndef MAX_CLUSTER_MEMBER_NAME_LEN +# define MAX_CLUSTER_MEMBER_NAME_LEN 64 +# endif +# define SINGLENODE_MAX_CLUSTER_MESSAGE 65535 +# ifndef MAX_CSID_LEN +# define MAX_CSID_LEN sizeof(int) +# endif +struct cluster_ops *init_singlenode_cluster(void); +#endif + +#endif
diff --git a/daemons/clvmd/clvmd-corosync.c b/daemons/clvmd/clvmd-corosync.c new file mode 100644 index 0000000..05c9882 --- /dev/null +++ b/daemons/clvmd/clvmd-corosync.c
@@ -0,0 +1,658 @@ +/* + * Copyright (C) 2009-2012 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * This provides the interface between clvmd and corosync/DLM as the cluster + * and lock manager. + */ + +#include "clvmd-common.h" + +#include <pthread.h> + +#include "clvm.h" +#include "clvmd-comms.h" +#include "clvmd.h" +#include "lvm-functions.h" + +#include "locking.h" + +#include <corosync/cpg.h> +#include <corosync/quorum.h> + +#ifdef HAVE_COROSYNC_CONFDB_H +# include <corosync/confdb.h> +#elif defined HAVE_COROSYNC_CMAP_H +# include <corosync/cmap.h> +#else +# error "Either HAVE_COROSYNC_CONFDB_H or HAVE_COROSYNC_CMAP_H must be defined." +#endif + +#include <libdlm.h> + +#include <syslog.h> + +/* Timeout value for several corosync calls */ +#define LOCKSPACE_NAME "clvmd" + +static void corosync_cpg_deliver_callback (cpg_handle_t handle, + const struct cpg_name *groupName, + uint32_t nodeid, + uint32_t pid, + void *msg, + size_t msg_len); +static void corosync_cpg_confchg_callback(cpg_handle_t handle, + const struct cpg_name *groupName, + const struct cpg_address *member_list, size_t member_list_entries, + const struct cpg_address *left_list, size_t left_list_entries, + const struct cpg_address *joined_list, size_t joined_list_entries); +static void _cluster_closedown(void); + +/* Hash list of nodes in the cluster */ +static struct dm_hash_table *node_hash; + +/* Number of active nodes */ +static int num_nodes; +static unsigned int our_nodeid; + +static struct local_client *cluster_client; + +/* Corosync handles */ +static cpg_handle_t cpg_handle; +static quorum_handle_t quorum_handle; + +/* DLM Handle */ +static dlm_lshandle_t *lockspace; + +static struct cpg_name cpg_group_name; + +/* Corosync callback structs */ +cpg_callbacks_t corosync_cpg_callbacks = { + .cpg_deliver_fn = corosync_cpg_deliver_callback, + .cpg_confchg_fn = corosync_cpg_confchg_callback, +}; + +quorum_callbacks_t quorum_callbacks = { + .quorum_notify_fn = NULL, +}; + +struct node_info +{ + enum {NODE_DOWN, NODE_CLVMD} state; + int nodeid; +}; + + +/* Set errno to something approximating the right value and return 0 or -1 */ +static int cs_to_errno(cs_error_t err) +{ + switch(err) + { + case CS_OK: + return 0; + case CS_ERR_LIBRARY: + errno = EINVAL; + break; + case CS_ERR_VERSION: + errno = EINVAL; + break; + case CS_ERR_INIT: + errno = EINVAL; + break; + case CS_ERR_TIMEOUT: + errno = ETIME; + break; + case CS_ERR_TRY_AGAIN: + errno = EAGAIN; + break; + case CS_ERR_INVALID_PARAM: + errno = EINVAL; + break; + case CS_ERR_NO_MEMORY: + errno = ENOMEM; + break; + case CS_ERR_BAD_HANDLE: + errno = EINVAL; + break; + case CS_ERR_BUSY: + errno = EBUSY; + break; + case CS_ERR_ACCESS: + errno = EPERM; + break; + case CS_ERR_NOT_EXIST: + errno = ENOENT; + break; + case CS_ERR_NAME_TOO_LONG: + errno = ENAMETOOLONG; + break; + case CS_ERR_EXIST: + errno = EEXIST; + break; + case CS_ERR_NO_SPACE: + errno = ENOSPC; + break; + case CS_ERR_INTERRUPT: + errno = EINTR; + break; + case CS_ERR_NAME_NOT_FOUND: + errno = ENOENT; + break; + case CS_ERR_NO_RESOURCES: + errno = ENOMEM; + break; + case CS_ERR_NOT_SUPPORTED: + errno = EOPNOTSUPP; + break; + case CS_ERR_BAD_OPERATION: + errno = EINVAL; + break; + case CS_ERR_FAILED_OPERATION: + errno = EIO; + break; + case CS_ERR_MESSAGE_ERROR: + errno = EIO; + break; + case CS_ERR_QUEUE_FULL: + errno = EXFULL; + break; + case CS_ERR_QUEUE_NOT_AVAILABLE: + errno = EINVAL; + break; + case CS_ERR_BAD_FLAGS: + errno = EINVAL; + break; + case CS_ERR_TOO_BIG: + errno = E2BIG; + break; + case CS_ERR_NO_SECTIONS: + errno = ENOMEM; + break; + default: + errno = EINVAL; + break; + } + return -1; +} + +static char *print_corosync_csid(const char *csid) +{ + static char buf[128]; + int id; + + memcpy(&id, csid, sizeof(int)); + sprintf(buf, "%d", id); + return buf; +} + +static void corosync_cpg_deliver_callback (cpg_handle_t handle, + const struct cpg_name *groupName, + uint32_t nodeid, + uint32_t pid, + void *msg, + size_t msg_len) +{ + int target_nodeid; + + memcpy(&target_nodeid, msg, COROSYNC_CSID_LEN); + + DEBUGLOG("%u got message from nodeid %d for %d. len %zd\n", + our_nodeid, nodeid, target_nodeid, msg_len-4); + + if (nodeid != our_nodeid) + if (target_nodeid == our_nodeid || target_nodeid == 0) + process_message(cluster_client, (char *)msg+COROSYNC_CSID_LEN, + msg_len-COROSYNC_CSID_LEN, (char*)&nodeid); +} + +static void corosync_cpg_confchg_callback(cpg_handle_t handle, + const struct cpg_name *groupName, + const struct cpg_address *member_list, size_t member_list_entries, + const struct cpg_address *left_list, size_t left_list_entries, + const struct cpg_address *joined_list, size_t joined_list_entries) +{ + int i; + struct node_info *ninfo; + + DEBUGLOG("confchg callback. %zd joined, %zd left, %zd members\n", + joined_list_entries, left_list_entries, member_list_entries); + + for (i=0; i<joined_list_entries; i++) { + ninfo = dm_hash_lookup_binary(node_hash, + (char *)&joined_list[i].nodeid, + COROSYNC_CSID_LEN); + if (!ninfo) { + ninfo = malloc(sizeof(struct node_info)); + if (!ninfo) { + break; + } + else { + ninfo->nodeid = joined_list[i].nodeid; + dm_hash_insert_binary(node_hash, + (char *)&ninfo->nodeid, + COROSYNC_CSID_LEN, ninfo); + } + } + ninfo->state = NODE_CLVMD; + } + + for (i=0; i<left_list_entries; i++) { + ninfo = dm_hash_lookup_binary(node_hash, + (char *)&left_list[i].nodeid, + COROSYNC_CSID_LEN); + if (ninfo) + ninfo->state = NODE_DOWN; + } + + num_nodes = member_list_entries; +} + +static int _init_cluster(void) +{ + cs_error_t err; + +#ifdef QUORUM_SET /* corosync/quorum.h */ + uint32_t quorum_type; +#endif + + node_hash = dm_hash_create(100); + + err = cpg_initialize(&cpg_handle, + &corosync_cpg_callbacks); + if (err != CS_OK) { + syslog(LOG_ERR, "Cannot initialise Corosync CPG service: %d", + err); + DEBUGLOG("Cannot initialise Corosync CPG service: %d", err); + return cs_to_errno(err); + } + +#ifdef QUORUM_SET + err = quorum_initialize(&quorum_handle, + &quorum_callbacks, + &quorum_type); + + if (quorum_type != QUORUM_SET) { + syslog(LOG_ERR, "Corosync quorum service is not configured"); + DEBUGLOG("Corosync quorum service is not configured"); + return EINVAL; + } +#else + err = quorum_initialize(&quorum_handle, + &quorum_callbacks); +#endif + + if (err != CS_OK) { + syslog(LOG_ERR, "Cannot initialise Corosync quorum service: %d", + err); + DEBUGLOG("Cannot initialise Corosync quorum service: %d", err); + return cs_to_errno(err); + } + + /* Create a lockspace for LV & VG locks to live in */ + lockspace = dlm_open_lockspace(LOCKSPACE_NAME); + if (!lockspace) { + lockspace = dlm_create_lockspace(LOCKSPACE_NAME, 0600); + if (!lockspace) { + syslog(LOG_ERR, "Unable to create DLM lockspace for CLVM: %m"); + return -1; + } + DEBUGLOG("Created DLM lockspace for CLVMD.\n"); + } else + DEBUGLOG("Opened existing DLM lockspace for CLVMD.\n"); + + dlm_ls_pthread_init(lockspace); + DEBUGLOG("DLM initialisation complete\n"); + + /* Connect to the clvmd group */ + strcpy((char *)cpg_group_name.value, "clvmd"); + cpg_group_name.length = strlen((char *)cpg_group_name.value); + err = cpg_join(cpg_handle, &cpg_group_name); + if (err != CS_OK) { + cpg_finalize(cpg_handle); + quorum_finalize(quorum_handle); + dlm_release_lockspace(LOCKSPACE_NAME, lockspace, 1); + syslog(LOG_ERR, "Cannot join clvmd process group"); + DEBUGLOG("Cannot join clvmd process group: %d\n", err); + return cs_to_errno(err); + } + + err = cpg_local_get(cpg_handle, + &our_nodeid); + if (err != CS_OK) { + cpg_finalize(cpg_handle); + quorum_finalize(quorum_handle); + dlm_release_lockspace(LOCKSPACE_NAME, lockspace, 1); + syslog(LOG_ERR, "Cannot get local node id\n"); + return cs_to_errno(err); + } + DEBUGLOG("Our local node id is %d\n", our_nodeid); + + DEBUGLOG("Connected to Corosync\n"); + + return 0; +} + +static void _cluster_closedown(void) +{ + dlm_release_lockspace(LOCKSPACE_NAME, lockspace, 1); + cpg_finalize(cpg_handle); + quorum_finalize(quorum_handle); +} + +static void _get_our_csid(char *csid) +{ + memcpy(csid, &our_nodeid, sizeof(int)); +} + +/* Corosync doesn't really have nmode names so we + just use the node ID in hex instead */ +static int _csid_from_name(char *csid, const char *name) +{ + int nodeid; + struct node_info *ninfo; + + if (sscanf(name, "%x", &nodeid) == 1) { + ninfo = dm_hash_lookup_binary(node_hash, csid, COROSYNC_CSID_LEN); + if (ninfo) + return nodeid; + } + return -1; +} + +static int _name_from_csid(const char *csid, char *name) +{ + struct node_info *ninfo; + + ninfo = dm_hash_lookup_binary(node_hash, csid, COROSYNC_CSID_LEN); + if (!ninfo) + { + sprintf(name, "UNKNOWN %s", print_corosync_csid(csid)); + return -1; + } + + sprintf(name, "%x", ninfo->nodeid); + return 0; +} + +static int _get_num_nodes(void) +{ + DEBUGLOG("num_nodes = %d\n", num_nodes); + return num_nodes; +} + +/* Node is now known to be running a clvmd */ +static void _add_up_node(const char *csid) +{ + struct node_info *ninfo; + + ninfo = dm_hash_lookup_binary(node_hash, csid, COROSYNC_CSID_LEN); + if (!ninfo) { + DEBUGLOG("corosync_add_up_node no node_hash entry for csid %s\n", + print_corosync_csid(csid)); + return; + } + + DEBUGLOG("corosync_add_up_node %d\n", ninfo->nodeid); + + ninfo->state = NODE_CLVMD; + + return; +} + +/* Call a callback for each node, so the caller knows whether it's up or down */ +static int _cluster_do_node_callback(struct local_client *master_client, + void (*callback)(struct local_client *, + const char *csid, int node_up)) +{ + struct dm_hash_node *hn; + struct node_info *ninfo; + + dm_hash_iterate(hn, node_hash) + { + char csid[COROSYNC_CSID_LEN]; + + ninfo = dm_hash_get_data(node_hash, hn); + memcpy(csid, dm_hash_get_key(node_hash, hn), COROSYNC_CSID_LEN); + + DEBUGLOG("down_callback. node %d, state = %d\n", ninfo->nodeid, + ninfo->state); + + if (ninfo->state == NODE_CLVMD) + callback(master_client, csid, 1); + } + return 0; +} + +/* Real locking */ +static int _lock_resource(const char *resource, int mode, int flags, int *lockid) +{ + struct dlm_lksb lksb; + int err; + + DEBUGLOG("lock_resource '%s', flags=%d, mode=%d\n", resource, flags, mode); + + if (flags & LKF_CONVERT) + lksb.sb_lkid = *lockid; + + err = dlm_ls_lock_wait(lockspace, + mode, + &lksb, + flags, + resource, + strlen(resource), + 0, + NULL, NULL, NULL); + + if (err != 0) + { + DEBUGLOG("dlm_ls_lock returned %d\n", errno); + return err; + } + if (lksb.sb_status != 0) + { + DEBUGLOG("dlm_ls_lock returns lksb.sb_status %d\n", lksb.sb_status); + errno = lksb.sb_status; + return -1; + } + + DEBUGLOG("lock_resource returning %d, lock_id=%x\n", err, lksb.sb_lkid); + + *lockid = lksb.sb_lkid; + + return 0; +} + + +static int _unlock_resource(const char *resource, int lockid) +{ + struct dlm_lksb lksb; + int err; + + DEBUGLOG("unlock_resource: %s lockid: %x\n", resource, lockid); + lksb.sb_lkid = lockid; + + err = dlm_ls_unlock_wait(lockspace, + lockid, + 0, + &lksb); + if (err != 0) + { + DEBUGLOG("Unlock returned %d\n", err); + return err; + } + if (lksb.sb_status != EUNLOCK) + { + DEBUGLOG("dlm_ls_unlock_wait returns lksb.sb_status: %d\n", lksb.sb_status); + errno = lksb.sb_status; + return -1; + } + + + return 0; +} + +static int _is_quorate(void) +{ + int quorate; + if (quorum_getquorate(quorum_handle, &quorate) == CS_OK) + return quorate; + else + return 0; +} + +static int _get_main_cluster_fd(void) +{ + int select_fd; + + cpg_fd_get(cpg_handle, &select_fd); + return select_fd; +} + +static int _cluster_fd_callback(struct local_client *fd, char *buf, int len, + const char *csid, + struct local_client **new_client) +{ + cluster_client = fd; + *new_client = NULL; + cpg_dispatch(cpg_handle, CS_DISPATCH_ONE); + return 1; +} + +static int _cluster_send_message(const void *buf, int msglen, const char *csid, + const char *errtext) +{ + struct iovec iov[2]; + cs_error_t err; + int target_node; + + if (csid) + memcpy(&target_node, csid, COROSYNC_CSID_LEN); + else + target_node = 0; + + iov[0].iov_base = &target_node; + iov[0].iov_len = sizeof(int); + iov[1].iov_base = (char *)buf; + iov[1].iov_len = msglen; + + err = cpg_mcast_joined(cpg_handle, CPG_TYPE_AGREED, iov, 2); + return cs_to_errno(err); +} + +#ifdef HAVE_COROSYNC_CONFDB_H +/* + * We are not necessarily connected to a Red Hat Cluster system, + * but if we are, this returns the cluster name from cluster.conf. + * I've used confdb rather than ccs to reduce the inter-package + * dependancies as well as to allow people to set a cluster name + * for themselves even if they are not running on RH cluster. + */ +static int _get_cluster_name(char *buf, int buflen) +{ + confdb_handle_t handle; + int result; + size_t namelen = buflen; + hdb_handle_t cluster_handle; + confdb_callbacks_t callbacks = { + .confdb_key_change_notify_fn = NULL, + .confdb_object_create_change_notify_fn = NULL, + .confdb_object_delete_change_notify_fn = NULL + }; + + /* This is a default in case everything else fails */ + strncpy(buf, "Corosync", buflen); + + /* Look for a cluster name in confdb */ + result = confdb_initialize (&handle, &callbacks); + if (result != CS_OK) + return 0; + + result = confdb_object_find_start(handle, OBJECT_PARENT_HANDLE); + if (result != CS_OK) + goto out; + + result = confdb_object_find(handle, OBJECT_PARENT_HANDLE, (void *)"cluster", strlen("cluster"), &cluster_handle); + if (result != CS_OK) + goto out; + + result = confdb_key_get(handle, cluster_handle, (void *)"name", strlen("name"), buf, &namelen); + if (result != CS_OK) + goto out; + + buf[namelen] = '\0'; + +out: + confdb_finalize(handle); + return 0; +} + +#elif defined HAVE_COROSYNC_CMAP_H + +static int _get_cluster_name(char *buf, int buflen) +{ + cmap_handle_t cmap_handle = 0; + int result; + char *name = NULL; + + /* This is a default in case everything else fails */ + strncpy(buf, "Corosync", buflen); + + /* Look for a cluster name in cmap */ + result = cmap_initialize(&cmap_handle); + if (result != CS_OK) + return 0; + + result = cmap_get_string(cmap_handle, "totem.cluster_name", &name); + if (result != CS_OK) + goto out; + + memset(buf, 0, buflen); + strncpy(buf, name, buflen - 1); + +out: + if (name) + free(name); + cmap_finalize(cmap_handle); + return 0; +} + +#endif + +static struct cluster_ops _cluster_corosync_ops = { + .name = "corosync", + .cluster_init_completed = NULL, + .cluster_send_message = _cluster_send_message, + .name_from_csid = _name_from_csid, + .csid_from_name = _csid_from_name, + .get_num_nodes = _get_num_nodes, + .cluster_fd_callback = _cluster_fd_callback, + .get_main_cluster_fd = _get_main_cluster_fd, + .cluster_do_node_callback = _cluster_do_node_callback, + .is_quorate = _is_quorate, + .get_our_csid = _get_our_csid, + .add_up_node = _add_up_node, + .reread_config = NULL, + .cluster_closedown = _cluster_closedown, + .get_cluster_name = _get_cluster_name, + .sync_lock = _lock_resource, + .sync_unlock = _unlock_resource, +}; + +struct cluster_ops *init_corosync_cluster(void) +{ + if (!_init_cluster()) + return &_cluster_corosync_ops; + else + return NULL; +}
diff --git a/daemons/clvmd/clvmd-openais.c b/daemons/clvmd/clvmd-openais.c new file mode 100644 index 0000000..2f1a4fd --- /dev/null +++ b/daemons/clvmd/clvmd-openais.c
@@ -0,0 +1,689 @@ +/* + * Copyright (C) 2007-2009 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * This provides the interface between clvmd and OpenAIS as the cluster + * and lock manager. + */ + +#include "clvmd-common.h" + +#include <pthread.h> +#include <fcntl.h> +#include <syslog.h> + +#include <openais/saAis.h> +#include <openais/saLck.h> + +#include <corosync/corotypes.h> +#include <corosync/cpg.h> + +#include "locking.h" +#include "clvm.h" +#include "clvmd-comms.h" +#include "lvm-functions.h" +#include "clvmd.h" + +/* Timeout value for several openais calls */ +#define TIMEOUT 10 + +static void openais_cpg_deliver_callback (cpg_handle_t handle, + const struct cpg_name *groupName, + uint32_t nodeid, + uint32_t pid, + void *msg, + size_t msg_len); +static void openais_cpg_confchg_callback(cpg_handle_t handle, + const struct cpg_name *groupName, + const struct cpg_address *member_list, size_t member_list_entries, + const struct cpg_address *left_list, size_t left_list_entries, + const struct cpg_address *joined_list, size_t joined_list_entries); + +static void _cluster_closedown(void); + +/* Hash list of nodes in the cluster */ +static struct dm_hash_table *node_hash; + +/* For associating lock IDs & resource handles */ +static struct dm_hash_table *lock_hash; + +/* Number of active nodes */ +static int num_nodes; +static unsigned int our_nodeid; + +static struct local_client *cluster_client; + +/* OpenAIS handles */ +static cpg_handle_t cpg_handle; +static SaLckHandleT lck_handle; + +static struct cpg_name cpg_group_name; + +/* Openais callback structs */ +cpg_callbacks_t openais_cpg_callbacks = { + .cpg_deliver_fn = openais_cpg_deliver_callback, + .cpg_confchg_fn = openais_cpg_confchg_callback, +}; + +struct node_info +{ + enum {NODE_UNKNOWN, NODE_DOWN, NODE_UP, NODE_CLVMD} state; + int nodeid; +}; + +struct lock_info +{ + SaLckResourceHandleT res_handle; + SaLckLockIdT lock_id; + SaNameT lock_name; +}; + +/* Set errno to something approximating the right value and return 0 or -1 */ +static int ais_to_errno(SaAisErrorT err) +{ + switch(err) + { + case SA_AIS_OK: + return 0; + case SA_AIS_ERR_LIBRARY: + errno = EINVAL; + break; + case SA_AIS_ERR_VERSION: + errno = EINVAL; + break; + case SA_AIS_ERR_INIT: + errno = EINVAL; + break; + case SA_AIS_ERR_TIMEOUT: + errno = ETIME; + break; + case SA_AIS_ERR_TRY_AGAIN: + errno = EAGAIN; + break; + case SA_AIS_ERR_INVALID_PARAM: + errno = EINVAL; + break; + case SA_AIS_ERR_NO_MEMORY: + errno = ENOMEM; + break; + case SA_AIS_ERR_BAD_HANDLE: + errno = EINVAL; + break; + case SA_AIS_ERR_BUSY: + errno = EBUSY; + break; + case SA_AIS_ERR_ACCESS: + errno = EPERM; + break; + case SA_AIS_ERR_NOT_EXIST: + errno = ENOENT; + break; + case SA_AIS_ERR_NAME_TOO_LONG: + errno = ENAMETOOLONG; + break; + case SA_AIS_ERR_EXIST: + errno = EEXIST; + break; + case SA_AIS_ERR_NO_SPACE: + errno = ENOSPC; + break; + case SA_AIS_ERR_INTERRUPT: + errno = EINTR; + break; + case SA_AIS_ERR_NAME_NOT_FOUND: + errno = ENOENT; + break; + case SA_AIS_ERR_NO_RESOURCES: + errno = ENOMEM; + break; + case SA_AIS_ERR_NOT_SUPPORTED: + errno = EOPNOTSUPP; + break; + case SA_AIS_ERR_BAD_OPERATION: + errno = EINVAL; + break; + case SA_AIS_ERR_FAILED_OPERATION: + errno = EIO; + break; + case SA_AIS_ERR_MESSAGE_ERROR: + errno = EIO; + break; + case SA_AIS_ERR_QUEUE_FULL: + errno = EXFULL; + break; + case SA_AIS_ERR_QUEUE_NOT_AVAILABLE: + errno = EINVAL; + break; + case SA_AIS_ERR_BAD_FLAGS: + errno = EINVAL; + break; + case SA_AIS_ERR_TOO_BIG: + errno = E2BIG; + break; + case SA_AIS_ERR_NO_SECTIONS: + errno = ENOMEM; + break; + default: + errno = EINVAL; + break; + } + return -1; +} + +static char *print_openais_csid(const char *csid) +{ + static char buf[128]; + int id; + + memcpy(&id, csid, sizeof(int)); + sprintf(buf, "%d", id); + return buf; +} + +static int add_internal_client(int fd, fd_callback_t callback) +{ + struct local_client *client; + + DEBUGLOG("Add_internal_client, fd = %d\n", fd); + + if (!(client = dm_zalloc(sizeof(*client)))) { + DEBUGLOG("malloc failed\n"); + return -1; + } + + client->fd = fd; + client->type = CLUSTER_INTERNAL; + client->callback = callback; + add_client(client); + + /* Set Close-on-exec */ + fcntl(fd, F_SETFD, 1); + + return 0; +} + +static void openais_cpg_deliver_callback (cpg_handle_t handle, + const struct cpg_name *groupName, + uint32_t nodeid, + uint32_t pid, + void *msg, + size_t msg_len) +{ + int target_nodeid; + + memcpy(&target_nodeid, msg, OPENAIS_CSID_LEN); + + DEBUGLOG("%u got message from nodeid %d for %d. len %" PRIsize_t "\n", + our_nodeid, nodeid, target_nodeid, msg_len-4); + + if (nodeid != our_nodeid) + if (target_nodeid == our_nodeid || target_nodeid == 0) + process_message(cluster_client, (char *)msg+OPENAIS_CSID_LEN, + msg_len-OPENAIS_CSID_LEN, (char*)&nodeid); +} + +static void openais_cpg_confchg_callback(cpg_handle_t handle, + const struct cpg_name *groupName, + const struct cpg_address *member_list, size_t member_list_entries, + const struct cpg_address *left_list, size_t left_list_entries, + const struct cpg_address *joined_list, size_t joined_list_entries) +{ + int i; + struct node_info *ninfo; + + DEBUGLOG("confchg callback. %" PRIsize_t " joined, " + FMTsize_t " left, %" PRIsize_t " members\n", + joined_list_entries, left_list_entries, member_list_entries); + + for (i=0; i<joined_list_entries; i++) { + ninfo = dm_hash_lookup_binary(node_hash, + (char *)&joined_list[i].nodeid, + OPENAIS_CSID_LEN); + if (!ninfo) { + ninfo = malloc(sizeof(struct node_info)); + if (!ninfo) { + break; + } + else { + ninfo->nodeid = joined_list[i].nodeid; + dm_hash_insert_binary(node_hash, + (char *)&ninfo->nodeid, + OPENAIS_CSID_LEN, ninfo); + } + } + ninfo->state = NODE_CLVMD; + } + + for (i=0; i<left_list_entries; i++) { + ninfo = dm_hash_lookup_binary(node_hash, + (char *)&left_list[i].nodeid, + OPENAIS_CSID_LEN); + if (ninfo) + ninfo->state = NODE_DOWN; + } + + for (i=0; i<member_list_entries; i++) { + if (member_list[i].nodeid == 0) continue; + ninfo = dm_hash_lookup_binary(node_hash, + (char *)&member_list[i].nodeid, + OPENAIS_CSID_LEN); + if (!ninfo) { + ninfo = malloc(sizeof(struct node_info)); + if (!ninfo) { + break; + } + else { + ninfo->nodeid = member_list[i].nodeid; + dm_hash_insert_binary(node_hash, + (char *)&ninfo->nodeid, + OPENAIS_CSID_LEN, ninfo); + } + } + ninfo->state = NODE_CLVMD; + } + + num_nodes = member_list_entries; +} + +static int lck_dispatch(struct local_client *client, char *buf, int len, + const char *csid, struct local_client **new_client) +{ + *new_client = NULL; + saLckDispatch(lck_handle, SA_DISPATCH_ONE); + return 1; +} + +static int _init_cluster(void) +{ + SaAisErrorT err; + SaVersionT ver = { 'B', 1, 1 }; + int select_fd; + + node_hash = dm_hash_create(100); + lock_hash = dm_hash_create(10); + + err = cpg_initialize(&cpg_handle, + &openais_cpg_callbacks); + if (err != SA_AIS_OK) { + syslog(LOG_ERR, "Cannot initialise OpenAIS CPG service: %d", + err); + DEBUGLOG("Cannot initialise OpenAIS CPG service: %d", err); + return ais_to_errno(err); + } + + err = saLckInitialize(&lck_handle, + NULL, + &ver); + if (err != SA_AIS_OK) { + cpg_initialize(&cpg_handle, &openais_cpg_callbacks); + syslog(LOG_ERR, "Cannot initialise OpenAIS lock service: %d", + err); + DEBUGLOG("Cannot initialise OpenAIS lock service: %d\n\n", err); + return ais_to_errno(err); + } + + /* Connect to the clvmd group */ + strcpy((char *)cpg_group_name.value, "clvmd"); + cpg_group_name.length = strlen((char *)cpg_group_name.value); + err = cpg_join(cpg_handle, &cpg_group_name); + if (err != SA_AIS_OK) { + cpg_finalize(cpg_handle); + saLckFinalize(lck_handle); + syslog(LOG_ERR, "Cannot join clvmd process group"); + DEBUGLOG("Cannot join clvmd process group: %d\n", err); + return ais_to_errno(err); + } + + err = cpg_local_get(cpg_handle, + &our_nodeid); + if (err != SA_AIS_OK) { + cpg_finalize(cpg_handle); + saLckFinalize(lck_handle); + syslog(LOG_ERR, "Cannot get local node id\n"); + return ais_to_errno(err); + } + DEBUGLOG("Our local node id is %d\n", our_nodeid); + + saLckSelectionObjectGet(lck_handle, (SaSelectionObjectT *)&select_fd); + add_internal_client(select_fd, lck_dispatch); + + DEBUGLOG("Connected to OpenAIS\n"); + + return 0; +} + +static void _cluster_closedown(void) +{ + saLckFinalize(lck_handle); + cpg_finalize(cpg_handle); +} + +static void _get_our_csid(char *csid) +{ + memcpy(csid, &our_nodeid, sizeof(int)); +} + +/* OpenAIS doesn't really have nmode names so we + just use the node ID in hex instead */ +static int _csid_from_name(char *csid, const char *name) +{ + int nodeid; + struct node_info *ninfo; + + if (sscanf(name, "%x", &nodeid) == 1) { + ninfo = dm_hash_lookup_binary(node_hash, csid, OPENAIS_CSID_LEN); + if (ninfo) + return nodeid; + } + return -1; +} + +static int _name_from_csid(const char *csid, char *name) +{ + struct node_info *ninfo; + + ninfo = dm_hash_lookup_binary(node_hash, csid, OPENAIS_CSID_LEN); + if (!ninfo) + { + sprintf(name, "UNKNOWN %s", print_openais_csid(csid)); + return -1; + } + + sprintf(name, "%x", ninfo->nodeid); + return 0; +} + +static int _get_num_nodes() +{ + DEBUGLOG("num_nodes = %d\n", num_nodes); + return num_nodes; +} + +/* Node is now known to be running a clvmd */ +static void _add_up_node(const char *csid) +{ + struct node_info *ninfo; + + ninfo = dm_hash_lookup_binary(node_hash, csid, OPENAIS_CSID_LEN); + if (!ninfo) { + DEBUGLOG("openais_add_up_node no node_hash entry for csid %s\n", + print_openais_csid(csid)); + return; + } + + DEBUGLOG("openais_add_up_node %d\n", ninfo->nodeid); + + ninfo->state = NODE_CLVMD; + + return; +} + +/* Call a callback for each node, so the caller knows whether it's up or down */ +static int _cluster_do_node_callback(struct local_client *master_client, + void (*callback)(struct local_client *, + const char *csid, int node_up)) +{ + struct dm_hash_node *hn; + struct node_info *ninfo; + int somedown = 0; + + dm_hash_iterate(hn, node_hash) + { + char csid[OPENAIS_CSID_LEN]; + + ninfo = dm_hash_get_data(node_hash, hn); + memcpy(csid, dm_hash_get_key(node_hash, hn), OPENAIS_CSID_LEN); + + DEBUGLOG("down_callback. node %d, state = %d\n", ninfo->nodeid, + ninfo->state); + + if (ninfo->state != NODE_DOWN) + callback(master_client, csid, ninfo->state == NODE_CLVMD); + if (ninfo->state != NODE_CLVMD) + somedown = -1; + } + return somedown; +} + +/* Real locking */ +static int _lock_resource(char *resource, int mode, int flags, int *lockid) +{ + struct lock_info *linfo; + SaLckResourceHandleT res_handle; + SaAisErrorT err; + SaLckLockIdT lock_id; + SaLckLockStatusT lockStatus; + + /* This needs to be converted from DLM/LVM2 value for OpenAIS LCK */ + if (flags & LCK_NONBLOCK) flags = SA_LCK_LOCK_NO_QUEUE; + + linfo = malloc(sizeof(struct lock_info)); + if (!linfo) + return -1; + + DEBUGLOG("lock_resource '%s', flags=%d, mode=%d\n", resource, flags, mode); + + linfo->lock_name.length = strlen(resource)+1; + strcpy((char *)linfo->lock_name.value, resource); + + err = saLckResourceOpen(lck_handle, &linfo->lock_name, + SA_LCK_RESOURCE_CREATE, TIMEOUT, &res_handle); + if (err != SA_AIS_OK) + { + DEBUGLOG("ResourceOpen returned %d\n", err); + free(linfo); + return ais_to_errno(err); + } + + err = saLckResourceLock( + res_handle, + &lock_id, + mode, + flags, + 0, + SA_TIME_END, + &lockStatus); + if (err != SA_AIS_OK && lockStatus != SA_LCK_LOCK_GRANTED) + { + free(linfo); + saLckResourceClose(res_handle); + return ais_to_errno(err); + } + + /* Wait for it to complete */ + + DEBUGLOG("lock_resource returning %d, lock_id=%" PRIx64 "\n", + err, lock_id); + + linfo->lock_id = lock_id; + linfo->res_handle = res_handle; + + dm_hash_insert(lock_hash, resource, linfo); + + return ais_to_errno(err); +} + + +static int _unlock_resource(char *resource, int lockid) +{ + SaAisErrorT err; + struct lock_info *linfo; + + DEBUGLOG("unlock_resource %s\n", resource); + linfo = dm_hash_lookup(lock_hash, resource); + if (!linfo) + return 0; + + DEBUGLOG("unlock_resource: lockid: %" PRIx64 "\n", linfo->lock_id); + err = saLckResourceUnlock(linfo->lock_id, SA_TIME_END); + if (err != SA_AIS_OK) + { + DEBUGLOG("Unlock returned %d\n", err); + return ais_to_errno(err); + } + + /* Release the resource */ + dm_hash_remove(lock_hash, resource); + saLckResourceClose(linfo->res_handle); + free(linfo); + + return ais_to_errno(err); +} + +static int _sync_lock(const char *resource, int mode, int flags, int *lockid) +{ + int status; + char lock1[strlen(resource)+3]; + char lock2[strlen(resource)+3]; + + snprintf(lock1, sizeof(lock1), "%s-1", resource); + snprintf(lock2, sizeof(lock2), "%s-2", resource); + + switch (mode) + { + case LCK_EXCL: + status = _lock_resource(lock1, SA_LCK_EX_LOCK_MODE, flags, lockid); + if (status) + goto out; + + /* If we can't get this lock too then bail out */ + status = _lock_resource(lock2, SA_LCK_EX_LOCK_MODE, LCK_NONBLOCK, + lockid); + if (status == SA_LCK_LOCK_NOT_QUEUED) + { + _unlock_resource(lock1, *lockid); + status = -1; + errno = EAGAIN; + } + break; + + case LCK_PREAD: + case LCK_READ: + status = _lock_resource(lock1, SA_LCK_PR_LOCK_MODE, flags, lockid); + if (status) + goto out; + _unlock_resource(lock2, *lockid); + break; + + case LCK_WRITE: + status = _lock_resource(lock2, SA_LCK_EX_LOCK_MODE, flags, lockid); + if (status) + goto out; + _unlock_resource(lock1, *lockid); + break; + + default: + status = -1; + errno = EINVAL; + break; + } +out: + *lockid = mode; + return status; +} + +static int _sync_unlock(const char *resource, int lockid) +{ + int status = 0; + char lock1[strlen(resource)+3]; + char lock2[strlen(resource)+3]; + + snprintf(lock1, sizeof(lock1), "%s-1", resource); + snprintf(lock2, sizeof(lock2), "%s-2", resource); + + _unlock_resource(lock1, lockid); + _unlock_resource(lock2, lockid); + + return status; +} + +/* We are always quorate ! */ +static int _is_quorate() +{ + return 1; +} + +static int _get_main_cluster_fd(void) +{ + int select_fd; + + cpg_fd_get(cpg_handle, &select_fd); + return select_fd; +} + +static int _cluster_fd_callback(struct local_client *fd, char *buf, int len, + const char *csid, + struct local_client **new_client) +{ + cluster_client = fd; + *new_client = NULL; + cpg_dispatch(cpg_handle, SA_DISPATCH_ONE); + return 1; +} + +static int _cluster_send_message(const void *buf, int msglen, const char *csid, + const char *errtext) +{ + struct iovec iov[2]; + SaAisErrorT err; + int target_node; + + if (csid) + memcpy(&target_node, csid, OPENAIS_CSID_LEN); + else + target_node = 0; + + iov[0].iov_base = &target_node; + iov[0].iov_len = sizeof(int); + iov[1].iov_base = (char *)buf; + iov[1].iov_len = msglen; + + err = cpg_mcast_joined(cpg_handle, CPG_TYPE_AGREED, iov, 2); + return ais_to_errno(err); +} + +/* We don't have a cluster name to report here */ +static int _get_cluster_name(char *buf, int buflen) +{ + strncpy(buf, "OpenAIS", buflen); + return 0; +} + +static struct cluster_ops _cluster_openais_ops = { + .name = "openais", + .cluster_init_completed = NULL, + .cluster_send_message = _cluster_send_message, + .name_from_csid = _name_from_csid, + .csid_from_name = _csid_from_name, + .get_num_nodes = _get_num_nodes, + .cluster_fd_callback = _cluster_fd_callback, + .get_main_cluster_fd = _get_main_cluster_fd, + .cluster_do_node_callback = _cluster_do_node_callback, + .is_quorate = _is_quorate, + .get_our_csid = _get_our_csid, + .add_up_node = _add_up_node, + .reread_config = NULL, + .cluster_closedown = _cluster_closedown, + .get_cluster_name = _get_cluster_name, + .sync_lock = _sync_lock, + .sync_unlock = _sync_unlock, +}; + +struct cluster_ops *init_openais_cluster(void) +{ + if (!_init_cluster()) + return &_cluster_openais_ops; + + return NULL; +}
diff --git a/daemons/clvmd/clvmd-singlenode.c b/daemons/clvmd/clvmd-singlenode.c new file mode 100644 index 0000000..af0a544 --- /dev/null +++ b/daemons/clvmd/clvmd-singlenode.c
@@ -0,0 +1,382 @@ +/* + * Copyright (C) 2009-2013 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "clvmd-common.h" + +#include <pthread.h> + +#include "locking.h" +#include "clvm.h" +#include "clvmd-comms.h" +#include "clvmd.h" + +#include <sys/un.h> +#include <sys/socket.h> +#include <fcntl.h> + +static const char SINGLENODE_CLVMD_SOCKNAME[] = DEFAULT_RUN_DIR "/clvmd_singlenode.sock"; +static int listen_fd = -1; + +static struct dm_hash_table *_locks; +static int _lockid; + +static pthread_mutex_t _lock_mutex = PTHREAD_MUTEX_INITIALIZER; +/* Using one common condition for all locks for simplicity */ +static pthread_cond_t _lock_cond = PTHREAD_COND_INITIALIZER; + +struct lock { + struct dm_list list; + int lockid; + int mode; +}; + +static void close_comms(void) +{ + if (listen_fd != -1 && close(listen_fd)) + stack; + (void)unlink(SINGLENODE_CLVMD_SOCKNAME); + listen_fd = -1; +} + +static int init_comms(void) +{ + mode_t old_mask; + struct sockaddr_un addr = { .sun_family = AF_UNIX }; + + if (!dm_strncpy(addr.sun_path, SINGLENODE_CLVMD_SOCKNAME, + sizeof(addr.sun_path))) { + DEBUGLOG("%s: singlenode socket name too long.", + SINGLENODE_CLVMD_SOCKNAME); + return -1; + } + + close_comms(); + + (void) dm_prepare_selinux_context(SINGLENODE_CLVMD_SOCKNAME, S_IFSOCK); + old_mask = umask(0077); + + listen_fd = socket(PF_UNIX, SOCK_STREAM, 0); + if (listen_fd < 0) { + DEBUGLOG("Can't create local socket: %s\n", strerror(errno)); + goto error; + } + /* Set Close-on-exec */ + if (fcntl(listen_fd, F_SETFD, 1)) { + DEBUGLOG("Setting CLOEXEC on client fd failed: %s\n", strerror(errno)); + goto error; + } + + if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + DEBUGLOG("Can't bind local socket: %s\n", strerror(errno)); + goto error; + } + if (listen(listen_fd, 10) < 0) { + DEBUGLOG("Can't listen local socket: %s\n", strerror(errno)); + goto error; + } + + umask(old_mask); + (void) dm_prepare_selinux_context(NULL, 0); + return 0; +error: + umask(old_mask); + (void) dm_prepare_selinux_context(NULL, 0); + close_comms(); + return -1; +} + +static int _init_cluster(void) +{ + int r; + + if (!(_locks = dm_hash_create(128))) { + DEBUGLOG("Failed to allocate single-node hash table.\n"); + return 1; + } + + r = init_comms(); + if (r) { + dm_hash_destroy(_locks); + _locks = NULL; + return r; + } + + DEBUGLOG("Single-node cluster initialised.\n"); + return 0; +} + +static void _cluster_closedown(void) +{ + close_comms(); + + /* If there is any awaited resource, kill it softly */ + pthread_mutex_lock(&_lock_mutex); + dm_hash_destroy(_locks); + _locks = NULL; + _lockid = 0; + pthread_cond_broadcast(&_lock_cond); /* wakeup waiters */ + pthread_mutex_unlock(&_lock_mutex); +} + +static void _get_our_csid(char *csid) +{ + int nodeid = 1; + memcpy(csid, &nodeid, sizeof(int)); +} + +static int _csid_from_name(char *csid, const char *name) +{ + return 1; +} + +static int _name_from_csid(const char *csid, char *name) +{ + strcpy(name, "SINGLENODE"); + return 0; +} + +static int _get_num_nodes(void) +{ + return 1; +} + +/* Node is now known to be running a clvmd */ +static void _add_up_node(const char *csid) +{ +} + +/* Call a callback for each node, so the caller knows whether it's up or down */ +static int _cluster_do_node_callback(struct local_client *master_client, + void (*callback)(struct local_client *, + const char *csid, int node_up)) +{ + return 0; +} + +int _lock_file(const char *file, uint32_t flags); + +static const char *_get_mode(int mode) +{ + switch (mode) { + case LCK_NULL: return "NULL"; + case LCK_READ: return "READ"; + case LCK_PREAD: return "PREAD"; + case LCK_WRITE: return "WRITE"; + case LCK_EXCL: return "EXCLUSIVE"; + case LCK_UNLOCK: return "UNLOCK"; + default: return "????"; + } +} + +/* Real locking */ +static int _lock_resource(const char *resource, int mode, int flags, int *lockid) +{ + /* DLM table of allowed transition states */ + static const int _dlm_table[6][6] = { + /* Mode NL CR CW PR PW EX */ + /* NL */ { 1, 1, 1, 1, 1, 1}, + /* CR */ { 1, 1, 1, 1, 1, 0}, + /* CW */ { 1, 1, 1, 0, 0, 0}, + /* PR */ { 1, 1, 0, 1, 0, 0}, + /* PW */ { 1, 1, 0, 0, 0, 0}, + /* EX */ { 1, 0, 0, 0, 0, 0} + }; + + struct lock *lck = NULL, *lckt; + struct dm_list *head; + + DEBUGLOG("Locking resource %s, flags=0x%02x (%s%s%s), mode=%s (%d)\n", + resource, flags, + (flags & LCKF_NOQUEUE) ? "NOQUEUE" : "", + ((flags & (LCKF_NOQUEUE | LCKF_CONVERT)) == + (LCKF_NOQUEUE | LCKF_CONVERT)) ? "|" : "", + (flags & LCKF_CONVERT) ? "CONVERT" : "", + _get_mode(mode), mode); + + mode &= LCK_TYPE_MASK; + pthread_mutex_lock(&_lock_mutex); + +retry: + if (!(head = dm_hash_lookup(_locks, resource))) { + if (flags & LCKF_CONVERT) { + /* In real DLM, lock is identified only by lockid, resource is not used */ + DEBUGLOG("Unlocked resource %s cannot be converted\n", resource); + goto_bad; + } + /* Add new locked resource */ + if (!(head = dm_malloc(sizeof(struct dm_list))) || + !dm_hash_insert(_locks, resource, head)) { + dm_free(head); + goto_bad; + } + + dm_list_init(head); + } else /* Update/convert locked resource */ + dm_list_iterate_items(lck, head) { + /* Check is all locks are compatible with requested lock */ + if (flags & LCKF_CONVERT) { + if (lck->lockid != *lockid) + continue; + + DEBUGLOG("Converting resource %s lockid=%d mode:%s -> %s...\n", + resource, lck->lockid, _get_mode(lck->mode), _get_mode(mode)); + dm_list_iterate_items(lckt, head) { + if ((lckt->lockid != *lockid) && + !_dlm_table[mode][lckt->mode]) { + if (!(flags & LCKF_NOQUEUE) && + /* TODO: Real dlm uses here conversion queues */ + !pthread_cond_wait(&_lock_cond, &_lock_mutex) && + _locks) /* End of the game? */ + goto retry; + goto bad; + } + } + lck->mode = mode; /* Lock is now converted */ + goto out; + } else if (!_dlm_table[mode][lck->mode]) { + DEBUGLOG("Resource %s already locked lockid=%d, mode:%s\n", + resource, lck->lockid, _get_mode(lck->mode)); + if (!(flags & LCKF_NOQUEUE) && + !pthread_cond_wait(&_lock_cond, &_lock_mutex) && + _locks) { /* End of the game? */ + DEBUGLOG("Resource %s retrying lock in mode:%s...\n", + resource, _get_mode(mode)); + goto retry; + } + goto bad; + } + } + + if (!(flags & LCKF_CONVERT)) { + if (!(lck = dm_malloc(sizeof(struct lock)))) + goto_bad; + + *lockid = lck->lockid = ++_lockid; + lck->mode = mode; + dm_list_add(head, &lck->list); + } +out: + pthread_cond_broadcast(&_lock_cond); /* to wakeup waiters */ + pthread_mutex_unlock(&_lock_mutex); + DEBUGLOG("Locked resource %s, lockid=%d, mode=%s\n", + resource, lck->lockid, _get_mode(lck->mode)); + + return 0; +bad: + pthread_cond_broadcast(&_lock_cond); /* to wakeup waiters */ + pthread_mutex_unlock(&_lock_mutex); + DEBUGLOG("Failed to lock resource %s\n", resource); + + return 1; /* fail */ +} + +static int _unlock_resource(const char *resource, int lockid) +{ + struct lock *lck; + struct dm_list *head; + int r = 1; + + if (lockid < 0) { + DEBUGLOG("Not tracking unlock of lockid -1: %s, lockid=%d\n", + resource, lockid); + return 1; + } + + DEBUGLOG("Unlocking resource %s, lockid=%d\n", resource, lockid); + pthread_mutex_lock(&_lock_mutex); + pthread_cond_broadcast(&_lock_cond); /* wakeup waiters */ + + if (!(head = dm_hash_lookup(_locks, resource))) { + pthread_mutex_unlock(&_lock_mutex); + DEBUGLOG("Resource %s is not locked.\n", resource); + return 1; + } + + dm_list_iterate_items(lck, head) + if (lck->lockid == lockid) { + dm_list_del(&lck->list); + dm_free(lck); + r = 0; + goto out; + } + + DEBUGLOG("Resource %s has wrong lockid %d.\n", resource, lockid); +out: + if (dm_list_empty(head)) { + //DEBUGLOG("Resource %s is no longer hashed (lockid=%d).\n", resource, lockid); + dm_hash_remove(_locks, resource); + dm_free(head); + } + + pthread_mutex_unlock(&_lock_mutex); + + return r; +} + +static int _is_quorate(void) +{ + return 1; +} + +static int _get_main_cluster_fd(void) +{ + return listen_fd; +} + +static int _cluster_fd_callback(struct local_client *fd, char *buf, int len, + const char *csid, + struct local_client **new_client) +{ + return 1; +} + +static int _cluster_send_message(const void *buf, int msglen, + const char *csid, + const char *errtext) +{ + return 0; +} + +static int _get_cluster_name(char *buf, int buflen) +{ + return dm_strncpy(buf, "localcluster", buflen) ? 0 : 1; +} + +static struct cluster_ops _cluster_singlenode_ops = { + .name = "singlenode", + .cluster_init_completed = NULL, + .cluster_send_message = _cluster_send_message, + .name_from_csid = _name_from_csid, + .csid_from_name = _csid_from_name, + .get_num_nodes = _get_num_nodes, + .cluster_fd_callback = _cluster_fd_callback, + .get_main_cluster_fd = _get_main_cluster_fd, + .cluster_do_node_callback = _cluster_do_node_callback, + .is_quorate = _is_quorate, + .get_our_csid = _get_our_csid, + .add_up_node = _add_up_node, + .reread_config = NULL, + .cluster_closedown = _cluster_closedown, + .get_cluster_name = _get_cluster_name, + .sync_lock = _lock_resource, + .sync_unlock = _unlock_resource, +}; + +struct cluster_ops *init_singlenode_cluster(void) +{ + if (!_init_cluster()) + return &_cluster_singlenode_ops; + + return NULL; +}
diff --git a/daemons/clvmd/clvmd.c b/daemons/clvmd/clvmd.c new file mode 100644 index 0000000..a276c63 --- /dev/null +++ b/daemons/clvmd/clvmd.c
@@ -0,0 +1,2381 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2014 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * CLVMD: Cluster LVM daemon + */ + +#include "clvmd-common.h" + +#include "clvmd-comms.h" +#include "clvm.h" +#include "clvmd.h" +#include "lvm-functions.h" +#include "lvm-version.h" +#include "refresh_clvmd.h" + +#ifdef HAVE_COROSYNC_CONFDB_H +#include <corosync/confdb.h> +#endif + +#include <pthread.h> +#include <getopt.h> +#include <ctype.h> +#include <stdarg.h> + +#include <fcntl.h> +#include <netinet/in.h> +#include <signal.h> +#include <stddef.h> +#include <syslog.h> +#include <sys/un.h> +#include <sys/utsname.h> + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif + +#define MAX_RETRIES 4 +#define MAX_MISSING_LEN 8000 /* Max supported clvmd message size ? */ + +#define ISLOCAL_CSID(c) (memcmp(c, our_csid, max_csid_len) == 0) + +/* Head of the fd list. Also contains + the cluster_socket details */ +static struct local_client local_client_head; + +static unsigned short global_xid = 0; /* Last transaction ID issued */ + +struct cluster_ops *clops = NULL; + +static char our_csid[MAX_CSID_LEN]; +static unsigned max_csid_len; +static unsigned max_cluster_message; +static unsigned max_cluster_member_name_len; + +/* Structure of items on the LVM thread list */ +struct lvm_thread_cmd { + struct dm_list list; + + struct local_client *client; + struct clvm_header *msg; + char csid[MAX_CSID_LEN]; + int remote; /* Flag */ + int msglen; + unsigned short xid; +}; + +struct lvm_startup_params { + struct dm_hash_table *excl_uuid; +}; + +static debug_t debug = DEBUG_OFF; +static int foreground_mode = 0; +static pthread_t lvm_thread; +/* Stack size 128KiB for thread, must be bigger then DEFAULT_RESERVED_STACK */ +static const size_t STACK_SIZE = 128 * 1024; +static pthread_attr_t stack_attr; +static int lvm_thread_exit = 0; +static pthread_mutex_t lvm_thread_mutex; +static pthread_cond_t lvm_thread_cond; +static pthread_barrier_t lvm_start_barrier; +static struct dm_list lvm_cmd_head; +static volatile sig_atomic_t quit = 0; +static volatile sig_atomic_t reread_config = 0; +static int child_pipe[2]; + +/* Reasons the daemon failed initialisation */ +#define DFAIL_INIT 1 +#define DFAIL_LOCAL_SOCK 2 +#define DFAIL_CLUSTER_IF 3 +#define DFAIL_MALLOC 4 +#define DFAIL_TIMEOUT 5 +#define SUCCESS 0 + +typedef enum {IF_AUTO, IF_CMAN, IF_OPENAIS, IF_COROSYNC, IF_SINGLENODE} if_type_t; + +/* Prototypes for code further down */ +static void sigusr2_handler(int sig); +static void sighup_handler(int sig); +static void sigterm_handler(int sig); +static void send_local_reply(struct local_client *client, int status, + int clientid); +static void free_reply(struct local_client *client); +static void send_version_message(void); +static void *pre_and_post_thread(void *arg); +static int send_message(void *buf, int msglen, const char *csid, int fd, + const char *errtext); +static int read_from_local_sock(struct local_client *thisfd); +static int cleanup_zombie(struct local_client *thisfd); +static int process_local_command(struct clvm_header *msg, int msglen, + struct local_client *client, + unsigned short xid); +static void process_remote_command(struct clvm_header *msg, int msglen, int fd, + const char *csid); +static int process_reply(const struct clvm_header *msg, int msglen, + const char *csid); +static int open_local_sock(void); +static void close_local_sock(int local_socket); +static int check_local_clvmd(void); +static struct local_client *find_client(int clientid); +static void main_loop(int cmd_timeout); +static void be_daemon(int start_timeout); +static int check_all_clvmds_running(struct local_client *client); +static int local_rendezvous_callback(struct local_client *thisfd, char *buf, + int len, const char *csid, + struct local_client **new_client); +static void *lvm_thread_fn(void *) __attribute__((noreturn)); +static int add_to_lvmqueue(struct local_client *client, struct clvm_header *msg, + int msglen, const char *csid); +static int distribute_command(struct local_client *thisfd); +static void hton_clvm(struct clvm_header *hdr); +static void ntoh_clvm(struct clvm_header *hdr); +static void add_reply_to_list(struct local_client *client, int status, + const char *csid, const char *buf, int len); +static if_type_t parse_cluster_interface(char *ifname); +static if_type_t get_cluster_type(void); + +static void usage(const char *prog, FILE *file) +{ + fprintf(file, "Usage: %s [options]\n" + " -C Sets debug level (from -d) on all clvmd instances clusterwide\n" + " -d[<n>] Set debug logging (0:none, 1:stderr (implies -f option), 2:syslog)\n" + " -E<uuid> Take this lock uuid as exclusively locked resource (for restart)\n" + " -f Don't fork, run in the foreground\n" + " -h Show this help information\n" + " -I<cmgr> Cluster manager (default: auto)\n" + " Available cluster managers: " +#ifdef USE_COROSYNC + "corosync " +#endif +#ifdef USE_CMAN + "cman " +#endif +#ifdef USE_OPENAIS + "openais " +#endif +#ifdef USE_SINGLENODE + "singlenode " +#endif + "\n" + " -R Tell all running clvmds in the cluster to reload their device cache\n" + " -S Restart clvmd, preserving exclusive locks\n" + " -t<secs> Command timeout (default: 60 seconds)\n" + " -T<secs> Startup timeout (default: 0 seconds)\n" + " -V Show version of clvmd\n" + "\n", prog); +} + +/* Called to signal the parent how well we got on during initialisation */ +static void child_init_signal(int status) +{ + if (child_pipe[1]) { + /* FIXME Use a proper wrapper around write */ + if (write(child_pipe[1], &status, sizeof(status)) < 0) + log_sys_error("write", "child_pipe"); + if (close(child_pipe[1])) + log_sys_error("close", "child_pipe"); + } +} + +static __attribute__((noreturn)) void child_init_signal_and_exit(int status) +{ + child_init_signal(status); + exit(status); +} + +static void safe_close(int *fd) +{ + if (*fd >= 0) { + int to_close = *fd; + *fd = -1; + if (close(to_close)) + log_sys_error("close", ""); /* path */ + } +} + +void debuglog(const char *fmt, ...) +{ + time_t P; + va_list ap; + static int syslog_init = 0; + char buf_ctime[64]; + + switch (clvmd_get_debug()) { + case DEBUG_STDERR: + va_start(ap,fmt); + time(&P); + fprintf(stderr, "CLVMD[%x]: %.15s ", (int)pthread_self(), ctime_r(&P, buf_ctime) + 4); + vfprintf(stderr, fmt, ap); + va_end(ap); + fflush(stderr); + break; + case DEBUG_SYSLOG: + if (!syslog_init) { + openlog("clvmd", LOG_PID, LOG_DAEMON); + syslog_init = 1; + } + + va_start(ap,fmt); + vsyslog(LOG_DEBUG, fmt, ap); + va_end(ap); + break; + case DEBUG_OFF: + break; + } +} + +void clvmd_set_debug(debug_t new_debug) +{ + if (!foreground_mode && new_debug == DEBUG_STDERR) + new_debug = DEBUG_SYSLOG; + + if (new_debug > DEBUG_SYSLOG) + new_debug = DEBUG_SYSLOG; + + debug = new_debug; +} + +debug_t clvmd_get_debug(void) +{ + return debug; +} + +int clvmd_get_foreground(void) +{ + return foreground_mode; +} + +static const char *decode_cmd(unsigned char cmdl) +{ + static char buf[128]; + const char *command; + + switch (cmdl) { + case CLVMD_CMD_TEST: + command = "TEST"; + break; + case CLVMD_CMD_LOCK_VG: + command = "LOCK_VG"; + break; + case CLVMD_CMD_LOCK_LV: + command = "LOCK_LV"; + break; + case CLVMD_CMD_REFRESH: + command = "REFRESH"; + break; + case CLVMD_CMD_SET_DEBUG: + command = "SET_DEBUG"; + break; + case CLVMD_CMD_GET_CLUSTERNAME: + command = "GET_CLUSTERNAME"; + break; + case CLVMD_CMD_VG_BACKUP: + command = "VG_BACKUP"; + break; + case CLVMD_CMD_REPLY: + command = "REPLY"; + break; + case CLVMD_CMD_VERSION: + command = "VERSION"; + break; + case CLVMD_CMD_GOAWAY: + command = "GOAWAY"; + break; + case CLVMD_CMD_LOCK: + command = "LOCK"; + break; + case CLVMD_CMD_UNLOCK: + command = "UNLOCK"; + break; + case CLVMD_CMD_LOCK_QUERY: + command = "LOCK_QUERY"; + break; + case CLVMD_CMD_RESTART: + command = "RESTART"; + break; + case CLVMD_CMD_SYNC_NAMES: + command = "SYNC_NAMES"; + break; + default: + command = "unknown"; + break; + } + + snprintf(buf, sizeof(buf), "%s (0x%x)", command, cmdl); + + return buf; +} + +static void remove_lockfile(void) +{ + if (unlink(CLVMD_PIDFILE)) + log_sys_error("unlink", CLVMD_PIDFILE); +} + +/* + * clvmd require dm-ioctl capability for operation + */ +static void check_permissions(void) +{ + if (getuid() || geteuid()) { + log_error("Cannot run as a non-root user."); + + /* + * Fail cleanly here if not run as root, instead of failing + * later when attempting a root-only operation + * Preferred exit code from an initscript for this. + */ + exit(4); + } +} + +int main(int argc, char *argv[]) +{ + int local_sock; + struct local_client *newfd, *delfd; + struct lvm_startup_params lvm_params; + int opt; + int cmd_timeout = DEFAULT_CMD_TIMEOUT; + int start_timeout = 0; + if_type_t cluster_iface = IF_AUTO; + sigset_t ss; + debug_t debug_opt = DEBUG_OFF; + debug_t debug_arg = DEBUG_OFF; + int clusterwide_opt = 0; + mode_t old_mask; + int ret = 1; + + struct option longopts[] = { + { "help", 0, 0, 'h' }, + { NULL, 0, 0, 0 } + }; + + if (!(lvm_params.excl_uuid = dm_hash_create(128))) { + fprintf(stderr, "Failed to allocate hash table\n"); + return 1; + } + + /* Deal with command-line arguments */ + opterr = 0; + optind = 0; + while ((opt = getopt_long(argc, argv, "Vhfd:t:RST:CI:E:", + longopts, NULL)) != -1) { + switch (opt) { + case 'h': + usage(argv[0], stdout); + exit(0); + + case 'R': + check_permissions(); + ret = (refresh_clvmd(1) == 1) ? 0 : 1; + goto out; + + case 'S': + check_permissions(); + ret = (restart_clvmd(clusterwide_opt) == 1) ? 0 : 1; + goto out; + + case 'C': + clusterwide_opt = 1; + break; + + case 'd': + debug_opt = DEBUG_STDERR; + debug_arg = (debug_t) atoi(optarg); + if (debug_arg == DEBUG_STDERR) + foreground_mode = 1; + break; + + case 'f': + foreground_mode = 1; + break; + case 't': + cmd_timeout = atoi(optarg); + if (!cmd_timeout) { + fprintf(stderr, "command timeout is invalid\n"); + usage(argv[0], stderr); + exit(1); + } + break; + case 'I': + cluster_iface = parse_cluster_interface(optarg); + break; + case 'E': + if (!dm_hash_insert(lvm_params.excl_uuid, optarg, optarg)) { + fprintf(stderr, "Failed to allocate hash entry\n"); + goto out; + } + break; + case 'T': + start_timeout = atoi(optarg); + if (start_timeout <= 0) { + fprintf(stderr, "startup timeout is invalid\n"); + usage(argv[0], stderr); + exit(1); + } + break; + + case 'V': + printf("Cluster LVM daemon version: %s\n", LVM_VERSION); + printf("Protocol version: %d.%d.%d\n", + CLVMD_MAJOR_VERSION, CLVMD_MINOR_VERSION, + CLVMD_PATCH_VERSION); + exit(0); + break; + + default: + usage(argv[0], stderr); + exit(2); + } + } + + check_permissions(); + + /* + * Switch to C locale to avoid reading large locale-archive file + * used by some glibc (on some distributions it takes over 100MB). + * Daemon currently needs to use mlockall(). + */ + if (setenv("LC_ALL", "C", 1)) + perror("Cannot set LC_ALL to C"); + + /* Setting debug options on an existing clvmd */ + if (debug_opt && !check_local_clvmd()) { + dm_hash_destroy(lvm_params.excl_uuid); + return debug_clvmd(debug_arg, clusterwide_opt)==1?0:1; + } + + clvmd_set_debug(debug_arg); + + /* Fork into the background (unless requested not to) */ + if (!foreground_mode) + be_daemon(start_timeout); + + (void) dm_prepare_selinux_context(DEFAULT_RUN_DIR, S_IFDIR); + old_mask = umask(0077); + if (dm_create_dir(DEFAULT_RUN_DIR) == 0) { + DEBUGLOG("clvmd: unable to create %s directory\n", + DEFAULT_RUN_DIR); + umask(old_mask); + exit(1); + } + umask(old_mask); + + /* Create pidfile */ + (void) dm_prepare_selinux_context(CLVMD_PIDFILE, S_IFREG); + if (dm_create_lockfile(CLVMD_PIDFILE) == 0) { + DEBUGLOG("clvmd: unable to create lockfile\n"); + exit(1); + } + (void) dm_prepare_selinux_context(NULL, 0); + + atexit(remove_lockfile); + + DEBUGLOG("CLVMD started\n"); + + /* Open the Unix socket we listen for commands on. + We do this before opening the cluster socket so that + potential clients will block rather than error if we are running + but the cluster is not ready yet */ + local_sock = open_local_sock(); + if (local_sock < 0) { + child_init_signal_and_exit(DFAIL_LOCAL_SOCK); + /* NOTREACHED */ + } + + /* Set up signal handlers, USR1 is for cluster change notifications (in cman) + USR2 causes child threads to exit. + (HUP used to cause gulm to re-read the nodes list from CCS.) + PIPE should be ignored */ + signal(SIGUSR2, sigusr2_handler); + signal(SIGHUP, sighup_handler); + signal(SIGPIPE, SIG_IGN); + + /* Block SIGUSR2/SIGINT/SIGTERM in process */ + sigemptyset(&ss); + sigaddset(&ss, SIGUSR2); + sigaddset(&ss, SIGINT); + sigaddset(&ss, SIGTERM); + sigprocmask(SIG_BLOCK, &ss, NULL); + + /* Initialise the LVM thread variables */ + dm_list_init(&lvm_cmd_head); + if (pthread_attr_init(&stack_attr) || + pthread_attr_setstacksize(&stack_attr, STACK_SIZE)) { + log_sys_error("pthread_attr_init", ""); + exit(1); + } + pthread_mutex_init(&lvm_thread_mutex, NULL); + pthread_cond_init(&lvm_thread_cond, NULL); + pthread_barrier_init(&lvm_start_barrier, NULL, 2); + init_lvhash(); + + /* Start the cluster interface */ + if (cluster_iface == IF_AUTO) + cluster_iface = get_cluster_type(); + +#ifdef USE_CMAN + if ((cluster_iface == IF_AUTO || cluster_iface == IF_CMAN) && + (clops = init_cman_cluster())) { + max_csid_len = CMAN_MAX_CSID_LEN; + max_cluster_message = CMAN_MAX_CLUSTER_MESSAGE; + max_cluster_member_name_len = CMAN_MAX_NODENAME_LEN; + syslog(LOG_NOTICE, "Cluster LVM daemon started - connected to CMAN"); + } +#endif +#ifdef USE_COROSYNC + if (!clops) + if (((cluster_iface == IF_AUTO || cluster_iface == IF_COROSYNC) && + (clops = init_corosync_cluster()))) { + max_csid_len = COROSYNC_CSID_LEN; + max_cluster_message = COROSYNC_MAX_CLUSTER_MESSAGE; + max_cluster_member_name_len = COROSYNC_MAX_CLUSTER_MEMBER_NAME_LEN; + syslog(LOG_NOTICE, "Cluster LVM daemon started - connected to Corosync"); + } +#endif +#ifdef USE_OPENAIS + if (!clops) + if ((cluster_iface == IF_AUTO || cluster_iface == IF_OPENAIS) && + (clops = init_openais_cluster())) { + max_csid_len = OPENAIS_CSID_LEN; + max_cluster_message = OPENAIS_MAX_CLUSTER_MESSAGE; + max_cluster_member_name_len = OPENAIS_MAX_CLUSTER_MEMBER_NAME_LEN; + syslog(LOG_NOTICE, "Cluster LVM daemon started - connected to OpenAIS"); + } +#endif +#ifdef USE_SINGLENODE + if (!clops) + if (cluster_iface == IF_SINGLENODE && (clops = init_singlenode_cluster())) { + max_csid_len = SINGLENODE_CSID_LEN; + max_cluster_message = SINGLENODE_MAX_CLUSTER_MESSAGE; + max_cluster_member_name_len = MAX_CLUSTER_MEMBER_NAME_LEN; + syslog(LOG_NOTICE, "Cluster LVM daemon started - running in single-node mode"); + } +#endif + + if (!clops) { + DEBUGLOG("Can't initialise cluster interface\n"); + log_error("Can't initialise cluster interface."); + child_init_signal_and_exit(DFAIL_CLUSTER_IF); + /* NOTREACHED */ + } + DEBUGLOG("Cluster ready, doing some more initialisation\n"); + + /* Save our CSID */ + clops->get_our_csid(our_csid); + + /* Initialise the FD list head */ + local_client_head.fd = clops->get_main_cluster_fd(); + local_client_head.type = CLUSTER_MAIN_SOCK; + local_client_head.callback = clops->cluster_fd_callback; + + /* Add the local socket to the list */ + if (!(newfd = dm_zalloc(sizeof(struct local_client)))) { + child_init_signal_and_exit(DFAIL_MALLOC); + /* NOTREACHED */ + } + + newfd->fd = local_sock; + newfd->type = LOCAL_RENDEZVOUS; + newfd->callback = local_rendezvous_callback; + newfd->next = local_client_head.next; + local_client_head.next = newfd; + + /* This needs to be started after cluster initialisation + as it may need to take out locks */ + DEBUGLOG("Starting LVM thread\n"); + DEBUGLOG("Main cluster socket fd %d (%p) with local socket %d (%p)\n", + local_client_head.fd, &local_client_head, newfd->fd, newfd); + + /* Don't let anyone else to do work until we are started */ + if (pthread_create(&lvm_thread, &stack_attr, lvm_thread_fn, &lvm_params)) { + log_sys_error("pthread_create", ""); + goto out; + } + + /* Don't start until the LVM thread is ready */ + pthread_barrier_wait(&lvm_start_barrier); + + /* Tell the rest of the cluster our version number */ + if (clops->cluster_init_completed) + clops->cluster_init_completed(); + + DEBUGLOG("clvmd ready for work\n"); + child_init_signal(SUCCESS); + + /* Try to shutdown neatly */ + signal(SIGTERM, sigterm_handler); + signal(SIGINT, sigterm_handler); + + /* Do some work */ + main_loop(cmd_timeout); + + pthread_mutex_lock(&lvm_thread_mutex); + lvm_thread_exit = 1; + pthread_cond_signal(&lvm_thread_cond); + pthread_mutex_unlock(&lvm_thread_mutex); + if ((errno = pthread_join(lvm_thread, NULL))) + log_sys_error("pthread_join", ""); + + close_local_sock(local_sock); + + while ((delfd = local_client_head.next)) { + local_client_head.next = delfd->next; + /* Failing cleanup_zombie leaks... */ + if (delfd->type == LOCAL_SOCK && !cleanup_zombie(delfd)) + cmd_client_cleanup(delfd); /* calls sync_unlock */ + if (delfd->fd != local_sock) + safe_close(&(delfd->fd)); + dm_free(delfd); + } + + DEBUGLOG("cluster_closedown\n"); + destroy_lvhash(); + clops->cluster_closedown(); + + ret = 0; +out: + dm_hash_destroy(lvm_params.excl_uuid); + + return ret; +} + +/* Called when the cluster layer has completed initialisation. + We send the version message */ +void clvmd_cluster_init_completed(void) +{ + send_version_message(); +} + +/* Data on a connected socket */ +static int local_sock_callback(struct local_client *thisfd, char *buf, int len, + const char *csid, + struct local_client **new_client) +{ + *new_client = NULL; + return read_from_local_sock(thisfd); +} + +/* Data on a connected socket */ +static int local_rendezvous_callback(struct local_client *thisfd, char *buf, + int len, const char *csid, + struct local_client **new_client) +{ + /* Someone connected to our local socket, accept it. */ + + struct sockaddr_un socka; + struct local_client *newfd; + socklen_t sl = sizeof(socka); + int client_fd = accept(thisfd->fd, (struct sockaddr *) &socka, &sl); + + if (client_fd == -1 && errno == EINTR) + return 1; + + if (client_fd >= 0) { + if (!(newfd = dm_zalloc(sizeof(*newfd)))) { + if (close(client_fd)) + log_sys_error("close", "socket"); + return 1; + } + + pthread_cond_init(&newfd->bits.localsock.cond, NULL); + pthread_mutex_init(&newfd->bits.localsock.mutex, NULL); + + if (fcntl(client_fd, F_SETFD, 1)) + DEBUGLOG("Setting CLOEXEC on client fd failed: %s\n", strerror(errno)); + + newfd->fd = client_fd; + newfd->type = LOCAL_SOCK; + newfd->callback = local_sock_callback; + newfd->bits.localsock.all_success = 1; + DEBUGLOG("Got new connection on fd %d (%p)\n", newfd->fd, newfd); + *new_client = newfd; + } + return 1; +} + +static int local_pipe_callback(struct local_client *thisfd, char *buf, + int maxlen, const char *csid, + struct local_client **new_client) +{ + int len; + char buffer[PIPE_BUF]; + struct local_client *sock_client = thisfd->bits.pipe.client; + int status = -1; /* in error by default */ + + len = read(thisfd->fd, buffer, sizeof(int)); + if (len == -1 && errno == EINTR) + return 1; + + if (len == sizeof(int)) + memcpy(&status, buffer, sizeof(int)); + + DEBUGLOG("Read on pipe %d, %d bytes, status %d\n", + thisfd->fd, len, status); + + /* EOF on pipe or an error, close it */ + if (len <= 0) { + void *ret = &status; + if (close(thisfd->fd)) + log_sys_error("close", "local_pipe"); + + /* Clear out the cross-link */ + if (thisfd->bits.pipe.client) + thisfd->bits.pipe.client->bits.localsock.pipe_client = NULL; + + /* Reap child thread */ + if (thisfd->bits.pipe.threadid) { + if ((errno = pthread_join(thisfd->bits.pipe.threadid, &ret))) + log_sys_error("pthread_join", ""); + + thisfd->bits.pipe.threadid = 0; + if (thisfd->bits.pipe.client) + thisfd->bits.pipe.client->bits.localsock.threadid = 0; + } + return -1; + } else { + DEBUGLOG("Background routine status was %d, sock_client (%p)\n", + status, sock_client); + /* But has the client gone away ?? */ + if (!sock_client) { + DEBUGLOG("Got pipe response for dead client, ignoring it\n"); + } else { + /* If error then just return that code */ + if (status) + send_local_reply(sock_client, status, + sock_client->fd); + else { + /* FIXME: closer inspect this code since state is write thread protected */ + pthread_mutex_lock(&sock_client->bits.localsock.mutex); + if (sock_client->bits.localsock.state == POST_COMMAND) { + pthread_mutex_unlock(&sock_client->bits.localsock.mutex); + send_local_reply(sock_client, 0, + sock_client->fd); + } else { + /* PRE_COMMAND finished. */ + pthread_mutex_unlock(&sock_client->bits.localsock.mutex); + if ((status = distribute_command(sock_client))) + send_local_reply(sock_client, EFBIG, + sock_client->fd); + } + } + } + } + return len; +} + +/* If a noed is up, look for it in the reply array, if it's not there then + add one with "ETIMEDOUT". + NOTE: This won't race with real replies because they happen in the same thread. +*/ +static void timedout_callback(struct local_client *client, const char *csid, + int node_up) +{ + struct node_reply *reply; + char nodename[max_cluster_member_name_len]; + + if (!node_up) + return; + + clops->name_from_csid(csid, nodename); + DEBUGLOG("Checking for a reply from %s\n", nodename); + pthread_mutex_lock(&client->bits.localsock.mutex); + + reply = client->bits.localsock.replies; + while (reply && strcmp(reply->node, nodename) != 0) + reply = reply->next; + + pthread_mutex_unlock(&client->bits.localsock.mutex); + + if (!reply) { + DEBUGLOG("Node %s timed-out\n", nodename); + add_reply_to_list(client, ETIMEDOUT, csid, + "Command timed out", 18); + } +} + +/* Called when the request has timed out on at least one node. We fill in + the remaining node entries with ETIMEDOUT and return. + + By the time we get here the node that caused + the timeout could have gone down, in which case we will never get the expected + number of replies that triggers the post command so we need to do it here +*/ +static void request_timed_out(struct local_client *client) +{ + DEBUGLOG("Request timed-out. padding\n"); + clops->cluster_do_node_callback(client, timedout_callback); + + if (!client->bits.localsock.threadid) + return; + + pthread_mutex_lock(&client->bits.localsock.mutex); + + if (!client->bits.localsock.finished && + (client->bits.localsock.num_replies != + client->bits.localsock.expected_replies)) { + /* Post-process the command */ + client->bits.localsock.state = POST_COMMAND; + pthread_cond_signal(&client->bits.localsock.cond); + } + + pthread_mutex_unlock(&client->bits.localsock.mutex); +} + +/* This is where the real work happens */ +static void main_loop(int cmd_timeout) +{ + sigset_t ss; + + DEBUGLOG("Using timeout of %d seconds\n", cmd_timeout); + + sigemptyset(&ss); + sigaddset(&ss, SIGINT); + sigaddset(&ss, SIGTERM); + pthread_sigmask(SIG_UNBLOCK, &ss, NULL); + /* Main loop */ + while (!quit) { + fd_set in; + int select_status; + struct local_client *thisfd; + struct timeval tv = { cmd_timeout, 0 }; + int quorate = clops->is_quorate(); + int client_count = 0; + int max_fd = 0; + struct local_client *lastfd = &local_client_head; + struct local_client *nextfd = local_client_head.next; + + /* Wait on the cluster FD and all local sockets/pipes */ + local_client_head.fd = clops->get_main_cluster_fd(); + FD_ZERO(&in); + + for (thisfd = &local_client_head; thisfd; thisfd = thisfd->next) { + client_count++; + max_fd = max(max_fd, thisfd->fd); + } + + if (max_fd > FD_SETSIZE - 32) { + fprintf(stderr, "WARNING: There are too many connections to clvmd. Investigate and take action now!\n"); + fprintf(stderr, "WARNING: Your cluster may freeze up if the number of clvmd file descriptors (%d) exceeds %d.\n", max_fd + 1, FD_SETSIZE); + } + + for (thisfd = &local_client_head; thisfd; thisfd = nextfd, nextfd = thisfd ? thisfd->next : NULL) { + + if (thisfd->removeme && !cleanup_zombie(thisfd)) { + struct local_client *free_fd = thisfd; + lastfd->next = nextfd; + DEBUGLOG("removeme set for %p with %d monitored fds remaining\n", free_fd, client_count - 1); + + /* Queue cleanup, this also frees the client struct */ + add_to_lvmqueue(free_fd, NULL, 0, NULL); + + continue; + } + + lastfd = thisfd; + + if (thisfd->removeme) + continue; + + /* if the cluster is not quorate then don't listen for new requests */ + if ((thisfd->type != LOCAL_RENDEZVOUS && + thisfd->type != LOCAL_SOCK) || quorate) + if (thisfd->fd < FD_SETSIZE) + FD_SET(thisfd->fd, &in); + } + + select_status = select(FD_SETSIZE, &in, NULL, NULL, &tv); + + if (reread_config) { + int saved_errno = errno; + + reread_config = 0; + DEBUGLOG("got SIGHUP\n"); + if (clops->reread_config) + clops->reread_config(); + errno = saved_errno; + } + + if (select_status > 0) { + char csid[MAX_CSID_LEN]; + char buf[max_cluster_message]; + + for (thisfd = &local_client_head; thisfd; thisfd = thisfd->next) { + if (thisfd->fd < FD_SETSIZE && FD_ISSET(thisfd->fd, &in)) { + struct local_client *newfd = NULL; + int ret; + + /* FIXME Remove from main thread in case it blocks! */ + /* Do callback */ + ret = thisfd->callback(thisfd, buf, sizeof(buf), + csid, &newfd); + /* Ignore EAGAIN */ + if (ret < 0 && (errno == EAGAIN || errno == EINTR)) { + continue; + } + + /* Got error or EOF: Remove it from the list safely */ + if (ret <= 0) { + int type = thisfd->type; + + /* If the cluster socket shuts down, so do we */ + if (type == CLUSTER_MAIN_SOCK || + type == CLUSTER_INTERNAL) + goto closedown; + + DEBUGLOG("ret == %d, errno = %d. removing client\n", + ret, errno); + thisfd->removeme = 1; + continue; + } + + /* New client...simply add it to the list */ + if (newfd) { + newfd->next = thisfd->next; + thisfd->next = newfd; + thisfd = newfd; + } + } + } + } + + /* Select timed out. Check for clients that have been waiting too long for a response */ + if (select_status == 0) { + time_t the_time = time(NULL); + + for (thisfd = &local_client_head; thisfd; thisfd = thisfd->next) { + if (thisfd->type == LOCAL_SOCK && + thisfd->bits.localsock.sent_out && + (thisfd->bits.localsock.sent_time + cmd_timeout) < the_time && + thisfd->bits.localsock.expected_replies != + thisfd->bits.localsock.num_replies) { + /* Send timed out message + replies we already have */ + DEBUGLOG("Request timed-out (send: %ld, now: %ld)\n", + thisfd->bits.localsock.sent_time, the_time); + + thisfd->bits.localsock.all_success = 0; + + request_timed_out(thisfd); + } + } + } + if (select_status < 0) { + if (errno == EINTR) + continue; + +#ifdef DEBUG + perror("select error"); + exit(-1); +#endif + } + } + + closedown: + if (quit) + DEBUGLOG("SIGTERM received\n"); +} + +static __attribute__ ((noreturn)) void wait_for_child(int c_pipe, int timeout) +{ + int child_status; + fd_set fds; + struct timeval tv = {timeout, 0}; + + FD_ZERO(&fds); + FD_SET(c_pipe, &fds); + + switch (select(c_pipe+1, &fds, NULL, NULL, timeout? &tv: NULL)) { + case 0: + fprintf(stderr, "clvmd startup timed out\n"); + exit(DFAIL_TIMEOUT); + case 1: + if (read(c_pipe, &child_status, sizeof(child_status)) != + sizeof(child_status)) { + fprintf(stderr, "clvmd failed in initialisation\n"); + exit(DFAIL_INIT); + } + + switch (child_status) { + case SUCCESS: + break; + case DFAIL_INIT: + fprintf(stderr, "clvmd failed in initialisation\n"); + break; + case DFAIL_LOCAL_SOCK: + fprintf(stderr, "clvmd could not create local socket\n"); + fprintf(stderr, "Another clvmd is probably already running\n"); + break; + case DFAIL_CLUSTER_IF: + fprintf(stderr, "clvmd could not connect to cluster manager\n"); + fprintf(stderr, "Consult syslog for more information\n"); + break; + case DFAIL_MALLOC: + fprintf(stderr, "clvmd failed, not enough memory\n"); + break; + default: + fprintf(stderr, "clvmd failed, error was %d\n", child_status); + break; + } + exit(child_status); + default: + fprintf(stderr, "clvmd startup, select failed: %s\n", strerror(errno)); + exit(DFAIL_INIT); + } +} + +/* + * Fork into the background and detach from our parent process. + * In the interests of user-friendliness we wait for the daemon + * to complete initialisation before returning its status + * the the user. + */ +static void be_daemon(int timeout) +{ + int devnull = open("/dev/null", O_RDWR); + if (devnull == -1) { + perror("Can't open /dev/null"); + exit(3); + } + + if (pipe(child_pipe)) { + perror("Error creating pipe"); + exit(3); + } + + switch (fork()) { + case -1: + perror("clvmd: can't fork"); + exit(2); + + case 0: /* Child */ + (void) close(child_pipe[0]); + break; + + default: /* Parent */ + (void) close(child_pipe[1]); + wait_for_child(child_pipe[0], timeout); + } + + /* Detach ourself from the calling environment */ + if (close(0) || close(1) || close(2)) { + perror("Error closing terminal FDs"); + exit(4); + } + setsid(); + + if (dup2(devnull, 0) < 0 || dup2(devnull, 1) < 0 + || dup2(devnull, 2) < 0) { + perror("Error setting terminal FDs to /dev/null"); + log_error("Error setting terminal FDs to /dev/null: %m"); + exit(5); + } + if ((devnull > STDERR_FILENO) && close(devnull)) { + log_sys_error("close", "/dev/null"); + exit(7); + } + if (chdir("/")) { + log_error("Error setting current directory to /: %m"); + exit(6); + } +} + +static int verify_message(char *buf, int len) +{ + struct clvm_header *h = (struct clvm_header *)buf; + + if (len < (int)sizeof(struct clvm_header)) { + log_error("verify_message short len %d.", len); + return -1; + } + + switch (h->cmd) { + case CLVMD_CMD_REPLY: + case CLVMD_CMD_VERSION: + case CLVMD_CMD_GOAWAY: + case CLVMD_CMD_TEST: + case CLVMD_CMD_LOCK: + case CLVMD_CMD_UNLOCK: + case CLVMD_CMD_LOCK_LV: + case CLVMD_CMD_LOCK_VG: + case CLVMD_CMD_LOCK_QUERY: + case CLVMD_CMD_REFRESH: + case CLVMD_CMD_GET_CLUSTERNAME: + case CLVMD_CMD_SET_DEBUG: + case CLVMD_CMD_VG_BACKUP: + case CLVMD_CMD_RESTART: + case CLVMD_CMD_SYNC_NAMES: + break; + default: + log_error("verify_message bad cmd %x.", h->cmd); + return -1; + } + + /* TODO: we may be able to narrow len/flags/clientid/arglen checks based on cmd */ + + if (h->flags & ~(CLVMD_FLAG_LOCAL | CLVMD_FLAG_SYSTEMLV | CLVMD_FLAG_NODEERRS | CLVMD_FLAG_REMOTE)) { + log_error("verify_message bad flags %x.", h->flags); + return -1; + } + + if (h->arglen > max_cluster_message) { + log_error("verify_message bad arglen %x max %d.", h->arglen, max_cluster_message); + return -1; + } + + return 0; +} + +static void dump_message(char *buf, int len) +{ + unsigned char row[8]; + char str[9]; + int i, j = 0; + + str[8] = '\0'; + if (len > 128) + len = 128; + + for (i = 0; i < len; ++i) { + row[j] = buf[i]; + str[j] = (isprint(buf[i])) ? buf[i] : ' '; + + if (i + 1 == len) { + for (;j < 8; ++j) { + row[j] = 0; + str[j] = ' '; + } + + log_error("%02x %02x %02x %02x %02x %02x %02x %02x [%s]", + row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], str); + j = 0; + } + } +} + +static int cleanup_zombie(struct local_client *thisfd) +{ + int *status; + struct local_client *pipe_client; + + if (thisfd->type != LOCAL_SOCK) + return 0; + + if (!thisfd->bits.localsock.cleanup_needed) + return 0; + + DEBUGLOG("EOF on local socket: inprogress=%d\n", + thisfd->bits.localsock.in_progress); + + if ((pipe_client = thisfd->bits.localsock.pipe_client)) + pipe_client = pipe_client->bits.pipe.client; + + /* If the client went away in mid command then tidy up */ + if (thisfd->bits.localsock.in_progress) { + DEBUGLOG("Sending SIGUSR2 to pre&post thread (%p in-progress)\n", pipe_client); + pthread_kill(thisfd->bits.localsock.threadid, SIGUSR2); + if (pthread_mutex_trylock(&thisfd->bits.localsock.mutex)) + return 1; + thisfd->bits.localsock.state = POST_COMMAND; + thisfd->bits.localsock.finished = 1; + pthread_cond_signal(&thisfd->bits.localsock.cond); + pthread_mutex_unlock(&thisfd->bits.localsock.mutex); + + /* Free any unsent buffers */ + free_reply(thisfd); + } + + /* Kill the subthread & free resources */ + if (thisfd->bits.localsock.threadid) { + DEBUGLOG("Waiting for pre&post thread (%p)\n", pipe_client); + pthread_mutex_lock(&thisfd->bits.localsock.mutex); + thisfd->bits.localsock.state = PRE_COMMAND; + thisfd->bits.localsock.finished = 1; + pthread_cond_signal(&thisfd->bits.localsock.cond); + pthread_mutex_unlock(&thisfd->bits.localsock.mutex); + + if ((errno = pthread_join(thisfd->bits.localsock.threadid, + (void **) &status))) + log_sys_error("pthread_join", ""); + + DEBUGLOG("Joined pre&post thread\n"); + + thisfd->bits.localsock.threadid = 0; + + /* Remove the pipe client */ + if (thisfd->bits.localsock.pipe_client) { + struct local_client *delfd; + struct local_client *lastfd; + + (void) close(thisfd->bits.localsock.pipe_client->fd); /* Close pipe */ + (void) close(thisfd->bits.localsock.pipe); + + /* Remove pipe client */ + for (lastfd = &local_client_head; (delfd = lastfd->next); lastfd = delfd) + if (thisfd->bits.localsock.pipe_client == delfd) { + thisfd->bits.localsock.pipe_client = NULL; + lastfd->next = delfd->next; + dm_free(delfd); + break; + } + } + } + + /* Free the command buffer */ + dm_free(thisfd->bits.localsock.cmd); + + safe_close(&(thisfd->fd)); + thisfd->bits.localsock.cleanup_needed = 0; + + return 0; +} + +/* Called when we have a read from the local socket. + was in the main loop but it's grown up and is a big girl now */ +static int read_from_local_sock(struct local_client *thisfd) +{ + int len; + int argslen; + int missing_len; + char buffer[PIPE_BUF + 1]; + char csid[MAX_CSID_LEN]; + int comms_pipe[2]; + struct local_client *newfd; + struct clvm_header *inheader = (struct clvm_header *) buffer; + int status; + + len = read(thisfd->fd, buffer, sizeof(buffer) - 1); + if (len == -1 && errno == EINTR) + return 1; + + DEBUGLOG("Read on local socket %d, len = %d\n", thisfd->fd, len); + + if (len && verify_message(buffer, len) < 0) { + log_error("read_from_local_sock from %d len %d bad verify.", + thisfd->fd, len); + dump_message(buffer, len); + /* force error handling below */ + len = 0; + } + + /* EOF or error on socket */ + if (len <= 0) { + thisfd->bits.localsock.cleanup_needed = 1; + (void) cleanup_zombie(thisfd); /* ignore errors here */ + return 0; + } + + buffer[len] = 0; /* Ensure \0 terminated */ + + /* Fill in the client ID */ + inheader->clientid = htonl(thisfd->fd); + + /* If we are already busy then return an error */ + if (thisfd->bits.localsock.in_progress) { + struct clvm_header reply = { + .cmd = CLVMD_CMD_REPLY, + .status = EBUSY + }; + send_message(&reply, sizeof(reply), our_csid, thisfd->fd, + "Error sending EBUSY reply to local user"); + return len; + } + + /* See if we have the whole message */ + argslen = len - strlen(inheader->node) - sizeof(struct clvm_header); + missing_len = inheader->arglen - argslen; + + if (missing_len < 0) + missing_len = 0; + + /* We need at least sizeof(struct clvm_header) bytes in buffer */ + if (len < (int)sizeof(struct clvm_header) || /* Already handled in verify_message() */ + argslen < 0 || missing_len > MAX_MISSING_LEN) { + struct clvm_header reply = { + .cmd = CLVMD_CMD_REPLY, + .status = EINVAL + }; + send_message(&reply, sizeof(reply), our_csid, thisfd->fd, + "Error sending EINVAL reply to local user"); + return 0; + } + + /* Free any old buffer space */ + dm_free(thisfd->bits.localsock.cmd); + + /* Save the message */ + if (!(thisfd->bits.localsock.cmd = dm_malloc(len + missing_len))) { + struct clvm_header reply = { + .cmd = CLVMD_CMD_REPLY, + .status = ENOMEM + }; + send_message(&reply, sizeof(reply), our_csid, thisfd->fd, + "Error sending ENOMEM reply to local user"); + return 0; + } + memcpy(thisfd->bits.localsock.cmd, buffer, len); + thisfd->bits.localsock.cmd_len = len + missing_len; + inheader = (struct clvm_header *) thisfd->bits.localsock.cmd; + + /* If we don't have the full message then read the rest now */ + if (missing_len) { + char *argptr = inheader->node + strlen(inheader->node) + 1; + + while (missing_len > 0) { + DEBUGLOG("got %d bytes, need another %d (total %d)\n", + argslen, missing_len, inheader->arglen); + len = read(thisfd->fd, argptr + argslen, missing_len); + if (len == -1 && errno == EINTR) + continue; + + if (len <= 0) { + /* EOF or error on socket */ + DEBUGLOG("EOF on local socket\n"); + dm_free(thisfd->bits.localsock.cmd); + thisfd->bits.localsock.cmd = NULL; + return 0; + } + + missing_len -= len; + argslen += len; + } + } + + /* Only run the command if all the cluster nodes are running CLVMD */ + if (((inheader->flags & CLVMD_FLAG_LOCAL) == 0) && + (check_all_clvmds_running(thisfd) == -1)) { + thisfd->bits.localsock.expected_replies = 0; + thisfd->bits.localsock.num_replies = 0; + send_local_reply(thisfd, EHOSTDOWN, thisfd->fd); + return len; + } + + /* Check the node name for validity */ + if (inheader->node[0] && clops->csid_from_name(csid, inheader->node)) { + /* Error, node is not in the cluster */ + struct clvm_header reply = { + .cmd = CLVMD_CMD_REPLY, + .status = ENOENT + }; + + DEBUGLOG("Unknown node: '%s'\n", inheader->node); + send_message(&reply, sizeof(reply), our_csid, thisfd->fd, + "Error sending ENOENT reply to local user"); + thisfd->bits.localsock.expected_replies = 0; + thisfd->bits.localsock.num_replies = 0; + thisfd->bits.localsock.in_progress = FALSE; + thisfd->bits.localsock.sent_out = FALSE; + return len; + } + + /* If we already have a subthread then just signal it to start */ + if (thisfd->bits.localsock.threadid) { + pthread_mutex_lock(&thisfd->bits.localsock.mutex); + thisfd->bits.localsock.state = PRE_COMMAND; + pthread_cond_signal(&thisfd->bits.localsock.cond); + pthread_mutex_unlock(&thisfd->bits.localsock.mutex); + return len; + } + + /* Create a pipe and add the reading end to our FD list */ + if (pipe(comms_pipe)) { + struct clvm_header reply = { + .cmd = CLVMD_CMD_REPLY, + .status = EBUSY + }; + + DEBUGLOG("Creating pipe failed: %s\n", strerror(errno)); + send_message(&reply, sizeof(reply), our_csid, thisfd->fd, + "Error sending EBUSY reply to local user"); + return len; + } + + if (!(newfd = dm_zalloc(sizeof(*newfd)))) { + struct clvm_header reply = { + .cmd = CLVMD_CMD_REPLY, + .status = ENOMEM + }; + + (void) close(comms_pipe[0]); + (void) close(comms_pipe[1]); + + send_message(&reply, sizeof(reply), our_csid, thisfd->fd, + "Error sending ENOMEM reply to local user"); + return len; + } + + DEBUGLOG("Creating pipe, [%d, %d]\n", comms_pipe[0], comms_pipe[1]); + + if (fcntl(comms_pipe[0], F_SETFD, 1)) + DEBUGLOG("setting CLOEXEC on pipe[0] failed: %s\n", strerror(errno)); + if (fcntl(comms_pipe[1], F_SETFD, 1)) + DEBUGLOG("setting CLOEXEC on pipe[1] failed: %s\n", strerror(errno)); + + newfd->fd = comms_pipe[0]; + newfd->type = THREAD_PIPE; + newfd->callback = local_pipe_callback; + newfd->bits.pipe.client = thisfd; + newfd->next = thisfd->next; + thisfd->next = newfd; + + /* Store a cross link to the pipe */ + thisfd->bits.localsock.pipe_client = newfd; + thisfd->bits.localsock.pipe = comms_pipe[1]; + + /* Make sure the thread has a copy of it's own ID */ + newfd->bits.pipe.threadid = thisfd->bits.localsock.threadid; + + /* Run the pre routine */ + thisfd->bits.localsock.in_progress = TRUE; + thisfd->bits.localsock.state = PRE_COMMAND; + thisfd->bits.localsock.cleanup_needed = 1; + DEBUGLOG("Creating pre&post thread for pipe fd %d (%p)\n", newfd->fd, newfd); + status = pthread_create(&thisfd->bits.localsock.threadid, + &stack_attr, pre_and_post_thread, thisfd); + DEBUGLOG("Created pre&post thread, state = %d\n", status); + + return len; +} + +/* Add a file descriptor from the cluster or comms interface to + our list of FDs for select +*/ +int add_client(struct local_client *new_client) +{ + new_client->next = local_client_head.next; + local_client_head.next = new_client; + + return 0; +} + +/* Called when the pre-command has completed successfully - we + now execute the real command on all the requested nodes */ +static int distribute_command(struct local_client *thisfd) +{ + struct clvm_header *inheader = + (struct clvm_header *) thisfd->bits.localsock.cmd; + int len = thisfd->bits.localsock.cmd_len; + + thisfd->xid = global_xid++; + DEBUGLOG("distribute command: XID = %d, flags=0x%x (%s%s)\n", + thisfd->xid, inheader->flags, + (inheader->flags & CLVMD_FLAG_LOCAL) ? "LOCAL" : "", + (inheader->flags & CLVMD_FLAG_REMOTE) ? "REMOTE" : ""); + + /* Forward it to other nodes in the cluster if needed */ + if (!(inheader->flags & CLVMD_FLAG_LOCAL)) { + /* if node is empty then do it on the whole cluster */ + if (inheader->node[0] == '\0') { + thisfd->bits.localsock.expected_replies = + clops->get_num_nodes(); + thisfd->bits.localsock.num_replies = 0; + thisfd->bits.localsock.sent_time = time(NULL); + thisfd->bits.localsock.in_progress = TRUE; + thisfd->bits.localsock.sent_out = TRUE; + + /* + * Send to local node first, even if CLVMD_FLAG_REMOTE + * is set so we still get a reply if this is the + * only node. + */ + add_to_lvmqueue(thisfd, inheader, len, NULL); + + DEBUGLOG("Sending message to all cluster nodes\n"); + inheader->xid = thisfd->xid; + send_message(inheader, len, NULL, -1, + "Error forwarding message to cluster"); + } else { + /* Do it on a single node */ + char csid[MAX_CSID_LEN]; + + if (clops->csid_from_name(csid, inheader->node)) + /* This has already been checked so should not happen */ + return 0; + + /* OK, found a node... */ + thisfd->bits.localsock.in_progress = TRUE; + thisfd->bits.localsock.expected_replies = 1; + thisfd->bits.localsock.num_replies = 0; + + /* Are we the requested node ?? */ + if (memcmp(csid, our_csid, max_csid_len) == 0) { + DEBUGLOG("Doing command on local node only\n"); + add_to_lvmqueue(thisfd, inheader, len, NULL); + } else { + DEBUGLOG("Sending message to single node: %s\n", + inheader->node); + inheader->xid = thisfd->xid; + send_message(inheader, len, csid, -1, + "Error forwarding message to cluster node"); + } + } + } else { + /* Local explicitly requested, ignore nodes */ + thisfd->bits.localsock.in_progress = TRUE; + thisfd->bits.localsock.expected_replies = 1; + thisfd->bits.localsock.num_replies = 0; + DEBUGLOG("Doing command explicitly on local node only\n"); + add_to_lvmqueue(thisfd, inheader, len, NULL); + } + + return 0; +} + +/* Process a command from a remote node and return the result */ +static void process_remote_command(struct clvm_header *msg, int msglen, int fd, + const char *csid) +{ + char *replyargs; + char nodename[max_cluster_member_name_len]; + int replylen = 0; + int buflen = max_cluster_message - sizeof(struct clvm_header) - 1; + int status; + + /* Get the node name as we /may/ need it later */ + clops->name_from_csid(csid, nodename); + + DEBUGLOG("process_remote_command %s for clientid 0x%x XID %d on node %s\n", + decode_cmd(msg->cmd), msg->clientid, msg->xid, nodename); + + /* Check for GOAWAY and sulk */ + if (msg->cmd == CLVMD_CMD_GOAWAY) { + DEBUGLOG("Told to go away by %s\n", nodename); + log_error("Told to go away by %s.", nodename); + exit(99); + } + + /* Version check is internal - don't bother exposing it in clvmd-command.c */ + if (msg->cmd == CLVMD_CMD_VERSION) { + int version_nums[3]; + char node[256]; + + memcpy(version_nums, msg->args, sizeof(version_nums)); + + clops->name_from_csid(csid, node); + DEBUGLOG("Remote node %s is version %d.%d.%d\n", + node, ntohl(version_nums[0]), + ntohl(version_nums[1]), ntohl(version_nums[2])); + + if (ntohl(version_nums[0]) != CLVMD_MAJOR_VERSION) { + struct clvm_header byebyemsg = { + .cmd = CLVMD_CMD_GOAWAY + }; + + DEBUGLOG("Telling node %s to go away because of incompatible version number\n", + node); + log_notice("Telling node %s to go away because of incompatible version number %d.%d.%d\n", + node, ntohl(version_nums[0]), + ntohl(version_nums[1]), ntohl(version_nums[2])); + + clops->cluster_send_message(&byebyemsg, sizeof(byebyemsg), our_csid, + "Error Sending GOAWAY message"); + } else + clops->add_up_node(csid); + + return; + } + + /* Allocate a default reply buffer */ + if ((replyargs = dm_malloc(max_cluster_message - sizeof(struct clvm_header)))) + /* Run the command */ + /* FIXME: usage of init_test() is unprotected */ + status = do_command(NULL, msg, msglen, &replyargs, + buflen, &replylen); + else + status = ENOMEM; + + /* If it wasn't a reply, then reply */ + if (msg->cmd != CLVMD_CMD_REPLY) { + char *aggreply; + + aggreply = dm_realloc(replyargs, replylen + sizeof(struct clvm_header)); + if (aggreply) { + struct clvm_header *agghead = + (struct clvm_header *) aggreply; + + replyargs = aggreply; + /* Move it up so there's room for a header in front of the data */ + memmove(aggreply + offsetof(struct clvm_header, args), + replyargs, replylen); + + agghead->xid = msg->xid; + agghead->cmd = CLVMD_CMD_REPLY; + agghead->status = status; + agghead->flags = 0; + agghead->clientid = msg->clientid; + agghead->arglen = replylen; + agghead->node[0] = '\0'; + send_message(aggreply, sizeof(struct clvm_header) + replylen, + csid, fd, "Error sending command reply"); + } else { + /* Return a failure response */ + struct clvm_header reply = { + .cmd = CLVMD_CMD_REPLY, + .status = ENOMEM, + .clientid = msg->clientid + }; + DEBUGLOG("Error attempting to realloc return buffer\n"); + send_message(&reply, sizeof(reply), csid, fd, + "Error sending ENOMEM command reply"); + } + } + + dm_free(replyargs); +} + +/* Add a reply to a command to the list of replies for this client. + If we have got a full set then send them to the waiting client down the local + socket */ +static void add_reply_to_list(struct local_client *client, int status, + const char *csid, const char *buf, int len) +{ + struct node_reply *reply; + + /* Add it to the list of replies */ + if (!(reply = dm_zalloc(sizeof(*reply)))) { + /* It's all gone horribly wrong... */ + send_local_reply(client, ENOMEM, client->fd); + return; + } + + reply->status = status; + clops->name_from_csid(csid, reply->node); + DEBUGLOG("Reply from node %s: %d bytes\n", reply->node, len); + + if (len > 0) { + if (!(reply->replymsg = dm_malloc(len))) + reply->status = ENOMEM; + else + memcpy(reply->replymsg, buf, len); + } else + reply->replymsg = NULL; + + pthread_mutex_lock(&client->bits.localsock.mutex); + + if (client->bits.localsock.finished) { + dm_free(reply->replymsg); + dm_free(reply); + } else { + /* Hook it onto the reply chain */ + reply->next = client->bits.localsock.replies; + client->bits.localsock.replies = reply; + + /* If we have the whole lot then do the post-process */ + /* Post-process the command */ + if (++client->bits.localsock.num_replies == + client->bits.localsock.expected_replies) { + client->bits.localsock.state = POST_COMMAND; + pthread_cond_signal(&client->bits.localsock.cond); + } + DEBUGLOG("Got %d replies, expecting: %d\n", + client->bits.localsock.num_replies, + client->bits.localsock.expected_replies); + } + pthread_mutex_unlock(&client->bits.localsock.mutex); +} + +/* This is the thread that runs the PRE and post commands for a particular connection */ +static __attribute__ ((noreturn)) void *pre_and_post_thread(void *arg) +{ + struct local_client *client = (struct local_client *) arg; + int status; + int write_status; + sigset_t ss; + int pipe_fd = client->bits.localsock.pipe; + + DEBUGLOG("Pre&post thread (%p), pipe fd %d\n", client, pipe_fd); + pthread_mutex_lock(&client->bits.localsock.mutex); + + /* Ignore SIGUSR1 (handled by master process) but enable + SIGUSR2 (kills subthreads) */ + sigemptyset(&ss); + sigaddset(&ss, SIGUSR1); + pthread_sigmask(SIG_BLOCK, &ss, NULL); + + sigdelset(&ss, SIGUSR1); + sigaddset(&ss, SIGUSR2); + pthread_sigmask(SIG_UNBLOCK, &ss, NULL); + + /* Loop around doing PRE and POST functions until the client goes away */ + while (!client->bits.localsock.finished) { + /* Execute the code */ + /* FIXME: usage of init_test() is unprotected as in do_command() */ + if ((status = do_pre_command(client))) + client->bits.localsock.all_success = 0; + + DEBUGLOG("Pre&post thread (%p) writes status %d down to pipe fd %d\n", + client, status, pipe_fd); + + /* Tell the parent process we have finished this bit */ + while ((write_status = write(pipe_fd, &status, sizeof(int))) != sizeof(int)) + if (write_status >=0 || (errno != EINTR && errno != EAGAIN)) { + log_error("Error sending to pipe: %m"); + break; + } + + if (status) { + client->bits.localsock.state = POST_COMMAND; + goto next_pre; + } + + /* We may need to wait for the condition variable before running the post command */ + if (client->bits.localsock.state != POST_COMMAND && + !client->bits.localsock.finished) { + DEBUGLOG("Pre&post thread (%p) waiting to do post command, state = %d\n", + client, client->bits.localsock.state); + pthread_cond_wait(&client->bits.localsock.cond, + &client->bits.localsock.mutex); + } + + DEBUGLOG("Pre&post thread (%p) got post command condition...\n", client); + + /* POST function must always run, even if the client aborts */ + status = 0; + do_post_command(client); + + while ((write_status = write(pipe_fd, &status, sizeof(int))) != sizeof(int)) + if (write_status >=0 || (errno != EINTR && errno != EAGAIN)) { + log_error("Error sending to pipe: %m"); + break; + } +next_pre: + if (client->bits.localsock.state != PRE_COMMAND && + !client->bits.localsock.finished) { + DEBUGLOG("Pre&post thread (%p) waiting for next pre command\n", client); + pthread_cond_wait(&client->bits.localsock.cond, + &client->bits.localsock.mutex); + } + + DEBUGLOG("Pre&post thread (%p) got pre command condition...\n", client); + } + pthread_mutex_unlock(&client->bits.localsock.mutex); + DEBUGLOG("Pre&post thread (%p) finished\n", client); + + pthread_exit(NULL); +} + +/* Process a command on the local node and store the result */ +static int process_local_command(struct clvm_header *msg, int msglen, + struct local_client *client, + unsigned short xid) +{ + char *replybuf; + int buflen = max_cluster_message - sizeof(struct clvm_header) - 1; + int replylen = 0; + int status; + + if (!(replybuf = dm_malloc(max_cluster_message))) + return -1; + + DEBUGLOG("process_local_command: %s msg=%p, msglen =%d, client=%p\n", + decode_cmd(msg->cmd), msg, msglen, client); + + /* If remote flag is set, just set a successful status code. */ + if (msg->flags & CLVMD_FLAG_REMOTE) + status = 0; + else + status = do_command(client, msg, msglen, &replybuf, buflen, &replylen); + + if (status) + client->bits.localsock.all_success = 0; + + /* If we took too long then discard the reply */ + if (xid == client->xid) + add_reply_to_list(client, status, our_csid, replybuf, replylen); + else + DEBUGLOG("Local command took too long, discarding xid %d, current is %d\n", + xid, client->xid); + + dm_free(replybuf); + + return status; +} + +static int process_reply(const struct clvm_header *msg, int msglen, const char *csid) +{ + struct local_client *client; + + if (!(client = find_client(msg->clientid))) { + DEBUGLOG("Got message for unknown client 0x%x\n", + msg->clientid); + log_error("Got message for unknown client 0x%x.", + msg->clientid); + return -1; + } + + if (msg->status) + client->bits.localsock.all_success = 0; + + /* Gather replies together for this client id */ + if (msg->xid == client->xid) + add_reply_to_list(client, msg->status, csid, msg->args, + msg->arglen); + else + DEBUGLOG("Discarding reply with old XID %d, current = %d\n", + msg->xid, client->xid); + + return 0; +} + +/* Send an aggregated reply back to the client */ +static void send_local_reply(struct local_client *client, int status, int fd) +{ + struct clvm_header *clientreply; + struct node_reply *thisreply = client->bits.localsock.replies; + char *replybuf; + char *ptr; + int message_len = 0; + + DEBUGLOG("Send local reply\n"); + + /* Work out the total size of the reply */ + while (thisreply) { + if (thisreply->replymsg) + message_len += strlen(thisreply->replymsg) + 1; + else + message_len++; + + message_len += strlen(thisreply->node) + 1 + sizeof(int); + + thisreply = thisreply->next; + } + + /* Add in the size of our header */ + message_len = message_len + sizeof(struct clvm_header); + if (!(replybuf = dm_malloc(message_len))) { + DEBUGLOG("Memory allocation fails\n"); + return; + } + + clientreply = (struct clvm_header *) replybuf; + clientreply->status = status; + clientreply->cmd = CLVMD_CMD_REPLY; + clientreply->node[0] = '\0'; + clientreply->xid = 0; + clientreply->clientid = 0; + clientreply->flags = 0; + + ptr = clientreply->args; + + /* Add in all the replies, and free them as we go */ + thisreply = client->bits.localsock.replies; + while (thisreply) { + struct node_reply *tempreply = thisreply; + + strcpy(ptr, thisreply->node); + ptr += strlen(thisreply->node) + 1; + + if (thisreply->status) + clientreply->flags |= CLVMD_FLAG_NODEERRS; + + memcpy(ptr, &thisreply->status, sizeof(int)); + ptr += sizeof(int); + + if (thisreply->replymsg) { + strcpy(ptr, thisreply->replymsg); + ptr += strlen(thisreply->replymsg) + 1; + } else { + ptr[0] = '\0'; + ptr++; + } + thisreply = thisreply->next; + + dm_free(tempreply->replymsg); + dm_free(tempreply); + } + + /* Terminate with an empty node name */ + *ptr = '\0'; + + clientreply->arglen = ptr - clientreply->args; + + /* And send it */ + send_message(replybuf, message_len, our_csid, fd, + "Error sending REPLY to client"); + dm_free(replybuf); + + /* Reset comms variables */ + client->bits.localsock.replies = NULL; + client->bits.localsock.expected_replies = 0; + client->bits.localsock.in_progress = FALSE; + client->bits.localsock.sent_out = FALSE; +} + +/* Just free a reply chain baceuse it wasn't used. */ +static void free_reply(struct local_client *client) +{ + /* Add in all the replies, and free them as we go */ + struct node_reply *thisreply = client->bits.localsock.replies; + while (thisreply) { + struct node_reply *tempreply = thisreply; + + thisreply = thisreply->next; + + dm_free(tempreply->replymsg); + dm_free(tempreply); + } + client->bits.localsock.replies = NULL; +} + +/* Send our version number to the cluster */ +static void send_version_message(void) +{ + char message[sizeof(struct clvm_header) + sizeof(int) * 3]; + struct clvm_header *msg = (struct clvm_header *) message; + int version_nums[3] = { + htonl(CLVMD_MAJOR_VERSION), + htonl(CLVMD_MINOR_VERSION), + htonl(CLVMD_PATCH_VERSION) + }; + + msg->cmd = CLVMD_CMD_VERSION; + msg->status = 0; + msg->flags = 0; + msg->clientid = 0; + msg->arglen = sizeof(version_nums); + + memcpy(&msg->args, version_nums, sizeof(version_nums)); + + hton_clvm(msg); + + clops->cluster_send_message(message, sizeof(message), NULL, + "Error Sending version number"); +} + +/* Send a message to either a local client or another server */ +static int send_message(void *buf, int msglen, const char *csid, int fd, + const char *errtext) +{ + int len = 0; + int ptr; + struct timespec delay; + struct timespec remtime; + int retry_cnt = 0; + + /* Send remote messages down the cluster socket */ + if (!csid || !ISLOCAL_CSID(csid)) { + hton_clvm((struct clvm_header *) buf); + return clops->cluster_send_message(buf, msglen, csid, errtext); + } + + /* Make sure it all goes */ + for (ptr = 0; ptr < msglen;) { + if ((len = write(fd, (char*)buf + ptr, msglen - ptr)) <= 0) { + if (errno == EINTR) + continue; + if ((errno == EAGAIN || errno == EIO || errno == ENOSPC) && + ++retry_cnt < MAX_RETRIES) { + delay.tv_sec = 0; + delay.tv_nsec = 100000; + remtime.tv_sec = 0; + remtime.tv_nsec = 0; + (void) nanosleep (&delay, &remtime); + continue; + } + log_error("%s", errtext); + break; + } + ptr += len; + } + + return len; +} + +static int process_work_item(struct lvm_thread_cmd *cmd) +{ + /* If msg is NULL then this is a cleanup request */ + if (cmd->msg == NULL) { + DEBUGLOG("process_work_item: free %p\n", cmd->client); + cmd_client_cleanup(cmd->client); + pthread_mutex_destroy(&cmd->client->bits.localsock.mutex); + pthread_cond_destroy(&cmd->client->bits.localsock.cond); + dm_free(cmd->client); + return 0; + } + + if (!cmd->remote) { + DEBUGLOG("process_work_item: local\n"); + process_local_command(cmd->msg, cmd->msglen, cmd->client, + cmd->xid); + } else { + DEBUGLOG("process_work_item: remote\n"); + process_remote_command(cmd->msg, cmd->msglen, cmd->client->fd, + cmd->csid); + } + + return 0; +} + +/* + * Routine that runs in the "LVM thread". + */ +static void *lvm_thread_fn(void *arg) +{ + sigset_t ss; + struct lvm_startup_params *lvm_params = arg; + struct lvm_thread_cmd *cmd; + + DEBUGLOG("LVM thread function started\n"); + + /* Ignore SIGUSR1 & 2 */ + sigemptyset(&ss); + sigaddset(&ss, SIGUSR1); + sigaddset(&ss, SIGUSR2); + pthread_sigmask(SIG_BLOCK, &ss, NULL); + + /* Initialise the interface to liblvm */ + init_clvm(lvm_params->excl_uuid); + + /* Allow others to get moving */ + pthread_barrier_wait(&lvm_start_barrier); + DEBUGLOG("LVM thread ready for work.\n"); + + /* Now wait for some actual work */ + pthread_mutex_lock(&lvm_thread_mutex); + + for (;;) { + while (!dm_list_empty(&lvm_cmd_head)) { + cmd = dm_list_item(dm_list_first(&lvm_cmd_head), + struct lvm_thread_cmd); + dm_list_del(&cmd->list); + pthread_mutex_unlock(&lvm_thread_mutex); + + process_work_item(cmd); + dm_free(cmd->msg); + dm_free(cmd); + + pthread_mutex_lock(&lvm_thread_mutex); + } + + if (lvm_thread_exit) + break; + + DEBUGLOG("LVM thread waiting for work\n"); + pthread_cond_wait(&lvm_thread_cond, &lvm_thread_mutex); + } + + pthread_mutex_unlock(&lvm_thread_mutex); + DEBUGLOG("LVM thread exits\n"); + + destroy_lvm(); + + pthread_exit(NULL); +} + +/* Pass down some work to the LVM thread */ +static int add_to_lvmqueue(struct local_client *client, struct clvm_header *msg, + int msglen, const char *csid) +{ + struct lvm_thread_cmd *cmd; + + if (!(cmd = dm_malloc(sizeof(*cmd)))) + return ENOMEM; + + if (msglen) { + if (!(cmd->msg = dm_malloc(msglen))) { + log_error("Unable to allocate buffer space."); + dm_free(cmd); + return -1; + } + memcpy(cmd->msg, msg, msglen); + } + else + cmd->msg = NULL; + + cmd->client = client; + cmd->msglen = msglen; + cmd->xid = client->xid; + + if (csid) { + memcpy(cmd->csid, csid, max_csid_len); + cmd->remote = 1; + } else + cmd->remote = 0; + + DEBUGLOG("add_to_lvmqueue: cmd=%p. client=%p, msg=%p, len=%d, csid=%p, xid=%d\n", + cmd, client, msg, msglen, csid, cmd->xid); + pthread_mutex_lock(&lvm_thread_mutex); + if (lvm_thread_exit) { + pthread_mutex_unlock(&lvm_thread_mutex); + dm_free(cmd->msg); + dm_free(cmd); + return -1; /* We are about to exit */ + } + dm_list_add(&lvm_cmd_head, &cmd->list); + pthread_cond_signal(&lvm_thread_cond); + pthread_mutex_unlock(&lvm_thread_mutex); + + return 0; +} + +/* Return 0 if we can talk to an existing clvmd */ +static int check_local_clvmd(void) +{ + int local_socket; + int ret = 0; + struct sockaddr_un sockaddr = { .sun_family = AF_UNIX }; + + if (!dm_strncpy(sockaddr.sun_path, CLVMD_SOCKNAME, sizeof(sockaddr.sun_path))) { + log_error("%s: clvmd socket name too long.", CLVMD_SOCKNAME); + return -1; + } + + /* Open local socket */ + if ((local_socket = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { + log_sys_error("socket", "local socket"); + return -1; + } + + if (connect(local_socket,(struct sockaddr *) &sockaddr, + sizeof(sockaddr))) { + log_sys_error("connect", "local socket"); + ret = -1; + } + + if (close(local_socket)) + log_sys_error("close", "local socket"); + + return ret; +} + +static void close_local_sock(int local_socket) +{ + if (local_socket != -1 && close(local_socket)) + log_sys_error("close", CLVMD_SOCKNAME); + + if (CLVMD_SOCKNAME[0] != '\0' && unlink(CLVMD_SOCKNAME)) + stack; +} + +/* Open the local socket, that's the one we talk to libclvm down */ +static int open_local_sock(void) +{ + mode_t old_mask; + int local_socket = -1; + struct sockaddr_un sockaddr = { .sun_family = AF_UNIX }; + + if (!dm_strncpy(sockaddr.sun_path, CLVMD_SOCKNAME, sizeof(sockaddr.sun_path))) { + log_error("%s: clvmd socket name too long.", CLVMD_SOCKNAME); + return -1; + } + + close_local_sock(local_socket); + + (void) dm_prepare_selinux_context(CLVMD_SOCKNAME, S_IFSOCK); + old_mask = umask(0077); + + /* Open local socket */ + if ((local_socket = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { + log_error("Can't create local socket: %m"); + goto error; + } + + /* Set Close-on-exec & non-blocking */ + if (fcntl(local_socket, F_SETFD, 1)) + DEBUGLOG("setting CLOEXEC on local_socket failed: %s\n", strerror(errno)); + if (fcntl(local_socket, F_SETFL, fcntl(local_socket, F_GETFL, 0) | O_NONBLOCK)) + DEBUGLOG("setting O_NONBLOCK on local_socket failed: %s\n", strerror(errno)); + + + if (bind(local_socket, (struct sockaddr *) &sockaddr, sizeof(sockaddr))) { + log_error("can't bind local socket: %m"); + goto error; + } + if (listen(local_socket, 1) != 0) { + log_error("listen local: %m"); + goto error; + } + + umask(old_mask); + (void) dm_prepare_selinux_context(NULL, 0); + return local_socket; +error: + close_local_sock(local_socket); + umask(old_mask); + (void) dm_prepare_selinux_context(NULL, 0); + return -1; +} + +void process_message(struct local_client *client, char *buf, int len, + const char *csid) +{ + char nodename[max_cluster_member_name_len]; + struct clvm_header *inheader = (struct clvm_header *) buf; + ntoh_clvm(inheader); /* Byteswap fields */ + + if (verify_message(buf, len) < 0) { + clops->name_from_csid(csid, nodename); + log_error("process_message from %s len %d bad verify.", nodename, len); + dump_message(buf, len); + return; + } + + if (inheader->cmd == CLVMD_CMD_REPLY) + process_reply(inheader, len, csid); + else + add_to_lvmqueue(client, inheader, len, csid); +} + + +static void check_all_callback(struct local_client *client, const char *csid, + int node_up) +{ + if (!node_up) + add_reply_to_list(client, EHOSTDOWN, csid, "CLVMD not running", 18); +} + +/* Check to see if all CLVMDs are running (ie one on + every node in the cluster). + If not, returns -1 and prints out a list of errant nodes */ +static int check_all_clvmds_running(struct local_client *client) +{ + DEBUGLOG("check_all_clvmds_running\n"); + return clops->cluster_do_node_callback(client, check_all_callback); +} + +/* Return a local_client struct given a client ID. + client IDs are in network byte order */ +static struct local_client *find_client(int clientid) +{ + struct local_client *thisfd; + + for (thisfd = &local_client_head; thisfd; thisfd = thisfd->next) + if (thisfd->fd == (int)ntohl(clientid)) + return thisfd; + + return NULL; +} + +/* Byte-swapping routines for the header so we + work in a heterogeneous environment */ +static void hton_clvm(struct clvm_header *hdr) +{ + hdr->status = htonl(hdr->status); + hdr->arglen = htonl(hdr->arglen); + hdr->xid = htons(hdr->xid); + /* Don't swap clientid as it's only a token as far as + remote nodes are concerned */ +} + +static void ntoh_clvm(struct clvm_header *hdr) +{ + hdr->status = ntohl(hdr->status); + hdr->arglen = ntohl(hdr->arglen); + hdr->xid = ntohs(hdr->xid); +} + +/* Handler for SIGUSR2 - sent to kill subthreads */ +static void sigusr2_handler(int sig) +{ + DEBUGLOG("SIGUSR2 received\n"); + return; +} + +static void sigterm_handler(int sig) +{ + quit = 1; + return; +} + +static void sighup_handler(int sig) +{ + reread_config = 1; +} + +int sync_lock(const char *resource, int mode, int flags, int *lockid) +{ + return clops->sync_lock(resource, mode, flags, lockid); +} + +int sync_unlock(const char *resource, int lockid) +{ + return clops->sync_unlock(resource, lockid); +} + +static if_type_t parse_cluster_interface(char *ifname) +{ + if_type_t iface = IF_AUTO; + + if (!strcmp(ifname, "auto")) + iface = IF_AUTO; + else if (!strcmp(ifname, "cman")) + iface = IF_CMAN; + else if (!strcmp(ifname, "openais")) + iface = IF_OPENAIS; + else if (!strcmp(ifname, "corosync")) + iface = IF_COROSYNC; + else if (!strcmp(ifname, "singlenode")) + iface = IF_SINGLENODE; + + return iface; +} + +/* + * Try and find a cluster system in corosync's objdb, if it is running. This is + * only called if the command-line option is not present, and if it fails + * we still try the interfaces in order. + */ +static if_type_t get_cluster_type(void) +{ +#ifdef HAVE_COROSYNC_CONFDB_H + confdb_handle_t handle; + if_type_t type = IF_AUTO; + int result; + char buf[255]; + size_t namelen = sizeof(buf); + hdb_handle_t cluster_handle; + hdb_handle_t clvmd_handle; + confdb_callbacks_t callbacks = { 0 }; + + result = confdb_initialize (&handle, &callbacks); + if (result != CS_OK) + return type; + + result = confdb_object_find_start(handle, OBJECT_PARENT_HANDLE); + if (result != CS_OK) + goto out; + + result = confdb_object_find(handle, OBJECT_PARENT_HANDLE, (void *)"cluster", strlen("cluster"), &cluster_handle); + if (result != CS_OK) + goto out; + + result = confdb_object_find_start(handle, cluster_handle); + if (result != CS_OK) + goto out; + + result = confdb_object_find(handle, cluster_handle, (void *)"clvmd", strlen("clvmd"), &clvmd_handle); + if (result != CS_OK) + goto out; + + result = confdb_key_get(handle, clvmd_handle, (void *)"interface", strlen("interface"), buf, &namelen); + if (result != CS_OK) + goto out; + + if (namelen >= sizeof(buf)) + namelen = sizeof(buf) - 1; + + buf[namelen] = '\0'; + type = parse_cluster_interface(buf); + DEBUGLOG("got interface type '%s' from confdb\n", buf); +out: + confdb_finalize(handle); + return type; +#else + return IF_AUTO; +#endif +}
diff --git a/daemons/clvmd/clvmd.h b/daemons/clvmd/clvmd.h new file mode 100644 index 0000000..edaee88 --- /dev/null +++ b/daemons/clvmd/clvmd.h
@@ -0,0 +1,126 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _CLVMD_H +#define _CLVMD_H + +#define CLVMD_MAJOR_VERSION 0 +#define CLVMD_MINOR_VERSION 2 +#define CLVMD_PATCH_VERSION 1 + +/* Default time (in seconds) we will wait for all remote commands to execute + before declaring them dead */ +#define DEFAULT_CMD_TIMEOUT 60 + +/* One of these for each reply we get from command execution on a node */ +struct node_reply { + char node[MAX_CLUSTER_MEMBER_NAME_LEN]; + char *replymsg; + int status; + struct node_reply *next; +}; + +typedef enum {DEBUG_OFF, DEBUG_STDERR, DEBUG_SYSLOG} debug_t; + +/* + * These exist for the use of local sockets only when we are + * collecting responses from all cluster nodes + */ +struct localsock_bits { + struct node_reply *replies; + int num_replies; + int expected_replies; + time_t sent_time; /* So we can check for timeouts */ + int in_progress; /* Only execute one cmd at a time per client */ + int sent_out; /* Flag to indicate that a command was sent + to remote nodes */ + void *private; /* Private area for command processor use */ + void *cmd; /* Whole command as passed down local socket */ + int cmd_len; /* Length of above */ + int pipe; /* Pipe to send PRE completion status down */ + int finished; /* Flag to tell subthread to exit */ + int all_success; /* Set to 0 if any node (or the pre_command) + failed */ + int cleanup_needed; /* helper for cleanup_zombie */ + struct local_client *pipe_client; + pthread_t threadid; + enum { PRE_COMMAND, POST_COMMAND } state; + pthread_mutex_t mutex; /* Main thread and worker synchronisation */ + pthread_cond_t cond; +}; + +/* Entries for PIPE clients */ +struct pipe_bits { + struct local_client *client; /* Actual (localsock) client */ + pthread_t threadid; /* Our own copy of the thread id */ +}; + +/* Entries for Network socket clients */ +struct netsock_bits { + void *private; + int flags; +}; + +typedef int (*fd_callback_t) (struct local_client * fd, char *buf, int len, + const char *csid, + struct local_client ** new_client); + +/* One of these for each fd we are listening on */ +struct local_client { + int fd; + enum { CLUSTER_MAIN_SOCK, CLUSTER_DATA_SOCK, LOCAL_RENDEZVOUS, + LOCAL_SOCK, THREAD_PIPE, CLUSTER_INTERNAL } type; + struct local_client *next; + unsigned short xid; + fd_callback_t callback; + uint8_t removeme; + + union { + struct localsock_bits localsock; + struct pipe_bits pipe; + struct netsock_bits net; + } bits; +}; + +#define DEBUGLOG(fmt, args...) debuglog(fmt, ## args) + +#ifndef max +#define max(a,b) ((a)>(b)?(a):(b)) +#endif + +/* The real command processor is in clvmd-command.c */ +extern int do_command(struct local_client *client, struct clvm_header *msg, + int msglen, char **buf, int buflen, int *retlen); + +/* Pre and post command routines are called only on the local node */ +extern int do_pre_command(struct local_client *client); +extern int do_post_command(struct local_client *client); +extern void cmd_client_cleanup(struct local_client *client); +extern int add_client(struct local_client *new_client); + +extern void clvmd_cluster_init_completed(void); +extern void process_message(struct local_client *client, char *buf, + int len, const char *csid); +extern void debuglog(const char *fmt, ... ) + __attribute__ ((format(printf, 1, 2))); + +void clvmd_set_debug(debug_t new_de); +debug_t clvmd_get_debug(void); +int clvmd_get_foreground(void); + +int sync_lock(const char *resource, int mode, int flags, int *lockid); +int sync_unlock(const char *resource, int lockid); + +#endif
diff --git a/daemons/clvmd/lvm-functions.c b/daemons/clvmd/lvm-functions.c new file mode 100644 index 0000000..e872fbe --- /dev/null +++ b/daemons/clvmd/lvm-functions.c
@@ -0,0 +1,939 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2012 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "clvmd-common.h" + +#include <pthread.h> + +#include "clvm.h" +#include "clvmd-comms.h" +#include "clvmd.h" +#include "lvm-functions.h" + +/* LVM2 headers */ +#include "toolcontext.h" +#include "lvmcache.h" +#include "lvm-globals.h" +#include "activate.h" +#include "archiver.h" +#include "memlock.h" + +#include <syslog.h> + +static struct cmd_context *cmd = NULL; +static struct dm_hash_table *lv_hash = NULL; +static pthread_mutex_t lv_hash_lock; +static pthread_mutex_t lvm_lock; +static char last_error[1024]; + +struct lv_info { + int lock_id; + int lock_mode; +}; + +static const char *decode_full_locking_cmd(uint32_t cmdl) +{ + static char buf[128]; + const char *type; + const char *scope; + const char *command; + + switch (cmdl & LCK_TYPE_MASK) { + case LCK_NULL: + type = "NULL"; + break; + case LCK_READ: + type = "READ"; + break; + case LCK_PREAD: + type = "PREAD"; + break; + case LCK_WRITE: + type = "WRITE"; + break; + case LCK_EXCL: + type = "EXCL"; + break; + case LCK_UNLOCK: + type = "UNLOCK"; + break; + default: + type = "unknown"; + break; + } + + switch (cmdl & LCK_SCOPE_MASK) { + case LCK_VG: + scope = "VG"; + command = "LCK_VG"; + break; + case LCK_LV: + scope = "LV"; + switch (cmdl & LCK_MASK) { + case LCK_LV_EXCLUSIVE & LCK_MASK: + command = "LCK_LV_EXCLUSIVE"; + break; + case LCK_LV_SUSPEND & LCK_MASK: + command = "LCK_LV_SUSPEND"; + break; + case LCK_LV_RESUME & LCK_MASK: + command = "LCK_LV_RESUME"; + break; + case LCK_LV_ACTIVATE & LCK_MASK: + command = "LCK_LV_ACTIVATE"; + break; + case LCK_LV_DEACTIVATE & LCK_MASK: + command = "LCK_LV_DEACTIVATE"; + break; + default: + command = "unknown"; + break; + } + break; + default: + scope = "unknown"; + command = "unknown"; + break; + } + + sprintf(buf, "0x%x %s (%s|%s%s%s%s%s)", cmdl, command, type, scope, + cmdl & LCK_NONBLOCK ? "|NONBLOCK" : "", + cmdl & LCK_HOLD ? "|HOLD" : "", + cmdl & LCK_CLUSTER_VG ? "|CLUSTER_VG" : "", + cmdl & LCK_CACHE ? "|CACHE" : ""); + + return buf; +} + +/* + * Only processes 8 bits: excludes LCK_CACHE. + */ +static const char *decode_locking_cmd(unsigned char cmdl) +{ + return decode_full_locking_cmd((uint32_t) cmdl); +} + +static const char *decode_flags(unsigned char flags) +{ + static char buf[128]; + int len; + + len = sprintf(buf, "0x%x ( %s%s%s%s%s%s%s%s)", flags, + flags & LCK_PARTIAL_MODE ? "PARTIAL_MODE|" : "", + flags & LCK_MIRROR_NOSYNC_MODE ? "MIRROR_NOSYNC|" : "", + flags & LCK_DMEVENTD_MONITOR_MODE ? "DMEVENTD_MONITOR|" : "", + flags & LCK_ORIGIN_ONLY_MODE ? "ORIGIN_ONLY|" : "", + flags & LCK_TEST_MODE ? "TEST|" : "", + flags & LCK_CONVERT_MODE ? "CONVERT|" : "", + flags & LCK_DMEVENTD_MONITOR_IGNORE ? "DMEVENTD_MONITOR_IGNORE|" : "", + flags & LCK_REVERT_MODE ? "REVERT|" : ""); + + if (len > 1) + buf[len - 2] = ' '; + else + buf[0] = '\0'; + + return buf; +} + +char *get_last_lvm_error(void) +{ + return last_error; +} + +/* + * Hash lock info helpers + */ +static struct lv_info *lookup_info(const char *resource) +{ + struct lv_info *lvi; + + pthread_mutex_lock(&lv_hash_lock); + lvi = dm_hash_lookup(lv_hash, resource); + pthread_mutex_unlock(&lv_hash_lock); + + return lvi; +} + +static int insert_info(const char *resource, struct lv_info *lvi) +{ + int ret; + + pthread_mutex_lock(&lv_hash_lock); + ret = dm_hash_insert(lv_hash, resource, lvi); + pthread_mutex_unlock(&lv_hash_lock); + + return ret; +} + +static void remove_info(const char *resource) +{ + int num_open; + + pthread_mutex_lock(&lv_hash_lock); + dm_hash_remove(lv_hash, resource); + + /* When last lock is remove, validate there are not left opened devices */ + if (!dm_hash_get_first(lv_hash)) { + if (critical_section()) + log_error(INTERNAL_ERROR "No volumes are locked however clvmd is in activation mode critical section."); + if ((num_open = dev_cache_check_for_open_devices())) + log_error(INTERNAL_ERROR "No volumes are locked however %d devices are still open.", num_open); + } + + pthread_mutex_unlock(&lv_hash_lock); +} + +/* + * Return the mode a lock is currently held at (or -1 if not held) + */ +static int get_current_lock(char *resource) +{ + struct lv_info *lvi; + + if ((lvi = lookup_info(resource))) + return lvi->lock_mode; + + return -1; +} + + +void init_lvhash(void) +{ + /* Create hash table for keeping LV locks & status */ + lv_hash = dm_hash_create(1024); + pthread_mutex_init(&lv_hash_lock, NULL); + pthread_mutex_init(&lvm_lock, NULL); +} + +/* Called at shutdown to tidy the lockspace */ +void destroy_lvhash(void) +{ + struct dm_hash_node *v; + struct lv_info *lvi; + char *resource; + int status; + + pthread_mutex_lock(&lv_hash_lock); + + dm_hash_iterate(v, lv_hash) { + lvi = dm_hash_get_data(lv_hash, v); + resource = dm_hash_get_key(lv_hash, v); + + if ((status = sync_unlock(resource, lvi->lock_id))) + DEBUGLOG("unlock_all. unlock failed(%d): %s\n", + status, strerror(errno)); + dm_free(lvi); + } + + dm_hash_destroy(lv_hash); + lv_hash = NULL; + + pthread_mutex_unlock(&lv_hash_lock); +} + +/* Gets a real lock and keeps the info in the hash table */ +static int hold_lock(char *resource, int mode, int flags) +{ + int status; + int saved_errno; + struct lv_info *lvi; + + /* Mask off invalid options */ + flags &= LCKF_NOQUEUE | LCKF_CONVERT; + + lvi = lookup_info(resource); + + if (lvi) { + if (lvi->lock_mode == mode) { + DEBUGLOG("hold_lock, lock mode %d already held\n", + mode); + return 0; + } + if ((lvi->lock_mode == LCK_EXCL) && (mode == LCK_WRITE)) { + DEBUGLOG("hold_lock, lock already held LCK_EXCL, " + "ignoring LCK_WRITE request\n"); + return 0; + } + } + + /* Only allow explicit conversions */ + if (lvi && !(flags & LCKF_CONVERT)) { + errno = EBUSY; + return -1; + } + if (lvi) { + /* Already exists - convert it */ + status = sync_lock(resource, mode, flags, &lvi->lock_id); + saved_errno = errno; + if (!status) + lvi->lock_mode = mode; + else + DEBUGLOG("hold_lock. convert to %d failed: %s\n", mode, + strerror(errno)); + errno = saved_errno; + } else { + if (!(lvi = dm_malloc(sizeof(struct lv_info)))) { + errno = ENOMEM; + return -1; + } + + lvi->lock_mode = mode; + lvi->lock_id = 0; + status = sync_lock(resource, mode, flags & ~LCKF_CONVERT, &lvi->lock_id); + saved_errno = errno; + if (status) { + dm_free(lvi); + DEBUGLOG("hold_lock. lock at %d failed: %s\n", mode, + strerror(errno)); + } else + if (!insert_info(resource, lvi)) { + errno = ENOMEM; + return -1; + } + + errno = saved_errno; + } + return status; +} + +/* Unlock and remove it from the hash table */ +static int hold_unlock(char *resource) +{ + struct lv_info *lvi; + int status; + int saved_errno; + + if (!(lvi = lookup_info(resource))) { + DEBUGLOG("hold_unlock, lock not already held\n"); + return 0; + } + + status = sync_unlock(resource, lvi->lock_id); + saved_errno = errno; + if (!status) { + remove_info(resource); + dm_free(lvi); + } else { + DEBUGLOG("hold_unlock. unlock failed(%d): %s\n", status, + strerror(errno)); + } + + errno = saved_errno; + return status; +} + +/* Watch the return codes here. + liblvm API functions return 1(true) for success, 0(false) for failure and don't set errno. + libdlm API functions return 0 for success, -1 for failure and do set errno. + These functions here return 0 for success or >0 for failure (where the retcode is errno) +*/ + +/* Activate LV exclusive or non-exclusive */ +static int do_activate_lv(char *resource, unsigned char command, unsigned char lock_flags, int mode) +{ + int oldmode; + int status; + int activate_lv; + int exclusive = 0; + struct lvinfo lvi; + + /* Is it already open ? */ + oldmode = get_current_lock(resource); + if (oldmode == mode && (command & LCK_CLUSTER_VG)) { + DEBUGLOG("do_activate_lv, lock already held at %d\n", oldmode); + return 0; /* Nothing to do */ + } + + /* Does the config file want us to activate this LV ? */ + if (!lv_activation_filter(cmd, resource, &activate_lv, NULL)) + return EIO; + + if (!activate_lv) + return 0; /* Success, we did nothing! */ + + /* Do we need to activate exclusively? */ + if ((activate_lv == 2) || (mode == LCK_EXCL)) { + exclusive = 1; + mode = LCK_EXCL; + } + + /* + * Try to get the lock if it's a clustered volume group. + * Use lock conversion only if requested, to prevent implicit conversion + * of exclusive lock to shared one during activation. + */ + if (!test_mode() && command & LCK_CLUSTER_VG) { + status = hold_lock(resource, mode, LCKF_NOQUEUE | ((lock_flags & LCK_CONVERT_MODE) ? LCKF_CONVERT:0)); + if (status) { + /* Return an LVM-sensible error for this. + * Forcing EIO makes the upper level return this text + * rather than the strerror text for EAGAIN. + */ + if (errno == EAGAIN) { + sprintf(last_error, "Volume is busy on another node"); + errno = EIO; + } + return errno; + } + } + + /* If it's suspended then resume it */ + if (!lv_info_by_lvid(cmd, resource, 0, &lvi, 0, 0)) + goto error; + + if (lvi.suspended) { + critical_section_inc(cmd, "resuming"); + if (!lv_resume(cmd, resource, 0, NULL)) { + critical_section_dec(cmd, "resumed"); + goto error; + } + } + + /* Now activate it */ + if (!lv_activate(cmd, resource, exclusive, 0, 0, NULL)) + goto error; + + return 0; + +error: + if (!test_mode() && (oldmode == -1 || oldmode != mode)) + (void)hold_unlock(resource); + return EIO; +} + +/* Resume the LV if it was active */ +static int do_resume_lv(char *resource, unsigned char command, unsigned char lock_flags) +{ + int oldmode, origin_only, exclusive, revert; + + /* Is it open ? */ + oldmode = get_current_lock(resource); + if (oldmode == -1 && (command & LCK_CLUSTER_VG)) { + DEBUGLOG("do_resume_lv, lock not already held\n"); + return 0; /* We don't need to do anything */ + } + origin_only = (lock_flags & LCK_ORIGIN_ONLY_MODE) ? 1 : 0; + exclusive = (oldmode == LCK_EXCL) ? 1 : 0; + revert = (lock_flags & LCK_REVERT_MODE) ? 1 : 0; + + if (!lv_resume_if_active(cmd, resource, origin_only, exclusive, revert, NULL)) + return EIO; + + return 0; +} + +/* Suspend the device if active */ +static int do_suspend_lv(char *resource, unsigned char command, unsigned char lock_flags) +{ + int oldmode; + unsigned origin_only = (lock_flags & LCK_ORIGIN_ONLY_MODE) ? 1 : 0; + unsigned exclusive; + + /* Is it open ? */ + oldmode = get_current_lock(resource); + if (oldmode == -1 && (command & LCK_CLUSTER_VG)) { + DEBUGLOG("do_suspend_lv, lock not already held\n"); + return 0; /* Not active, so it's OK */ + } + + exclusive = (oldmode == LCK_EXCL) ? 1 : 0; + + /* Always call lv_suspend to read commited and precommited data */ + if (!lv_suspend_if_active(cmd, resource, origin_only, exclusive, NULL, NULL)) + return EIO; + + return 0; +} + +static int do_deactivate_lv(char *resource, unsigned char command, unsigned char lock_flags) +{ + int oldmode; + int status; + + /* Is it open ? */ + oldmode = get_current_lock(resource); + if (oldmode == -1 && (command & LCK_CLUSTER_VG)) { + DEBUGLOG("do_deactivate_lock, lock not already held\n"); + return 0; /* We don't need to do anything */ + } + + if (!lv_deactivate(cmd, resource, NULL)) + return EIO; + + if (!test_mode() && command & LCK_CLUSTER_VG) { + status = hold_unlock(resource); + if (status) + return errno; + } + + return 0; +} + +const char *do_lock_query(char *resource) +{ + int mode; + const char *type; + + mode = get_current_lock(resource); + switch (mode) { + case LCK_NULL: type = "NL"; break; + case LCK_READ: type = "CR"; break; + case LCK_PREAD:type = "PR"; break; + case LCK_WRITE:type = "PW"; break; + case LCK_EXCL: type = "EX"; break; + default: type = NULL; + } + + DEBUGLOG("do_lock_query: resource '%s', mode %i (%s)\n", resource, mode, type ?: "--"); + + return type; +} + +/* This is the LOCK_LV part that happens on all nodes in the cluster - + it is responsible for the interaction with device-mapper and LVM */ +int do_lock_lv(unsigned char command, unsigned char lock_flags, char *resource) +{ + int status = 0; + + DEBUGLOG("do_lock_lv: resource '%s', cmd = %s, flags = %s, critical_section = %d\n", + resource, decode_locking_cmd(command), decode_flags(lock_flags), critical_section()); + + if (!cmd->initialized.config || config_files_changed(cmd)) { + /* Reinitialise various settings inc. logging, filters */ + if (do_refresh_cache()) { + log_error("Updated config file invalid. Aborting."); + return EINVAL; + } + } + + pthread_mutex_lock(&lvm_lock); + init_test((lock_flags & LCK_TEST_MODE) ? 1 : 0); + + if (lock_flags & LCK_MIRROR_NOSYNC_MODE) + init_mirror_in_sync(1); + + if (lock_flags & LCK_DMEVENTD_MONITOR_IGNORE) + init_dmeventd_monitor(DMEVENTD_MONITOR_IGNORE); + else { + if (lock_flags & LCK_DMEVENTD_MONITOR_MODE) + init_dmeventd_monitor(1); + else + init_dmeventd_monitor(0); + } + + cmd->partial_activation = (lock_flags & LCK_PARTIAL_MODE) ? 1 : 0; + + /* clvmd should never try to read suspended device */ + init_ignore_suspended_devices(1); + + switch (command & LCK_MASK) { + case LCK_LV_EXCLUSIVE: + status = do_activate_lv(resource, command, lock_flags, LCK_EXCL); + break; + + case LCK_LV_SUSPEND: + status = do_suspend_lv(resource, command, lock_flags); + break; + + case LCK_UNLOCK: + case LCK_LV_RESUME: /* if active */ + status = do_resume_lv(resource, command, lock_flags); + break; + + case LCK_LV_ACTIVATE: + status = do_activate_lv(resource, command, lock_flags, LCK_READ); + break; + + case LCK_LV_DEACTIVATE: + status = do_deactivate_lv(resource, command, lock_flags); + break; + + default: + DEBUGLOG("Invalid LV command 0x%x\n", command); + status = EINVAL; + break; + } + + if (lock_flags & LCK_MIRROR_NOSYNC_MODE) + init_mirror_in_sync(0); + + cmd->partial_activation = 0; + + /* clean the pool for another command */ + dm_pool_empty(cmd->mem); + init_test(0); + pthread_mutex_unlock(&lvm_lock); + + DEBUGLOG("Command return is %d, critical_section is %d\n", status, critical_section()); + return status; +} + +/* Functions to do on the local node only BEFORE the cluster-wide stuff above happens */ +int pre_lock_lv(unsigned char command, unsigned char lock_flags, char *resource) +{ + /* Nearly all the stuff happens cluster-wide. Apart from SUSPEND. Here we get the + lock out on this node (because we are the node modifying the metadata) + before suspending cluster-wide. + LCKF_CONVERT is used always, local node is going to modify metadata + */ + if ((command & (LCK_SCOPE_MASK | LCK_TYPE_MASK)) == LCK_LV_SUSPEND && + (command & LCK_CLUSTER_VG)) { + DEBUGLOG("pre_lock_lv: resource '%s', cmd = %s, flags = %s\n", + resource, decode_locking_cmd(command), decode_flags(lock_flags)); + + if (!(lock_flags & LCK_TEST_MODE) && + hold_lock(resource, LCK_WRITE, LCKF_NOQUEUE | LCKF_CONVERT)) + return errno; + } + return 0; +} + +/* Functions to do on the local node only AFTER the cluster-wide stuff above happens */ +int post_lock_lv(unsigned char command, unsigned char lock_flags, + char *resource) +{ + int status; + unsigned origin_only = (lock_flags & LCK_ORIGIN_ONLY_MODE) ? 1 : 0; + + /* Opposite of above, done on resume after a metadata update */ + if ((command & (LCK_SCOPE_MASK | LCK_TYPE_MASK)) == LCK_LV_RESUME && + (command & LCK_CLUSTER_VG)) { + int oldmode; + + DEBUGLOG("post_lock_lv: resource '%s', cmd = %s, flags = %s\n", + resource, decode_locking_cmd(command), decode_flags(lock_flags)); + + /* If the lock state is PW then restore it to what it was */ + oldmode = get_current_lock(resource); + if (oldmode == LCK_WRITE) { + struct lvinfo lvi; + + pthread_mutex_lock(&lvm_lock); + status = lv_info_by_lvid(cmd, resource, origin_only, &lvi, 0, 0); + pthread_mutex_unlock(&lvm_lock); + if (!status) + return EIO; + + if (!(lock_flags & LCK_TEST_MODE)) { + if (lvi.exists) { + if (hold_lock(resource, LCK_READ, LCKF_CONVERT)) + return errno; + } else if (hold_unlock(resource)) + return errno; + } + } + } + return 0; +} + +/* Check if a VG is in use by LVM1 so we don't stomp on it */ +int do_check_lvm1(const char *vgname) +{ + int status; + + status = check_lvm1_vg_inactive(cmd, vgname); + + return status == 1 ? 0 : EBUSY; +} + +int do_refresh_cache(void) +{ + DEBUGLOG("Refreshing context\n"); + log_notice("Refreshing context"); + + pthread_mutex_lock(&lvm_lock); + + if (!refresh_toolcontext(cmd)) { + pthread_mutex_unlock(&lvm_lock); + return -1; + } + + init_full_scan_done(0); + init_ignore_suspended_devices(1); + lvmcache_force_next_label_scan(); + lvmcache_label_scan(cmd); + dm_pool_empty(cmd->mem); + + pthread_mutex_unlock(&lvm_lock); + + return 0; +} + +/* + * Handle VG lock - drop metadata or update lvmcache state + */ +void do_lock_vg(unsigned char command, unsigned char lock_flags, char *resource) +{ + uint32_t lock_cmd = command; + char *vgname = resource + 2; + + lock_cmd &= (LCK_SCOPE_MASK | LCK_TYPE_MASK | LCK_HOLD); + + /* + * Check if LCK_CACHE should be set. All P_ locks except # are cache related. + */ + if (strncmp(resource, "P_#", 3) && !strncmp(resource, "P_", 2)) + lock_cmd |= LCK_CACHE; + + DEBUGLOG("do_lock_vg: resource '%s', cmd = %s, flags = %s, critical_section = %d\n", + resource, decode_full_locking_cmd(lock_cmd), decode_flags(lock_flags), critical_section()); + + /* P_#global causes a full cache refresh */ + if (!strcmp(resource, "P_" VG_GLOBAL)) { + do_refresh_cache(); + return; + } + + pthread_mutex_lock(&lvm_lock); + init_test((lock_flags & LCK_TEST_MODE) ? 1 : 0); + + switch (lock_cmd) { + case LCK_VG_COMMIT: + DEBUGLOG("vg_commit notification for VG %s\n", vgname); + lvmcache_commit_metadata(vgname); + break; + case LCK_VG_REVERT: + DEBUGLOG("vg_revert notification for VG %s\n", vgname); + lvmcache_drop_metadata(vgname, 1); + break; + case LCK_VG_DROP_CACHE: + default: + DEBUGLOG("Invalidating cached metadata for VG %s\n", vgname); + lvmcache_drop_metadata(vgname, 0); + } + + init_test(0); + pthread_mutex_unlock(&lvm_lock); +} + +/* + * Ideally, clvmd should be started before any LVs are active + * but this may not be the case... + * I suppose this also comes in handy if clvmd crashes, not that it would! + */ +static int get_initial_state(struct dm_hash_table *excl_uuid) +{ + int lock_mode; + char lv[65], vg[65], flags[26], vg_flags[26]; /* with space for '\0' */ + char uuid[65]; + char line[255]; + char *lvs_cmd; + const char *lvm_binary = getenv("LVM_BINARY") ? : LVM_PATH; + FILE *lvs; + + if (dm_asprintf(&lvs_cmd, "%s lvs --config 'log{command_names=0 prefix=\"\"}' " + "--nolocking --noheadings -o vg_uuid,lv_uuid,lv_attr,vg_attr", + lvm_binary) < 0) + return_0; + + /* FIXME: Maybe link and use liblvm2cmd directly instead of fork */ + if (!(lvs = popen(lvs_cmd, "r"))) { + dm_free(lvs_cmd); + return 0; + } + + while (fgets(line, sizeof(line), lvs)) { + if (sscanf(line, "%64s %64s %25s %25s\n", vg, lv, flags, vg_flags) == 4) { + + /* States: s:suspended a:active S:dropped snapshot I:invalid snapshot */ + if (strlen(vg) == 38 && /* is is a valid UUID ? */ + (flags[4] == 'a' || flags[4] == 's') && /* is it active or suspended? */ + vg_flags[5] == 'c') { /* is it clustered ? */ + /* Convert hyphen-separated UUIDs into one */ + memcpy(&uuid[0], &vg[0], 6); + memcpy(&uuid[6], &vg[7], 4); + memcpy(&uuid[10], &vg[12], 4); + memcpy(&uuid[14], &vg[17], 4); + memcpy(&uuid[18], &vg[22], 4); + memcpy(&uuid[22], &vg[27], 4); + memcpy(&uuid[26], &vg[32], 6); + memcpy(&uuid[32], &lv[0], 6); + memcpy(&uuid[38], &lv[7], 4); + memcpy(&uuid[42], &lv[12], 4); + memcpy(&uuid[46], &lv[17], 4); + memcpy(&uuid[50], &lv[22], 4); + memcpy(&uuid[54], &lv[27], 4); + memcpy(&uuid[58], &lv[32], 6); + uuid[64] = '\0'; + + /* Look for this lock in the list of EX locks + we were passed on the command-line */ + lock_mode = (dm_hash_lookup(excl_uuid, uuid)) ? + LCK_EXCL : LCK_READ; + + DEBUGLOG("getting initial lock for %s\n", uuid); + if (hold_lock(uuid, lock_mode, LCKF_NOQUEUE)) + DEBUGLOG("Failed to hold lock %s\n", uuid); + } + } + } + if (pclose(lvs)) + DEBUGLOG("lvs pclose failed: %s\n", strerror(errno)); + + dm_free(lvs_cmd); + + return 1; +} + +static void lvm2_log_fn(int level, const char *file, int line, int dm_errno, + const char *message) +{ + + /* Send messages to the normal LVM2 logging system too, + so we get debug output when it's asked for. + We need to NULL the function ptr otherwise it will just call + back into here! */ + init_log_fn(NULL); + print_log(level, file, line, dm_errno, "%s", message); + init_log_fn(lvm2_log_fn); + + /* + * Ignore non-error messages, but store the latest one for returning + * to the user. + */ + if (level != _LOG_ERR && level != _LOG_FATAL) + return; + + strncpy(last_error, message, sizeof(last_error)); + last_error[sizeof(last_error)-1] = '\0'; +} + +/* This checks some basic cluster-LVM configuration stuff */ +static void check_config(void) +{ + int locking_type; + + locking_type = find_config_tree_int(cmd, global_locking_type_CFG, NULL); + + if (locking_type == 3) /* compiled-in cluster support */ + return; + + if (locking_type == 2) { /* External library, check name */ + const char *libname; + + libname = find_config_tree_str(cmd, global_locking_library_CFG, NULL); + if (libname && strstr(libname, "liblvm2clusterlock.so")) + return; + + log_error("Incorrect LVM locking library specified in lvm.conf, cluster operations may not work."); + return; + } + log_error("locking_type not set correctly in lvm.conf, cluster operations will not work."); +} + +/* Backups up the LVM metadata if it's changed */ +void lvm_do_backup(const char *vgname) +{ + struct volume_group * vg; + int consistent = 0; + + DEBUGLOG("Triggering backup of VG metadata for %s.\n", vgname); + + pthread_mutex_lock(&lvm_lock); + + vg = vg_read_internal(cmd, vgname, NULL /*vgid*/, WARN_PV_READ, &consistent); + + if (vg && consistent) + check_current_backup(vg); + else + log_error("Error backing up metadata, can't find VG for group %s", vgname); + + release_vg(vg); + dm_pool_empty(cmd->mem); + + pthread_mutex_unlock(&lvm_lock); +} + +struct dm_hash_node *get_next_excl_lock(struct dm_hash_node *v, char **name) +{ + struct lv_info *lvi; + + *name = NULL; + if (!v) + v = dm_hash_get_first(lv_hash); + + do { + if (v) { + lvi = dm_hash_get_data(lv_hash, v); + DEBUGLOG("Looking for EX locks. found %x mode %d\n", lvi->lock_id, lvi->lock_mode); + + if (lvi->lock_mode == LCK_EXCL) { + *name = dm_hash_get_key(lv_hash, v); + } + v = dm_hash_get_next(lv_hash, v); + } + } while (v && !*name); + + if (*name) + DEBUGLOG("returning EXclusive UUID %s\n", *name); + return v; +} + +void lvm_do_fs_unlock(void) +{ + pthread_mutex_lock(&lvm_lock); + DEBUGLOG("Syncing device names\n"); + fs_unlock(); + pthread_mutex_unlock(&lvm_lock); +} + +/* Called to initialise the LVM context of the daemon */ +int init_clvm(struct dm_hash_table *excl_uuid) +{ + /* Use LOG_DAEMON for syslog messages instead of LOG_USER */ + init_syslog(LOG_DAEMON); + openlog("clvmd", LOG_PID, LOG_DAEMON); + + /* Initialise already held locks */ + if (!get_initial_state(excl_uuid)) + log_error("Cannot load initial lock states."); + + if (!udev_init_library_context()) + stack; + + if (!(cmd = create_toolcontext(1, NULL, 0, 1, 1, 1))) { + log_error("Failed to allocate command context"); + udev_fin_library_context(); + return 0; + } + + if (stored_errno()) { + destroy_toolcontext(cmd); + return 0; + } + + cmd->cmd_line = "clvmd"; + + /* Check lvm.conf is setup for cluster-LVM */ + check_config(); + init_ignore_suspended_devices(1); + + /* Trap log messages so we can pass them back to the user */ + init_log_fn(lvm2_log_fn); + memlock_inc_daemon(cmd); + + return 1; +} + +void destroy_lvm(void) +{ + if (cmd) { + memlock_dec_daemon(cmd); + destroy_toolcontext(cmd); + udev_fin_library_context(); + cmd = NULL; + } +}
diff --git a/daemons/clvmd/lvm-functions.h b/daemons/clvmd/lvm-functions.h new file mode 100644 index 0000000..eac966f --- /dev/null +++ b/daemons/clvmd/lvm-functions.h
@@ -0,0 +1,41 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2010 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* Functions in lvm-functions.c */ + +#ifndef _LVM_FUNCTIONS_H +#define _LVM_FUNCTIONS_H + +extern int pre_lock_lv(unsigned char lock_cmd, unsigned char lock_flags, + char *resource); +extern int do_lock_lv(unsigned char lock_cmd, unsigned char lock_flags, + char *resource); +extern const char *do_lock_query(char *resource); +extern int post_lock_lv(unsigned char lock_cmd, unsigned char lock_flags, + char *resource); +extern int do_check_lvm1(const char *vgname); +extern int do_refresh_cache(void); +extern int init_clvm(struct dm_hash_table *excl_uuid); +extern void destroy_lvm(void); +extern void init_lvhash(void); +extern void destroy_lvhash(void); +extern void lvm_do_backup(const char *vgname); +extern char *get_last_lvm_error(void); +extern void do_lock_vg(unsigned char command, unsigned char lock_flags, + char *resource); +extern struct dm_hash_node *get_next_excl_lock(struct dm_hash_node *v, char **name); +void lvm_do_fs_unlock(void); + +#endif
diff --git a/daemons/clvmd/refresh_clvmd.c b/daemons/clvmd/refresh_clvmd.c new file mode 100644 index 0000000..6f89566 --- /dev/null +++ b/daemons/clvmd/refresh_clvmd.c
@@ -0,0 +1,382 @@ +/* + * Copyright (C) 2002-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2010 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* FIXME Remove duplicated functions from this file. */ + +/* + * Send a command to a running clvmd from the command-line + */ + +#include "clvmd-common.h" + +#include "clvm.h" +#include "refresh_clvmd.h" + +#include <stddef.h> +#include <sys/socket.h> +#include <sys/un.h> + +typedef struct lvm_response { + char node[255]; + char *response; + int status; + int len; +} lvm_response_t; + +/* + * This gets stuck at the start of memory we allocate so we + * can sanity-check it at deallocation time + */ +#define LVM_SIGNATURE 0x434C564D + +static int _clvmd_sock = -1; + +/* Open connection to the clvm daemon */ +static int _open_local_sock(void) +{ + int local_socket; + struct sockaddr_un sockaddr = { .sun_family = AF_UNIX }; + + if (!dm_strncpy(sockaddr.sun_path, CLVMD_SOCKNAME, sizeof(sockaddr.sun_path))) { + fprintf(stderr, "%s: clvmd socket name too long.", CLVMD_SOCKNAME); + return -1; + } + + /* Open local socket */ + if ((local_socket = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { + fprintf(stderr, "Local socket creation failed: %s", strerror(errno)); + return -1; + } + + if (connect(local_socket,(struct sockaddr *) &sockaddr, + sizeof(sockaddr))) { + int saved_errno = errno; + + fprintf(stderr, "connect() failed on local socket: %s\n", + strerror(errno)); + if (close(local_socket)) + return -1; + + errno = saved_errno; + return -1; + } + + return local_socket; +} + +/* Send a request and return the status */ +static int _send_request(const char *inbuf, int inlen, char **retbuf, int no_response) +{ + char outbuf[PIPE_BUF]; + struct clvm_header *outheader = (struct clvm_header *) outbuf; + int len; + unsigned off; + int buflen; + int err; + + /* Send it to CLVMD */ + rewrite: + if ( (err = write(_clvmd_sock, inbuf, inlen)) != inlen) { + if (err == -1 && errno == EINTR) + goto rewrite; + fprintf(stderr, "Error writing data to clvmd: %s", strerror(errno)); + return 0; + } + if (no_response) + return 1; + + /* Get the response */ + reread: + if ((len = read(_clvmd_sock, outbuf, sizeof(struct clvm_header))) < 0) { + if (errno == EINTR) + goto reread; + fprintf(stderr, "Error reading data from clvmd: %s", strerror(errno)); + return 0; + } + + if (len == 0) { + fprintf(stderr, "EOF reading CLVMD"); + errno = ENOTCONN; + return 0; + } + + /* Allocate buffer */ + buflen = len + outheader->arglen; + *retbuf = dm_malloc(buflen); + if (!*retbuf) { + errno = ENOMEM; + return 0; + } + + /* Copy the header */ + memcpy(*retbuf, outbuf, len); + outheader = (struct clvm_header *) *retbuf; + + /* Read the returned values */ + off = 1; /* we've already read the first byte */ + while (off <= outheader->arglen && len > 0) { + len = read(_clvmd_sock, outheader->args + off, + buflen - off - offsetof(struct clvm_header, args)); + if (len > 0) + off += len; + } + + /* Was it an error ? */ + if (outheader->status != 0) { + errno = outheader->status; + + /* Only return an error here if there are no node-specific + errors present in the message that might have more detail */ + if (!(outheader->flags & CLVMD_FLAG_NODEERRS)) { + fprintf(stderr, "cluster request failed: %s\n", strerror(errno)); + return 0; + } + + } + + return 1; +} + +/* Build the structure header and parse-out wildcard node names */ +static void _build_header(struct clvm_header *head, int cmd, const char *node, + unsigned int len) +{ + head->cmd = cmd; + head->status = 0; + head->flags = 0; + head->xid = 0; + head->clientid = 0; + if (len) + /* 1 byte is used from struct clvm_header.args[1], so -> len - 1 */ + head->arglen = len - 1; + else { + head->arglen = 0; + *head->args = '\0'; + } + + /* + * Translate special node names. + */ + if (!node || !strcmp(node, NODE_ALL)) + head->node[0] = '\0'; + else if (!strcmp(node, NODE_LOCAL)) { + head->node[0] = '\0'; + head->flags = CLVMD_FLAG_LOCAL; + } else + strcpy(head->node, node); +} + +/* + * Send a message to a(or all) node(s) in the cluster and wait for replies + */ +static int _cluster_request(char cmd, const char *node, void *data, int len, + lvm_response_t ** response, int *num, int no_response) +{ + char outbuf[sizeof(struct clvm_header) + len + strlen(node) + 1]; + char *inptr; + char *retbuf = NULL; + int status; + int i; + int num_responses = 0; + struct clvm_header *head = (struct clvm_header *) outbuf; + lvm_response_t *rarray; + + *num = 0; + + if (_clvmd_sock == -1) + _clvmd_sock = _open_local_sock(); + + if (_clvmd_sock == -1) + return 0; + + _build_header(head, cmd, node, len); + if (len) + memcpy(head->node + strlen(head->node) + 1, data, len); + + status = _send_request(outbuf, sizeof(struct clvm_header) + + strlen(head->node) + len, &retbuf, no_response); + if (!status || no_response) + goto out; + + /* Count the number of responses we got */ + head = (struct clvm_header *) retbuf; + inptr = head->args; + while (inptr[0]) { + num_responses++; + inptr += strlen(inptr) + 1; + inptr += sizeof(int); + inptr += strlen(inptr) + 1; + } + + /* + * Allocate response array. + * With an extra pair of INTs on the front to sanity + * check the pointer when we are given it back to free + */ + *response = NULL; + if (!(rarray = dm_malloc(sizeof(lvm_response_t) * num_responses + + sizeof(int) * 2))) { + errno = ENOMEM; + status = 0; + goto out; + } + + /* Unpack the response into an lvm_response_t array */ + inptr = head->args; + i = 0; + while (inptr[0]) { + strcpy(rarray[i].node, inptr); + inptr += strlen(inptr) + 1; + + memcpy(&rarray[i].status, inptr, sizeof(int)); + inptr += sizeof(int); + + rarray[i].response = dm_malloc(strlen(inptr) + 1); + if (rarray[i].response == NULL) { + /* Free up everything else and return error */ + int j; + for (j = 0; j < i; j++) + dm_free(rarray[i].response); + dm_free(rarray); + errno = ENOMEM; + status = 0; + goto out; + } + + strcpy(rarray[i].response, inptr); + rarray[i].len = strlen(inptr); + inptr += strlen(inptr) + 1; + i++; + } + *num = num_responses; + *response = rarray; + + out: + dm_free(retbuf); + + return status; +} + +/* Free reply array */ +static int _cluster_free_request(lvm_response_t * response, int num) +{ + int i; + + for (i = 0; i < num; i++) { + dm_free(response[i].response); + } + + dm_free(response); + + return 1; +} + +int refresh_clvmd(int all_nodes) +{ + int num_responses; + char args[1]; // No args really. + lvm_response_t *response = NULL; + int saved_errno; + int status; + int i; + + status = _cluster_request(CLVMD_CMD_REFRESH, all_nodes ? NODE_ALL : NODE_LOCAL, args, 0, &response, &num_responses, 0); + + /* If any nodes were down then display them and return an error */ + for (i = 0; i < num_responses; i++) { + if (response[i].status == EHOSTDOWN) { + fprintf(stderr, "clvmd not running on node %s", + response[i].node); + status = 0; + errno = response[i].status; + } else if (response[i].status) { + fprintf(stderr, "Error resetting node %s: %s", + response[i].node, + response[i].response[0] ? + response[i].response : + strerror(response[i].status)); + status = 0; + errno = response[i].status; + } + } + + saved_errno = errno; + _cluster_free_request(response, num_responses); + errno = saved_errno; + + return status; +} + +int restart_clvmd(int all_nodes) +{ + int dummy, status; + + status = _cluster_request(CLVMD_CMD_RESTART, all_nodes ? NODE_ALL : NODE_LOCAL, NULL, 0, NULL, &dummy, 1); + + /* + * FIXME: we cannot receive response, clvmd re-exec before it. + * but also should not close socket too early (the whole rq is dropped then). + * FIXME: This should be handled this way: + * - client waits for RESTART ack (and socket close) + * - server restarts + * - client checks that server is ready again (VERSION command?) + */ + usleep(500000); + + return status; +} + +int debug_clvmd(int level, int clusterwide) +{ + int num_responses; + char args[1]; + const char *nodes; + lvm_response_t *response = NULL; + int saved_errno; + int status; + int i; + + args[0] = level; + if (clusterwide) + nodes = NODE_ALL; + else + nodes = NODE_LOCAL; + + status = _cluster_request(CLVMD_CMD_SET_DEBUG, nodes, args, 1, &response, &num_responses, 0); + + /* If any nodes were down then display them and return an error */ + for (i = 0; i < num_responses; i++) { + if (response[i].status == EHOSTDOWN) { + fprintf(stderr, "clvmd not running on node %s", + response[i].node); + status = 0; + errno = response[i].status; + } else if (response[i].status) { + fprintf(stderr, "Error setting debug on node %s: %s", + response[i].node, + response[i].response[0] ? + response[i].response : + strerror(response[i].status)); + status = 0; + errno = response[i].status; + } + } + + saved_errno = errno; + _cluster_free_request(response, num_responses); + errno = saved_errno; + + return status; +}
diff --git a/daemons/clvmd/refresh_clvmd.h b/daemons/clvmd/refresh_clvmd.h new file mode 100644 index 0000000..b9d775e --- /dev/null +++ b/daemons/clvmd/refresh_clvmd.h
@@ -0,0 +1,19 @@ +/* + * Copyright (C) 2007 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + + +int refresh_clvmd(int all_nodes); +int restart_clvmd(int all_nodes); +int debug_clvmd(int level, int clusterwide); +
diff --git a/daemons/cmirrord/.gitignore b/daemons/cmirrord/.gitignore new file mode 100644 index 0000000..2711e77 --- /dev/null +++ b/daemons/cmirrord/.gitignore
@@ -0,0 +1 @@ +cmirrord
diff --git a/daemons/cmirrord/Makefile.in b/daemons/cmirrord/Makefile.in new file mode 100644 index 0000000..9d9dd7a --- /dev/null +++ b/daemons/cmirrord/Makefile.in
@@ -0,0 +1,39 @@ +# +# Copyright (C) 2009-2010 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +CPG_LIBS = @CPG_LIBS@ +CPG_CFLAGS = @CPG_CFLAGS@ +SACKPT_LIBS = @SACKPT_LIBS@ +SACKPT_CFLAGS = @SACKPT_CFLAGS@ + +SOURCES = clogd.c cluster.c compat.c functions.c link_mon.c local.c logging.c + +TARGETS = cmirrord + +include $(top_builddir)/make.tmpl + +LIBS += -ldevmapper +LMLIBS += $(CPG_LIBS) $(SACKPT_LIBS) +CFLAGS += $(CPG_CFLAGS) $(SACKPT_CFLAGS) $(EXTRA_EXEC_CFLAGS) +LDFLAGS += $(EXTRA_EXEC_LDFLAGS) + +cmirrord: $(OBJECTS) $(top_builddir)/lib/liblvm-internal.a + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJECTS) \ + $(LVMLIBS) $(LMLIBS) $(LIBS) + +install: $(TARGETS) + $(INSTALL_PROGRAM) -D cmirrord $(usrsbindir)/cmirrord
diff --git a/daemons/cmirrord/clogd.c b/daemons/cmirrord/clogd.c new file mode 100644 index 0000000..c9f65af --- /dev/null +++ b/daemons/cmirrord/clogd.c
@@ -0,0 +1,292 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "logging.h" +#include "common.h" +#include "functions.h" +#include "link_mon.h" +#include "local.h" + +#include <getopt.h> +#include <errno.h> +#include <fcntl.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <unistd.h> + +static volatile sig_atomic_t exit_now = 0; +/* FIXME Review signal handling. Should be volatile sig_atomic_t */ +static sigset_t signal_mask; +static volatile sig_atomic_t signal_received; + +static void process_signals(void); +static void daemonize(void); +static void init_all(void); +static void cleanup_all(void); + +static void usage (FILE *dest) +{ + fprintf (dest, "Usage: cmirrord [options]\n" + " -f, --foreground stay in the foreground, log to the terminal\n" + " -h, --help print this help\n"); +} + +int main(int argc, char *argv[]) +{ + int foreground_mode = 0; + struct option longopts[] = { + { "foreground", no_argument, NULL, 'f' }, + { "help" , no_argument, NULL, 'h' }, + { 0, 0, 0, 0 } + }; + int opt; + + while ((opt = getopt_long (argc, argv, "fh", longopts, NULL)) != -1) { + switch (opt) { + case 'f': + foreground_mode = 1; + break; + case 'h': + usage (stdout); + exit (0); + default: + usage (stderr); + exit (2); + } + } + if (optind < argc) { + usage (stderr); + exit (2); + } + + if (!foreground_mode) + daemonize(); + + init_all(); + + /* Parent can now exit, we're ready to handle requests */ + if (!foreground_mode) + kill(getppid(), SIGTERM); + + LOG_PRINT("Starting cmirrord:"); + LOG_PRINT(" Built: "__DATE__" "__TIME__"\n"); + LOG_DBG(" Compiled with debugging."); + + while (!exit_now) { + links_monitor(); + + links_issue_callbacks(); + + process_signals(); + } + exit(EXIT_SUCCESS); +} + +/* + * parent_exit_handler: exit the parent + * @sig: the signal + * + */ +static void parent_exit_handler(int sig __attribute__((unused))) +{ + exit_now = 1; +} + +static void sig_handler(int sig) +{ + /* FIXME Races - don't touch signal_mask here. */ + sigaddset(&signal_mask, sig); + signal_received = 1; +} + +static void process_signal(int sig){ + int r = 0; + + switch(sig) { + case SIGINT: + case SIGQUIT: + case SIGTERM: + case SIGHUP: + r += log_status(); + break; + case SIGUSR1: + case SIGUSR2: + log_debug(); + /*local_debug();*/ + cluster_debug(); + return; + default: + LOG_PRINT("Unknown signal received... ignoring"); + return; + } + + if (!r) { + LOG_DBG("No current cluster logs... safe to exit."); + cleanup_all(); + exit(EXIT_SUCCESS); + } + + LOG_ERROR("Cluster logs exist. Refusing to exit."); +} + +static void process_signals(void) +{ + int x; + + if (!signal_received) + return; + + signal_received = 0; + + for (x = 1; x < _NSIG; x++) { + if (sigismember(&signal_mask, x)) { + sigdelset(&signal_mask, x); + process_signal(x); + } + } +} + +static void remove_lockfile(void) +{ + if (unlink(CMIRRORD_PIDFILE)) + LOG_ERROR("Unable to remove \"" CMIRRORD_PIDFILE "\" %s", strerror(errno)); +} + +/* + * daemonize + * + * Performs the steps necessary to become a daemon. + */ +static void daemonize(void) +{ + int pid; + int status; + int devnull; + + if ((devnull = open("/dev/null", O_RDWR)) == -1) { + LOG_ERROR("Can't open /dev/null: %s", strerror(errno)); + exit(EXIT_FAILURE); + } + + signal(SIGTERM, &parent_exit_handler); + + pid = fork(); + + if (pid < 0) { + LOG_ERROR("Unable to fork()"); + exit(EXIT_FAILURE); + } + + if (pid) { + /* Parent waits here for child to get going */ + while (!waitpid(pid, &status, WNOHANG) && !exit_now); + if (exit_now) + exit(EXIT_SUCCESS); + + switch (WEXITSTATUS(status)) { + case EXIT_LOCKFILE: + LOG_ERROR("Failed to create lockfile"); + LOG_ERROR("Process already running?"); + break; + case EXIT_KERNEL_SOCKET: + LOG_ERROR("Unable to create netlink socket"); + break; + case EXIT_KERNEL_BIND: + LOG_ERROR("Unable to bind to netlink socket"); + break; + case EXIT_KERNEL_SETSOCKOPT: + LOG_ERROR("Unable to setsockopt on netlink socket"); + break; + case EXIT_CLUSTER_CKPT_INIT: + LOG_ERROR("Unable to initialize checkpoint service"); + LOG_ERROR("Has the cluster infrastructure been started?"); + break; + case EXIT_FAILURE: + LOG_ERROR("Failed to start: Generic error"); + break; + default: + LOG_ERROR("Failed to start: Unknown error"); + break; + } + exit(EXIT_FAILURE); + } + + setsid(); + if (chdir("/")) { + LOG_ERROR("Failed to chdir /: %s", strerror(errno)); + exit(EXIT_FAILURE); + } + + umask(0); + + if (close(0) || close(1) || close(2)) { + LOG_ERROR("Failed to close terminal FDs"); + exit(EXIT_FAILURE); + } + + if ((dup2(devnull, 0) < 0) || /* reopen stdin */ + (dup2(devnull, 1) < 0) || /* reopen stdout */ + (dup2(devnull, 2) < 0)) /* reopen stderr */ + exit(EXIT_FAILURE); + + if ((devnull > STDERR_FILENO) && close(devnull)) { + LOG_ERROR("Failed to close descriptor %d: %s", + devnull, strerror(errno)); + exit(EXIT_FAILURE); + } + + LOG_OPEN("cmirrord", LOG_PID, LOG_DAEMON); +} + +/* + * init_all + * + * Initialize modules. Exit on failure. + */ +static void init_all(void) +{ + int r; + + (void) dm_prepare_selinux_context(CMIRRORD_PIDFILE, S_IFREG); + if (dm_create_lockfile(CMIRRORD_PIDFILE) == 0) + exit(EXIT_LOCKFILE); + (void) dm_prepare_selinux_context(NULL, 0); + + atexit(remove_lockfile); + + /* FIXME Replace with sigaction. (deprecated) */ + signal(SIGINT, &sig_handler); + signal(SIGQUIT, &sig_handler); + signal(SIGTERM, &sig_handler); + signal(SIGHUP, &sig_handler); + signal(SIGPIPE, SIG_IGN); + signal(SIGUSR1, &sig_handler); + signal(SIGUSR2, &sig_handler); + sigemptyset(&signal_mask); + signal_received = 0; + + if ((r = init_local()) || + (r = init_cluster())) { + exit(r); + } +} + +/* + * cleanup_all + * + * Clean up before exiting + */ +static void cleanup_all(void) +{ + cleanup_local(); + cleanup_cluster(); +}
diff --git a/daemons/cmirrord/cluster.c b/daemons/cmirrord/cluster.c new file mode 100644 index 0000000..e196eb2 --- /dev/null +++ b/daemons/cmirrord/cluster.c
@@ -0,0 +1,1814 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "logging.h" +#include "cluster.h" +#include "common.h" +#include "compat.h" +#include "functions.h" +#include "link_mon.h" +#include "local.h" +#include "xlate.h" + +#include <corosync/cpg.h> +#include <errno.h> +#include <signal.h> +#include <unistd.h> +#if CMIRROR_HAS_CHECKPOINT +#include <openais/saAis.h> +#include <openais/saCkpt.h> + +/* Open AIS error codes */ +#define str_ais_error(x) \ + ((x) == SA_AIS_OK) ? "SA_AIS_OK" : \ + ((x) == SA_AIS_ERR_LIBRARY) ? "SA_AIS_ERR_LIBRARY" : \ + ((x) == SA_AIS_ERR_VERSION) ? "SA_AIS_ERR_VERSION" : \ + ((x) == SA_AIS_ERR_INIT) ? "SA_AIS_ERR_INIT" : \ + ((x) == SA_AIS_ERR_TIMEOUT) ? "SA_AIS_ERR_TIMEOUT" : \ + ((x) == SA_AIS_ERR_TRY_AGAIN) ? "SA_AIS_ERR_TRY_AGAIN" : \ + ((x) == SA_AIS_ERR_INVALID_PARAM) ? "SA_AIS_ERR_INVALID_PARAM" : \ + ((x) == SA_AIS_ERR_NO_MEMORY) ? "SA_AIS_ERR_NO_MEMORY" : \ + ((x) == SA_AIS_ERR_BAD_HANDLE) ? "SA_AIS_ERR_BAD_HANDLE" : \ + ((x) == SA_AIS_ERR_BUSY) ? "SA_AIS_ERR_BUSY" : \ + ((x) == SA_AIS_ERR_ACCESS) ? "SA_AIS_ERR_ACCESS" : \ + ((x) == SA_AIS_ERR_NOT_EXIST) ? "SA_AIS_ERR_NOT_EXIST" : \ + ((x) == SA_AIS_ERR_NAME_TOO_LONG) ? "SA_AIS_ERR_NAME_TOO_LONG" : \ + ((x) == SA_AIS_ERR_EXIST) ? "SA_AIS_ERR_EXIST" : \ + ((x) == SA_AIS_ERR_NO_SPACE) ? "SA_AIS_ERR_NO_SPACE" : \ + ((x) == SA_AIS_ERR_INTERRUPT) ? "SA_AIS_ERR_INTERRUPT" : \ + ((x) == SA_AIS_ERR_NAME_NOT_FOUND) ? "SA_AIS_ERR_NAME_NOT_FOUND" : \ + ((x) == SA_AIS_ERR_NO_RESOURCES) ? "SA_AIS_ERR_NO_RESOURCES" : \ + ((x) == SA_AIS_ERR_NOT_SUPPORTED) ? "SA_AIS_ERR_NOT_SUPPORTED" : \ + ((x) == SA_AIS_ERR_BAD_OPERATION) ? "SA_AIS_ERR_BAD_OPERATION" : \ + ((x) == SA_AIS_ERR_FAILED_OPERATION) ? "SA_AIS_ERR_FAILED_OPERATION" : \ + ((x) == SA_AIS_ERR_MESSAGE_ERROR) ? "SA_AIS_ERR_MESSAGE_ERROR" : \ + ((x) == SA_AIS_ERR_QUEUE_FULL) ? "SA_AIS_ERR_QUEUE_FULL" : \ + ((x) == SA_AIS_ERR_QUEUE_NOT_AVAILABLE) ? "SA_AIS_ERR_QUEUE_NOT_AVAILABLE" : \ + ((x) == SA_AIS_ERR_BAD_FLAGS) ? "SA_AIS_ERR_BAD_FLAGS" : \ + ((x) == SA_AIS_ERR_TOO_BIG) ? "SA_AIS_ERR_TOO_BIG" : \ + ((x) == SA_AIS_ERR_NO_SECTIONS) ? "SA_AIS_ERR_NO_SECTIONS" : \ + "ais_error_unknown" +#else +#define str_ais_error(x) \ + ((x) == CS_OK) ? "CS_OK" : \ + ((x) == CS_ERR_LIBRARY) ? "CS_ERR_LIBRARY" : \ + ((x) == CS_ERR_VERSION) ? "CS_ERR_VERSION" : \ + ((x) == CS_ERR_INIT) ? "CS_ERR_INIT" : \ + ((x) == CS_ERR_TIMEOUT) ? "CS_ERR_TIMEOUT" : \ + ((x) == CS_ERR_TRY_AGAIN) ? "CS_ERR_TRY_AGAIN" : \ + ((x) == CS_ERR_INVALID_PARAM) ? "CS_ERR_INVALID_PARAM" : \ + ((x) == CS_ERR_NO_MEMORY) ? "CS_ERR_NO_MEMORY" : \ + ((x) == CS_ERR_BAD_HANDLE) ? "CS_ERR_BAD_HANDLE" : \ + ((x) == CS_ERR_BUSY) ? "CS_ERR_BUSY" : \ + ((x) == CS_ERR_ACCESS) ? "CS_ERR_ACCESS" : \ + ((x) == CS_ERR_NOT_EXIST) ? "CS_ERR_NOT_EXIST" : \ + ((x) == CS_ERR_NAME_TOO_LONG) ? "CS_ERR_NAME_TOO_LONG" : \ + ((x) == CS_ERR_EXIST) ? "CS_ERR_EXIST" : \ + ((x) == CS_ERR_NO_SPACE) ? "CS_ERR_NO_SPACE" : \ + ((x) == CS_ERR_INTERRUPT) ? "CS_ERR_INTERRUPT" : \ + ((x) == CS_ERR_NAME_NOT_FOUND) ? "CS_ERR_NAME_NOT_FOUND" : \ + ((x) == CS_ERR_NO_RESOURCES) ? "CS_ERR_NO_RESOURCES" : \ + ((x) == CS_ERR_NOT_SUPPORTED) ? "CS_ERR_NOT_SUPPORTED" : \ + ((x) == CS_ERR_BAD_OPERATION) ? "CS_ERR_BAD_OPERATION" : \ + ((x) == CS_ERR_FAILED_OPERATION) ? "CS_ERR_FAILED_OPERATION" : \ + ((x) == CS_ERR_MESSAGE_ERROR) ? "CS_ERR_MESSAGE_ERROR" : \ + ((x) == CS_ERR_QUEUE_FULL) ? "CS_ERR_QUEUE_FULL" : \ + ((x) == CS_ERR_QUEUE_NOT_AVAILABLE) ? "CS_ERR_QUEUE_NOT_AVAILABLE" : \ + ((x) == CS_ERR_BAD_FLAGS) ? "CS_ERR_BAD_FLAGS" : \ + ((x) == CS_ERR_TOO_BIG) ? "CS_ERR_TOO_BIG" : \ + ((x) == CS_ERR_NO_SECTIONS) ? "CS_ERR_NO_SECTIONS" : \ + ((x) == CS_ERR_CONTEXT_NOT_FOUND) ? "CS_ERR_CONTEXT_NOT_FOUND" : \ + ((x) == CS_ERR_TOO_MANY_GROUPS) ? "CS_ERR_TOO_MANY_GROUPS" : \ + ((x) == CS_ERR_SECURITY) ? "CS_ERR_SECURITY" : \ + "cs_error_unknown" +#endif + +#define _RQ_TYPE(x) \ + ((x) == DM_ULOG_CHECKPOINT_READY) ? "DM_ULOG_CHECKPOINT_READY": \ + ((x) == DM_ULOG_MEMBER_JOIN) ? "DM_ULOG_MEMBER_JOIN": \ + RQ_TYPE((x) & ~DM_ULOG_RESPONSE) + +static uint32_t my_cluster_id = 0xDEAD; +#if CMIRROR_HAS_CHECKPOINT +static SaCkptHandleT ckpt_handle = 0; +static SaCkptCallbacksT callbacks = { 0, 0 }; +static SaVersionT version = { 'B', 1, 1 }; +#endif + +#define DEBUGGING_HISTORY 100 +#define DEBUGGING_BUFLEN 128 +#define LOG_SPRINT(cc, f, arg...) do { \ + cc->idx++; \ + cc->idx = cc->idx % DEBUGGING_HISTORY; \ + snprintf(cc->debugging[cc->idx], DEBUGGING_BUFLEN, f, ## arg); \ + } while (0) + +static int log_resp_rec = 0; + +#define RECOVERING_REGION_SECTION_SIZE 64 +struct checkpoint_data { + uint32_t requester; + char uuid[CPG_MAX_NAME_LENGTH]; + + int bitmap_size; /* in bytes */ + char *sync_bits; + char *clean_bits; + char *recovering_region; + struct checkpoint_data *next; +}; + +#define INVALID 0 +#define VALID 1 +#define LEAVING 2 + +#define MAX_CHECKPOINT_REQUESTERS 10 +struct clog_cpg { + struct dm_list list; + + uint32_t lowest_id; + cpg_handle_t handle; + struct cpg_name name; + uint64_t luid; + + /* Are we the first, or have we received checkpoint? */ + int state; + int cpg_state; /* FIXME: debugging */ + int free_me; + int delay; + int resend_requests; + struct dm_list startup_list; + struct dm_list working_list; + + int checkpoints_needed; + uint32_t checkpoint_requesters[MAX_CHECKPOINT_REQUESTERS]; + struct checkpoint_data *checkpoint_list; + int idx; + char debugging[DEBUGGING_HISTORY][DEBUGGING_BUFLEN]; +}; + +static struct dm_list clog_cpg_list; + +/* + * cluster_send + * @rq + * + * Returns: 0 on success, -Exxx on error + */ +int cluster_send(struct clog_request *rq) +{ + int r; + int found = 0; + struct iovec iov; + struct clog_cpg *entry; + + dm_list_iterate_items(entry, &clog_cpg_list) + if (!strncmp(entry->name.value, rq->u_rq.uuid, + CPG_MAX_NAME_LENGTH)) { + found = 1; + break; + } + + if (!found) { + rq->u_rq.error = -ENOENT; + return -ENOENT; + } + + /* + * Once the request heads for the cluster, the luid looses + * all its meaning. + */ + rq->u_rq.luid = 0; + + iov.iov_base = rq; + iov.iov_len = sizeof(struct clog_request) + rq->u_rq.data_size; + + rq->u.version[0] = xlate64(CLOG_TFR_VERSION); + rq->u.version[1] = CLOG_TFR_VERSION; + + r = clog_request_to_network(rq); + if (r < 0) + /* FIXME: Better error code for byteswap failure? */ + return -EINVAL; + + if (entry->cpg_state != VALID) + return -EINVAL; + +#if CMIRROR_HAS_CHECKPOINT + do { + int count = 0; + + r = cpg_mcast_joined(entry->handle, CPG_TYPE_AGREED, &iov, 1); + if (r != SA_AIS_ERR_TRY_AGAIN) + break; + count++; + if (count < 10) + LOG_PRINT("[%s] Retry #%d of cpg_mcast_joined: %s", + SHORT_UUID(rq->u_rq.uuid), count, + str_ais_error(r)); + else if ((count < 100) && !(count % 10)) + LOG_ERROR("[%s] Retry #%d of cpg_mcast_joined: %s", + SHORT_UUID(rq->u_rq.uuid), count, + str_ais_error(r)); + else if ((count < 1000) && !(count % 100)) + LOG_ERROR("[%s] Retry #%d of cpg_mcast_joined: %s", + SHORT_UUID(rq->u_rq.uuid), count, + str_ais_error(r)); + else if ((count < 10000) && !(count % 1000)) + LOG_ERROR("[%s] Retry #%d of cpg_mcast_joined: %s - " + "OpenAIS not handling the load?", + SHORT_UUID(rq->u_rq.uuid), count, + str_ais_error(r)); + usleep(1000); + } while (1); +#else + r = cpg_mcast_joined(entry->handle, CPG_TYPE_AGREED, &iov, 1); +#endif + if (r == CS_OK) + return 0; + + /* error codes found in openais/cpg.h */ + LOG_ERROR("cpg_mcast_joined error: %d", r); + + rq->u_rq.error = -EBADE; + return -EBADE; +} + +static struct clog_request *get_matching_rq(struct clog_request *rq, + struct dm_list *l) +{ + struct clog_request *match, *n; + + dm_list_iterate_items_gen_safe(match, n, l, u.list) + if (match->u_rq.seq == rq->u_rq.seq) { + dm_list_del(&match->u.list); + return match; + } + + return NULL; +} + +static char rq_buffer[DM_ULOG_REQUEST_SIZE]; +static int handle_cluster_request(struct clog_cpg *entry __attribute__((unused)), + struct clog_request *rq, int server) +{ + int r = 0; + struct clog_request *tmp = (struct clog_request *)rq_buffer; + + /* + * We need a separate dm_ulog_request struct, one that can carry + * a return payload. Otherwise, the memory address after + * rq will be altered - leading to problems + */ + memset(rq_buffer, 0, sizeof(rq_buffer)); + memcpy(tmp, rq, sizeof(struct clog_request) + rq->u_rq.data_size); + + /* + * With resumes, we only handle our own. + * Resume is a special case that requires + * local action (to set up CPG), followed by + * a cluster action to co-ordinate reading + * the disk and checkpointing + */ + if (tmp->u_rq.request_type == DM_ULOG_RESUME) { + if (tmp->originator == my_cluster_id) { + r = do_request(tmp, server); + + r = kernel_send(&tmp->u_rq); + if (r < 0) + LOG_ERROR("Failed to send resume response to kernel"); + } + return r; + } + + r = do_request(tmp, server); + + if (server && + (tmp->u_rq.request_type != DM_ULOG_CLEAR_REGION) && + (tmp->u_rq.request_type != DM_ULOG_POSTSUSPEND)) { + tmp->u_rq.request_type |= DM_ULOG_RESPONSE; + + /* + * Errors from previous functions are in the rq struct. + */ + r = cluster_send(tmp); + if (r < 0) + LOG_ERROR("cluster_send failed: %s", strerror(-r)); + } + + return r; +} + +static int handle_cluster_response(struct clog_cpg *entry, + struct clog_request *rq) +{ + int r = 0; + struct clog_request *orig_rq; + + /* + * If I didn't send it, then I don't care about the response + */ + if (rq->originator != my_cluster_id) + return 0; + + rq->u_rq.request_type &= ~DM_ULOG_RESPONSE; + orig_rq = get_matching_rq(rq, &entry->working_list); + + if (!orig_rq) { + /* Unable to find match for response */ + + LOG_ERROR("[%s] No match for cluster response: %s:%u", + SHORT_UUID(rq->u_rq.uuid), + _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq); + + LOG_ERROR("Current local list:"); + if (dm_list_empty(&entry->working_list)) + LOG_ERROR(" [none]"); + + dm_list_iterate_items_gen(orig_rq, &entry->working_list, u.list) + LOG_ERROR(" [%s] %s:%u", + SHORT_UUID(orig_rq->u_rq.uuid), + _RQ_TYPE(orig_rq->u_rq.request_type), + orig_rq->u_rq.seq); + + return -EINVAL; + } + + if (log_resp_rec > 0) { + LOG_COND(log_resend_requests, + "[%s] Response received to %s/#%u", + SHORT_UUID(rq->u_rq.uuid), + _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq); + log_resp_rec--; + } + + /* FIXME: Ensure memcpy cannot explode */ + memcpy(orig_rq, rq, sizeof(*rq) + rq->u_rq.data_size); + + r = kernel_send(&orig_rq->u_rq); + if (r) + LOG_ERROR("Failed to send response to kernel"); + + free(orig_rq); + return r; +} + +static struct clog_cpg *find_clog_cpg(cpg_handle_t handle) +{ + struct clog_cpg *match; + + dm_list_iterate_items(match, &clog_cpg_list) + if (match->handle == handle) + return match; + + return NULL; +} + +/* + * prepare_checkpoint + * @entry: clog_cpg describing the log + * @cp_requester: nodeid requesting the checkpoint + * + * Creates and fills in a new checkpoint_data struct. + * + * Returns: checkpoint_data on success, NULL on error + */ +static struct checkpoint_data *prepare_checkpoint(struct clog_cpg *entry, + uint32_t cp_requester) +{ + int r; + struct checkpoint_data *new; + + if (entry->state != VALID) { + /* + * We can't store bitmaps yet, because the log is not + * valid yet. + */ + LOG_ERROR("Forced to refuse checkpoint for nodeid %u - log not valid yet", + cp_requester); + return NULL; + } + + new = malloc(sizeof(*new)); + if (!new) { + LOG_ERROR("Unable to create checkpoint data for %u", + cp_requester); + return NULL; + } + memset(new, 0, sizeof(*new)); + new->requester = cp_requester; + strncpy(new->uuid, entry->name.value, entry->name.length); + + new->bitmap_size = push_state(entry->name.value, entry->luid, + "clean_bits", + &new->clean_bits, cp_requester); + if (new->bitmap_size <= 0) { + LOG_ERROR("Failed to store clean_bits to checkpoint for node %u", + new->requester); + free(new); + return NULL; + } + + new->bitmap_size = push_state(entry->name.value, entry->luid, + "sync_bits", + &new->sync_bits, cp_requester); + if (new->bitmap_size <= 0) { + LOG_ERROR("Failed to store sync_bits to checkpoint for node %u", + new->requester); + free(new->clean_bits); + free(new); + return NULL; + } + + r = push_state(entry->name.value, entry->luid, + "recovering_region", + &new->recovering_region, cp_requester); + if (r <= 0) { + LOG_ERROR("Failed to store recovering_region to checkpoint for node %u", + new->requester); + free(new->sync_bits); + free(new->clean_bits); + free(new); + return NULL; + } + LOG_DBG("[%s] Checkpoint prepared for node %u:", + SHORT_UUID(new->uuid), new->requester); + LOG_DBG(" bitmap_size = %d", new->bitmap_size); + + return new; +} + +/* + * free_checkpoint + * @cp: the checkpoint_data struct to free + * + */ +static void free_checkpoint(struct checkpoint_data *cp) +{ + free(cp->recovering_region); + free(cp->sync_bits); + free(cp->clean_bits); + free(cp); +} + +#if CMIRROR_HAS_CHECKPOINT +static int export_checkpoint(struct checkpoint_data *cp) +{ + SaCkptCheckpointCreationAttributesT attr; + SaCkptCheckpointHandleT h; + SaCkptSectionIdT section_id; + SaCkptSectionCreationAttributesT section_attr; + SaCkptCheckpointOpenFlagsT flags; + SaNameT name; + SaAisErrorT rv; + struct clog_request *rq; + int len, r = 0; + char buf[32]; + + LOG_DBG("Sending checkpointed data to %u", cp->requester); + + len = snprintf((char *)(name.value), SA_MAX_NAME_LENGTH, + "bitmaps_%s_%u", SHORT_UUID(cp->uuid), cp->requester); + name.length = (SaUint16T)len; + + len = (int)strlen(cp->recovering_region) + 1; + + attr.creationFlags = SA_CKPT_WR_ALL_REPLICAS; + attr.checkpointSize = cp->bitmap_size * 2 + len; + + attr.retentionDuration = SA_TIME_MAX; + attr.maxSections = 4; /* don't know why we need +1 */ + + attr.maxSectionSize = (cp->bitmap_size > len) ? cp->bitmap_size : len; + attr.maxSectionIdSize = 22; + + flags = SA_CKPT_CHECKPOINT_READ | + SA_CKPT_CHECKPOINT_WRITE | + SA_CKPT_CHECKPOINT_CREATE; + +open_retry: + rv = saCkptCheckpointOpen(ckpt_handle, &name, &attr, flags, 0, &h); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("export_checkpoint: ckpt open retry"); + usleep(1000); + goto open_retry; + } + + if (rv == SA_AIS_ERR_EXIST) { + LOG_DBG("export_checkpoint: checkpoint already exists"); + return -EEXIST; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("[%s] Failed to open checkpoint for %u: %s", + SHORT_UUID(cp->uuid), cp->requester, + str_ais_error(rv)); + return -EIO; /* FIXME: better error */ + } + + /* + * Add section for sync_bits + */ + section_id.idLen = (SaUint16T)snprintf(buf, 32, "sync_bits"); + section_id.id = (unsigned char *)buf; + section_attr.sectionId = §ion_id; + section_attr.expirationTime = SA_TIME_END; + +sync_create_retry: + rv = saCkptSectionCreate(h, §ion_attr, + cp->sync_bits, cp->bitmap_size); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("Sync checkpoint section create retry"); + usleep(1000); + goto sync_create_retry; + } + + if (rv == SA_AIS_ERR_EXIST) { + LOG_DBG("Sync checkpoint section already exists"); + saCkptCheckpointClose(h); + return -EEXIST; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("Sync checkpoint section creation failed: %s", + str_ais_error(rv)); + saCkptCheckpointClose(h); + return -EIO; /* FIXME: better error */ + } + + /* + * Add section for clean_bits + */ + section_id.idLen = snprintf(buf, 32, "clean_bits"); + section_id.id = (unsigned char *)buf; + section_attr.sectionId = §ion_id; + section_attr.expirationTime = SA_TIME_END; + +clean_create_retry: + rv = saCkptSectionCreate(h, §ion_attr, cp->clean_bits, cp->bitmap_size); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("Clean checkpoint section create retry"); + usleep(1000); + goto clean_create_retry; + } + + if (rv == SA_AIS_ERR_EXIST) { + LOG_DBG("Clean checkpoint section already exists"); + saCkptCheckpointClose(h); + return -EEXIST; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("Clean checkpoint section creation failed: %s", + str_ais_error(rv)); + saCkptCheckpointClose(h); + return -EIO; /* FIXME: better error */ + } + + /* + * Add section for recovering_region + */ + section_id.idLen = snprintf(buf, 32, "recovering_region"); + section_id.id = (unsigned char *)buf; + section_attr.sectionId = §ion_id; + section_attr.expirationTime = SA_TIME_END; + +rr_create_retry: + rv = saCkptSectionCreate(h, §ion_attr, cp->recovering_region, + strlen(cp->recovering_region) + 1); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("RR checkpoint section create retry"); + usleep(1000); + goto rr_create_retry; + } + + if (rv == SA_AIS_ERR_EXIST) { + LOG_DBG("RR checkpoint section already exists"); + saCkptCheckpointClose(h); + return -EEXIST; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("RR checkpoint section creation failed: %s", + str_ais_error(rv)); + saCkptCheckpointClose(h); + return -EIO; /* FIXME: better error */ + } + + LOG_DBG("export_checkpoint: closing checkpoint"); + saCkptCheckpointClose(h); + + rq = malloc(DM_ULOG_REQUEST_SIZE); + if (!rq) { + LOG_ERROR("export_checkpoint: Unable to allocate transfer structs"); + return -ENOMEM; + } + memset(rq, 0, sizeof(*rq)); + + dm_list_init(&rq->u.list); + rq->u_rq.request_type = DM_ULOG_CHECKPOINT_READY; + rq->originator = cp->requester; /* FIXME: hack to overload meaning of originator */ + strncpy(rq->u_rq.uuid, cp->uuid, CPG_MAX_NAME_LENGTH); + rq->u_rq.seq = my_cluster_id; + + r = cluster_send(rq); + if (r) + LOG_ERROR("Failed to send checkpoint ready notice: %s", + strerror(-r)); + + free(rq); + return 0; +} + +#else +static int export_checkpoint(struct checkpoint_data *cp) +{ + int r, rq_size; + struct clog_request *rq; + + rq_size = sizeof(*rq); + rq_size += RECOVERING_REGION_SECTION_SIZE; + rq_size += cp->bitmap_size * 2; /* clean|sync_bits */ + + rq = malloc(rq_size); + if (!rq) { + LOG_ERROR("export_checkpoint: " + "Unable to allocate transfer structs"); + return -ENOMEM; + } + memset(rq, 0, rq_size); + + dm_list_init(&rq->u.list); + rq->u_rq.request_type = DM_ULOG_CHECKPOINT_READY; + rq->originator = cp->requester; + strncpy(rq->u_rq.uuid, cp->uuid, CPG_MAX_NAME_LENGTH); + rq->u_rq.seq = my_cluster_id; + rq->u_rq.data_size = rq_size - sizeof(*rq); + + /* Sync bits */ + memcpy(rq->u_rq.data, cp->sync_bits, cp->bitmap_size); + + /* Clean bits */ + memcpy(rq->u_rq.data + cp->bitmap_size, cp->clean_bits, cp->bitmap_size); + + /* Recovering region */ + memcpy(rq->u_rq.data + (cp->bitmap_size * 2), cp->recovering_region, + strlen(cp->recovering_region)); + + r = cluster_send(rq); + if (r) + LOG_ERROR("Failed to send checkpoint ready notice: %s", + strerror(-r)); + + free(rq); + return 0; +} +#endif /* CMIRROR_HAS_CHECKPOINT */ + +#if CMIRROR_HAS_CHECKPOINT +static int import_checkpoint(struct clog_cpg *entry, int no_read, + struct clog_request *rq __attribute__((unused))) +{ + int rtn = 0; + SaCkptCheckpointHandleT h; + SaCkptSectionIterationHandleT itr; + SaCkptSectionDescriptorT desc; + SaCkptIOVectorElementT iov; + SaNameT name; + SaAisErrorT rv; + char *bitmap = NULL; + int len; + + bitmap = malloc(1024*1024); + if (!bitmap) + return -ENOMEM; + + len = snprintf((char *)(name.value), SA_MAX_NAME_LENGTH, "bitmaps_%s_%u", + SHORT_UUID(entry->name.value), my_cluster_id); + name.length = (SaUint16T)len; + +open_retry: + rv = saCkptCheckpointOpen(ckpt_handle, &name, NULL, + SA_CKPT_CHECKPOINT_READ, 0, &h); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("import_checkpoint: ckpt open retry"); + usleep(1000); + goto open_retry; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("[%s] Failed to open checkpoint: %s", + SHORT_UUID(entry->name.value), str_ais_error(rv)); + free(bitmap); + return -EIO; /* FIXME: better error */ + } + +unlink_retry: + rv = saCkptCheckpointUnlink(ckpt_handle, &name); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("import_checkpoint: ckpt unlink retry"); + usleep(1000); + goto unlink_retry; + } + + if (no_read) { + LOG_DBG("Checkpoint for this log already received"); + goto no_read; + } + +init_retry: + rv = saCkptSectionIterationInitialize(h, SA_CKPT_SECTIONS_ANY, + SA_TIME_END, &itr); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("import_checkpoint: sync create retry"); + usleep(1000); + goto init_retry; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("[%s] Sync checkpoint section creation failed: %s", + SHORT_UUID(entry->name.value), str_ais_error(rv)); + free(bitmap); + return -EIO; /* FIXME: better error */ + } + + len = 0; + while (1) { + rv = saCkptSectionIterationNext(itr, &desc); + if (rv == SA_AIS_OK) + len++; + else if ((rv == SA_AIS_ERR_NO_SECTIONS) && len) + break; + else if (rv != SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("saCkptSectionIterationNext failure: %d", rv); + break; + } + } + saCkptSectionIterationFinalize(itr); + if (len != 3) { + LOG_ERROR("import_checkpoint: %d checkpoint sections found", + len); + usleep(1000); + goto init_retry; + } + saCkptSectionIterationInitialize(h, SA_CKPT_SECTIONS_ANY, + SA_TIME_END, &itr); + + while (1) { + rv = saCkptSectionIterationNext(itr, &desc); + if (rv == SA_AIS_ERR_NO_SECTIONS) + break; + + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("import_checkpoint: ckpt iternext retry"); + usleep(1000); + continue; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("import_checkpoint: clean checkpoint section " + "creation failed: %s", str_ais_error(rv)); + rtn = -EIO; /* FIXME: better error */ + goto fail; + } + + if (!desc.sectionSize) { + LOG_ERROR("Checkpoint section empty"); + continue; + } + + memset(bitmap, 0, sizeof(*bitmap)); + iov.sectionId = desc.sectionId; + iov.dataBuffer = bitmap; + iov.dataSize = desc.sectionSize; + iov.dataOffset = 0; + + read_retry: + rv = saCkptCheckpointRead(h, &iov, 1, NULL); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("ckpt read retry"); + usleep(1000); + goto read_retry; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("import_checkpoint: ckpt read error: %s", + str_ais_error(rv)); + rtn = -EIO; /* FIXME: better error */ + goto fail; + } + + if (iov.readSize) { + if (pull_state(entry->name.value, entry->luid, + (char *)desc.sectionId.id, bitmap, + iov.readSize)) { + LOG_ERROR("Error loading state"); + rtn = -EIO; + goto fail; + } + } else { + /* Need to request new checkpoint */ + rtn = -EAGAIN; + goto fail; + } + } + +fail: + saCkptSectionIterationFinalize(itr); +no_read: + saCkptCheckpointClose(h); + + free(bitmap); + return rtn; +} + +#else +static int import_checkpoint(struct clog_cpg *entry, int no_read, + struct clog_request *rq) +{ + int bitmap_size; + + if (no_read) { + LOG_DBG("Checkpoint for this log already received"); + return 0; + } + + bitmap_size = (rq->u_rq.data_size - RECOVERING_REGION_SECTION_SIZE) / 2; + if (bitmap_size < 0) { + LOG_ERROR("Checkpoint has invalid payload size."); + return -EINVAL; + } + + if (pull_state(entry->name.value, entry->luid, "sync_bits", + rq->u_rq.data, bitmap_size) || + pull_state(entry->name.value, entry->luid, "clean_bits", + rq->u_rq.data + bitmap_size, bitmap_size) || + pull_state(entry->name.value, entry->luid, "recovering_region", + rq->u_rq.data + (bitmap_size * 2), + RECOVERING_REGION_SECTION_SIZE)) { + LOG_ERROR("Error loading bitmap state from checkpoint."); + return -EIO; + } + return 0; +} +#endif /* CMIRROR_HAS_CHECKPOINT */ + +static void do_checkpoints(struct clog_cpg *entry, int leaving) +{ + struct checkpoint_data *cp; + + for (cp = entry->checkpoint_list; cp;) { + /* + * FIXME: Check return code. Could send failure + * notice in rq in export_checkpoint function + * by setting rq->error + */ + switch (export_checkpoint(cp)) { + case -EEXIST: + LOG_SPRINT(entry, "[%s] Checkpoint for %u already handled%s", + SHORT_UUID(entry->name.value), cp->requester, + (leaving) ? "(L)": ""); + LOG_COND(log_checkpoint, + "[%s] Checkpoint for %u already handled%s", + SHORT_UUID(entry->name.value), cp->requester, + (leaving) ? "(L)": ""); + entry->checkpoint_list = cp->next; + free_checkpoint(cp); + cp = entry->checkpoint_list; + break; + case 0: + LOG_SPRINT(entry, "[%s] Checkpoint data available for node %u%s", + SHORT_UUID(entry->name.value), cp->requester, + (leaving) ? "(L)": ""); + LOG_COND(log_checkpoint, + "[%s] Checkpoint data available for node %u%s", + SHORT_UUID(entry->name.value), cp->requester, + (leaving) ? "(L)": ""); + entry->checkpoint_list = cp->next; + free_checkpoint(cp); + cp = entry->checkpoint_list; + break; + default: + /* FIXME: Skipping will cause list corruption */ + LOG_ERROR("[%s] Failed to export checkpoint for %u%s", + SHORT_UUID(entry->name.value), cp->requester, + (leaving) ? "(L)": ""); + } + } +} + +static int resend_requests(struct clog_cpg *entry) +{ + int r = 0; + struct clog_request *rq, *n; + + if (!entry->resend_requests || entry->delay) + return 0; + + if (entry->state != VALID) + return 0; + + entry->resend_requests = 0; + + dm_list_iterate_items_gen_safe(rq, n, &entry->working_list, u.list) { + dm_list_del(&rq->u.list); + + if (strcmp(entry->name.value, rq->u_rq.uuid)) { + LOG_ERROR("[%s] Stray request from another log (%s)", + SHORT_UUID(entry->name.value), + SHORT_UUID(rq->u_rq.uuid)); + free(rq); + continue; + } + + switch (rq->u_rq.request_type) { + case DM_ULOG_SET_REGION_SYNC: + /* + * Some requests simply do not need to be resent. + * If it is a request that just changes log state, + * then it doesn't need to be resent (everyone makes + * updates). + */ + LOG_COND(log_resend_requests, + "[%s] Skipping resend of %s/#%u...", + SHORT_UUID(entry->name.value), + _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq); + LOG_SPRINT(entry, "### No resend: [%s] %s/%u ###", + SHORT_UUID(entry->name.value), + _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq); + + rq->u_rq.data_size = 0; + if (kernel_send(&rq->u_rq)) + LOG_ERROR("Failed to respond to kernel [%s]", + RQ_TYPE(rq->u_rq.request_type)); + break; + + default: + /* + * If an action or a response is required, then + * the request must be resent. + */ + LOG_COND(log_resend_requests, + "[%s] Resending %s(#%u) due to new server(%u)", + SHORT_UUID(entry->name.value), + _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq, entry->lowest_id); + LOG_SPRINT(entry, "*** Resending: [%s] %s/%u ***", + SHORT_UUID(entry->name.value), + _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq); + r = cluster_send(rq); + if (r < 0) + LOG_ERROR("Failed resend"); + } + free(rq); + } + + return r; +} + +static int do_cluster_work(void *data __attribute__((unused))) +{ + int r = CS_OK; + struct clog_cpg *entry, *tmp; + + dm_list_iterate_items_safe(entry, tmp, &clog_cpg_list) { + r = cpg_dispatch(entry->handle, CS_DISPATCH_ALL); + if (r != CS_OK) { + if ((r == CS_ERR_BAD_HANDLE) && + ((entry->state == INVALID) || + (entry->state == LEAVING))) + /* It's ok if we've left the cluster */ + r = CS_OK; + else + LOG_ERROR("cpg_dispatch failed: %s", + str_ais_error(r)); + } + + if (entry->free_me) { + free(entry); + continue; + } + do_checkpoints(entry, 0); + + resend_requests(entry); + } + + return (r == CS_OK) ? 0 : -1; /* FIXME: good error number? */ +} + +static int flush_startup_list(struct clog_cpg *entry) +{ + int r = 0; + int i_was_server; + struct clog_request *rq, *n; + struct checkpoint_data *new; + + dm_list_iterate_items_gen_safe(rq, n, &entry->startup_list, u.list) { + dm_list_del(&rq->u.list); + + if (rq->u_rq.request_type == DM_ULOG_MEMBER_JOIN) { + new = prepare_checkpoint(entry, rq->originator); + if (!new) { + /* + * FIXME: Need better error handling. Other nodes + * will be trying to send the checkpoint too, and we + * must continue processing the list; so report error + * but continue. + */ + LOG_ERROR("Failed to prepare checkpoint for %u!!!", + rq->originator); + free(rq); + continue; + } + LOG_SPRINT(entry, "[%s] Checkpoint prepared for %u", + SHORT_UUID(entry->name.value), rq->originator); + LOG_COND(log_checkpoint, "[%s] Checkpoint prepared for %u", + SHORT_UUID(entry->name.value), rq->originator); + new->next = entry->checkpoint_list; + entry->checkpoint_list = new; + } else { + LOG_DBG("[%s] Processing delayed request: %s", + SHORT_UUID(rq->u_rq.uuid), + _RQ_TYPE(rq->u_rq.request_type)); + i_was_server = (rq->pit_server == my_cluster_id) ? 1 : 0; + r = handle_cluster_request(entry, rq, i_was_server); + + if (r) + /* + * FIXME: If we error out here, we will never get + * another opportunity to retry these requests + */ + LOG_ERROR("Error while processing delayed CPG message"); + } + free(rq); + } + + return 0; +} + +static void cpg_message_callback(cpg_handle_t handle, const struct cpg_name *gname __attribute__((unused)), + uint32_t nodeid, uint32_t pid __attribute__((unused)), + void *msg, size_t msg_len) +{ + int i; + int r = 0; + int i_am_server; + int response = 0; + struct clog_request *rq = msg; + struct clog_request *tmp_rq, *tmp_rq2; + struct clog_cpg *match; + + match = find_clog_cpg(handle); + if (!match) { + LOG_ERROR("Unable to find clog_cpg for cluster message"); + return; + } + + /* + * Perform necessary endian and version compatibility conversions + */ + if (clog_request_from_network(rq, msg_len) < 0) + /* Any error messages come from 'clog_request_from_network' */ + return; + + if ((nodeid == my_cluster_id) && + !(rq->u_rq.request_type & DM_ULOG_RESPONSE) && + (rq->u_rq.request_type != DM_ULOG_RESUME) && + (rq->u_rq.request_type != DM_ULOG_CLEAR_REGION) && + (rq->u_rq.request_type != DM_ULOG_CHECKPOINT_READY)) { + tmp_rq = malloc(DM_ULOG_REQUEST_SIZE); + if (!tmp_rq) { + /* + * FIXME: It may be possible to continue... but we + * would not be able to resend any messages that might + * be necessary during membership changes + */ + LOG_ERROR("[%s] Unable to record request: -ENOMEM", + SHORT_UUID(rq->u_rq.uuid)); + return; + } + memcpy(tmp_rq, rq, sizeof(*rq) + rq->u_rq.data_size); + dm_list_init(&tmp_rq->u.list); + dm_list_add(&match->working_list, &tmp_rq->u.list); + } + + if (rq->u_rq.request_type == DM_ULOG_POSTSUSPEND) { + /* + * If the server (lowest_id) indicates it is leaving, + * then we must resend any outstanding requests. However, + * we do not want to resend them if the next server in + * line is in the process of leaving. + */ + if (nodeid == my_cluster_id) { + LOG_COND(log_resend_requests, "[%s] I am leaving.1.....", + SHORT_UUID(rq->u_rq.uuid)); + } else { + if (nodeid < my_cluster_id) { + if (nodeid == match->lowest_id) { + match->resend_requests = 1; + LOG_COND(log_resend_requests, "[%s] %u is leaving, resend required%s", + SHORT_UUID(rq->u_rq.uuid), nodeid, + (dm_list_empty(&match->working_list)) ? " -- working_list empty": ""); + + dm_list_iterate_items_gen(tmp_rq, &match->working_list, u.list) + LOG_COND(log_resend_requests, + "[%s] %s/%u", + SHORT_UUID(tmp_rq->u_rq.uuid), + _RQ_TYPE(tmp_rq->u_rq.request_type), + tmp_rq->u_rq.seq); + } + + match->delay++; + LOG_COND(log_resend_requests, "[%s] %u is leaving, delay = %d", + SHORT_UUID(rq->u_rq.uuid), nodeid, match->delay); + } + rq->originator = nodeid; /* don't really need this, but nice for debug */ + goto out; + } + } + + /* + * We can receive messages after we do a cpg_leave but before we + * get our config callback. However, since we can't respond after + * leaving, we simply return. + */ + if (match->state == LEAVING) + return; + + i_am_server = (my_cluster_id == match->lowest_id) ? 1 : 0; + + if (rq->u_rq.request_type == DM_ULOG_CHECKPOINT_READY) { + if (my_cluster_id == rq->originator) { + /* Redundant checkpoints ignored if match->valid */ + LOG_SPRINT(match, "[%s] CHECKPOINT_READY notification from %u", + SHORT_UUID(rq->u_rq.uuid), nodeid); + if (import_checkpoint(match, + (match->state != INVALID), rq)) { + LOG_SPRINT(match, + "[%s] Failed to import checkpoint from %u", + SHORT_UUID(rq->u_rq.uuid), nodeid); + LOG_ERROR("[%s] Failed to import checkpoint from %u", + SHORT_UUID(rq->u_rq.uuid), nodeid); + kill(getpid(), SIGUSR1); + /* Could we retry? */ + goto out; + } else if (match->state == INVALID) { + LOG_SPRINT(match, + "[%s] Checkpoint data received from %u. Log is now valid", + SHORT_UUID(match->name.value), nodeid); + LOG_COND(log_checkpoint, + "[%s] Checkpoint data received from %u. Log is now valid", + SHORT_UUID(match->name.value), nodeid); + match->state = VALID; + + flush_startup_list(match); + } else { + LOG_SPRINT(match, + "[%s] Redundant checkpoint from %u ignored.", + SHORT_UUID(rq->u_rq.uuid), nodeid); + } + } + goto out; + } + + if (rq->u_rq.request_type & DM_ULOG_RESPONSE) { + response = 1; + r = handle_cluster_response(match, rq); + } else { + rq->originator = nodeid; + + if (match->state == LEAVING) { + LOG_ERROR("[%s] Ignoring %s from %u. Reason: I'm leaving", + SHORT_UUID(rq->u_rq.uuid), _RQ_TYPE(rq->u_rq.request_type), + rq->originator); + goto out; + } + + if (match->state == INVALID) { + LOG_DBG("Log not valid yet, storing request"); + if (!(tmp_rq2 = malloc(DM_ULOG_REQUEST_SIZE))) { + LOG_ERROR("cpg_message_callback: Unable to" + " allocate transfer structs"); + r = -ENOMEM; /* FIXME: Better error #? */ + goto out; + } + + memcpy(tmp_rq2, rq, sizeof(*rq) + rq->u_rq.data_size); + tmp_rq2->pit_server = match->lowest_id; + dm_list_init(&tmp_rq2->u.list); + dm_list_add(&match->startup_list, &tmp_rq2->u.list); + goto out; + } + + r = handle_cluster_request(match, rq, i_am_server); + } + + /* + * If the log is now valid, we can queue the checkpoints + */ + for (i = match->checkpoints_needed; i; ) { + struct checkpoint_data *new; + + if (log_get_state(&rq->u_rq) != LOG_RESUMED) { + LOG_DBG("[%s] Withholding checkpoints until log is valid (%s from %u)", + SHORT_UUID(rq->u_rq.uuid), _RQ_TYPE(rq->u_rq.request_type), nodeid); + break; + } + + i--; + new = prepare_checkpoint(match, match->checkpoint_requesters[i]); + if (!new) { + /* FIXME: Need better error handling */ + LOG_ERROR("[%s] Failed to prepare checkpoint for %u!!!", + SHORT_UUID(rq->u_rq.uuid), match->checkpoint_requesters[i]); + break; + } + LOG_SPRINT(match, "[%s] Checkpoint prepared for %u* (%s)", + SHORT_UUID(rq->u_rq.uuid), match->checkpoint_requesters[i], + (log_get_state(&rq->u_rq) != LOG_RESUMED)? "LOG_RESUMED": "LOG_SUSPENDED"); + LOG_COND(log_checkpoint, "[%s] Checkpoint prepared for %u*", + SHORT_UUID(rq->u_rq.uuid), match->checkpoint_requesters[i]); + match->checkpoints_needed--; + + new->next = match->checkpoint_list; + match->checkpoint_list = new; + } + +out: + /* nothing happens after this point. It is just for debugging */ + if (r) { + LOG_ERROR("[%s] Error while processing CPG message, %s: %s", + SHORT_UUID(rq->u_rq.uuid), + _RQ_TYPE(rq->u_rq.request_type & ~DM_ULOG_RESPONSE), + strerror(-r)); + LOG_ERROR("[%s] Response : %s", SHORT_UUID(rq->u_rq.uuid), + (response) ? "YES" : "NO"); + LOG_ERROR("[%s] Originator: %u", + SHORT_UUID(rq->u_rq.uuid), rq->originator); + if (response) + LOG_ERROR("[%s] Responder : %u", + SHORT_UUID(rq->u_rq.uuid), nodeid); + + LOG_ERROR("HISTORY::"); + for (i = 0; i < DEBUGGING_HISTORY; i++) { + match->idx++; + match->idx = match->idx % DEBUGGING_HISTORY; + if (match->debugging[match->idx][0] == '\0') + continue; + LOG_ERROR("%d:%d) %s", i, match->idx, + match->debugging[match->idx]); + } + } else if (!(rq->u_rq.request_type & DM_ULOG_RESPONSE) || + (rq->originator == my_cluster_id)) { + if (!response) + LOG_SPRINT(match, "SEQ#=%u, UUID=%s, TYPE=%s, ORIG=%u, RESP=%s", + rq->u_rq.seq, SHORT_UUID(rq->u_rq.uuid), + _RQ_TYPE(rq->u_rq.request_type), + rq->originator, (response) ? "YES" : "NO"); + else + LOG_SPRINT(match, "SEQ#=%u, UUID=%s, TYPE=%s, ORIG=%u, RESP=%s, RSPR=%u, error=%d", + rq->u_rq.seq, SHORT_UUID(rq->u_rq.uuid), + _RQ_TYPE(rq->u_rq.request_type), + rq->originator, (response) ? "YES" : "NO", + nodeid, rq->u_rq.error); + } +} + +static void cpg_join_callback(struct clog_cpg *match, + const struct cpg_address *joined, + const struct cpg_address *member_list, + size_t member_list_entries) +{ + unsigned i; + uint32_t my_pid = (uint32_t)getpid(); + uint32_t lowest = match->lowest_id; + struct clog_request *rq; + char dbuf[64] = { 0 }; + char *dbuf_p = dbuf; + size_t dbuf_rem = sizeof dbuf; + + /* Assign my_cluster_id */ + if ((my_cluster_id == 0xDEAD) && (joined->pid == my_pid)) + my_cluster_id = joined->nodeid; + + /* Am I the very first to join? */ + if (member_list_entries == 1) { + match->lowest_id = joined->nodeid; + match->state = VALID; + } + + /* If I am part of the joining list, I do not send checkpoints */ + if (joined->nodeid == my_cluster_id) + goto out; + + for (i = 0; i < member_list_entries - 1; i++) { + int written = snprintf(dbuf_p, dbuf_rem, "%u-", member_list[i].nodeid); + if (written < 0) continue; /* impossible */ + if ((unsigned)written >= dbuf_rem) { + dbuf_rem = 0; + break; + } + dbuf_rem -= written; + dbuf_p += written; + } + snprintf(dbuf_p, dbuf_rem, "(%u)", joined->nodeid); + LOG_COND(log_checkpoint, "[%s] Joining node, %u needs checkpoint [%s]", + SHORT_UUID(match->name.value), joined->nodeid, dbuf); + + /* + * FIXME: remove checkpoint_requesters/checkpoints_needed, and use + * the startup_list interface exclusively + */ + if (dm_list_empty(&match->startup_list) && (match->state == VALID) && + (match->checkpoints_needed < MAX_CHECKPOINT_REQUESTERS)) { + match->checkpoint_requesters[match->checkpoints_needed++] = joined->nodeid; + goto out; + } + + rq = malloc(DM_ULOG_REQUEST_SIZE); + if (!rq) { + LOG_ERROR("cpg_config_callback: " + "Unable to allocate transfer structs"); + LOG_ERROR("cpg_config_callback: " + "Unable to perform checkpoint"); + goto out; + } + rq->u_rq.request_type = DM_ULOG_MEMBER_JOIN; + rq->originator = joined->nodeid; + dm_list_init(&rq->u.list); + dm_list_add(&match->startup_list, &rq->u.list); + +out: + /* Find the lowest_id, i.e. the server */ + match->lowest_id = member_list[0].nodeid; + for (i = 0; i < member_list_entries; i++) + if (match->lowest_id > member_list[i].nodeid) + match->lowest_id = member_list[i].nodeid; + + if (lowest == 0xDEAD) + LOG_COND(log_membership_change, "[%s] Server change <none> -> %u (%u %s)", + SHORT_UUID(match->name.value), match->lowest_id, + joined->nodeid, (member_list_entries == 1) ? + "is first to join" : "joined"); + else if (lowest != match->lowest_id) + LOG_COND(log_membership_change, "[%s] Server change %u -> %u (%u joined)", + SHORT_UUID(match->name.value), lowest, + match->lowest_id, joined->nodeid); + else + LOG_COND(log_membership_change, "[%s] Server unchanged at %u (%u joined)", + SHORT_UUID(match->name.value), + lowest, joined->nodeid); + LOG_SPRINT(match, "+++ UUID=%s %u join +++", + SHORT_UUID(match->name.value), joined->nodeid); +} + +static void cpg_leave_callback(struct clog_cpg *match, + const struct cpg_address *left, + const struct cpg_address *member_list, + size_t member_list_entries) +{ + unsigned i; + int j, fd; + uint32_t lowest = match->lowest_id; + struct clog_request *rq, *n; + struct checkpoint_data *p_cp, *c_cp; + + LOG_SPRINT(match, "--- UUID=%s %u left ---", + SHORT_UUID(match->name.value), left->nodeid); + + /* Am I leaving? */ + if (my_cluster_id == left->nodeid) { + LOG_DBG("Finalizing leave..."); + dm_list_del(&match->list); + + cpg_fd_get(match->handle, &fd); + links_unregister(fd); + + cluster_postsuspend(match->name.value, match->luid); + + dm_list_iterate_items_gen_safe(rq, n, &match->working_list, u.list) { + dm_list_del(&rq->u.list); + + if (rq->u_rq.request_type == DM_ULOG_POSTSUSPEND) + if (kernel_send(&rq->u_rq)) + LOG_ERROR("Failed to respond to kernel [%s]", + RQ_TYPE(rq->u_rq.request_type)); + free(rq); + } + + cpg_finalize(match->handle); + + match->free_me = 1; + match->lowest_id = 0xDEAD; + match->state = INVALID; + } + + /* Remove any pending checkpoints for the leaving node. */ + for (p_cp = NULL, c_cp = match->checkpoint_list; + c_cp && (c_cp->requester != left->nodeid); + p_cp = c_cp, c_cp = c_cp->next); + if (c_cp) { + if (p_cp) + p_cp->next = c_cp->next; + else + match->checkpoint_list = c_cp->next; + + LOG_COND(log_checkpoint, + "[%s] Removing pending checkpoint (%u is leaving)", + SHORT_UUID(match->name.value), left->nodeid); + free_checkpoint(c_cp); + } + dm_list_iterate_items_gen_safe(rq, n, &match->startup_list, u.list) { + if ((rq->u_rq.request_type == DM_ULOG_MEMBER_JOIN) && + (rq->originator == left->nodeid)) { + LOG_COND(log_checkpoint, + "[%s] Removing pending ckpt from startup list (%u is leaving)", + SHORT_UUID(match->name.value), left->nodeid); + dm_list_del(&rq->u.list); + free(rq); + } + } + for (i = 0, j = 0; (int) i < match->checkpoints_needed; i++, j++) { + match->checkpoint_requesters[j] = match->checkpoint_requesters[i]; + if (match->checkpoint_requesters[i] == left->nodeid) { + LOG_ERROR("[%s] Removing pending ckpt from needed list (%u is leaving)", + SHORT_UUID(match->name.value), left->nodeid); + j--; + } + } + match->checkpoints_needed = j; + + if (left->nodeid < my_cluster_id) { + match->delay = (match->delay > 0) ? match->delay - 1 : 0; + if (!match->delay && dm_list_empty(&match->working_list)) + match->resend_requests = 0; + LOG_COND(log_resend_requests, "[%s] %u has left, delay = %d%s", + SHORT_UUID(match->name.value), left->nodeid, + match->delay, (dm_list_empty(&match->working_list)) ? + " -- working_list empty": ""); + } + + /* Find the lowest_id, i.e. the server */ + if (!member_list_entries) { + match->lowest_id = 0xDEAD; + LOG_COND(log_membership_change, "[%s] Server change %u -> <none> " + "(%u is last to leave)", + SHORT_UUID(match->name.value), left->nodeid, + left->nodeid); + return; + } + + match->lowest_id = member_list[0].nodeid; + for (i = 0; i < member_list_entries; i++) + if (match->lowest_id > member_list[i].nodeid) + match->lowest_id = member_list[i].nodeid; + + if (lowest != match->lowest_id) { + LOG_COND(log_membership_change, "[%s] Server change %u -> %u (%u left)", + SHORT_UUID(match->name.value), lowest, + match->lowest_id, left->nodeid); + } else + LOG_COND(log_membership_change, "[%s] Server unchanged at %u (%u left)", + SHORT_UUID(match->name.value), lowest, left->nodeid); + + if ((match->state == INVALID) && !match->free_me) { + /* + * If all CPG members are waiting for checkpoints and they + * are all present in my startup_list, then I was the first to + * join and I must assume control. + * + * We do not normally end up here, but if there was a quick + * 'resume -> suspend -> resume' across the cluster, we may + * have initially thought we were not the first to join because + * of the presence of out-going (and unable to respond) members. + */ + + i = 1; /* We do not have a DM_ULOG_MEMBER_JOIN entry of our own */ + dm_list_iterate_items_gen(rq, &match->startup_list, u.list) + if (rq->u_rq.request_type == DM_ULOG_MEMBER_JOIN) + i++; + + if (i == member_list_entries) { + /* + * Last node who could have given me a checkpoint just left. + * Setting log state to VALID and acting as 'first join'. + */ + match->state = VALID; + flush_startup_list(match); + } + } +} + +static void cpg_config_callback(cpg_handle_t handle, const struct cpg_name *gname __attribute__((unused)), + const struct cpg_address *member_list, + size_t member_list_entries, + const struct cpg_address *left_list, + size_t left_list_entries, + const struct cpg_address *joined_list, + size_t joined_list_entries) +{ + struct clog_cpg *match; + int found = 0; + + dm_list_iterate_items(match, &clog_cpg_list) + if (match->handle == handle) { + found = 1; + break; + } + + if (!found) { + LOG_ERROR("Unable to find match for CPG config callback"); + return; + } + + if ((joined_list_entries + left_list_entries) > 1) + LOG_ERROR("[%s] More than one node joining/leaving", + SHORT_UUID(match->name.value)); + + if (joined_list_entries) + cpg_join_callback(match, joined_list, + member_list, member_list_entries); + else + cpg_leave_callback(match, left_list, + member_list, member_list_entries); +} + +cpg_callbacks_t cpg_callbacks = { + .cpg_deliver_fn = cpg_message_callback, + .cpg_confchg_fn = cpg_config_callback, +}; + +/* + * remove_checkpoint + * @entry + * + * Returns: 1 if checkpoint removed, 0 if no checkpoints, -EXXX on error + */ +static int remove_checkpoint(struct clog_cpg *entry) +{ +#if CMIRROR_HAS_CHECKPOINT + int len; + SaNameT name; + SaAisErrorT rv; + SaCkptCheckpointHandleT h; + + len = snprintf((char *)(name.value), SA_MAX_NAME_LENGTH, "bitmaps_%s_%u", + SHORT_UUID(entry->name.value), my_cluster_id); + name.length = len; + +open_retry: + rv = saCkptCheckpointOpen(ckpt_handle, &name, NULL, + SA_CKPT_CHECKPOINT_READ, 0, &h); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("abort_startup: ckpt open retry"); + usleep(1000); + goto open_retry; + } + + if (rv != SA_AIS_OK) + return 0; + + LOG_DBG("[%s] Removing checkpoint", SHORT_UUID(entry->name.value)); +unlink_retry: + rv = saCkptCheckpointUnlink(ckpt_handle, &name); + if (rv == SA_AIS_ERR_TRY_AGAIN) { + LOG_ERROR("abort_startup: ckpt unlink retry"); + usleep(1000); + goto unlink_retry; + } + + if (rv != SA_AIS_OK) { + LOG_ERROR("[%s] Failed to unlink checkpoint: %s", + SHORT_UUID(entry->name.value), str_ais_error(rv)); + return -EIO; + } + + saCkptCheckpointClose(h); + + return 1; +#else + /* No checkpoint to remove, so 'success' */ + return 1; +#endif +} + +int create_cluster_cpg(char *uuid, uint64_t luid) +{ + int r; + size_t size; + struct clog_cpg *new = NULL; + struct clog_cpg *tmp; + + dm_list_iterate_items(tmp, &clog_cpg_list) + if (!strncmp(tmp->name.value, uuid, CPG_MAX_NAME_LENGTH)) { + LOG_ERROR("Log entry already exists: %s", uuid); + return -EEXIST; + } + + new = malloc(sizeof(*new)); + if (!new) { + LOG_ERROR("Unable to allocate memory for clog_cpg"); + return -ENOMEM; + } + memset(new, 0, sizeof(*new)); + dm_list_init(&new->list); + new->lowest_id = 0xDEAD; + dm_list_init(&new->startup_list); + dm_list_init(&new->working_list); + + size = ((strlen(uuid) + 1) > CPG_MAX_NAME_LENGTH) ? + CPG_MAX_NAME_LENGTH : (strlen(uuid) + 1); + strncpy(new->name.value, uuid, size); + new->name.length = (uint32_t)size; + new->luid = luid; + + /* + * Ensure there are no stale checkpoints around before we join + */ + if (remove_checkpoint(new) == 1) + LOG_COND(log_checkpoint, + "[%s] Removing checkpoints left from previous session", + SHORT_UUID(new->name.value)); + + r = cpg_initialize(&new->handle, &cpg_callbacks); + if (r != CS_OK) { + LOG_ERROR("cpg_initialize failed: Cannot join cluster"); + free(new); + return -EPERM; + } + + r = cpg_join(new->handle, &new->name); + if (r != CS_OK) { + LOG_ERROR("cpg_join failed: Cannot join cluster"); + free(new); + return -EPERM; + } + + new->cpg_state = VALID; + dm_list_add(&clog_cpg_list, &new->list); + LOG_DBG("New handle: %llu", (unsigned long long)new->handle); + LOG_DBG("New name: %s", new->name.value); + + /* FIXME: better variable */ + cpg_fd_get(new->handle, &r); + links_register(r, "cluster", do_cluster_work, NULL); + + return 0; +} + +static void abort_startup(struct clog_cpg *del) +{ + struct clog_request *rq, *n; + + LOG_DBG("[%s] CPG teardown before checkpoint received", + SHORT_UUID(del->name.value)); + + dm_list_iterate_items_gen_safe(rq, n, &del->startup_list, u.list) { + dm_list_del(&rq->u.list); + + LOG_DBG("[%s] Ignoring request from %u: %s", + SHORT_UUID(del->name.value), rq->originator, + _RQ_TYPE(rq->u_rq.request_type)); + free(rq); + } + + remove_checkpoint(del); +} + +static int _destroy_cluster_cpg(struct clog_cpg *del) +{ + int r; + int state; + + LOG_COND(log_resend_requests, "[%s] I am leaving.2.....", + SHORT_UUID(del->name.value)); + + /* + * We must send any left over checkpoints before + * leaving. If we don't, an incoming node could + * be stuck with no checkpoint and stall. + do_checkpoints(del); --- THIS COULD BE CAUSING OUR PROBLEMS: + + - Incoming node deletes old checkpoints before joining + - A stale checkpoint is issued here by leaving node + - (leaving node leaves) + - Incoming node joins cluster and finds stale checkpoint. + - (leaving node leaves - option 2) + */ + do_checkpoints(del, 1); + + state = del->state; + + del->cpg_state = INVALID; + del->state = LEAVING; + + /* + * If the state is VALID, we might be processing the + * startup list. If so, we certainly don't want to + * clear the startup_list here by calling abort_startup + */ + if (!dm_list_empty(&del->startup_list) && (state != VALID)) + abort_startup(del); + + r = cpg_leave(del->handle, &del->name); + if (r != CS_OK) + LOG_ERROR("Error leaving CPG!"); + return 0; +} + +int destroy_cluster_cpg(char *uuid) +{ + struct clog_cpg *del, *tmp; + + dm_list_iterate_items_safe(del, tmp, &clog_cpg_list) + if (!strncmp(del->name.value, uuid, CPG_MAX_NAME_LENGTH)) + _destroy_cluster_cpg(del); + + return 0; +} + +int init_cluster(void) +{ +#if CMIRROR_HAS_CHECKPOINT + SaAisErrorT rv; + + rv = saCkptInitialize(&ckpt_handle, &callbacks, &version); + + if (rv != SA_AIS_OK) + return EXIT_CLUSTER_CKPT_INIT; +#endif + dm_list_init(&clog_cpg_list); + return 0; +} + +void cleanup_cluster(void) +{ +#if CMIRROR_HAS_CHECKPOINT + SaAisErrorT err; + + err = saCkptFinalize(ckpt_handle); + if (err != SA_AIS_OK) + LOG_ERROR("Failed to finalize checkpoint handle"); +#endif +} + +void cluster_debug(void) +{ + struct checkpoint_data *cp; + struct clog_cpg *entry; + struct clog_request *rq; + int i; + + LOG_ERROR(""); + LOG_ERROR("CLUSTER COMPONENT DEBUGGING::"); + dm_list_iterate_items(entry, &clog_cpg_list) { + LOG_ERROR("%s::", SHORT_UUID(entry->name.value)); + LOG_ERROR(" lowest_id : %u", entry->lowest_id); + LOG_ERROR(" state : %s", (entry->state == INVALID) ? + "INVALID" : (entry->state == VALID) ? "VALID" : + (entry->state == LEAVING) ? "LEAVING" : "UNKNOWN"); + LOG_ERROR(" cpg_state : %d", entry->cpg_state); + LOG_ERROR(" free_me : %d", entry->free_me); + LOG_ERROR(" delay : %d", entry->delay); + LOG_ERROR(" resend_requests : %d", entry->resend_requests); + LOG_ERROR(" checkpoints_needed: %d", entry->checkpoints_needed); + for (i = 0, cp = entry->checkpoint_list; + i < MAX_CHECKPOINT_REQUESTERS; i++) + if (cp) + cp = cp->next; + else + break; + LOG_ERROR(" CKPTs waiting : %d", i); + LOG_ERROR(" Working list:"); + dm_list_iterate_items_gen(rq, &entry->working_list, u.list) + LOG_ERROR(" %s/%u", _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq); + + LOG_ERROR(" Startup list:"); + dm_list_iterate_items_gen(rq, &entry->startup_list, u.list) + LOG_ERROR(" %s/%u", _RQ_TYPE(rq->u_rq.request_type), + rq->u_rq.seq); + + LOG_ERROR("Command History:"); + for (i = 0; i < DEBUGGING_HISTORY; i++) { + entry->idx++; + entry->idx = entry->idx % DEBUGGING_HISTORY; + if (entry->debugging[entry->idx][0] == '\0') + continue; + LOG_ERROR("%d:%d) %s", i, entry->idx, + entry->debugging[entry->idx]); + } + } +}
diff --git a/daemons/cmirrord/cluster.h b/daemons/cmirrord/cluster.h new file mode 100644 index 0000000..5b1e58b --- /dev/null +++ b/daemons/cmirrord/cluster.h
@@ -0,0 +1,76 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef _LVM_CLOG_CLUSTER_H +#define _LVM_CLOG_CLUSTER_H + +#include "dm-log-userspace.h" +#include "libdevmapper.h" + +#define DM_ULOG_RESPONSE 0x1000U /* in last byte of 32-bit value */ +#define DM_ULOG_CHECKPOINT_READY 21 +#define DM_ULOG_MEMBER_JOIN 22 + +/* + * There is other information in addition to what can + * be found in the dm_ulog_request structure that we + * need for processing. 'clog_request' is the wrapping + * structure we use to make the additional fields + * available. + */ +struct clog_request { + /* + * If we don't use a union, the structure size will + * vary between 32-bit and 64-bit machines. So, we + * pack two 64-bit version numbers in there to force + * the size of the structure to be the same. + * + * The two version numbers also help us with endian + * issues. The first is always little endian, while + * the second is in native format of the sending + * machine. If the two are equal, there is no need + * to do endian conversions. + */ + union { + uint64_t version[2]; /* LE version and native version */ + struct dm_list list; + } u; + + /* + * 'originator' is the machine from which the requests + * was made. + */ + uint32_t originator; + + /* + * 'pit_server' is the "point-in-time" server for the + * request. (I.e. The machine that was the server at + * the time the request was issued - only important during + * startup. + */ + uint32_t pit_server; + + /* + * The request from the kernel that is being processed + */ + struct dm_ulog_request u_rq; +}; + +int init_cluster(void); +void cleanup_cluster(void); +void cluster_debug(void); + +int create_cluster_cpg(char *uuid, uint64_t luid); +int destroy_cluster_cpg(char *uuid); + +int cluster_send(struct clog_request *rq); + +#endif /* _LVM_CLOG_CLUSTER_H */
diff --git a/daemons/cmirrord/common.h b/daemons/cmirrord/common.h new file mode 100644 index 0000000..d928d0c --- /dev/null +++ b/daemons/cmirrord/common.h
@@ -0,0 +1,33 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef _LVM_CLOG_COMMON_H +#define _LVM_CLOG_COMMON_H + +/* + * If there are problems when forking off to become a daemon, + * the child will exist with one of these codes. This allows + * the parent to know the reason for the failure and print it + * to the launching terminal. + * + * #define EXIT_SUCCESS 0 (from stdlib.h) + * #define EXIT_FAILURE 1 (from stdlib.h) + */ +#define EXIT_LOCKFILE 2 +#define EXIT_KERNEL_SOCKET 3 /* Failed netlink socket create */ +#define EXIT_KERNEL_BIND 4 +#define EXIT_KERNEL_SETSOCKOPT 5 +#define EXIT_CLUSTER_CKPT_INIT 6 /* Failed to init checkpoint */ +#define EXIT_QUEUE_NOMEM 7 + +#define DM_ULOG_REQUEST_SIZE 1024 + +#endif /* _LVM_CLOG_COMMON_H */
diff --git a/daemons/cmirrord/compat.c b/daemons/cmirrord/compat.c new file mode 100644 index 0000000..a9696d7 --- /dev/null +++ b/daemons/cmirrord/compat.c
@@ -0,0 +1,210 @@ +/* + * Copyright (C) 2010 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ +#include "logging.h" +#include "cluster.h" +#include "compat.h" +#include "xlate.h" + +#include <errno.h> + +/* + * Older versions of the log daemon communicate with different + * versions of the inter-machine communication structure, which + * varies in size and fields. The older versions append the + * standard upstream version of the structure to every request. + * COMPAT_OFFSET is where the upstream structure starts. + */ +#define COMPAT_OFFSET 256 + +static void v5_data_endian_switch(struct clog_request *rq, int to_network __attribute__((unused))) +{ + int i, end; + int64_t *pi64; + uint64_t *pu64; + uint32_t rq_type = rq->u_rq.request_type & ~DM_ULOG_RESPONSE; + + if (rq->u_rq.request_type & DM_ULOG_RESPONSE) { + switch (rq_type) { + case DM_ULOG_CTR: + case DM_ULOG_DTR: + LOG_ERROR("Invalid response type in endian switch"); + exit(EXIT_FAILURE); + + case DM_ULOG_PRESUSPEND: + case DM_ULOG_POSTSUSPEND: + case DM_ULOG_RESUME: + case DM_ULOG_FLUSH: + case DM_ULOG_MARK_REGION: + case DM_ULOG_CLEAR_REGION: + case DM_ULOG_SET_REGION_SYNC: + case DM_ULOG_CHECKPOINT_READY: + case DM_ULOG_MEMBER_JOIN: + case DM_ULOG_STATUS_INFO: + case DM_ULOG_STATUS_TABLE: + /* No outbound data */ + break; + + case DM_ULOG_GET_REGION_SIZE: + case DM_ULOG_GET_SYNC_COUNT: + pu64 = (uint64_t *)rq->u_rq.data; + *pu64 = xlate64(*pu64); + break; + case DM_ULOG_IS_CLEAN: + case DM_ULOG_IN_SYNC: + pi64 = (int64_t *)rq->u_rq.data; + *pi64 = xlate64(*pi64); + break; + case DM_ULOG_GET_RESYNC_WORK: + case DM_ULOG_IS_REMOTE_RECOVERING: + pi64 = (int64_t *)rq->u_rq.data; + pu64 = ((uint64_t *)rq->u_rq.data) + 1; + *pi64 = xlate64(*pi64); + *pu64 = xlate64(*pu64); + break; + default: + LOG_ERROR("Unknown request type, %u", rq_type); + return; + } + } else { + switch (rq_type) { + case DM_ULOG_CTR: + case DM_ULOG_DTR: + LOG_ERROR("Invalid request type in endian switch"); + exit(EXIT_FAILURE); + + case DM_ULOG_PRESUSPEND: + case DM_ULOG_POSTSUSPEND: + case DM_ULOG_RESUME: + case DM_ULOG_GET_REGION_SIZE: + case DM_ULOG_FLUSH: + case DM_ULOG_GET_RESYNC_WORK: + case DM_ULOG_GET_SYNC_COUNT: + case DM_ULOG_STATUS_INFO: + case DM_ULOG_STATUS_TABLE: + case DM_ULOG_CHECKPOINT_READY: + case DM_ULOG_MEMBER_JOIN: + /* No incoming data */ + break; + case DM_ULOG_IS_CLEAN: + case DM_ULOG_IN_SYNC: + case DM_ULOG_IS_REMOTE_RECOVERING: + pu64 = (uint64_t *)rq->u_rq.data; + *pu64 = xlate64(*pu64); + break; + case DM_ULOG_MARK_REGION: + case DM_ULOG_CLEAR_REGION: + end = rq->u_rq.data_size/sizeof(uint64_t); + + pu64 = (uint64_t *)rq->u_rq.data; + for (i = 0; i < end; i++) + pu64[i] = xlate64(pu64[i]); + break; + case DM_ULOG_SET_REGION_SYNC: + pu64 = (uint64_t *)rq->u_rq.data; + pi64 = ((int64_t *)rq->u_rq.data) + 1; + *pu64 = xlate64(*pu64); + *pi64 = xlate64(*pi64); + break; + default: + LOG_ERROR("Unknown request type, %u", rq_type); + exit(EXIT_FAILURE); + } + } +} + +static int v5_endian_to_network(struct clog_request *rq) +{ + int size; + struct dm_ulog_request *u_rq = &rq->u_rq; + + size = sizeof(*rq) + u_rq->data_size; + + u_rq->error = xlate32(u_rq->error); + u_rq->seq = xlate32(u_rq->seq); + + rq->originator = xlate32(rq->originator); + + v5_data_endian_switch(rq, 1); + + u_rq->request_type = xlate32(u_rq->request_type); + u_rq->data_size = xlate32(u_rq->data_size); + + return size; +} + +int clog_request_to_network(struct clog_request *rq) +{ + int r; + + /* FIXME: Remove this safety check */ + if (rq->u.version[0] != xlate64(rq->u.version[1])) { + LOG_ERROR("Programmer error: version[0] must be LE"); + exit(EXIT_FAILURE); + } + + /* + * Are we already running in the endian mode we send + * over the wire? + */ + if (rq->u.version[0] == rq->u.version[1]) + return 0; + + r = v5_endian_to_network(rq); + if (r < 0) + return r; + return 0; +} + +static int v5_endian_from_network(struct clog_request *rq) +{ + int size; + struct dm_ulog_request *u_rq = &rq->u_rq; + + u_rq->error = xlate32(u_rq->error); + u_rq->seq = xlate32(u_rq->seq); + u_rq->request_type = xlate32(u_rq->request_type); + u_rq->data_size = xlate32(u_rq->data_size); + + rq->originator = xlate32(rq->originator); + + size = sizeof(*rq) + u_rq->data_size; + + v5_data_endian_switch(rq, 0); + + return size; +} + +int clog_request_from_network(void *data, size_t data_len) +{ + uint64_t *vp = data; + uint64_t version = xlate64(vp[0]); + struct clog_request *rq = data; + + switch (version) { + case 5: /* Upstream */ + if (version == vp[0]) + return 0; + break; + case 4: /* RHEL 5.[45] */ + case 3: /* RHEL 5.3 */ + case 2: /* RHEL 5.2 */ + /* FIXME: still need to account for payload */ + if (data_len < (COMPAT_OFFSET + sizeof(*rq))) + return -ENOSPC; + + rq = (struct clog_request *)((char *)data + COMPAT_OFFSET); + break; + default: + LOG_ERROR("Unable to process cluster message: " + "Incompatible version"); + return -EINVAL; + } + + v5_endian_from_network(rq); + return 0; +}
diff --git a/daemons/cmirrord/compat.h b/daemons/cmirrord/compat.h new file mode 100644 index 0000000..1e0edd4 --- /dev/null +++ b/daemons/cmirrord/compat.h
@@ -0,0 +1,25 @@ +/* + * Copyright (C) 2010 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ +#ifndef _LVM_CLOG_COMPAT_H +#define _LVM_CLOG_COMPAT_H + +/* + * The intermachine communication structure version are: + * 0: Unused + * 1: Never in the wild + * 2: RHEL 5.2 + * 3: RHEL 5.3 + * 4: RHEL 5.4, RHEL 5.5 + * 5: RHEL 6, Current Upstream Format + */ +#define CLOG_TFR_VERSION 5 + +int clog_request_to_network(struct clog_request *rq); +int clog_request_from_network(void *data, size_t data_len); + +#endif /* _LVM_CLOG_COMPAT_H */
diff --git a/daemons/cmirrord/functions.c b/daemons/cmirrord/functions.c new file mode 100644 index 0000000..757d8e8 --- /dev/null +++ b/daemons/cmirrord/functions.c
@@ -0,0 +1,1962 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "logging.h" +#include "functions.h" + +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <signal.h> +#include <sys/stat.h> +#include <time.h> +#include <unistd.h> + +#define BYTE_SHIFT 3 + +/* + * Magic for persistent mirrors: "MiRr" + * Following on-disk header information is stolen from + * drivers/md/dm-log.c + */ +#define MIRROR_MAGIC 0x4D695272 +#define MIRROR_DISK_VERSION 2 +#define LOG_OFFSET 2 + +#define RESYNC_HISTORY 50 +#define RESYNC_BUFLEN 128 +//static char resync_history[RESYNC_HISTORY][128]; +//static int idx = 0; +#define LOG_SPRINT(_lc, f, arg...) do { \ + lc->idx++; \ + lc->idx = lc->idx % RESYNC_HISTORY; \ + snprintf(lc->resync_history[lc->idx], RESYNC_BUFLEN, f, ## arg); \ + } while (0) + +struct log_header { + uint32_t magic; + uint32_t version; + uint64_t nr_regions; +}; + +struct log_c { + struct dm_list list; + + char uuid[DM_UUID_LEN]; + uint64_t luid; + + time_t delay; /* limits how fast a resume can happen after suspend */ + int touched; + int in_sync; /* An in-sync that stays set until suspend/resume */ + uint32_t region_size; + uint32_t region_count; + uint64_t sync_count; + + dm_bitset_t clean_bits; + dm_bitset_t sync_bits; + uint32_t recoverer; + uint64_t recovering_region; /* -1 means not recovering */ + uint64_t skip_bit_warning; /* used to warn if region skipped */ + int sync_search; + + int resume_override; + + uint32_t block_on_error; + enum sync { + DEFAULTSYNC, /* Synchronize if necessary */ + NOSYNC, /* Devices known to be already in sync */ + FORCESYNC, /* Force a sync to happen */ + } sync; + + uint32_t state; /* current operational state of the log */ + + struct dm_list mark_list; + + uint32_t recovery_halted; + struct recovery_request *recovery_request_list; + + int disk_fd; /* -1 means no disk log */ + int log_dev_failed; + uint64_t disk_nr_regions; + size_t disk_size; /* size of disk_buffer in bytes */ + void *disk_buffer; /* aligned memory for O_DIRECT */ + int idx; + char resync_history[RESYNC_HISTORY][RESYNC_BUFLEN]; +}; + +struct mark_entry { + struct dm_list list; + uint32_t nodeid; + uint64_t region; +}; + +struct recovery_request { + uint64_t region; + struct recovery_request *next; +}; + +static DM_LIST_INIT(log_list); +static DM_LIST_INIT(log_pending_list); + +static int log_test_bit(dm_bitset_t bs, int bit) +{ + return dm_bit(bs, bit) ? 1 : 0; +} + +static void log_set_bit(struct log_c *lc, dm_bitset_t bs, int bit) +{ + dm_bit_set(bs, bit); + lc->touched = 1; +} + +static void log_clear_bit(struct log_c *lc, dm_bitset_t bs, int bit) +{ + dm_bit_clear(bs, bit); + lc->touched = 1; +} + +static uint64_t find_next_zero_bit(dm_bitset_t bs, unsigned start) +{ + for (; dm_bit(bs, start); start++) + if (start >= *bs) + return (uint64_t)-1; + + return start; +} + +static uint64_t count_bits32(dm_bitset_t bs) +{ + unsigned i, size = bs[0]/(unsigned)DM_BITS_PER_INT + 1; + unsigned count = 0; + + for (i = 1; i <= size; i++) + count += hweight32(bs[i]); + + return (uint64_t)count; +} + +/* + * get_log + * + * Returns: log if found, NULL otherwise + */ +static struct log_c *get_log(const char *uuid, uint64_t luid) +{ + struct log_c *lc; + + dm_list_iterate_items(lc, &log_list) + if (!strcmp(lc->uuid, uuid) && + (!luid || (luid == lc->luid))) + return lc; + + return NULL; +} + +/* + * get_pending_log + * + * Pending logs are logs that have been 'clog_ctr'ed, but + * have not joined the CPG (via clog_resume). + * + * Returns: log if found, NULL otherwise + */ +static struct log_c *get_pending_log(const char *uuid, uint64_t luid) +{ + struct log_c *lc; + + dm_list_iterate_items(lc, &log_pending_list) + if (!strcmp(lc->uuid, uuid) && + (!luid || (luid == lc->luid))) + return lc; + + return NULL; +} + +static void header_to_disk(struct log_header *mem, struct log_header *disk) +{ + memcpy(disk, mem, sizeof(struct log_header)); +} + +static void header_from_disk(struct log_header *mem, struct log_header *disk) +{ + memcpy(mem, disk, sizeof(struct log_header)); +} + +static int rw_log(struct log_c *lc, int do_write) +{ + int r; + + r = (int)lseek(lc->disk_fd, 0, SEEK_SET); + if (r < 0) { + LOG_ERROR("[%s] rw_log: lseek failure: %s", + SHORT_UUID(lc->uuid), strerror(errno)); + return -errno; + } + + if (do_write) { + /* FIXME Cope with full set of non-error conditions */ + r = write(lc->disk_fd, lc->disk_buffer, lc->disk_size); + if (r < 0) { + LOG_ERROR("[%s] rw_log: write failure: %s", + SHORT_UUID(lc->uuid), strerror(errno)); + return -EIO; /* Failed disk write */ + } + return 0; + } + + /* Read */ + /* FIXME Cope with full set of non-error conditions */ + r = read(lc->disk_fd, lc->disk_buffer, lc->disk_size); + if (r < 0) + LOG_ERROR("[%s] rw_log: read failure: %s", + SHORT_UUID(lc->uuid), strerror(errno)); + if (r != lc->disk_size) + return -EIO; /* Failed disk read */ + return 0; +} + +/* + * read_log + * @lc + * + * Valid return codes: + * -EINVAL: Invalid header, bits not copied + * -EIO: Unable to read disk log + * 0: Valid header, disk bit -> lc->clean_bits + * + * Returns: 0 on success, -EXXX on failure + */ +static int read_log(struct log_c *lc) +{ + struct log_header lh = { 0 }; + size_t bitset_size; + + if (rw_log(lc, 0)) + return -EIO; /* Failed disk read */ + + header_from_disk(&lh, lc->disk_buffer); + if (lh.magic != MIRROR_MAGIC) + return -EINVAL; + + lc->disk_nr_regions = lh.nr_regions; + + /* Read disk bits into sync_bits */ + bitset_size = lc->region_count / 8; + bitset_size += (lc->region_count % 8) ? 1 : 0; + + /* 'lc->clean_bits + 1' becasue dm_bitset_t leads with a uint32_t */ + memcpy(lc->clean_bits + 1, (char *)lc->disk_buffer + 1024, bitset_size); + + return 0; +} + +/* + * write_log + * @lc + * + * Returns: 0 on success, -EIO on failure + */ +static int write_log(struct log_c *lc) +{ + struct log_header lh; + size_t bitset_size; + + lh.magic = MIRROR_MAGIC; + lh.version = MIRROR_DISK_VERSION; + lh.nr_regions = lc->region_count; + + header_to_disk(&lh, lc->disk_buffer); + + /* Write disk bits from clean_bits */ + bitset_size = lc->region_count / 8; + bitset_size += (lc->region_count % 8) ? 1 : 0; + + /* 'lc->clean_bits + 1' becasue dm_bitset_t leads with a uint32_t */ + memcpy((char *)lc->disk_buffer + 1024, lc->clean_bits + 1, bitset_size); + + if (rw_log(lc, 1)) { + lc->log_dev_failed = 1; + return -EIO; /* Failed disk write */ + } + return 0; +} + +/* FIXME Rewrite this function taking advantage of the udev changes (where in use) to improve its efficiency! */ +static int find_disk_path(char *major_minor_str, char *path_rtn, int *unlink_path __attribute__((unused))) +{ + int r; + DIR *dp; + struct dirent *dep; + struct stat statbuf; + int major, minor; + + if (!strstr(major_minor_str, ":")) { + r = stat(major_minor_str, &statbuf); + if (r) + return -errno; + if (!S_ISBLK(statbuf.st_mode)) + return -EINVAL; + sprintf(path_rtn, "%s", major_minor_str); + return 0; + } + + r = sscanf(major_minor_str, "%d:%d", &major, &minor); + if (r != 2) + return -EINVAL; + + /* FIXME dm_dir() */ + LOG_DBG("Checking /dev/mapper for device %d:%d", major, minor); + /* Check /dev/mapper dir */ + dp = opendir("/dev/mapper"); + if (!dp) + return -ENOENT; + + while ((dep = readdir(dp)) != NULL) { + /* + * FIXME: This is racy. By the time the path is used, + * it may point to something else. 'fstat' will be + * required upon opening to ensure we got what we + * wanted. + */ + + sprintf(path_rtn, "/dev/mapper/%s", dep->d_name); + if (stat(path_rtn, &statbuf) < 0) { + LOG_DBG("Unable to stat %s", path_rtn); + continue; + } + if (S_ISBLK(statbuf.st_mode) && + (major(statbuf.st_rdev) == major) && + (minor(statbuf.st_rdev) == minor)) { + LOG_DBG(" %s: YES", dep->d_name); + if (closedir(dp)) + LOG_DBG("Unable to closedir /dev/mapper %s", + strerror(errno)); + return 0; + } else { + LOG_DBG(" %s: NO", dep->d_name); + } + } + + if (closedir(dp)) + LOG_DBG("Unable to closedir /dev/mapper %s", + strerror(errno)); + + /* FIXME Find out why this was here and deal with underlying problem. */ + LOG_DBG("Path not found for %d/%d", major, minor); + return -ENOENT; + + // LOG_DBG("Creating /dev/mapper/%d-%d", major, minor); + // sprintf(path_rtn, "/dev/mapper/%d-%d", major, minor); + // r = mknod(path_rtn, S_IFBLK | S_IRUSR | S_IWUSR, MKDEV(major, minor)); + /* + * If we have to make the path, we unlink it after we open it + */ + // *unlink_path = 1; + // return r ? -errno : 0; +} + +static int _clog_ctr(char *uuid, uint64_t luid, + int argc, char **argv, uint64_t device_size) +{ + int i; + int r = 0; + char *p; + uint64_t region_size; + uint64_t region_count; + struct log_c *lc = NULL; + enum sync log_sync = DEFAULTSYNC; + uint32_t block_on_error = 0; + + int disk_log; + char disk_path[128]; + int unlink_path = 0; + long page_size; + int pages; + + /* If core log request, then argv[0] will be region_size */ + if (!strtoll(argv[0], &p, 0) || *p) { + disk_log = 1; + + if ((argc < 2) || (argc > 4)) { + LOG_ERROR("Too %s arguments to clustered-disk log type", + (argc < 3) ? "few" : "many"); + r = -EINVAL; + goto fail; + } + + r = find_disk_path(argv[0], disk_path, &unlink_path); + if (r) { + LOG_ERROR("Unable to find path to device %s", argv[0]); + goto fail; + } + LOG_DBG("Clustered log disk is %s", disk_path); + } else { + disk_log = 0; + + if ((argc < 1) || (argc > 3)) { + LOG_ERROR("Too %s arguments to clustered-core log type", + (argc < 2) ? "few" : "many"); + r = -EINVAL; + goto fail; + } + } + + if (!(region_size = strtoll(argv[disk_log], &p, 0)) || *p) { + LOG_ERROR("Invalid region_size argument to clustered-%s log type", + (disk_log) ? "disk" : "core"); + r = -EINVAL; + goto fail; + } + + region_count = device_size / region_size; + if (device_size % region_size) { + /* + * I can't remember if device_size must be a multiple + * of region_size, so check it anyway. + */ + region_count++; + } + + for (i = 0; i < argc; i++) { + if (!strcmp(argv[i], "sync")) + log_sync = FORCESYNC; + else if (!strcmp(argv[i], "nosync")) + log_sync = NOSYNC; + else if (!strcmp(argv[i], "block_on_error")) + block_on_error = 1; + } + + lc = dm_zalloc(sizeof(*lc)); + if (!lc) { + LOG_ERROR("Unable to allocate cluster log context"); + r = -ENOMEM; + goto fail; + } + + lc->region_size = region_size; + lc->region_count = region_count; + lc->sync = log_sync; + lc->block_on_error = block_on_error; + lc->sync_search = 0; + lc->recovering_region = (uint64_t)-1; + lc->skip_bit_warning = region_count; + lc->disk_fd = -1; + lc->log_dev_failed = 0; + strncpy(lc->uuid, uuid, DM_UUID_LEN); + lc->luid = luid; + + if (get_log(lc->uuid, lc->luid) || + get_pending_log(lc->uuid, lc->luid)) { + LOG_ERROR("[%s/%" PRIu64 "u] Log already exists, unable to create.", + SHORT_UUID(lc->uuid), lc->luid); + dm_free(lc); + return -EINVAL; + } + + dm_list_init(&lc->mark_list); + + lc->clean_bits = dm_bitset_create(NULL, region_count); + if (!lc->clean_bits) { + LOG_ERROR("Unable to allocate clean bitset"); + r = -ENOMEM; + goto fail; + } + + lc->sync_bits = dm_bitset_create(NULL, region_count); + if (!lc->sync_bits) { + LOG_ERROR("Unable to allocate sync bitset"); + r = -ENOMEM; + goto fail; + } + if (log_sync == NOSYNC) + dm_bit_set_all(lc->sync_bits); + + lc->sync_count = (log_sync == NOSYNC) ? region_count : 0; + + if (disk_log) { + if ((page_size = sysconf(_SC_PAGESIZE)) < 0) { + LOG_ERROR("Unable to read pagesize: %s", + strerror(errno)); + r = errno; + goto fail; + } + pages = *(lc->clean_bits) / page_size; + pages += *(lc->clean_bits) % page_size ? 1 : 0; + pages += 1; /* for header */ + + r = open(disk_path, O_RDWR | O_DIRECT); + if (r < 0) { + LOG_ERROR("Unable to open log device, %s: %s", + disk_path, strerror(errno)); + r = errno; + goto fail; + } + if (unlink_path) + if (unlink(disk_path) < 0) { + LOG_DBG("Warning: Unable to unlink log device, %s: %s", + disk_path, strerror(errno)); + } + + lc->disk_fd = r; + lc->disk_size = pages * page_size; + + r = posix_memalign(&(lc->disk_buffer), page_size, + lc->disk_size); + if (r) { + LOG_ERROR("Unable to allocate memory for disk_buffer"); + goto fail; + } + memset(lc->disk_buffer, 0, lc->disk_size); + LOG_DBG("Disk log ready"); + } + + dm_list_add(&log_pending_list, &lc->list); + + return 0; +fail: + if (lc) { + if (lc->disk_fd >= 0 && close(lc->disk_fd)) + LOG_ERROR("Close device error, %s: %s", + disk_path, strerror(errno)); + free(lc->disk_buffer); + dm_free(lc->sync_bits); + dm_free(lc->clean_bits); + dm_free(lc); + } + return r; +} + +/* + * clog_ctr + * @rq + * + * rq->data should contain constructor string as follows: + * <log_type> [disk] <region_size> [[no]sync] <device_len> + * The kernel is responsible for adding the <dev_len> argument + * to the end; otherwise, we cannot compute the region_count. + * + * FIXME: Currently relies on caller to fill in rq->error + */ +static int clog_dtr(struct dm_ulog_request *rq); +static int clog_ctr(struct dm_ulog_request *rq) +{ + int argc, i, r = 0; + char *p, **argv = NULL; + char *dev_size_str; + uint64_t device_size; + + /* Sanity checks */ + if (!rq->data_size) { + LOG_ERROR("Received constructor request with no data"); + return -EINVAL; + } + + if (strlen(rq->data) > rq->data_size) { + LOG_ERROR("Received constructor request with bad data"); + LOG_ERROR("strlen(rq->data)[%d] != rq->data_size[%llu]", + (int)strlen(rq->data), + (unsigned long long)rq->data_size); + LOG_ERROR("rq->data = '%s' [%d]", + rq->data, (int)strlen(rq->data)); + return -EINVAL; + } + + /* Split up args */ + for (argc = 0, p = rq->data; (p = strstr(p, " ")); p++, argc++) + *p = '\0'; + + if (!argc) { + LOG_ERROR("Received constructor request with bad data %s", + rq->data); + return -EINVAL; + } + + argv = malloc(argc * sizeof(char *)); + if (!argv) + return -ENOMEM; + + p = dev_size_str = rq->data; + p += strlen(p) + 1; + for (i = 0; i < argc; i++, p = p + strlen(p) + 1) + argv[i] = p; + + if (strcmp(argv[0], "clustered-disk") && + strcmp(argv[0], "clustered-core")) { + LOG_ERROR("Unsupported userspace log type, \"%s\"", argv[0]); + free(argv); + return -EINVAL; + } + + if (!(device_size = strtoll(dev_size_str, &p, 0)) || *p) { + LOG_ERROR("Invalid device size argument: %s", dev_size_str); + free(argv); + return -EINVAL; + } + + r = _clog_ctr(rq->uuid, rq->luid, argc - 1, argv + 1, device_size); + + /* We join the CPG when we resume */ + + /* No returning data */ + if ((rq->version > 1) && !strcmp(argv[0], "clustered-disk")) + rq->data_size = sprintf(rq->data, "%s", argv[1]) + 1; + else + rq->data_size = 0; + + if (r) { + LOG_ERROR("Failed to create cluster log (%s)", rq->uuid); + for (i = 0; i < argc; i++) + LOG_ERROR("argv[%d] = %s", i, argv[i]); + } + else + LOG_DBG("[%s] Cluster log created", + SHORT_UUID(rq->uuid)); + + free(argv); + return r; +} + +/* + * clog_dtr + * @rq + * + */ +static int clog_dtr(struct dm_ulog_request *rq) +{ + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (lc) { + /* + * The log should not be on the official list. There + * should have been a suspend first. + */ + LOG_ERROR("[%s] DTR before SUS: leaving CPG", + SHORT_UUID(rq->uuid)); + destroy_cluster_cpg(rq->uuid); + } else if (!(lc = get_pending_log(rq->uuid, rq->luid))) { + LOG_ERROR("clog_dtr called on log that is not official or pending"); + return -EINVAL; + } + + LOG_DBG("[%s] Cluster log removed", SHORT_UUID(lc->uuid)); + + dm_list_del(&lc->list); + if (lc->disk_fd != -1 && close(lc->disk_fd)) + LOG_ERROR("Failed to close disk log: %s", + strerror(errno)); + if (lc->disk_buffer) + free(lc->disk_buffer); + dm_free(lc->clean_bits); + dm_free(lc->sync_bits); + dm_free(lc); + + return 0; +} + +/* + * clog_presuspend + * @rq + * + */ +static int clog_presuspend(struct dm_ulog_request *rq) +{ + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (lc->touched) + LOG_DBG("WARNING: log still marked as 'touched' during suspend"); + + lc->recovery_halted = 1; + + return 0; +} + +/* + * clog_postsuspend + * @rq + * + */ +static int clog_postsuspend(struct dm_ulog_request *rq) +{ + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + LOG_DBG("[%s] clog_postsuspend: leaving CPG", SHORT_UUID(lc->uuid)); + destroy_cluster_cpg(rq->uuid); + + lc->state = LOG_SUSPENDED; + lc->recovering_region = (uint64_t)-1; + lc->recoverer = (uint32_t)-1; + lc->delay = time(NULL); + + return 0; +} + +/* + * cluster_postsuspend + * @rq + * + */ +int cluster_postsuspend(char *uuid, uint64_t luid) +{ + struct log_c *lc = get_log(uuid, luid); + + if (!lc) + return -EINVAL; + + LOG_DBG("[%s] clog_postsuspend: finalizing", SHORT_UUID(lc->uuid)); + lc->resume_override = 0; + + /* move log to pending list */ + dm_list_del(&lc->list); + dm_list_add(&log_pending_list, &lc->list); + + return 0; +} + +/* + * clog_resume + * @rq + * + * Does the main work of resuming. + */ +static int clog_resume(struct dm_ulog_request *rq) +{ + uint32_t i; + int commit_log = 0; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + lc->in_sync = 0; + switch (lc->resume_override) { + case 1000: + LOG_ERROR("[%s] Additional resume issued before suspend", + SHORT_UUID(rq->uuid)); +#ifdef DEBUG + kill(getpid(), SIGUSR1); +#endif + return 0; + case 0: + lc->resume_override = 1000; + if (lc->disk_fd == -1) { + LOG_DBG("[%s] Master resume.", + SHORT_UUID(lc->uuid)); + goto no_disk; + } + + LOG_DBG("[%s] Master resume: reading disk log", + SHORT_UUID(lc->uuid)); + commit_log = 1; + break; + case 1: + LOG_ERROR("Error:: partial bit loading (just sync_bits)"); + return -EINVAL; + case 2: + LOG_ERROR("Error:: partial bit loading (just clean_bits)"); + return -EINVAL; + case 3: + LOG_DBG("[%s] Non-master resume: bits pre-loaded", + SHORT_UUID(lc->uuid)); + lc->resume_override = 1000; + goto out; + default: + LOG_ERROR("Error:: multiple loading of bits (%d)", + lc->resume_override); + return -EINVAL; + } + + if (lc->log_dev_failed) { + LOG_ERROR("Log device has failed, unable to read bits"); + rq->error = 0; /* We can handle this so far */ + lc->disk_nr_regions = 0; + } else + rq->error = read_log(lc); + + switch (rq->error) { + case 0: + if (lc->disk_nr_regions < lc->region_count) + LOG_DBG("[%s] Mirror has grown, updating log bits", + SHORT_UUID(lc->uuid)); + else if (lc->disk_nr_regions > lc->region_count) + LOG_DBG("[%s] Mirror has shrunk, updating log bits", + SHORT_UUID(lc->uuid)); + break; + case -EINVAL: + LOG_DBG("[%s] (Re)initializing mirror log - resync issued.", + SHORT_UUID(lc->uuid)); + lc->disk_nr_regions = 0; + break; + default: + LOG_ERROR("Failed to read disk log"); + lc->disk_nr_regions = 0; + break; + } + +no_disk: + /* If mirror has grown, set bits appropriately */ + if (lc->sync == NOSYNC) + for (i = lc->disk_nr_regions; i < lc->region_count; i++) + log_set_bit(lc, lc->clean_bits, i); + else + for (i = lc->disk_nr_regions; i < lc->region_count; i++) + log_clear_bit(lc, lc->clean_bits, i); + + /* Clear any old bits if device has shrunk */ + for (i = lc->region_count; i % 32; i++) + log_clear_bit(lc, lc->clean_bits, i); + + /* copy clean across to sync */ + dm_bit_copy(lc->sync_bits, lc->clean_bits); + + if (commit_log && (lc->disk_fd >= 0)) { + rq->error = write_log(lc); + if (rq->error) + LOG_ERROR("Failed initial disk log write"); + else + LOG_DBG("Disk log initialized"); + lc->touched = 0; + } +out: + /* + * Clear any old bits if device has shrunk - necessary + * for non-master resume + */ + for (i = lc->region_count; i % 32; i++) { + log_clear_bit(lc, lc->clean_bits, i); + log_clear_bit(lc, lc->sync_bits, i); + } + + lc->sync_count = count_bits32(lc->sync_bits); + + LOG_SPRINT(lc, "[%s] Initial sync_count = %llu", + SHORT_UUID(lc->uuid), (unsigned long long)lc->sync_count); + lc->sync_search = 0; + lc->state = LOG_RESUMED; + lc->recovery_halted = 0; + + return rq->error; +} + +/* + * local_resume + * @rq + * + * If the log is pending, we must first join the cpg and + * put the log in the official list. + * + */ +int local_resume(struct dm_ulog_request *rq) +{ + int r; + time_t t; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) { + /* Is the log in the pending list? */ + lc = get_pending_log(rq->uuid, rq->luid); + if (!lc) { + LOG_ERROR("clog_resume called on log that is not official or pending"); + return -EINVAL; + } + + t = time(NULL); + t -= lc->delay; + /* + * This should be considered a temporary fix. It addresses + * a problem that exists when nodes suspend/resume in rapid + * succession. While the problem is very rare, it has been + * seen to happen in real-world-like testing. + * + * The problem: + * - Node A joins cluster + * - Node B joins cluster + * - Node A prepares checkpoint + * - Node A gets ready to write checkpoint + * - Node B leaves + * - Node B joins + * - Node A finishes write of checkpoint + * - Node B receives checkpoint meant for previous session + * -- Node B can now be non-coherent + * + * This timer will solve the problem for now, but could be + * replaced by a generation number sent with the resume + * command from the kernel. The generation number would + * be included in the name of the checkpoint to prevent + * reading stale data. + */ + if ((t < 3) && (t >= 0)) + sleep(3 - t); + + /* Join the CPG */ + r = create_cluster_cpg(rq->uuid, rq->luid); + if (r) { + LOG_ERROR("clog_resume: Failed to create cluster CPG"); + return r; + } + + /* move log to official list */ + dm_list_del(&lc->list); + dm_list_add(&log_list, &lc->list); + } + + return 0; +} + +/* + * clog_get_region_size + * @rq + * + * Since this value doesn't change, the kernel + * should not need to talk to server to get this + * The function is here for completness + * + * Returns: 0 on success, -EXXX on failure + */ +static int clog_get_region_size(struct dm_ulog_request *rq) +{ + uint64_t *rtn = (uint64_t *)rq->data; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc && !(lc = get_pending_log(rq->uuid, rq->luid))) + return -EINVAL; + + *rtn = lc->region_size; + rq->data_size = sizeof(*rtn); + + return 0; +} + +/* + * clog_is_clean + * @rq + * + * Returns: 1 if clean, 0 otherwise + */ +static int clog_is_clean(struct dm_ulog_request *rq) +{ + int64_t *rtn = (int64_t *)rq->data; + uint64_t *region = (uint64_t *)rq->data; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + *rtn = log_test_bit(lc->clean_bits, *region); + rq->data_size = sizeof(*rtn); + + return 0; +} + +/* + * clog_in_sync + * @rq + * + * We ignore any request for non-block. That + * should be handled elsewhere. (If the request + * has come this far, it has already blocked.) + * + * Returns: 1 if in-sync, 0 otherwise + */ +static int clog_in_sync(struct dm_ulog_request *rq) +{ + int64_t *rtn = (int64_t *)rq->data; + uint64_t *region_p = (uint64_t *)rq->data; + uint64_t region = *region_p; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (region > lc->region_count) + return -EINVAL; + + *rtn = log_test_bit(lc->sync_bits, region); + + /* + * If the mirror was successfully recovered, we want to always + * force every machine to write to all devices - otherwise, + * corruption will occur. Here's how: + * Node1 suffers a failure and marks a region out-of-sync + * Node2 attempts a write, gets by is_remote_recovering, + * and queries the sync status of the region - finding + * it out-of-sync. + * Node2 thinks the write should be a nosync write, but it + * hasn't suffered the drive failure that Node1 has yet. + * It then issues a generic_make_request directly to + * the primary image only - which is exactly the device + * that has suffered the failure. + * Node2 suffers a lost write - which completely bypasses the + * mirror layer because it had gone through generic_m_r. + * The file system will likely explode at this point due to + * I/O errors. If it wasn't the primary that failed, it is + * easily possible in this case to issue writes to just one + * of the remaining images - also leaving the mirror inconsistent. + * + * We let in_sync() return 1 in a cluster regardless of what is + * in the bitmap once recovery has successfully completed on a + * mirror. This ensures the mirroring code will continue to + * attempt to write to all mirror images. The worst that can + * happen for reads is that additional read attempts may be + * taken. + * + * Futher investigation may be required to determine if there are + * similar possible outcomes when the mirror is in the process of + * recovering. In that case, lc->in_sync would not have been set + * yet. + */ + if (!*rtn && lc->in_sync) + *rtn = 1; + + if (*rtn) + LOG_DBG("[%s] Region is in-sync: %llu", + SHORT_UUID(lc->uuid), (unsigned long long)region); + else + LOG_DBG("[%s] Region is not in-sync: %llu", + SHORT_UUID(lc->uuid), (unsigned long long)region); + + rq->data_size = sizeof(*rtn); + + return 0; +} + +/* + * clog_flush + * @rq + * + */ +static int clog_flush(struct dm_ulog_request *rq, int server) +{ + int r = 0; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (!lc->touched) + return 0; + + /* + * Do the actual flushing of the log only + * if we are the server. + */ + if (server && (lc->disk_fd >= 0)) { + r = rq->error = write_log(lc); + if (r) + LOG_ERROR("[%s] Error writing to disk log", + SHORT_UUID(lc->uuid)); + else + LOG_DBG("[%s] Disk log written", SHORT_UUID(lc->uuid)); + } + + lc->touched = 0; + + return r; + +} + +/* + * mark_region + * @lc + * @region + * @who + * + * Put a mark region request in the tree for tracking. + * + * Returns: 0 on success, -EXXX on error + */ +static int mark_region(struct log_c *lc, uint64_t region, uint32_t who) +{ + int found = 0; + struct mark_entry *m; + + dm_list_iterate_items(m, &lc->mark_list) + if (m->region == region) { + found = 1; + if (m->nodeid == who) + return 0; + } + + if (!found) + log_clear_bit(lc, lc->clean_bits, region); + + /* + * Save allocation until here - if there is a failure, + * at least we have cleared the bit. + */ + m = malloc(sizeof(*m)); + if (!m) { + LOG_ERROR("Unable to allocate space for mark_entry: %llu/%u", + (unsigned long long)region, who); + return -ENOMEM; + } + + m->nodeid = who; + m->region = region; + dm_list_add(&lc->mark_list, &m->list); + + return 0; +} + +/* + * clog_mark_region + * @rq + * + * rq may contain more than one mark request. We + * can determine the number from the 'data_size' field. + * + * Returns: 0 on success, -EXXX on failure + */ +static int clog_mark_region(struct dm_ulog_request *rq, uint32_t originator) +{ + int r; + int count; + uint64_t *region; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (rq->data_size % sizeof(uint64_t)) { + LOG_ERROR("Bad data size given for mark_region request"); + return -EINVAL; + } + + count = rq->data_size / sizeof(uint64_t); + region = (uint64_t *)&rq->data; + + for (; count > 0; count--, region++) { + r = mark_region(lc, *region, originator); + if (r) + return r; + } + + rq->data_size = 0; + + return 0; +} + +static int clear_region(struct log_c *lc, uint64_t region, uint32_t who) +{ + int other_matches = 0; + struct mark_entry *m, *n; + + dm_list_iterate_items_safe(m, n, &lc->mark_list) + if (m->region == region) { + if (m->nodeid == who) { + dm_list_del(&m->list); + free(m); + } else + other_matches = 1; + } + + /* + * Clear region if: + * 1) It is in-sync + * 2) There are no other machines that have it marked + */ + if (!other_matches && log_test_bit(lc->sync_bits, region)) + log_set_bit(lc, lc->clean_bits, region); + + return 0; +} + +/* + * clog_clear_region + * @rq + * + * rq may contain more than one clear request. We + * can determine the number from the 'data_size' field. + * + * Returns: 0 on success, -EXXX on failure + */ +static int clog_clear_region(struct dm_ulog_request *rq, uint32_t originator) +{ + int r; + int count; + uint64_t *region; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (rq->data_size % sizeof(uint64_t)) { + LOG_ERROR("Bad data size given for clear_region request"); + return -EINVAL; + } + + count = rq->data_size / sizeof(uint64_t); + region = (uint64_t *)&rq->data; + + for (; count > 0; count--, region++) { + r = clear_region(lc, *region, originator); + if (r) + return r; + } + + rq->data_size = 0; + + return 0; +} + +/* + * clog_get_resync_work + * @rq + * + */ +static int clog_get_resync_work(struct dm_ulog_request *rq, uint32_t originator) +{ + struct { + int64_t i; + uint64_t r; + } *pkg = (void *)rq->data; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + rq->data_size = sizeof(*pkg); + pkg->i = 0; + + if (lc->sync_search >= lc->region_count) { + /* + * FIXME: handle intermittent errors during recovery + * by resetting sync_search... but not to many times. + */ + LOG_SPRINT(lc, "GET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Recovery finished", + rq->seq, SHORT_UUID(lc->uuid), originator); + return 0; + } + + if (lc->recovering_region != (uint64_t)-1) { + if (lc->recoverer == originator) { + LOG_SPRINT(lc, "GET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Re-requesting work (%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)lc->recovering_region); + pkg->r = lc->recovering_region; + pkg->i = 1; + LOG_COND(log_resend_requests, "***** RE-REQUEST *****"); + } else { + LOG_SPRINT(lc, "GET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Someone already recovering (%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)lc->recovering_region); + } + + return 0; + } + + while (lc->recovery_request_list) { + struct recovery_request *del; + + del = lc->recovery_request_list; + lc->recovery_request_list = del->next; + + pkg->r = del->region; + free(del); + + if (!log_test_bit(lc->sync_bits, pkg->r)) { + LOG_SPRINT(lc, "GET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Assigning priority resync work (%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)pkg->r); + pkg->i = 1; + lc->recovering_region = pkg->r; + lc->recoverer = originator; + return 0; + } + } + + pkg->r = find_next_zero_bit(lc->sync_bits, lc->sync_search); + + if (pkg->r >= lc->region_count) { + LOG_SPRINT(lc, "GET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Resync work complete.", + rq->seq, SHORT_UUID(lc->uuid), originator); + lc->sync_search = lc->region_count + 1; + return 0; + } + + lc->sync_search = pkg->r + 1; + + LOG_SPRINT(lc, "GET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Assigning resync work (%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)pkg->r); + pkg->i = 1; + lc->recovering_region = pkg->r; + lc->recoverer = originator; + + return 0; +} + +/* + * clog_set_region_sync + * @rq + */ +static int clog_set_region_sync(struct dm_ulog_request *rq, uint32_t originator) +{ + struct { + uint64_t region; + int64_t in_sync; + } *pkg = (void *)rq->data; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + lc->recovering_region = (uint64_t)-1; + + if (pkg->in_sync) { + if (log_test_bit(lc->sync_bits, pkg->region)) { + LOG_SPRINT(lc, "SET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Region already set (%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)pkg->region); + } else { + log_set_bit(lc, lc->sync_bits, pkg->region); + lc->sync_count++; + + /* The rest of this section is all for debugging */ + LOG_SPRINT(lc, "SET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Setting region (%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)pkg->region); + if (pkg->region == lc->skip_bit_warning) + lc->skip_bit_warning = lc->region_count; + + if (pkg->region > (lc->skip_bit_warning + 5)) { + LOG_SPRINT(lc, "*** Region #%llu skipped during recovery ***", + (unsigned long long)lc->skip_bit_warning); + lc->skip_bit_warning = lc->region_count; +#ifdef DEBUG + kill(getpid(), SIGUSR1); +#endif + } + + if (!log_test_bit(lc->sync_bits, + (pkg->region) ? pkg->region - 1 : 0)) { + LOG_SPRINT(lc, "*** Previous bit not set ***"); + lc->skip_bit_warning = (pkg->region) ? + pkg->region - 1 : 0; + } + } + } else if (log_test_bit(lc->sync_bits, pkg->region)) { + lc->sync_count--; + log_clear_bit(lc, lc->sync_bits, pkg->region); + LOG_SPRINT(lc, "SET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "Unsetting region (%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)pkg->region); + } + + if (lc->sync_count != count_bits32(lc->sync_bits)) { + unsigned long long reset = count_bits32(lc->sync_bits); + + LOG_SPRINT(lc, "SET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "sync_count(%llu) != bitmap count(%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)lc->sync_count, reset); +#ifdef DEBUG + kill(getpid(), SIGUSR1); +#endif + lc->sync_count = reset; + } + + if (lc->sync_count > lc->region_count) + LOG_SPRINT(lc, "SET - SEQ#=%u, UUID=%s, nodeid = %u:: " + "(lc->sync_count > lc->region_count) - this is bad", + rq->seq, SHORT_UUID(lc->uuid), originator); + + if (lc->sync_count == lc->region_count) + lc->in_sync = 1; + + rq->data_size = 0; + return 0; +} + +/* + * clog_get_sync_count + * @rq + */ +static int clog_get_sync_count(struct dm_ulog_request *rq, uint32_t originator) +{ + uint64_t *sync_count = (uint64_t *)rq->data; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + /* + * FIXME: Mirror requires us to be able to ask for + * the sync count while pending... but I don't like + * it because other machines may not be suspended and + * the stored value may not be accurate. + */ + if (!lc) + lc = get_pending_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + *sync_count = lc->sync_count; + + rq->data_size = sizeof(*sync_count); + + if (lc->sync_count != count_bits32(lc->sync_bits)) { + unsigned long long reset = count_bits32(lc->sync_bits); + + LOG_SPRINT(lc, "get_sync_count - SEQ#=%u, UUID=%s, nodeid = %u:: " + "sync_count(%llu) != bitmap count(%llu)", + rq->seq, SHORT_UUID(lc->uuid), originator, + (unsigned long long)lc->sync_count, reset); +#ifdef DEBUG + kill(getpid(), SIGUSR1); +#endif + lc->sync_count = reset; + } + + return 0; +} + +static int core_status_info(struct log_c *lc __attribute__((unused)), struct dm_ulog_request *rq) +{ + int r; + char *data = (char *)rq->data; + + r = sprintf(data, "1 clustered-core"); + if (r < 0) + return r; + + rq->data_size = r; + + return 0; +} + +static int disk_status_info(struct log_c *lc, struct dm_ulog_request *rq) +{ + int r; + char *data = (char *)rq->data; + struct stat statbuf; + + if (fstat(lc->disk_fd, &statbuf)) { + rq->error = -errno; + return -errno; + } + + r = sprintf(data, "3 clustered-disk %d:%d %c", + major(statbuf.st_rdev), minor(statbuf.st_rdev), + (lc->log_dev_failed) ? 'D' : 'A'); + if (r < 0) + return r; + + rq->data_size = r; + + return 0; +} + +/* + * clog_status_info + * @rq + * + */ +static int clog_status_info(struct dm_ulog_request *rq) +{ + int r; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + lc = get_pending_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (lc->disk_fd == -1) + r = core_status_info(lc, rq); + else + r = disk_status_info(lc, rq); + + return r; +} + +static int core_status_table(struct log_c *lc, struct dm_ulog_request *rq) +{ + int r; + char *data = (char *)rq->data; + + r = sprintf(data, "clustered-core %u %s%s ", + lc->region_size, + (lc->sync == DEFAULTSYNC) ? "" : + (lc->sync == NOSYNC) ? "nosync " : "sync ", + (lc->block_on_error) ? "block_on_error" : ""); + if (r < 0) + return r; + + rq->data_size = r; + return 0; +} + +static int disk_status_table(struct log_c *lc, struct dm_ulog_request *rq) +{ + int r; + char *data = (char *)rq->data; + struct stat statbuf; + + if (fstat(lc->disk_fd, &statbuf)) { + rq->error = -errno; + return -errno; + } + + r = sprintf(data, "clustered-disk %d:%d %u %s%s ", + major(statbuf.st_rdev), minor(statbuf.st_rdev), + lc->region_size, + (lc->sync == DEFAULTSYNC) ? "" : + (lc->sync == NOSYNC) ? "nosync " : "sync ", + (lc->block_on_error) ? "block_on_error" : ""); + if (r < 0) + return r; + + rq->data_size = r; + return 0; +} + +/* + * clog_status_table + * @rq + * + */ +static int clog_status_table(struct dm_ulog_request *rq) +{ + int r; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + lc = get_pending_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (lc->disk_fd == -1) + r = core_status_table(lc, rq); + else + r = disk_status_table(lc, rq); + + return r; +} + +/* + * clog_is_remote_recovering + * @rq + * + */ +static int clog_is_remote_recovering(struct dm_ulog_request *rq) +{ + uint64_t *region_p = (uint64_t *)rq->data; + uint64_t region = *region_p; + struct { + int64_t is_recovering; + uint64_t in_sync_hint; + } *pkg = (void *)rq->data; + struct log_c *lc = get_log(rq->uuid, rq->luid); + + if (!lc) + return -EINVAL; + + if (region > lc->region_count) + return -EINVAL; + + if (lc->recovery_halted) { + LOG_DBG("[%s] Recovery halted... [not remote recovering]: %llu", + SHORT_UUID(lc->uuid), (unsigned long long)region); + pkg->is_recovering = 0; + pkg->in_sync_hint = lc->region_count; /* none are recovering */ + } else { + pkg->is_recovering = !log_test_bit(lc->sync_bits, region); + + /* + * Remember, 'lc->sync_search' is 1 plus the region + * currently being recovered. So, we must take off 1 + * to account for that; but only if 'sync_search > 1'. + */ + pkg->in_sync_hint = lc->sync_search ? (lc->sync_search - 1) : 0; + LOG_DBG("[%s] Region is %s: %llu", + SHORT_UUID(lc->uuid), + (region == lc->recovering_region) ? + "currently remote recovering" : + (pkg->is_recovering) ? "pending remote recovery" : + "not remote recovering", (unsigned long long)region); + } + + if (pkg->is_recovering && + (region != lc->recovering_region)) { + struct recovery_request *rr; + + /* Already in the list? */ + for (rr = lc->recovery_request_list; rr; rr = rr->next) + if (rr->region == region) + goto out; + + /* Failure to allocated simply means we can't prioritize it */ + rr = malloc(sizeof(*rr)); + if (!rr) + goto out; + + LOG_DBG("[%s] Adding region to priority list: %llu", + SHORT_UUID(lc->uuid), (unsigned long long)region); + rr->region = region; + rr->next = lc->recovery_request_list; + lc->recovery_request_list = rr; + } + +out: + + rq->data_size = sizeof(*pkg); + + return 0; +} + + +/* + * do_request + * @rq: the request + * @server: is this request performed by the server + * + * An inability to perform this function will return an error + * from this function. However, an inability to successfully + * perform the request will fill in the 'rq->error' field. + * + * 'rq' (or more correctly, rq->u_rq.data) should be of sufficient + * size to hold any returning data. Currently, local.c uses 2kiB + * to hold 'rq' - leaving ~1.5kiB for return data... more than + * enough for all the implemented functions here. + * + * Returns: 0 on success, -EXXX on error + */ +int do_request(struct clog_request *rq, int server) +{ + int r; + + if (!rq) + return 0; + + if (rq->u_rq.error) + LOG_DBG("Programmer error: rq struct has error set"); + + switch (rq->u_rq.request_type) { + case DM_ULOG_CTR: + r = clog_ctr(&rq->u_rq); + break; + case DM_ULOG_DTR: + r = clog_dtr(&rq->u_rq); + break; + case DM_ULOG_PRESUSPEND: + r = clog_presuspend(&rq->u_rq); + break; + case DM_ULOG_POSTSUSPEND: + r = clog_postsuspend(&rq->u_rq); + break; + case DM_ULOG_RESUME: + r = clog_resume(&rq->u_rq); + break; + case DM_ULOG_GET_REGION_SIZE: + r = clog_get_region_size(&rq->u_rq); + break; + case DM_ULOG_IS_CLEAN: + r = clog_is_clean(&rq->u_rq); + break; + case DM_ULOG_IN_SYNC: + r = clog_in_sync(&rq->u_rq); + break; + case DM_ULOG_FLUSH: + r = clog_flush(&rq->u_rq, server); + break; + case DM_ULOG_MARK_REGION: + r = clog_mark_region(&rq->u_rq, rq->originator); + break; + case DM_ULOG_CLEAR_REGION: + r = clog_clear_region(&rq->u_rq, rq->originator); + break; + case DM_ULOG_GET_RESYNC_WORK: + r = clog_get_resync_work(&rq->u_rq, rq->originator); + break; + case DM_ULOG_SET_REGION_SYNC: + r = clog_set_region_sync(&rq->u_rq, rq->originator); + break; + case DM_ULOG_GET_SYNC_COUNT: + r = clog_get_sync_count(&rq->u_rq, rq->originator); + break; + case DM_ULOG_STATUS_INFO: + r = clog_status_info(&rq->u_rq); + break; + case DM_ULOG_STATUS_TABLE: + r = clog_status_table(&rq->u_rq); + break; + case DM_ULOG_IS_REMOTE_RECOVERING: + r = clog_is_remote_recovering(&rq->u_rq); + break; + default: + LOG_ERROR("Unknown request"); + r = rq->u_rq.error = -EINVAL; + break; + } + + if (r && !rq->u_rq.error) + rq->u_rq.error = r; + else if (r != rq->u_rq.error) + LOG_DBG("Warning: error from function != rq->u_rq.error"); + + if (rq->u_rq.error && rq->u_rq.data_size) { + /* Make sure I'm handling errors correctly above */ + LOG_DBG("Programmer error: rq->u_rq.error && rq->u_rq.data_size"); + rq->u_rq.data_size = 0; + } + + return 0; +} + +static void print_bits(dm_bitset_t bs, int print) +{ + int i, size; + char outbuf[128] = { 0 }; + unsigned char *buf = (unsigned char *)(bs + 1); + + size = (*bs % 8) ? 1 : 0; + size += (*bs / 8); + + for (i = 0; i < size; i++) { + if (!(i % 16)) { + if (outbuf[0] != '\0') { + if (print) + LOG_PRINT("%s", outbuf); + else + LOG_DBG("%s", outbuf); + } + memset(outbuf, 0, sizeof(outbuf)); + sprintf(outbuf, "[%3d - %3d]", i, i+15); + } + sprintf(outbuf + strlen(outbuf), " %.2X", (unsigned char)buf[i]); + } + if (outbuf[0] != '\0') { + if (print) + LOG_PRINT("%s", outbuf); + else + LOG_DBG("%s", outbuf); + } +} + +/* int store_bits(const char *uuid, const char *which, char **buf)*/ +int push_state(const char *uuid, uint64_t luid, + const char *which, char **buf, uint32_t debug_who) +{ + int bitset_size; + struct log_c *lc; + + if (*buf) + LOG_ERROR("store_bits: *buf != NULL"); + + lc = get_log(uuid, luid); + if (!lc) { + LOG_ERROR("store_bits: No log found for %s", uuid); + return -EINVAL; + } + + if (!strcmp(which, "recovering_region")) { + *buf = malloc(64); /* easily handles the 2 written numbers */ + if (!*buf) + return -ENOMEM; + sprintf(*buf, "%llu %u", (unsigned long long)lc->recovering_region, + lc->recoverer); + + LOG_SPRINT(lc, "CKPT SEND - SEQ#=X, UUID=%s, nodeid = %u:: " + "recovering_region=%llu, recoverer=%u, sync_count=%llu", + SHORT_UUID(lc->uuid), debug_who, + (unsigned long long)lc->recovering_region, + lc->recoverer, + (unsigned long long)count_bits32(lc->sync_bits)); + return 64; + } + + /* Size in 'int's */ + bitset_size = (*(lc->clean_bits) / DM_BITS_PER_INT) + 1; + + /* Size in bytes */ + bitset_size *= 4; + + *buf = malloc(bitset_size); + + if (!*buf) { + LOG_ERROR("store_bits: Unable to allocate memory"); + return -ENOMEM; + } + + if (!strncmp(which, "sync_bits", 9)) { + memcpy(*buf, lc->sync_bits + 1, bitset_size); + + LOG_DBG("[%s] storing sync_bits (sync_count = %llu):", + SHORT_UUID(uuid), (unsigned long long) + count_bits32(lc->sync_bits)); + + print_bits(lc->sync_bits, 0); + } else if (!strncmp(which, "clean_bits", 9)) { + memcpy(*buf, lc->clean_bits + 1, bitset_size); + + LOG_DBG("[%s] storing clean_bits:", SHORT_UUID(lc->uuid)); + + print_bits(lc->clean_bits, 0); + } + + return bitset_size; +} + +/*int load_bits(const char *uuid, const char *which, char *buf, int size)*/ +int pull_state(const char *uuid, uint64_t luid, + const char *which, char *buf, int size) +{ + int bitset_size; + struct log_c *lc; + + if (!buf) { + LOG_ERROR("pull_state: buf == NULL"); + return -EINVAL; + } + + lc = get_log(uuid, luid); + if (!lc) { + LOG_ERROR("pull_state: No log found for %s", uuid); + return -EINVAL; + } + + if (!strncmp(which, "recovering_region", 17)) { + if (sscanf(buf, "%llu %u", (unsigned long long *)&lc->recovering_region, + &lc->recoverer) != 2) { + LOG_ERROR("cannot parse recovering region from: %s", buf); + return -EINVAL; + } + LOG_SPRINT(lc, "CKPT INIT - SEQ#=X, UUID=%s, nodeid = X:: " + "recovering_region=%llu, recoverer=%u", + SHORT_UUID(lc->uuid), + (unsigned long long)lc->recovering_region, lc->recoverer); + return 0; + } + + /* Size in 'int's */ + bitset_size = (*(lc->clean_bits) /DM_BITS_PER_INT) + 1; + + /* Size in bytes */ + bitset_size *= 4; + + if (bitset_size != size) { + LOG_ERROR("pull_state(%s): bad bitset_size (%d vs %d)", + which, size, bitset_size); + return -EINVAL; + } + + if (!strncmp(which, "sync_bits", 9)) { + lc->resume_override += 1; + memcpy(lc->sync_bits + 1, buf, bitset_size); + + LOG_DBG("[%s] loading sync_bits (sync_count = %llu):", + SHORT_UUID(lc->uuid),(unsigned long long) + count_bits32(lc->sync_bits)); + + print_bits(lc->sync_bits, 0); + } else if (!strncmp(which, "clean_bits", 9)) { + lc->resume_override += 2; + memcpy(lc->clean_bits + 1, buf, bitset_size); + + LOG_DBG("[%s] loading clean_bits:", SHORT_UUID(lc->uuid)); + + print_bits(lc->clean_bits, 0); + } + + return 0; +} + +int log_get_state(struct dm_ulog_request *rq) +{ + struct log_c *lc; + + lc = get_log(rq->uuid, rq->luid); + if (!lc) + /* FIXME Callers are ignoring this */ + return -EINVAL; + + return (int)lc->state; +} + +/* + * log_status + * + * Returns: 1 if logs are still present, 0 otherwise + */ +int log_status(void) +{ + if (!dm_list_empty(&log_list) || !dm_list_empty(&log_pending_list)) + return 1; + + return 0; +} + +void log_debug(void) +{ + struct log_c *lc; + uint64_t r; + int i; + + LOG_ERROR(""); + LOG_ERROR("LOG COMPONENT DEBUGGING::"); + LOG_ERROR("Official log list:"); + LOG_ERROR("Pending log list:"); + dm_list_iterate_items(lc, &log_pending_list) { + LOG_ERROR("%s", lc->uuid); + LOG_ERROR("sync_bits:"); + print_bits(lc->sync_bits, 1); + LOG_ERROR("clean_bits:"); + print_bits(lc->clean_bits, 1); + } + + dm_list_iterate_items(lc, &log_list) { + LOG_ERROR("%s", lc->uuid); + LOG_ERROR(" recoverer : %" PRIu32, lc->recoverer); + LOG_ERROR(" recovering_region: %" PRIu64, lc->recovering_region); + LOG_ERROR(" recovery_halted : %s", (lc->recovery_halted) ? + "YES" : "NO"); + LOG_ERROR("sync_bits:"); + print_bits(lc->sync_bits, 1); + LOG_ERROR("clean_bits:"); + print_bits(lc->clean_bits, 1); + + LOG_ERROR("Validating %s::", SHORT_UUID(lc->uuid)); + r = find_next_zero_bit(lc->sync_bits, 0); + LOG_ERROR(" lc->region_count = %" PRIu32, lc->region_count); + LOG_ERROR(" lc->sync_count = %" PRIu64, lc->sync_count); + LOG_ERROR(" next zero bit = %" PRIu64, r); + if ((r > lc->region_count) || + ((r == lc->region_count) && (lc->sync_count > lc->region_count))) { + LOG_ERROR("ADJUSTING SYNC_COUNT"); + lc->sync_count = lc->region_count; + } + + LOG_ERROR("Resync request history:"); + for (i = 0; i < RESYNC_HISTORY; i++) { + lc->idx++; + lc->idx = lc->idx % RESYNC_HISTORY; + if (lc->resync_history[lc->idx][0] == '\0') + continue; + LOG_ERROR("%d:%d) %s", i, lc->idx, + lc->resync_history[lc->idx]); + } + } +}
diff --git a/daemons/cmirrord/functions.h b/daemons/cmirrord/functions.h new file mode 100644 index 0000000..4620f99 --- /dev/null +++ b/daemons/cmirrord/functions.h
@@ -0,0 +1,34 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef _LVM_CLOG_FUNCTIONS_H +#define _LVM_CLOG_FUNCTIONS_H + +#include "dm-log-userspace.h" +#include "cluster.h" + +#define LOG_RESUMED 1 +#define LOG_SUSPENDED 2 + +int local_resume(struct dm_ulog_request *rq); +int cluster_postsuspend(char *, uint64_t); + +int do_request(struct clog_request *rq, int server); +int push_state(const char *uuid, uint64_t luid, + const char *which, char **buf, uint32_t debug_who); +int pull_state(const char *uuid, uint64_t luid, + const char *which, char *buf, int size); + +int log_get_state(struct dm_ulog_request *rq); +int log_status(void); +void log_debug(void); + +#endif /* _LVM_CLOG_FUNCTIONS_H */
diff --git a/daemons/cmirrord/link_mon.c b/daemons/cmirrord/link_mon.c new file mode 100644 index 0000000..5dc49e5 --- /dev/null +++ b/daemons/cmirrord/link_mon.c
@@ -0,0 +1,151 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "logging.h" +#include "link_mon.h" + +#include <errno.h> +#include <poll.h> +#include <stdlib.h> + +struct link_callback { + int fd; + const char *name; + void *data; + int (*callback)(void *data); + + struct link_callback *next; +}; + +static unsigned used_pfds = 0; +static unsigned free_pfds = 0; +static struct pollfd *pfds = NULL; +static struct link_callback *callbacks = NULL; + +int links_register(int fd, const char *name, int (*callback)(void *data), void *data) +{ + unsigned i; + struct link_callback *lc; + + for (i = 0; i < used_pfds; i++) { + if (fd == pfds[i].fd) { + LOG_ERROR("links_register: Duplicate file descriptor"); + return -EINVAL; + } + } + + lc = malloc(sizeof(*lc)); + if (!lc) + return -ENOMEM; + + lc->fd = fd; + lc->name = name; + lc->data = data; + lc->callback = callback; + + if (!free_pfds) { + struct pollfd *tmp; + tmp = realloc(pfds, sizeof(struct pollfd) * ((used_pfds*2) + 1)); + if (!tmp) { + free(lc); + return -ENOMEM; + } + + pfds = tmp; + free_pfds = used_pfds + 1; + } + + free_pfds--; + pfds[used_pfds].fd = fd; + pfds[used_pfds].events = POLLIN; + pfds[used_pfds].revents = 0; + used_pfds++; + + lc->next = callbacks; + callbacks = lc; + LOG_DBG("Adding %s/%d", lc->name, lc->fd); + LOG_DBG(" used_pfds = %u, free_pfds = %u", + used_pfds, free_pfds); + + return 0; +} + +int links_unregister(int fd) +{ + unsigned i; + struct link_callback *p, *c; + + for (i = 0; i < used_pfds; i++) + if (fd == pfds[i].fd) { + /* entire struct is copied (overwritten) */ + pfds[i] = pfds[used_pfds - 1]; + used_pfds--; + free_pfds++; + } + + for (p = NULL, c = callbacks; c; p = c, c = c->next) + if (fd == c->fd) { + LOG_DBG("Freeing up %s/%d", c->name, c->fd); + LOG_DBG(" used_pfds = %u, free_pfds = %u", + used_pfds, free_pfds); + if (p) + p->next = c->next; + else + callbacks = c->next; + free(c); + break; + } + + return 0; +} + +int links_monitor(void) +{ + unsigned i; + int r; + + for (i = 0; i < used_pfds; i++) { + pfds[i].revents = 0; + } + + r = poll(pfds, used_pfds, -1); + if (r <= 0) + return r; + + r = 0; + /* FIXME: handle POLLHUP */ + for (i = 0; i < used_pfds; i++) + if (pfds[i].revents & POLLIN) { + LOG_DBG("Data ready on %d", pfds[i].fd); + + /* FIXME: Add this back return 1;*/ + r++; + } + + return r; +} + +int links_issue_callbacks(void) +{ + unsigned i; + struct link_callback *lc; + + for (i = 0; i < used_pfds; i++) + if (pfds[i].revents & POLLIN) + for (lc = callbacks; lc; lc = lc->next) + if (pfds[i].fd == lc->fd) { + LOG_DBG("Issuing callback on %s/%d", + lc->name, lc->fd); + lc->callback(lc->data); + break; + } + return 0; +}
diff --git a/daemons/cmirrord/link_mon.h b/daemons/cmirrord/link_mon.h new file mode 100644 index 0000000..4d58b04 --- /dev/null +++ b/daemons/cmirrord/link_mon.h
@@ -0,0 +1,20 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef _LVM_CLOG_LINK_MON_H +#define _LVM_CLOG_LINK_MON_H + +int links_register(int fd, const char *name, int (*callback)(void *data), void *data); +int links_unregister(int fd); +int links_monitor(void); +int links_issue_callbacks(void); + +#endif /* _LVM_CLOG_LINK_MON_H */
diff --git a/daemons/cmirrord/local.c b/daemons/cmirrord/local.c new file mode 100644 index 0000000..d0a25e1 --- /dev/null +++ b/daemons/cmirrord/local.c
@@ -0,0 +1,424 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "logging.h" +#include "common.h" +#include "functions.h" +#include "link_mon.h" +#include "local.h" + +#include <errno.h> +#include <sys/socket.h> +#include <linux/connector.h> +#include <linux/netlink.h> +#include <unistd.h> + +#ifndef CN_IDX_DM +/* Kernel 2.6.31 is required to run this code */ +#define CN_IDX_DM 0x7 /* Device Mapper */ +#define CN_VAL_DM_USERSPACE_LOG 0x1 +#endif + +static int cn_fd = -1; /* Connector (netlink) socket fd */ +static char recv_buf[2048]; +static char send_buf[2048]; + + +/* FIXME: merge this function with kernel_send_helper */ +static int kernel_ack(uint32_t seq, int error) +{ + int r; + struct nlmsghdr *nlh = (struct nlmsghdr *)send_buf; + struct cn_msg *msg = NLMSG_DATA(nlh); + + if (error < 0) { + LOG_ERROR("Programmer error: error codes must be positive"); + return -EINVAL; + } + + memset(send_buf, 0, sizeof(send_buf)); + + nlh->nlmsg_seq = 0; + nlh->nlmsg_pid = getpid(); + nlh->nlmsg_type = NLMSG_DONE; + nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct cn_msg)); + nlh->nlmsg_flags = 0; + + msg->len = 0; + msg->id.idx = CN_IDX_DM; + msg->id.val = CN_VAL_DM_USERSPACE_LOG; + msg->seq = seq; + msg->ack = error; + + r = send(cn_fd, nlh, NLMSG_LENGTH(sizeof(struct cn_msg)), 0); + /* FIXME: do better error processing */ + if (r <= 0) + return -EBADE; + + return 0; +} + + +/* + * kernel_recv + * @rq: the newly allocated request from kernel + * + * Read requests from the kernel and allocate space for the new request. + * If there is no request from the kernel, *rq is NULL. + * + * This function is not thread safe due to returned stack pointer. In fact, + * the returned pointer must not be in-use when this function is called again. + * + * Returns: 0 on success, -EXXX on error + */ +static int kernel_recv(struct clog_request **rq) +{ + int r = 0; + ssize_t len; + char *foo; + struct cn_msg *msg; + struct dm_ulog_request *u_rq; + struct nlmsghdr *nlmsg_h; + + *rq = NULL; + memset(recv_buf, 0, sizeof(recv_buf)); + + len = recv(cn_fd, recv_buf, sizeof(recv_buf), 0); + if (len < 0) { + LOG_ERROR("Failed to recv message from kernel"); + r = -errno; + goto fail; + } + + nlmsg_h = (struct nlmsghdr *)recv_buf; + switch (nlmsg_h->nlmsg_type) { + case NLMSG_ERROR: + LOG_ERROR("Unable to recv message from kernel: NLMSG_ERROR"); + r = -EBADE; + goto fail; + case NLMSG_DONE: + msg = (struct cn_msg *)NLMSG_DATA((struct nlmsghdr *)recv_buf); + len -= (ssize_t)sizeof(struct nlmsghdr); + + if (len < (ssize_t)sizeof(struct cn_msg)) { + LOG_ERROR("Incomplete request from kernel received"); + r = -EBADE; + goto fail; + } + + if (msg->len > DM_ULOG_REQUEST_SIZE) { + LOG_ERROR("Not enough space to receive kernel request (%d/%d)", + msg->len, DM_ULOG_REQUEST_SIZE); + r = -EBADE; + goto fail; + } + + if (!msg->len) + LOG_ERROR("Zero length message received"); + + len -= (ssize_t)sizeof(struct cn_msg); + + if (len < msg->len) + LOG_ERROR("len = %zd, msg->len = %" PRIu16, len, msg->len); + + msg->data[msg->len] = '\0'; /* Cleaner way to ensure this? */ + u_rq = (struct dm_ulog_request *)msg->data; + + if (!u_rq->request_type) { + LOG_DBG("Bad transmission, requesting resend [%u]", + msg->seq); + r = -EAGAIN; + + if (kernel_ack(msg->seq, EAGAIN)) { + LOG_ERROR("Failed to NACK kernel transmission [%u]", + msg->seq); + r = -EBADE; + } + } + + /* + * Now we've got sizeof(struct cn_msg) + sizeof(struct nlmsghdr) + * worth of space that precede the request structure from the + * kernel. Since that space isn't going to be used again, we + * can take it for our purposes; rather than allocating a whole + * new structure and doing a memcpy. + * + * We should really make sure 'clog_request' doesn't grow + * beyond what is available to us, but we need only check it + * once... perhaps at compile time? + */ + foo = (char *)u_rq; + foo -= (sizeof(struct clog_request) - sizeof(struct dm_ulog_request)); + *rq = (struct clog_request *) foo; + + /* Clear the wrapper container fields */ + memset(*rq, 0, (size_t)((char *)u_rq - (char *)(*rq))); + break; + default: + LOG_ERROR("Unknown nlmsg_type"); + r = -EBADE; + } + +fail: + if (r) + *rq = NULL; + + return (r == -EAGAIN) ? 0 : r; +} + +static int kernel_send_helper(void *data, uint16_t out_size) +{ + int r; + struct nlmsghdr *nlh; + struct cn_msg *msg; + + memset(send_buf, 0, sizeof(send_buf)); + + nlh = (struct nlmsghdr *)send_buf; + nlh->nlmsg_seq = 0; /* FIXME: Is this used? */ + nlh->nlmsg_pid = getpid(); + nlh->nlmsg_type = NLMSG_DONE; + nlh->nlmsg_len = NLMSG_LENGTH(out_size + sizeof(struct cn_msg)); + nlh->nlmsg_flags = 0; + + msg = NLMSG_DATA(nlh); + memcpy(msg->data, data, out_size); + msg->len = out_size; + msg->id.idx = CN_IDX_DM; + msg->id.val = CN_VAL_DM_USERSPACE_LOG; + msg->seq = 0; + + r = send(cn_fd, nlh, NLMSG_LENGTH(out_size + sizeof(struct cn_msg)), 0); + /* FIXME: do better error processing */ + if (r <= 0) + return -EBADE; + + return 0; +} + +/* + * do_local_work + * + * Any processing errors are placed in the 'rq' + * structure to be reported back to the kernel. + * It may be pointless for this function to + * return an int. + * + * Returns: 0 on success, -EXXX on failure + */ +static int do_local_work(void *data __attribute__((unused))) +{ + int r; + struct clog_request *rq; + struct dm_ulog_request *u_rq = NULL; + + r = kernel_recv(&rq); + if (r) + return r; + + if (!rq) + return 0; + + u_rq = &rq->u_rq; + LOG_DBG("[%s] Request from kernel received: [%s/%u]", + SHORT_UUID(u_rq->uuid), RQ_TYPE(u_rq->request_type), + u_rq->seq); + switch (u_rq->request_type) { + case DM_ULOG_CTR: + case DM_ULOG_DTR: + case DM_ULOG_GET_REGION_SIZE: + case DM_ULOG_IN_SYNC: + case DM_ULOG_GET_SYNC_COUNT: + case DM_ULOG_STATUS_TABLE: + case DM_ULOG_PRESUSPEND: + /* We do not specify ourselves as server here */ + r = do_request(rq, 0); + if (r) + LOG_DBG("Returning failed request to kernel [%s]", + RQ_TYPE(u_rq->request_type)); + r = kernel_send(u_rq); + if (r) + LOG_ERROR("Failed to respond to kernel [%s]", + RQ_TYPE(u_rq->request_type)); + + break; + case DM_ULOG_RESUME: + /* + * Resume is a special case that requires a local + * component to join the CPG, and a cluster component + * to handle the request. + */ + r = local_resume(u_rq); + if (r) { + LOG_DBG("Returning failed request to kernel [%s]", + RQ_TYPE(u_rq->request_type)); + r = kernel_send(u_rq); + if (r) + LOG_ERROR("Failed to respond to kernel [%s]", + RQ_TYPE(u_rq->request_type)); + break; + } + /* ELSE, fall through */ + case DM_ULOG_IS_CLEAN: + case DM_ULOG_FLUSH: + case DM_ULOG_MARK_REGION: + case DM_ULOG_GET_RESYNC_WORK: + case DM_ULOG_SET_REGION_SYNC: + case DM_ULOG_STATUS_INFO: + case DM_ULOG_IS_REMOTE_RECOVERING: + case DM_ULOG_POSTSUSPEND: + r = cluster_send(rq); + if (r) { + u_rq->data_size = 0; + u_rq->error = r; + if (kernel_send(u_rq)) + LOG_ERROR("Failed to respond to kernel [%s]", + RQ_TYPE(u_rq->request_type)); + } + + break; + case DM_ULOG_CLEAR_REGION: + r = kernel_ack(u_rq->seq, 0); + + r = cluster_send(rq); + if (r) { + /* + * FIXME: store error for delivery on flush + * This would allow us to optimize MARK_REGION + * too. + */ + } + + break; + default: + LOG_ERROR("Invalid log request received (%u), ignoring.", + u_rq->request_type); + + return 0; + } + + if (r && !u_rq->error) + u_rq->error = r; + + return r; +} + +/* + * kernel_send + * @u_rq: result to pass back to kernel + * + * This function returns the u_rq structure + * (containing the results) to the kernel. + * It then frees the structure. + * + * WARNING: should the structure be freed if + * there is an error? I vote 'yes'. If the + * kernel doesn't get the response, it should + * resend the request. + * + * Returns: 0 on success, -EXXX on failure + */ +int kernel_send(struct dm_ulog_request *u_rq) +{ + int r; + uint16_t size; + + if (!u_rq) + return -EINVAL; + + size = (uint16_t)(sizeof(struct dm_ulog_request) + u_rq->data_size); + + if (!u_rq->data_size && !u_rq->error) { + /* An ACK is all that is needed */ + + /* FIXME: add ACK code */ + } else if (size > DM_ULOG_REQUEST_SIZE) { + /* + * If we gotten here, we've already overrun + * our allotted space somewhere. + * + * We must do something, because the kernel + * is waiting for a response. + */ + LOG_ERROR("Not enough space to respond to server"); + u_rq->error = -ENOSPC; + size = sizeof(struct dm_ulog_request); + } + + r = kernel_send_helper(u_rq, size); + if (r) + LOG_ERROR("Failed to send msg to kernel."); + + return r; +} + +/* + * init_local + * + * Initialize kernel communication socket (netlink) + * + * Returns: 0 on success, values from common.h on failure + */ +int init_local(void) +{ + int r = 0; + unsigned opt; + struct sockaddr_nl addr; + + cn_fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); + if (cn_fd < 0) + return EXIT_KERNEL_SOCKET; + + /* memset to fix valgrind complaint */ + memset(&addr, 0, sizeof(struct sockaddr_nl)); + + addr.nl_family = AF_NETLINK; + addr.nl_groups = CN_IDX_DM; + addr.nl_pid = 0; + + r = bind(cn_fd, (struct sockaddr *) &addr, sizeof(addr)); + if (r < 0) { + if (close(cn_fd)) + LOG_ERROR("Failed to close socket: %s", + strerror(errno)); + return EXIT_KERNEL_BIND; + } + + opt = addr.nl_groups; + r = setsockopt(cn_fd, 270, NETLINK_ADD_MEMBERSHIP, &opt, sizeof(opt)); + if (r) { + if (close(cn_fd)) + LOG_ERROR("Failed to close socket: %s", + strerror(errno)); + return EXIT_KERNEL_SETSOCKOPT; + } + + /* + r = fcntl(cn_fd, F_SETFL, FNDELAY); + */ + + links_register(cn_fd, "local", do_local_work, NULL); + + return 0; +} + +/* + * cleanup_local + * + * Clean up before exiting + */ +void cleanup_local(void) +{ + links_unregister(cn_fd); + if (cn_fd >= 0 && close(cn_fd)) + LOG_ERROR("Failed to close socket: %s", + strerror(errno)); +}
diff --git a/daemons/cmirrord/local.h b/daemons/cmirrord/local.h new file mode 100644 index 0000000..90c9e4b --- /dev/null +++ b/daemons/cmirrord/local.h
@@ -0,0 +1,20 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef _LVM_CLOG_LOCAL_H +#define _LVM_CLOG_LOCAL_H + +int init_local(void); +void cleanup_local(void); + +int kernel_send(struct dm_ulog_request *rq); + +#endif /* _LVM_CLOG_LOCAL_H */
diff --git a/daemons/cmirrord/logging.c b/daemons/cmirrord/logging.c new file mode 100644 index 0000000..2db66f4 --- /dev/null +++ b/daemons/cmirrord/logging.c
@@ -0,0 +1,57 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "logging.h" + +const char *__rq_types_off_by_one[] = { + "DM_ULOG_CTR", + "DM_ULOG_DTR", + "DM_ULOG_PRESUSPEND", + "DM_ULOG_POSTSUSPEND", + "DM_ULOG_RESUME", + "DM_ULOG_GET_REGION_SIZE", + "DM_ULOG_IS_CLEAN", + "DM_ULOG_IN_SYNC", + "DM_ULOG_FLUSH", + "DM_ULOG_MARK_REGION", + "DM_ULOG_CLEAR_REGION", + "DM_ULOG_GET_RESYNC_WORK", + "DM_ULOG_SET_REGION_SYNC", + "DM_ULOG_GET_SYNC_COUNT", + "DM_ULOG_STATUS_INFO", + "DM_ULOG_STATUS_TABLE", + "DM_ULOG_IS_REMOTE_RECOVERING", + NULL +}; + +int log_tabbing = 0; +int log_is_open = 0; + +/* + * Variables for various conditional logging + */ +#ifdef MEMB +int log_membership_change = 1; +#else +int log_membership_change = 0; +#endif + +#ifdef CKPT +int log_checkpoint = 1; +#else +int log_checkpoint = 0; +#endif + +#ifdef RESEND +int log_resend_requests = 1; +#else +int log_resend_requests = 0; +#endif
diff --git a/daemons/cmirrord/logging.h b/daemons/cmirrord/logging.h new file mode 100644 index 0000000..3ede0c7 --- /dev/null +++ b/daemons/cmirrord/logging.h
@@ -0,0 +1,77 @@ +/* + * Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _LVM_CLOG_LOGGING_H +#define _LVM_CLOG_LOGGING_H + +#define _GNU_SOURCE +#define _FILE_OFFSET_BITS 64 + +#include "configure.h" +#include <stdio.h> +#include <stdint.h> +#include <syslog.h> + +/* SHORT_UUID - print last 8 chars of a string */ +#define SHORT_UUID(x) (strlen(x) > 8) ? ((x) + (strlen(x) - 8)) : (x) + +extern const char *__rq_types_off_by_one[]; +#define RQ_TYPE(x) __rq_types_off_by_one[(x) - 1] + +extern int log_tabbing; +extern int log_is_open; +extern int log_membership_change; +extern int log_checkpoint; +extern int log_resend_requests; + +#define LOG_OPEN(ident, option, facility) do { \ + openlog(ident, option, facility); \ + log_is_open = 1; \ + } while (0) + +#define LOG_CLOSE(void) do { \ + log_is_open = 0; \ + closelog(); \ + } while (0) + +#define LOG_OUTPUT(level, f, arg...) do { \ + int __i; \ + char __buffer[16]; \ + FILE *fp = (level > LOG_NOTICE) ? stderr : stdout; \ + if (log_is_open) { \ + for (__i = 0; (__i < log_tabbing) && (__i < 15); __i++) \ + __buffer[__i] = '\t'; \ + __buffer[__i] = '\0'; \ + syslog(level, "%s" f "\n", __buffer, ## arg); \ + } else { \ + for (__i = 0; __i < log_tabbing; __i++) \ + fprintf(fp, "\t"); \ + fprintf(fp, f "\n", ## arg); \ + } \ + } while (0) + + +#ifdef DEBUG +#define LOG_DBG(f, arg...) LOG_OUTPUT(LOG_DEBUG, f, ## arg) +#else /* DEBUG */ +#define LOG_DBG(f, arg...) do {} while (0) +#endif /* DEBUG */ + +#define LOG_COND(__X, f, arg...) do {\ + if (__X) { \ + LOG_OUTPUT(LOG_NOTICE, f, ## arg); \ + } \ + } while (0) +#define LOG_PRINT(f, arg...) LOG_OUTPUT(LOG_NOTICE, f, ## arg) +#define LOG_ERROR(f, arg...) LOG_OUTPUT(LOG_ERR, f, ## arg) + +#endif /* _LVM_CLOG_LOGGING_H */
diff --git a/daemons/dmeventd/.exported_symbols b/daemons/dmeventd/.exported_symbols new file mode 100644 index 0000000..fab74dc --- /dev/null +++ b/daemons/dmeventd/.exported_symbols
@@ -0,0 +1,4 @@ +init_fifos +fini_fifos +daemon_talk +dm_event_get_version
diff --git a/daemons/dmeventd/.gitignore b/daemons/dmeventd/.gitignore new file mode 100644 index 0000000..71cca4c --- /dev/null +++ b/daemons/dmeventd/.gitignore
@@ -0,0 +1 @@ +dmeventd
diff --git a/daemons/dmeventd/Makefile.in b/daemons/dmeventd/Makefile.in new file mode 100644 index 0000000..52ec938 --- /dev/null +++ b/daemons/dmeventd/Makefile.in
@@ -0,0 +1,110 @@ +# +# Copyright (C) 2005-2011 Red Hat, Inc. All rights reserved. +# +# This file is part of the device-mapper userspace tools. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU Lesser General Public License v.2.1. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +SOURCES = libdevmapper-event.c +SOURCES2 = dmeventd.c + +TARGETS = dmeventd + +.PHONY: install_lib_dynamic install_lib_static install_include \ + install_pkgconfig install_dmeventd_dynamic install_dmeventd_static \ + install_lib install_dmeventd + +INSTALL_DMEVENTD_TARGETS = install_dmeventd_dynamic +INSTALL_LIB_TARGETS = install_lib_dynamic + +LIB_NAME = libdevmapper-event +ifeq ("@STATIC_LINK@", "yes") + LIB_STATIC = $(LIB_NAME).a + TARGETS += $(LIB_STATIC) dmeventd.static + INSTALL_DMEVENTD_TARGETS += install_dmeventd_static + INSTALL_LIB_TARGETS += install_lib_static +endif + +LIB_VERSION = $(LIB_VERSION_DM) +LIB_SHARED = $(LIB_NAME).$(LIB_SUFFIX) + +CLEAN_TARGETS = dmeventd.static $(LIB_NAME).a + +ifneq ($(MAKECMDGOALS),device-mapper) + SUBDIRS+=plugins +endif + +CFLOW_LIST = $(SOURCES) +CFLOW_LIST_TARGET = $(LIB_NAME).cflow +CFLOW_TARGET = dmeventd + +EXPORTED_HEADER = $(srcdir)/libdevmapper-event.h +EXPORTED_FN_PREFIX = dm_event + +include $(top_builddir)/make.tmpl + +all: device-mapper +device-mapper: $(TARGETS) + +LIBS += -ldevmapper +LVMLIBS += -ldevmapper-event $(PTHREAD_LIBS) + +CFLAGS_dmeventd.o += $(EXTRA_EXEC_CFLAGS) + +dmeventd: $(LIB_SHARED) dmeventd.o + $(CC) $(CFLAGS) $(LDFLAGS) $(EXTRA_EXEC_LDFLAGS) $(ELDFLAGS) -L. -o $@ dmeventd.o \ + $(DL_LIBS) $(LVMLIBS) $(LIBS) -rdynamic + +dmeventd.static: $(LIB_STATIC) dmeventd.o $(interfacebuilddir)/libdevmapper.a + $(CC) $(CFLAGS) $(LDFLAGS) $(ELDFLAGS) -static -L. -L$(interfacebuilddir) -o $@ \ + dmeventd.o $(DL_LIBS) $(LVMLIBS) $(LIBS) $(STATIC_LIBS) + +ifeq ("@PKGCONFIG@", "yes") + INSTALL_LIB_TARGETS += install_pkgconfig +endif + +ifneq ("$(CFLOW_CMD)", "") +CFLOW_SOURCES = $(addprefix $(srcdir)/, $(SOURCES)) +-include $(top_builddir)/libdm/libdevmapper.cflow +-include $(top_builddir)/lib/liblvm-internal.cflow +-include $(top_builddir)/lib/liblvm2cmd.cflow +-include $(top_builddir)/daemons/dmeventd/$(LIB_NAME).cflow +-include $(top_builddir)/daemons/dmeventd/plugins/mirror/$(LIB_NAME)-lvm2mirror.cflow +endif + +install_include: $(srcdir)/libdevmapper-event.h + $(INSTALL_DATA) -D $< $(includedir)/$(<F) + +install_pkgconfig: libdevmapper-event.pc + $(INSTALL_DATA) -D $< $(pkgconfigdir)/devmapper-event.pc + +install_lib_dynamic: install_lib_shared + +install_lib_static: $(LIB_STATIC) + $(INSTALL_DATA) -D $< $(usrlibdir)/$(<F) + +install_lib: $(INSTALL_LIB_TARGETS) + +install_dmeventd_dynamic: dmeventd + $(INSTALL_PROGRAM) -D $< $(sbindir)/$(<F) + +install_dmeventd_static: dmeventd.static + $(INSTALL_PROGRAM) -D $< $(staticdir)/$(<F) + +install_dmeventd: $(INSTALL_DMEVENTD_TARGETS) + +install: install_include install_lib install_dmeventd + +install_device-mapper: install_include install_lib install_dmeventd + +DISTCLEAN_TARGETS += libdevmapper-event.pc
diff --git a/daemons/dmeventd/dmeventd.c b/daemons/dmeventd/dmeventd.c new file mode 100644 index 0000000..25b34a7 --- /dev/null +++ b/daemons/dmeventd/dmeventd.c
@@ -0,0 +1,2285 @@ +/* + * Copyright (C) 2005-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of the device-mapper userspace tools. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * dmeventd - dm event daemon to monitor active mapped devices + */ + +#include "dm-logging.h" + +#include "libdevmapper-event.h" +#include "dmeventd.h" + +#include "tool.h" + +#include <dlfcn.h> +#include <pthread.h> +#include <sys/file.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <signal.h> +#include <arpa/inet.h> /* for htonl, ntohl */ +#include <fcntl.h> /* for musl libc */ + +#ifdef __linux__ +/* + * Kernel version 2.6.36 and higher has + * new OOM killer adjustment interface. + */ +# define OOM_ADJ_FILE_OLD "/proc/self/oom_adj" +# define OOM_ADJ_FILE "/proc/self/oom_score_adj" + +/* From linux/oom.h */ +/* Old interface */ +# define OOM_DISABLE (-17) +# define OOM_ADJUST_MIN (-16) +/* New interface */ +# define OOM_SCORE_ADJ_MIN (-1000) + +/* Systemd on-demand activation support */ +# define SD_RUNTIME_UNIT_FILE_DIR DEFAULT_DM_RUN_DIR "/systemd/system/" +# define SD_ACTIVATION_ENV_VAR_NAME "SD_ACTIVATION" +# define SD_LISTEN_PID_ENV_VAR_NAME "LISTEN_PID" +# define SD_LISTEN_FDS_ENV_VAR_NAME "LISTEN_FDS" +# define SD_LISTEN_FDS_START 3 +# define SD_FD_FIFO_SERVER SD_LISTEN_FDS_START +# define SD_FD_FIFO_CLIENT (SD_LISTEN_FDS_START + 1) + +#endif + +#include <syslog.h> + +static volatile sig_atomic_t _exit_now = 0; /* set to '1' when signal is given to exit */ + +/* List (un)link macros. */ +#define LINK(x, head) dm_list_add(head, &(x)->list) +#define LINK_DSO(dso) LINK(dso, &_dso_registry) +#define LINK_THREAD(thread) LINK(thread, &_thread_registry) + +#define UNLINK(x) dm_list_del(&(x)->list) +#define UNLINK_DSO(x) UNLINK(x) +#define UNLINK_THREAD(x) UNLINK(x) + +#define DAEMON_NAME "dmeventd" + +/* + Global mutex for thread list access. Has to be held when: + - iterating thread list + - adding or removing elements from thread list + - changing or reading thread_status's fields: + processing, status, events + Use _lock_mutex() and _unlock_mutex() to hold/release it +*/ +static pthread_mutex_t _global_mutex; + +static const size_t THREAD_STACK_SIZE = 300 * 1024; + +/* Default idle exit timeout 1 hour (in seconds) */ +static const time_t DMEVENTD_IDLE_EXIT_TIMEOUT = 60 * 60; + +static int _debug_level = 0; +static int _use_syslog = 1; +static int _systemd_activation = 0; +static int _foreground = 0; +static int _restart = 0; +static time_t _idle_since = 0; +static char **_initial_registrations = 0; + +/* FIXME Make configurable at runtime */ +__attribute__((format(printf, 4, 5))) +static void _dmeventd_log(int level, const char *file, int line, + const char *format, ...) +{ + va_list ap; + va_start(ap, format); + dm_event_log("dm", level, file, line, 0, format, ap); + va_end(ap); +} + +#ifdef DEBUG +# define DEBUGLOG log_debug +static const char *decode_cmd(uint32_t cmd) +{ + switch (cmd) { + case DM_EVENT_CMD_ACTIVE: return "ACTIVE"; + case DM_EVENT_CMD_REGISTER_FOR_EVENT: return "REGISTER_FOR_EVENT"; + case DM_EVENT_CMD_UNREGISTER_FOR_EVENT: return "UNREGISTER_FOR_EVENT"; + case DM_EVENT_CMD_GET_REGISTERED_DEVICE: return "GET_REGISTERED_DEVICE"; + case DM_EVENT_CMD_GET_NEXT_REGISTERED_DEVICE: return "GET_NEXT_REGISTERED_DEVICE"; + case DM_EVENT_CMD_SET_TIMEOUT: return "SET_TIMEOUT"; + case DM_EVENT_CMD_GET_TIMEOUT: return "GET_TIMEOUT"; + case DM_EVENT_CMD_HELLO: return "HELLO"; + case DM_EVENT_CMD_DIE: return "DIE"; + case DM_EVENT_CMD_GET_STATUS: return "GET_STATUS"; + case DM_EVENT_CMD_GET_PARAMETERS: return "GET_PARAMETERS"; + default: return "unknown"; + } +} + +#else +# define DEBUGLOG(fmt, args...) do { } while (0) +#endif + +/* Data kept about a DSO. */ +struct dso_data { + struct dm_list list; + + char *dso_name; /* DSO name (eg, "evms", "dmraid", "lvm2"). */ + + void *dso_handle; /* Opaque handle as returned from dlopen(). */ + unsigned int ref_count; /* Library reference count. */ + + /* + * Event processing. + * + * The DSO can do whatever appropriate steps if an event + * happens such as changing the mapping in case a mirror + * fails, update the application metadata etc. + * + * This function gets a dm_task that is a result of + * DM_DEVICE_WAITEVENT ioctl (results equivalent to + * DM_DEVICE_STATUS). It should not destroy it. + * The caller must dispose of the task. + */ + void (*process_event)(struct dm_task *dmt, enum dm_event_mask event, void **user); + + /* + * Device registration. + * + * When an application registers a device for an event, the DSO + * can carry out appropriate steps so that a later call to + * the process_event() function is sane (eg, read metadata + * and activate a mapping). + */ + int (*register_device)(const char *device, const char *uuid, int major, + int minor, void **user); + + /* + * Device unregistration. + * + * In case all devices of a mapping (eg, RAID10) are unregistered + * for events, the DSO can recognize this and carry out appropriate + * steps (eg, deactivate mapping, metadata update). + */ + int (*unregister_device)(const char *device, const char *uuid, + int major, int minor, void **user); +}; +static DM_LIST_INIT(_dso_registry); + +/* Structure to keep parsed register variables from client message. */ +struct message_data { + char *id; + char *dso_name; /* Name of DSO. */ + char *device_uuid; /* Mapped device path. */ + char *events_str; /* Events string as fetched from message. */ + enum dm_event_mask events_field; /* Events bitfield. */ + char *timeout_str; + uint32_t timeout_secs; + struct dm_event_daemon_message *msg; /* Pointer to message buffer. */ +}; + +/* There are three states a thread can attain. */ +enum { + DM_THREAD_REGISTERING, /* Registering, transitions to RUNNING */ + DM_THREAD_RUNNING, /* Working on events, transitions to DONE */ + DM_THREAD_DONE /* Terminated and cleanup is pending */ +}; + +/* + * Housekeeping of thread+device states. + * + * One thread per mapped device which can block on it until an event + * occurs and the event processing function of the DSO gets called. + */ +struct thread_status { + struct dm_list list; + + pthread_t thread; + + struct dso_data *dso_data; /* DSO this thread accesses. */ + + struct { + char *uuid; + char *name; + int major, minor; + } device; + int processing; /* Set when event is being processed */ + + int status; /* See DM_THREAD_{REGISTERING,RUNNING,DONE} */ + + int events; /* bitfield for event filter. */ + int current_events; /* bitfield for occured events. */ + struct dm_task *wait_task; + int pending; /* Set when event filter change is pending */ + time_t next_time; + uint32_t timeout; + struct dm_list timeout_list; + void *dso_private; /* dso per-thread status variable */ + /* TODO per-thread mutex */ +}; + +static DM_LIST_INIT(_thread_registry); +static DM_LIST_INIT(_thread_registry_unused); + +static int _timeout_running; +static DM_LIST_INIT(_timeout_registry); +static pthread_mutex_t _timeout_mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t _timeout_cond = PTHREAD_COND_INITIALIZER; + + +/********** + * DSO + **********/ + +/* DSO data allocate/free. */ +static void _free_dso_data(struct dso_data *data) +{ + dm_free(data->dso_name); + dm_free(data); +} + +static struct dso_data *_alloc_dso_data(struct message_data *data) +{ + struct dso_data *ret = (typeof(ret)) dm_zalloc(sizeof(*ret)); + + if (!ret) + return_NULL; + + if (!(ret->dso_name = dm_strdup(data->dso_name))) { + dm_free(ret); + return_NULL; + } + + return ret; +} + +/* DSO reference counting. */ +static void _lib_get(struct dso_data *data) +{ + data->ref_count++; +} + +static void _lib_put(struct dso_data *data) +{ + if (!--data->ref_count) { + dlclose(data->dso_handle); + UNLINK_DSO(data); + _free_dso_data(data); + + /* Close control device if there is no plugin in-use */ + if (dm_list_empty(&_dso_registry)) { + DEBUGLOG("Unholding control device."); + dm_hold_control_dev(0); + dm_lib_release(); + _idle_since = time(NULL); + } + } +} + +/* Find DSO data. */ +static struct dso_data *_lookup_dso(struct message_data *data) +{ + struct dso_data *dso_data, *ret = NULL; + + dm_list_iterate_items(dso_data, &_dso_registry) + if (!strcmp(data->dso_name, dso_data->dso_name)) { + ret = dso_data; + break; + } + + return ret; +} + +/* Lookup DSO symbols we need. */ +static int _lookup_symbol(void *dl, void **symbol, const char *name) +{ + if (!(*symbol = dlsym(dl, name))) + return_0; + + return 1; +} + +static int _lookup_symbols(void *dl, struct dso_data *data) +{ + return _lookup_symbol(dl, (void *) &data->process_event, + "process_event") && + _lookup_symbol(dl, (void *) &data->register_device, + "register_device") && + _lookup_symbol(dl, (void *) &data->unregister_device, + "unregister_device"); +} + +/* Load an application specific DSO. */ +static struct dso_data *_load_dso(struct message_data *data) +{ + void *dl; + struct dso_data *ret; + const char *dlerr; + + if (!(dl = dlopen(data->dso_name, RTLD_NOW))) { + dlerr = dlerror(); + goto_bad; + } + + if (!(ret = _alloc_dso_data(data))) { + dlclose(dl); + dlerr = "no memory"; + goto_bad; + } + + if (!(_lookup_symbols(dl, ret))) { + _free_dso_data(ret); + dlclose(dl); + dlerr = "symbols missing"; + goto_bad; + } + + /* Keep control device open until last user closes */ + if (dm_list_empty(&_dso_registry)) { + DEBUGLOG("Holding control device open."); + dm_hold_control_dev(1); + _idle_since = 0; + } + + /* + * Keep handle to close the library once + * we've got no references to it any more. + */ + ret->dso_handle = dl; + LINK_DSO(ret); + + return ret; +bad: + log_error("dmeventd %s dlopen failed: %s.", data->dso_name, dlerr); + data->msg->size = dm_asprintf(&(data->msg->data), "%s %s dlopen failed: %s", + data->id, data->dso_name, dlerr); + return NULL; +} + +/************ + * THREAD + ************/ + +/* Allocate/free the thread status structure for a monitoring thread. */ +static void _free_thread_status(struct thread_status *thread) +{ + + _lib_put(thread->dso_data); + if (thread->wait_task) + dm_task_destroy(thread->wait_task); + dm_free(thread->device.uuid); + dm_free(thread->device.name); + dm_free(thread); +} + +/* Note: events_field must not be 0, ensured by caller */ +static struct thread_status *_alloc_thread_status(const struct message_data *data, + struct dso_data *dso_data) +{ + struct thread_status *thread; + + if (!(thread = dm_zalloc(sizeof(*thread)))) { + log_error("Cannot create new thread, out of memory."); + return NULL; + } + + _lib_get(dso_data); + thread->dso_data = dso_data; + + if (!(thread->wait_task = dm_task_create(DM_DEVICE_WAITEVENT))) + goto_out; + + if (!dm_task_set_uuid(thread->wait_task, data->device_uuid)) + goto_out; + + if (!(thread->device.uuid = dm_strdup(data->device_uuid))) + goto_out; + + /* Until real name resolved, use UUID */ + if (!(thread->device.name = dm_strdup(data->device_uuid))) + goto_out; + + /* runs ioctl and may register lvm2 pluging */ + thread->processing = 1; + thread->status = DM_THREAD_REGISTERING; + + thread->events = data->events_field; + thread->pending = DM_EVENT_REGISTRATION_PENDING; + thread->timeout = data->timeout_secs; + dm_list_init(&thread->timeout_list); + + return thread; + +out: + _free_thread_status(thread); + + return NULL; +} + +/* + * Create a device monitoring thread. + * N.B. Error codes returned are positive. + */ +static int _pthread_create_smallstack(pthread_t *t, void *(*fun)(void *), void *arg) +{ + int r; + pthread_t tmp; + pthread_attr_t attr; + + /* + * From pthread_attr_init man page: + * POSIX.1-2001 documents an ENOMEM error for pthread_attr_init(); on + * Linux these functions always succeed (but portable and future-proof + * applications should nevertheless handle a possible error return). + */ + if ((r = pthread_attr_init(&attr)) != 0) { + log_sys_error("pthread_attr_init", ""); + return r; + } + + /* + * We use a smaller stack since it gets preallocated in its entirety + */ + pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE); + + /* + * If no-one will be waiting, we need to detach. + */ + if (!t) { + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + t = &tmp; + } + + if ((r = pthread_create(t, &attr, fun, arg))) + log_sys_error("pthread_create", ""); + + pthread_attr_destroy(&attr); + + return r; +} + +/* + * Fetch a string off src and duplicate it into *ptr. + * Pay attention to zero-length and 'empty' strings ('-'). + */ +/* FIXME? move to libdevmapper to share with the client lib (need to + make delimiter a parameter then) */ +static int _fetch_string(char **ptr, char **src, const int delimiter) +{ + int ret = 1; + char *p; + size_t len; + *ptr = NULL; /* Empty field returns NULL pointer */ + + if ((*src)[0] == '-') { + /* Could be empty field '-', handle without allocation */ + if ((*src)[1] == '\0') { + (*src)++; + goto out; + } else if ((*src)[1] == delimiter) { + (*src) += 2; + goto out; + } + } + + if ((p = strchr(*src, delimiter))) { + if (*src < p) { + *p = 0; /* Temporary exit with \0 */ + if (!(*ptr = dm_strdup(*src))) { + log_error("Failed to fetch item %s.", *src); + ret = 0; /* Allocation fail */ + } + *p = delimiter; + *src = p; + } + (*src)++; /* Skip delmiter, next field */ + } else if ((len = strlen(*src))) { + /* No delimiter, item ends with '\0' */ + if (!(*ptr = dm_strdup(*src))) { + log_error("Failed to fetch last item %s.", *src); + ret = 0; /* Fail */ + } + *src += len + 1; + } +out: + return ret; +} + +/* Free message memory. */ +static void _free_message(struct message_data *message_data) +{ + dm_free(message_data->id); + dm_free(message_data->dso_name); + dm_free(message_data->device_uuid); + dm_free(message_data->events_str); + dm_free(message_data->timeout_str); +} + +/* Parse a register message from the client. */ +static int _parse_message(struct message_data *message_data) +{ + int ret = 0; + struct dm_event_daemon_message *msg = message_data->msg; + char *p = msg->data; + + if (!msg->data) + return 0; + + /* + * Retrieve application identifier, mapped device + * path and events # string from message. + */ + if (_fetch_string(&message_data->id, &p, ' ') && + _fetch_string(&message_data->dso_name, &p, ' ') && + _fetch_string(&message_data->device_uuid, &p, ' ') && + _fetch_string(&message_data->events_str, &p, ' ') && + _fetch_string(&message_data->timeout_str, &p, ' ')) { + if (message_data->events_str) + message_data->events_field = + atoi(message_data->events_str); + if (message_data->timeout_str) + message_data->timeout_secs = + atoi(message_data->timeout_str) + ? : DM_EVENT_DEFAULT_TIMEOUT; + ret = 1; + } + + dm_free(msg->data); + msg->data = NULL; + + return ret; +} + +/* Global mutex to lock access to lists et al. See _global_mutex + above. */ +static int _lock_mutex(void) +{ + return pthread_mutex_lock(&_global_mutex); +} + +static int _unlock_mutex(void) +{ + return pthread_mutex_unlock(&_global_mutex); +} + +/* Check, if a device exists. */ +static int _fill_device_data(struct thread_status *ts) +{ + struct dm_task *dmt; + struct dm_info dmi; + int ret = 0; + + if (!(dmt = dm_task_create(DM_DEVICE_INFO))) + return 0; + + if (!dm_task_set_uuid(dmt, ts->device.uuid)) + goto fail; + + if (!dm_task_run(dmt)) + goto fail; + + dm_free(ts->device.name); + if (!(ts->device.name = dm_strdup(dm_task_get_name(dmt)))) + goto fail; + + if (!dm_task_get_info(dmt, &dmi)) + goto fail; + + ts->device.major = dmi.major; + ts->device.minor = dmi.minor; + dm_task_set_event_nr(ts->wait_task, dmi.event_nr); + + ret = 1; +fail: + dm_task_destroy(dmt); + + return ret; +} + +static struct dm_task *_get_device_status(struct thread_status *ts) +{ + struct dm_task *dmt = dm_task_create(DM_DEVICE_STATUS); + + if (!dmt) + return_NULL; + + if (!dm_task_set_uuid(dmt, ts->device.uuid)) { + dm_task_destroy(dmt); + return_NULL; + } + + /* Non-blocking status read */ + if (!dm_task_no_flush(dmt)) + log_warn("WARNING: Can't set no_flush for dm status."); + + if (!dm_task_run(dmt)) { + dm_task_destroy(dmt); + return_NULL; + } + + return dmt; +} + +/* + * Find an existing thread for a device. + * + * Mutex must be held when calling this. + */ +static struct thread_status *_lookup_thread_status(struct message_data *data) +{ + struct thread_status *thread; + + dm_list_iterate_items(thread, &_thread_registry) + if (!strcmp(data->device_uuid, thread->device.uuid)) + return thread; + + return NULL; +} + +static int _get_status(struct message_data *message_data) +{ + struct dm_event_daemon_message *msg = message_data->msg; + struct thread_status *thread; + int i = 0, j; + int ret = -ENOMEM; + int count; + int size = 0, current; + size_t len; + char **buffers; + char *message; + + _lock_mutex(); + count = dm_list_size(&_thread_registry); + buffers = alloca(sizeof(char*) * count); + dm_list_iterate_items(thread, &_thread_registry) { + if ((current = dm_asprintf(buffers + i, "0:%d %s %s %u %" PRIu32 ";", + i, thread->dso_data->dso_name, + thread->device.uuid, thread->events, + thread->timeout)) < 0) { + _unlock_mutex(); + goto out; + } + ++i; + size += current; /* count with trailing '\0' */ + } + _unlock_mutex(); + + len = strlen(message_data->id); + msg->size = size + len + 1; + dm_free(msg->data); + if (!(msg->data = dm_malloc(msg->size))) + goto out; + + memcpy(msg->data, message_data->id, len); + message = msg->data + len; + *message++ = ' '; + for (j = 0; j < i; ++j) { + len = strlen(buffers[j]); + memcpy(message, buffers[j], len); + message += len; + } + + ret = 0; + out: + for (j = 0; j < i; ++j) + dm_free(buffers[j]); + + return ret; +} + +static int _get_parameters(struct message_data *message_data) { + struct dm_event_daemon_message *msg = message_data->msg; + int size; + + dm_free(msg->data); + if ((size = dm_asprintf(&msg->data, "%s pid=%d daemon=%s exec_method=%s", + message_data->id, getpid(), + _foreground ? "no" : "yes", + _systemd_activation ? "systemd" : "direct")) < 0) { + stack; + return -ENOMEM; + } + + msg->size = (uint32_t) size; + + return 0; +} + +/* Cleanup at exit. */ +static void _exit_dm_lib(void) +{ + dm_lib_release(); + dm_lib_exit(); +} + +static void _exit_timeout(void *unused __attribute__((unused))) +{ + _timeout_running = 0; + pthread_mutex_unlock(&_timeout_mutex); +} + +/* Wake up monitor threads every so often. */ +static void *_timeout_thread(void *unused __attribute__((unused))) +{ + struct thread_status *thread; + struct timespec timeout; + time_t curr_time; + + DEBUGLOG("Timeout thread starting."); + pthread_cleanup_push(_exit_timeout, NULL); + pthread_mutex_lock(&_timeout_mutex); + + while (!dm_list_empty(&_timeout_registry)) { + timeout.tv_sec = 0; + timeout.tv_nsec = 0; + curr_time = time(NULL); + + dm_list_iterate_items_gen(thread, &_timeout_registry, timeout_list) { + if (thread->next_time <= curr_time) { + thread->next_time = curr_time + thread->timeout; + _lock_mutex(); + if (thread->processing) { + /* Cannot signal processing monitoring thread */ + log_debug("Skipping SIGALRM to processing Thr %x for timeout.", + (int) thread->thread); + } else { + DEBUGLOG("Sending SIGALRM to Thr %x for timeout.", + (int) thread->thread); + pthread_kill(thread->thread, SIGALRM); + } + _unlock_mutex(); + } + + if (thread->next_time < timeout.tv_sec || !timeout.tv_sec) + timeout.tv_sec = thread->next_time; + } + + pthread_cond_timedwait(&_timeout_cond, &_timeout_mutex, + &timeout); + } + + DEBUGLOG("Timeout thread finished."); + pthread_cleanup_pop(1); + + return NULL; +} + +static int _register_for_timeout(struct thread_status *thread) +{ + int ret = 0; + + pthread_mutex_lock(&_timeout_mutex); + + if (dm_list_empty(&thread->timeout_list)) { + thread->next_time = time(NULL) + thread->timeout; + dm_list_add(&_timeout_registry, &thread->timeout_list); + if (_timeout_running) + pthread_cond_signal(&_timeout_cond); + } + + if (!_timeout_running && + !(ret = _pthread_create_smallstack(NULL, _timeout_thread, NULL))) + _timeout_running = 1; + + pthread_mutex_unlock(&_timeout_mutex); + + return ret; +} + +static void _unregister_for_timeout(struct thread_status *thread) +{ + pthread_mutex_lock(&_timeout_mutex); + if (!dm_list_empty(&thread->timeout_list)) { + dm_list_del(&thread->timeout_list); + dm_list_init(&thread->timeout_list); + if (dm_list_empty(&_timeout_registry)) + /* No more work -> wakeup to finish quickly */ + pthread_cond_signal(&_timeout_cond); + } + pthread_mutex_unlock(&_timeout_mutex); +} + +#ifdef DEBUG_SIGNALS +/* Print list of signals within a signal set */ +static void _print_sigset(const char *prefix, const sigset_t *sigset) +{ + int sig, cnt = 0; + + for (sig = 1; sig < NSIG; sig++) + if (!sigismember(sigset, sig)) { + cnt++; + log_debug("%s%d (%s)", prefix, sig, strsignal(sig)); + } + + if (!cnt) + log_debug("%s<empty signal set>", prefix); +} +#endif + +static sigset_t _unblock_sigalrm(void) +{ + sigset_t set, old; + + sigemptyset(&set); + sigaddset(&set, SIGALRM); + pthread_sigmask(SIG_UNBLOCK, &set, &old); + + return old; +} + +enum { + DM_WAIT_RETRY, + DM_WAIT_INTR, + DM_WAIT_FATAL +}; + +/* Wait on a device until an event occurs. */ +static int _event_wait(struct thread_status *thread) +{ + sigset_t set; + int ret = DM_WAIT_RETRY; + struct dm_info info; + + /* TODO: audit libdm thread usage */ + + /* + * This is so that you can break out of waiting on an event, + * either for a timeout event, or to cancel the thread. + */ + set = _unblock_sigalrm(); + + if (dm_task_run(thread->wait_task)) { + thread->current_events |= DM_EVENT_DEVICE_ERROR; + ret = DM_WAIT_INTR; + /* Update event_nr */ + if (dm_task_get_info(thread->wait_task, &info)) + dm_task_set_event_nr(thread->wait_task, info.event_nr); + } else { + switch (dm_task_get_errno(thread->wait_task)) { + case ENXIO: + log_error("%s disappeared, detaching.", + thread->device.name); + ret = DM_WAIT_FATAL; + break; + case EINTR: + thread->current_events |= DM_EVENT_TIMEOUT; + ret = DM_WAIT_INTR; + break; + default: + log_sys_error("dm_task_run", "waitevent"); + } + } + + pthread_sigmask(SIG_SETMASK, &set, NULL); + +#ifdef DEBUG_SIGNALS + _print_sigset("dmeventd blocking ", &set); +#endif + DEBUGLOG("Completed waitevent task for %s.", thread->device.name); + + return ret; +} + +/* Register a device with the DSO. */ +static int _do_register_device(struct thread_status *thread) +{ + return thread->dso_data->register_device(thread->device.name, + thread->device.uuid, + thread->device.major, + thread->device.minor, + &(thread->dso_private)); +} + +/* Unregister a device with the DSO. */ +static int _do_unregister_device(struct thread_status *thread) +{ + return thread->dso_data->unregister_device(thread->device.name, + thread->device.uuid, + thread->device.major, + thread->device.minor, + &(thread->dso_private)); +} + +/* Process an event in the DSO. */ +static void _do_process_event(struct thread_status *thread) +{ + struct dm_task *task; + + /* NOTE: timeout event gets status */ + task = (thread->current_events & DM_EVENT_TIMEOUT) + ? _get_device_status(thread) : thread->wait_task; + + if (!task) + log_error("Lost event in Thr %x.", (int)thread->thread); + else { + thread->dso_data->process_event(task, thread->current_events, &(thread->dso_private)); + if (task != thread->wait_task) + dm_task_destroy(task); + } +} + +static void _thread_unused(struct thread_status *thread) +{ + UNLINK_THREAD(thread); + LINK(thread, &_thread_registry_unused); +} + +/* Thread cleanup handler to unregister device. */ +static void _monitor_unregister(void *arg) +{ + struct thread_status *thread = arg, *thread_iter; + + dm_list_iterate_items(thread_iter, &_thread_registry) + if (thread_iter == thread) { + /* Relink to _unused */ + _thread_unused(thread); + break; + } + + thread->events = 0; /* Filter is now empty */ + thread->pending = 0; /* Event pending resolved */ + thread->processing = 1; /* Process unregistering */ + + _unlock_mutex(); + + DEBUGLOG("Unregistering monitor for %s.", thread->device.name); + _unregister_for_timeout(thread); + + if ((thread->status != DM_THREAD_REGISTERING) && + !_do_unregister_device(thread)) + log_error("%s: %s unregister failed.", __func__, + thread->device.name); + + DEBUGLOG("Marking Thr %x as DONE and unused.", (int)thread->thread); + + _lock_mutex(); + thread->status = DM_THREAD_DONE; /* Last access to thread memory! */ + _unlock_mutex(); +} + +/* Device monitoring thread. */ +static void *_monitor_thread(void *arg) +{ + struct thread_status *thread = arg; + int ret; + sigset_t pendmask; + + pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); + pthread_cleanup_push(_monitor_unregister, thread); + + if (!_fill_device_data(thread)) { + log_error("Failed to fill device data for %s.", thread->device.uuid); + _lock_mutex(); + goto out; + } + + if (!_do_register_device(thread)) { + log_error("Failed to register device %s.", thread->device.name); + _lock_mutex(); + goto out; + } + + _lock_mutex(); + thread->status = DM_THREAD_RUNNING; + thread->processing = 0; + + /* Loop awaiting/analyzing device events. */ + while (thread->events) { + + thread->pending = 0; /* Event is no longer pending... */ + + /* + * Check against bitmask filter. + * + * If there's current events delivered from _event_wait() AND + * the device got registered for those events AND + * those events haven't been processed yet, call + * the DSO's process_event() handler. + */ + if (thread->events & thread->current_events) { + thread->processing = 1; /* Cannot be removed/signaled */ + _unlock_mutex(); + + _do_process_event(thread); + thread->current_events = 0; /* Current events processed */ + + _lock_mutex(); + thread->processing = 0; + + /* + * Thread can terminate itself from plugin via SIGALRM + * Timer thread will not send signal while processing + * TODO: maybe worth API change and return value for + * _do_process_event() instead of this signal solution + */ + if (sigpending(&pendmask) < 0) + log_sys_error("sigpending", ""); + else if (sigismember(&pendmask, SIGALRM)) + break; + } else { + _unlock_mutex(); + + if ((ret = _event_wait(thread)) == DM_WAIT_RETRY) + usleep(100); /* Avoid busy loop, wait without mutex */ + + _lock_mutex(); + + if (ret == DM_WAIT_FATAL) + break; + } + } +out: + /* ';' fixes gcc compilation problem with older pthread macros + * "label at end of compound statement" */ + ; + + pthread_cleanup_pop(1); + + return NULL; +} + +/* Create a device monitoring thread. */ +static int _create_thread(struct thread_status *thread) +{ + return _pthread_create_smallstack(&thread->thread, _monitor_thread, thread); +} + +/* Update events - needs to be locked */ +static int _update_events(struct thread_status *thread, int events) +{ + int ret = 0; + + if (thread->events == events) + return 0; /* Nothing has changed */ + + thread->events = events; + thread->pending = DM_EVENT_REGISTRATION_PENDING; + + /* Only non-processing threads can be notified */ + if (!thread->processing) { + DEBUGLOG("Sending SIGALRM to wakeup Thr %x.", (int)thread->thread); + + /* Notify thread waiting in ioctl (to speed-up) */ + if ((ret = pthread_kill(thread->thread, SIGALRM))) { + if (ret == ESRCH) + thread->events = 0; /* thread is gone */ + else + log_error("Unable to wakeup thread: %s", + strerror(ret)); + } + } + + /* Threads with no events has to be moved to unused */ + if (!thread->events) + _thread_unused(thread); + + return -ret; +} + +/* Return success on daemon active check. */ +static int _active(struct message_data *message_data) +{ + return 0; +} + +/* + * Unregister for an event. + * + * Only one caller at a time here as with register_for_event(). + */ +static int _unregister_for_event(struct message_data *message_data) +{ + struct thread_status *thread; + int ret; + + /* + * Clear event in bitfield and deactivate + * monitoring thread in case bitfield is 0. + */ + _lock_mutex(); + + if (!(thread = _lookup_thread_status(message_data))) { + _unlock_mutex(); + return -ENODEV; + } + + /* AND mask event ~# from events bitfield. */ + ret = _update_events(thread, (thread->events & ~message_data->events_field)); + + _unlock_mutex(); + + /* If there are no events, thread is later garbage + * collected by _cleanup_unused_threads */ + if (message_data->events_field & DM_EVENT_TIMEOUT) + _unregister_for_timeout(thread); + + DEBUGLOG("Unregistered event for %s.", thread->device.name); + + return ret; +} + +/* + * Register for an event. + * + * Only one caller at a time here, because we use + * a FIFO and lock it against multiple accesses. + */ +static int _register_for_event(struct message_data *message_data) +{ + int ret = 0; + struct thread_status *thread; + struct dso_data *dso_data; + + if (!(dso_data = _lookup_dso(message_data)) && + !(dso_data = _load_dso(message_data))) { + stack; +#ifdef ELIBACC + ret = ELIBACC; +#else + ret = ENODEV; +#endif + return ret; + } + + _lock_mutex(); + + if ((thread = _lookup_thread_status(message_data))) { + /* OR event # into events bitfield. */ + ret = _update_events(thread, (thread->events | message_data->events_field)); + } else { + _unlock_mutex(); + + /* Only creating thread during event processing + * Remaining initialization happens within monitoring thread */ + if (!(thread = _alloc_thread_status(message_data, dso_data))) { + stack; + return -ENOMEM; + } + + if ((ret = _create_thread(thread))) { + stack; + _free_thread_status(thread); + return -ret; + } + + _lock_mutex(); + /* Note: same uuid can't be added in parallel */ + LINK_THREAD(thread); + } + + _unlock_mutex(); + + /* If creation of timeout thread fails (as it may), we fail + here completely. The client is responsible for either + retrying later or trying to register without timeout + events. However, if timeout thread cannot be started, it + usually means we are so starved on resources that we are + almost as good as dead already... */ + if ((message_data->events_field & DM_EVENT_TIMEOUT) && + (ret = _register_for_timeout(thread))) { + stack; + _unregister_for_event(message_data); + } + + return -ret; +} + +/* + * Get registered device. + * + * Only one caller at a time here as with register_for_event(). + */ +static int _registered_device(struct message_data *message_data, + struct thread_status *thread) +{ + int r; + struct dm_event_daemon_message *msg = message_data->msg; + + dm_free(msg->data); + + if ((r = dm_asprintf(&(msg->data), "%s %s %s %u", + message_data->id, + thread->dso_data->dso_name, + thread->device.uuid, + thread->events | thread->pending)) < 0) + return -ENOMEM; + + msg->size = (uint32_t) r; + DEBUGLOG("Registered %s.", msg->data); + + return 0; +} + +static int _want_registered_device(char *dso_name, char *device_uuid, + struct thread_status *thread) +{ + /* If DSO names and device paths are equal. */ + if (dso_name && device_uuid) + return !strcmp(dso_name, thread->dso_data->dso_name) && + !strcmp(device_uuid, thread->device.uuid); + + /* If DSO names are equal. */ + if (dso_name) + return !strcmp(dso_name, thread->dso_data->dso_name); + + /* If device paths are equal. */ + if (device_uuid) + return !strcmp(device_uuid, thread->device.uuid); + + return 1; +} + +static int _get_registered_dev(struct message_data *message_data, int next) +{ + struct thread_status *thread, *hit = NULL; + int ret = -ENOENT; + + DEBUGLOG("Get%s dso:%s uuid:%s.", next ? "" : "Next", + message_data->dso_name, + message_data->device_uuid); + _lock_mutex(); + + /* Iterate list of threads checking if we want a particular one. */ + dm_list_iterate_items(thread, &_thread_registry) + if (_want_registered_device(message_data->dso_name, + message_data->device_uuid, + thread)) { + hit = thread; + break; + } + + /* + * If we got a registered device and want the next one -> + * fetch next conforming element off the list. + */ + if (hit && !next) + goto reg; + + /* + * If we didn't get a match, try the threads waiting to be deleted. + * FIXME Do something similar if 'next' is set. + */ + if (!hit && !next) + dm_list_iterate_items(thread, &_thread_registry_unused) + if (_want_registered_device(message_data->dso_name, + message_data->device_uuid, thread)) { + hit = thread; + goto reg; + } + + if (!hit) { + DEBUGLOG("Get%s not registered", next ? "" : "Next"); + goto out; + } + + while (1) { + if (dm_list_end(&_thread_registry, &thread->list)) + goto out; + + thread = dm_list_item(thread->list.n, struct thread_status); + if (_want_registered_device(message_data->dso_name, NULL, thread)) { + hit = thread; + break; + } + } + + reg: + ret = _registered_device(message_data, hit); + + out: + _unlock_mutex(); + + return ret; +} + +static int _get_registered_device(struct message_data *message_data) +{ + return _get_registered_dev(message_data, 0); +} + +static int _get_next_registered_device(struct message_data *message_data) +{ + return _get_registered_dev(message_data, 1); +} + +static int _set_timeout(struct message_data *message_data) +{ + struct thread_status *thread; + + _lock_mutex(); + thread = _lookup_thread_status(message_data); + _unlock_mutex(); + + if (!thread) + return -ENODEV; + + /* Lets reprogram timer */ + pthread_mutex_lock(&_timeout_mutex); + thread->timeout = message_data->timeout_secs; + thread->next_time = 0; + pthread_cond_signal(&_timeout_cond); + pthread_mutex_unlock(&_timeout_mutex); + + return 0; +} + +static int _get_timeout(struct message_data *message_data) +{ + struct thread_status *thread; + struct dm_event_daemon_message *msg = message_data->msg; + + _lock_mutex(); + thread = _lookup_thread_status(message_data); + _unlock_mutex(); + + if (!thread) + return -ENODEV; + + dm_free(msg->data); + msg->size = dm_asprintf(&(msg->data), "%s %" PRIu32, + message_data->id, thread->timeout); + + return (msg->data && msg->size) ? 0 : -ENOMEM; +} + +static int _open_fifo(const char *path) +{ + struct stat st; + int fd = -1; + + /* + * FIXME Explicitly verify the code's requirement that path is secure: + * - All parent directories owned by root without group/other write access unless sticky. + */ + + /* If path exists, only use it if it is root-owned fifo mode 0600 */ + if ((lstat(path, &st) < 0)) { + if (errno != ENOENT) { + log_sys_error("stat", path); + return -1; + } + } else if (!S_ISFIFO(st.st_mode) || st.st_uid || + (st.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO))) { + log_warn("WARNING: %s has wrong attributes: Replacing.", path); + if (unlink(path)) { + log_sys_error("unlink", path); + return -1; + } + } + + /* Create fifo. */ + (void) dm_prepare_selinux_context(path, S_IFIFO); + if ((mkfifo(path, 0600) == -1) && errno != EEXIST) { + log_sys_error("mkfifo", path); + (void) dm_prepare_selinux_context(NULL, 0); + goto fail; + } + + (void) dm_prepare_selinux_context(NULL, 0); + + /* Need to open read+write or we will block or fail */ + if ((fd = open(path, O_RDWR)) < 0) { + log_sys_error("open", path); + goto fail; + } + + /* Warn about wrong permissions if applicable */ + if (fstat(fd, &st)) { + log_sys_error("fstat", path); + goto fail; + } + + if (!S_ISFIFO(st.st_mode) || st.st_uid || + (st.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO))) { + log_error("%s: fifo has incorrect attributes", path); + goto fail; + } + + if (fcntl(fd, F_SETFD, FD_CLOEXEC)) { + log_sys_error("fcntl(FD_CLOEXEC)", path); + goto fail; + } + + return fd; + +fail: + if ((fd >= 0) && close(fd)) + log_sys_error("close", path); + + return -1; +} + +/* Open fifos used for client communication. */ +static int _open_fifos(struct dm_event_fifos *fifos) +{ + /* Create client fifo. */ + if ((fifos->client = _open_fifo(fifos->client_path)) < 0) + goto fail; + + /* Create server fifo. */ + if ((fifos->server = _open_fifo(fifos->server_path)) < 0) + goto fail; + + return 1; + +fail: + if (fifos->client >= 0 && close(fifos->client)) + log_sys_error("close", fifos->client_path); + + return 0; +} + +/* + * Read message from client making sure that data is available + * and a complete message is read. Must not block indefinitely. + */ +static int _client_read(struct dm_event_fifos *fifos, + struct dm_event_daemon_message *msg) +{ + struct timeval t; + unsigned bytes = 0; + int ret = 0; + fd_set fds; + size_t size = 2 * sizeof(uint32_t); /* status + size */ + uint32_t *header = alloca(size); + char *buf = (char *)header; + + msg->data = NULL; + + errno = 0; + while (bytes < size && errno != EOF) { + /* Watch client read FIFO for input. */ + FD_ZERO(&fds); + FD_SET(fifos->client, &fds); + t.tv_sec = 1; + t.tv_usec = 0; + ret = select(fifos->client + 1, &fds, NULL, NULL, &t); + + if (!ret && !bytes) /* nothing to read */ + return 0; + + if (!ret) /* trying to finish read */ + continue; + + if (ret < 0) /* error */ + return 0; + + ret = read(fifos->client, buf + bytes, size - bytes); + bytes += ret > 0 ? ret : 0; + if (header && (bytes == 2 * sizeof(uint32_t))) { + msg->cmd = ntohl(header[0]); + size = msg->size = ntohl(header[1]); + bytes = 0; + if (!size) + break; /* No data -> error */ + buf = msg->data = dm_malloc(msg->size); + if (!buf) + break; /* No mem -> error */ + header = 0; + } + } + + if (bytes != size) { + dm_free(msg->data); + msg->data = NULL; + return 0; + } + + return 1; +} + +/* + * Write a message to the client making sure that it is ready to write. + */ +static int _client_write(struct dm_event_fifos *fifos, + struct dm_event_daemon_message *msg) +{ + uint32_t temp[2]; + unsigned bytes = 0; + int ret = 0; + fd_set fds; + + size_t size = 2 * sizeof(uint32_t) + ((msg->data) ? msg->size : 0); + uint32_t *header = dm_malloc(size); + char *buf = (char *)header; + + if (!header) { + /* Reply with ENOMEM message */ + header = temp; + size = sizeof(temp); + header[0] = htonl(-ENOMEM); + header[1] = 0; + } else { + header[0] = htonl(msg->cmd); + header[1] = htonl((msg->data) ? msg->size : 0); + if (msg->data) + memcpy(buf + 2 * sizeof(uint32_t), msg->data, msg->size); + } + + while (bytes < size) { + do { + /* Watch client write FIFO to be ready for output. */ + FD_ZERO(&fds); + FD_SET(fifos->server, &fds); + } while (select(fifos->server + 1, NULL, &fds, NULL, NULL) != 1); + + if ((ret = write(fifos->server, buf + bytes, size - bytes)) > 0) + bytes += ret; + else if (errno == EIO) + break; + } + + if (header != temp) + dm_free(header); + + return (bytes == size); +} + +/* + * Handle a client request. + * + * We put the request handling functions into + * a list because of the growing number. + */ +static int _handle_request(struct dm_event_daemon_message *msg, + struct message_data *message_data) +{ + switch (msg->cmd) { + case DM_EVENT_CMD_REGISTER_FOR_EVENT: + if (!message_data->events_field) + return -EINVAL; + return _register_for_event(message_data); + case DM_EVENT_CMD_UNREGISTER_FOR_EVENT: + return _unregister_for_event(message_data); + case DM_EVENT_CMD_GET_REGISTERED_DEVICE: + return _get_registered_device(message_data); + case DM_EVENT_CMD_GET_NEXT_REGISTERED_DEVICE: + return _get_next_registered_device(message_data); + case DM_EVENT_CMD_SET_TIMEOUT: + return _set_timeout(message_data); + case DM_EVENT_CMD_GET_TIMEOUT: + return _get_timeout(message_data); + case DM_EVENT_CMD_ACTIVE: + return _active(message_data); + case DM_EVENT_CMD_GET_STATUS: + return _get_status(message_data); + /* dmeventd parameters of running dmeventd, + * returns 'pid=<pid> daemon=<no/yes> exec_method=<direct/systemd>' + * pid - pidfile of running dmeventd + * daemon - running as a daemon or not (foreground)? + * exec_method - "direct" if executed directly or + * "systemd" if executed via systemd + */ + case DM_EVENT_CMD_GET_PARAMETERS: + return _get_parameters(message_data); + default: + return -EINVAL; + } +} + +/* Process a request passed from the communication thread. */ +static int _do_process_request(struct dm_event_daemon_message *msg) +{ + int ret; + char *answer; + struct message_data message_data = { .msg = msg }; + + /* Parse the message. */ + if (msg->cmd == DM_EVENT_CMD_HELLO || msg->cmd == DM_EVENT_CMD_DIE) { + ret = 0; + answer = msg->data; + if (answer) { + msg->size = dm_asprintf(&(msg->data), "%s %s %d", answer, + (msg->cmd == DM_EVENT_CMD_DIE) ? "DYING" : "HELLO", + DM_EVENT_PROTOCOL_VERSION); + dm_free(answer); + } + } else if (msg->cmd != DM_EVENT_CMD_ACTIVE && !_parse_message(&message_data)) { + stack; + ret = -EINVAL; + } else + ret = _handle_request(msg, &message_data); + + msg->cmd = ret; + if (!msg->data) + msg->size = dm_asprintf(&(msg->data), "%s %s", message_data.id, strerror(-ret)); + + _free_message(&message_data); + + return ret; +} + +/* Only one caller at a time. */ +static void _process_request(struct dm_event_fifos *fifos) +{ + struct dm_event_daemon_message msg = { 0 }; + int cmd; + /* + * Read the request from the client (client_read, client_write + * give true on success and false on failure). + */ + if (!_client_read(fifos, &msg)) + return; + + cmd = msg.cmd; + + DEBUGLOG(">>> CMD:%s (0x%x) processing...", decode_cmd(cmd), cmd); + + /* _do_process_request fills in msg (if memory allows for + data, otherwise just cmd and size = 0) */ + _do_process_request(&msg); + + if (!_client_write(fifos, &msg)) + stack; + + DEBUGLOG("<<< CMD:%s (0x%x) completed (result %d).", decode_cmd(cmd), cmd, msg.cmd); + + dm_free(msg.data); + + if (cmd == DM_EVENT_CMD_DIE) { + if (unlink(DMEVENTD_PIDFILE)) + log_sys_error("unlink", DMEVENTD_PIDFILE); + _exit(0); + } +} + +static void _process_initial_registrations(void) +{ + int i; + char *reg; + struct dm_event_daemon_message msg = { 0 }; + + for (i = 0; (reg = _initial_registrations[i]); ++i) { + msg.cmd = DM_EVENT_CMD_REGISTER_FOR_EVENT; + if ((msg.size = strlen(reg))) { + msg.data = reg; + _do_process_request(&msg); + } + } +} + +static void _cleanup_unused_threads(void) +{ + struct dm_list *l; + struct thread_status *thread; + int ret; + + _lock_mutex(); + + while ((l = dm_list_first(&_thread_registry_unused))) { + thread = dm_list_item(l, struct thread_status); + if (thread->status != DM_THREAD_DONE) { + if (thread->processing) + break; /* cleanup on the next round */ + + /* Signal possibly sleeping thread */ + ret = pthread_kill(thread->thread, SIGALRM); + if (!ret || (ret != ESRCH)) + break; /* check again on the next round */ + + /* thread is likely gone */ + } + + dm_list_del(l); + _unlock_mutex(); + + DEBUGLOG("Destroying Thr %x.", (int)thread->thread); + + if (pthread_join(thread->thread, NULL)) + log_sys_error("pthread_join", ""); + + _free_thread_status(thread); + _lock_mutex(); + } + + _unlock_mutex(); +} + +static void _sig_alarm(int signum __attribute__((unused))) +{ + /* empty SIG_IGN */; +} + +/* Init thread signal handling. */ +static void _init_thread_signals(void) +{ + sigset_t my_sigset; + struct sigaction act = { .sa_handler = _sig_alarm }; + + sigaction(SIGALRM, &act, NULL); + sigfillset(&my_sigset); + + /* These are used for exiting */ + sigdelset(&my_sigset, SIGTERM); + sigdelset(&my_sigset, SIGINT); + sigdelset(&my_sigset, SIGHUP); + sigdelset(&my_sigset, SIGQUIT); + + pthread_sigmask(SIG_BLOCK, &my_sigset, NULL); +} + +/* + * exit_handler + * @sig + * + * Set the global variable which the process should + * be watching to determine when to exit. + */ +static void _exit_handler(int sig __attribute__((unused))) +{ + _exit_now = 1; +} + +#ifdef __linux__ +static int _set_oom_adj(const char *oom_adj_path, int val) +{ + FILE *fp; + + if (!(fp = fopen(oom_adj_path, "w"))) { + log_sys_error("open", oom_adj_path); + return 0; + } + + fprintf(fp, "%i", val); + + if (dm_fclose(fp)) + log_sys_error("fclose", oom_adj_path); + + return 1; +} + +/* + * Protection against OOM killer if kernel supports it + */ +static int _protect_against_oom_killer(void) +{ + struct stat st; + + if (stat(OOM_ADJ_FILE, &st) == -1) { + if (errno != ENOENT) + log_sys_error("stat", OOM_ADJ_FILE); + + /* Try old oom_adj interface as a fallback */ + if (stat(OOM_ADJ_FILE_OLD, &st) == -1) { + log_sys_error("stat", OOM_ADJ_FILE_OLD); + return 1; + } + + return _set_oom_adj(OOM_ADJ_FILE_OLD, OOM_DISABLE) || + _set_oom_adj(OOM_ADJ_FILE_OLD, OOM_ADJUST_MIN); + } + + return _set_oom_adj(OOM_ADJ_FILE, OOM_SCORE_ADJ_MIN); +} + +static int _handle_preloaded_fifo(int fd, const char *path) +{ + struct stat st_fd, st_path; + int flags; + + if ((flags = fcntl(fd, F_GETFD)) < 0) + return 0; + + if (flags & FD_CLOEXEC) + return 0; + + if (fstat(fd, &st_fd) < 0 || !S_ISFIFO(st_fd.st_mode)) + return 0; + + if (stat(path, &st_path) < 0 || + st_path.st_dev != st_fd.st_dev || + st_path.st_ino != st_fd.st_ino) + return 0; + + if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) + return 0; + + return 1; +} + +static int _systemd_handover(struct dm_event_fifos *fifos) +{ + const char *e; + char *p; + unsigned long env_pid, env_listen_fds; + int r = 0; + + /* SD_ACTIVATION must be set! */ + if (!(e = getenv(SD_ACTIVATION_ENV_VAR_NAME)) || strcmp(e, "1")) + goto out; + + /* LISTEN_PID must be equal to our PID! */ + if (!(e = getenv(SD_LISTEN_PID_ENV_VAR_NAME))) + goto out; + + errno = 0; + env_pid = strtoul(e, &p, 10); + if (errno || !p || *p || env_pid <= 0 || + getpid() != (pid_t) env_pid) + goto out; + + /* LISTEN_FDS must be 2 and the fds must be FIFOSs! */ + if (!(e = getenv(SD_LISTEN_FDS_ENV_VAR_NAME))) + goto out; + + errno = 0; + env_listen_fds = strtoul(e, &p, 10); + if (errno || !p || *p || env_listen_fds != 2) + goto out; + + /* Check and handle the FIFOs passed in */ + r = (_handle_preloaded_fifo(SD_FD_FIFO_SERVER, DM_EVENT_FIFO_SERVER) && + _handle_preloaded_fifo(SD_FD_FIFO_CLIENT, DM_EVENT_FIFO_CLIENT)); + + if (r) { + fifos->server = SD_FD_FIFO_SERVER; + fifos->server_path = DM_EVENT_FIFO_SERVER; + fifos->client = SD_FD_FIFO_CLIENT; + fifos->client_path = DM_EVENT_FIFO_CLIENT; + } + +out: + unsetenv(SD_ACTIVATION_ENV_VAR_NAME); + unsetenv(SD_LISTEN_PID_ENV_VAR_NAME); + unsetenv(SD_LISTEN_FDS_ENV_VAR_NAME); + return r; +} + +#endif + +static void _remove_files_on_exit(void) +{ + if (unlink(DMEVENTD_PIDFILE)) + log_sys_error("unlink", DMEVENTD_PIDFILE); + + if (!_systemd_activation) { + if (unlink(DM_EVENT_FIFO_CLIENT)) + log_sys_error("unlink", DM_EVENT_FIFO_CLIENT); + + if (unlink(DM_EVENT_FIFO_SERVER)) + log_sys_error("unlink", DM_EVENT_FIFO_SERVER); + } +} + +static void _daemonize(void) +{ + int child_status; + int fd; + pid_t pid; + struct rlimit rlim; + struct timeval tval; + sigset_t my_sigset; + + sigemptyset(&my_sigset); + if (sigprocmask(SIG_SETMASK, &my_sigset, NULL) < 0) { + fprintf(stderr, "Unable to restore signals.\n"); + exit(EXIT_FAILURE); + } + signal(SIGTERM, &_exit_handler); + + switch (pid = fork()) { + case -1: + log_sys_error("fork", ""); + exit(EXIT_FAILURE); + case 0: /* Child */ + break; + + default: + /* Wait for response from child */ + while (!waitpid(pid, &child_status, WNOHANG) && !_exit_now) { + tval.tv_sec = 0; + tval.tv_usec = 250000; /* .25 sec */ + select(0, NULL, NULL, NULL, &tval); + } + + if (_exit_now) /* Child has signaled it is ok - we can exit now */ + exit(EXIT_SUCCESS); + + /* Problem with child. Determine what it is by exit code */ + switch (WEXITSTATUS(child_status)) { + case EXIT_DESC_CLOSE_FAILURE: + case EXIT_DESC_OPEN_FAILURE: + case EXIT_FIFO_FAILURE: + case EXIT_CHDIR_FAILURE: + default: + fprintf(stderr, "Child exited with code %d\n", WEXITSTATUS(child_status)); + break; + } + + exit(WEXITSTATUS(child_status)); + } + + if (chdir("/")) + exit(EXIT_CHDIR_FAILURE); + + if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) + fd = 256; /* just have to guess */ + else + fd = rlim.rlim_cur; + + for (--fd; fd >= 0; fd--) { +#ifdef __linux__ + /* Do not close fds preloaded by systemd! */ + if (_systemd_activation && + (fd == SD_FD_FIFO_SERVER || fd == SD_FD_FIFO_CLIENT)) + continue; +#endif + (void) close(fd); + } + + if ((open("/dev/null", O_RDONLY) < 0) || + (open("/dev/null", O_WRONLY) < 0) || + (open("/dev/null", O_WRONLY) < 0)) + exit(EXIT_DESC_OPEN_FAILURE); + + setsid(); +} + +static int _reinstate_registrations(struct dm_event_fifos *fifos) +{ + static const char _failed_parsing_msg[] = "Failed to parse existing event registration.\n"; + static const char *_delim = " "; + struct dm_event_daemon_message msg = { 0 }; + char *endp, *dso_name, *dev_name, *mask, *timeout; + unsigned long mask_value, timeout_value; + int i, ret; + + ret = daemon_talk(fifos, &msg, DM_EVENT_CMD_HELLO, NULL, NULL, 0, 0); + dm_free(msg.data); + msg.data = NULL; + + if (ret) { + fprintf(stderr, "Failed to communicate with new instance of dmeventd.\n"); + return 0; + } + + for (i = 0; _initial_registrations[i]; ++i) { + if (!(strtok(_initial_registrations[i], _delim)) || + !(dso_name = strtok(NULL, _delim)) || + !(dev_name = strtok(NULL, _delim)) || + !(mask = strtok(NULL, _delim)) || + !(timeout = strtok(NULL, _delim))) { + fputs(_failed_parsing_msg, stderr); + continue; + } + + errno = 0; + mask_value = strtoul(mask, &endp, 10); + if (errno || !endp || *endp) { + fputs(_failed_parsing_msg, stderr); + continue; + } + + errno = 0; + timeout_value = strtoul(timeout, &endp, 10); + if (errno || !endp || *endp) { + fputs(_failed_parsing_msg, stderr); + continue; + } + + if (daemon_talk(fifos, &msg, DM_EVENT_CMD_REGISTER_FOR_EVENT, + dso_name, + dev_name, + (enum dm_event_mask) mask_value, + timeout_value)) + fprintf(stderr, "Failed to reinstate monitoring for device %s.\n", dev_name); + } + + return 1; +} + +static void _restart_dmeventd(void) +{ + struct dm_event_fifos fifos = { + .server = -1, + .client = -1, + /* FIXME Make these either configurable or depend directly on dmeventd_path */ + .client_path = DM_EVENT_FIFO_CLIENT, + .server_path = DM_EVENT_FIFO_SERVER + }; + struct dm_event_daemon_message msg = { 0 }; + int i, count = 0; + char *message; + int version; + const char *e; + + /* Get the list of registrations from the running daemon. */ + if (!init_fifos(&fifos)) { + fprintf(stderr, "WARNING: Could not initiate communication with existing dmeventd.\n"); + exit(EXIT_FAILURE); + } + + if (!dm_event_get_version(&fifos, &version)) { + fprintf(stderr, "WARNING: Could not communicate with existing dmeventd.\n"); + goto bad; + } + + if (version < 1) { + fprintf(stderr, "WARNING: The running dmeventd instance is too old.\n" + "Protocol version %d (required: 1). Action cancelled.\n", + version); + goto bad; + } + + if (daemon_talk(&fifos, &msg, DM_EVENT_CMD_GET_STATUS, "-", "-", 0, 0)) + goto bad; + + message = strchr(msg.data, ' ') + 1; + for (i = 0; msg.data[i]; ++i) + if (msg.data[i] == ';') { + msg.data[i] = 0; + ++count; + } + + if (!(_initial_registrations = dm_malloc(sizeof(char*) * (count + 1)))) { + fprintf(stderr, "Memory allocation registration failed.\n"); + goto bad; + } + + for (i = 0; i < count; ++i) { + if (!(_initial_registrations[i] = dm_strdup(message))) { + fprintf(stderr, "Memory allocation for message failed.\n"); + goto bad; + } + message += strlen(message) + 1; + } + _initial_registrations[count] = NULL; + + if (version >= 2) { + if (daemon_talk(&fifos, &msg, DM_EVENT_CMD_GET_PARAMETERS, "-", "-", 0, 0)) { + fprintf(stderr, "Failed to acquire parameters from old dmeventd.\n"); + goto bad; + } + if (strstr(msg.data, "exec_method=systemd")) + _systemd_activation = 1; + } +#ifdef __linux__ + /* + * If the protocol version is old, just assume that if systemd is running, + * the dmeventd is also run as a systemd service via fifo activation. + */ + if (version < 2) { + /* This check is copied from sd-daemon.c. */ + struct stat st; + if (!lstat(SD_RUNTIME_UNIT_FILE_DIR, &st) && !!S_ISDIR(st.st_mode)) + _systemd_activation = 1; + } +#endif + + if (daemon_talk(&fifos, &msg, DM_EVENT_CMD_DIE, "-", "-", 0, 0)) { + fprintf(stderr, "Old dmeventd refused to die.\n"); + goto bad; + } + + if (!_systemd_activation && + ((e = getenv(SD_ACTIVATION_ENV_VAR_NAME)) && strcmp(e, "1"))) + _systemd_activation = 1; + + for (i = 0; i < 10; ++i) { + if ((access(DMEVENTD_PIDFILE, F_OK) == -1) && (errno == ENOENT)) + break; + usleep(10); + } + + if (!_systemd_activation) { + fini_fifos(&fifos); + return; + } + + /* Reopen fifos. */ + fini_fifos(&fifos); + if (!init_fifos(&fifos)) { + fprintf(stderr, "Could not initiate communication with new instance of dmeventd.\n"); + exit(EXIT_FAILURE); + } + + if (!_reinstate_registrations(&fifos)) { + fprintf(stderr, "Failed to reinstate monitoring with new instance of dmeventd.\n"); + goto bad; + } + + fini_fifos(&fifos); + exit(EXIT_SUCCESS); +bad: + fini_fifos(&fifos); + exit(EXIT_FAILURE); +} + +static void _usage(char *prog, FILE *file) +{ + fprintf(file, "Usage:\n" + "%s [-d [-d [-d]]] [-f] [-h] [-l] [-R] [-V] [-?]\n\n" + " -d Log debug messages to syslog (-d, -dd, -ddd)\n" + " -f Don't fork, run in the foreground\n" + " -h Show this help information\n" + " -l Log to stdout,stderr instead of syslog\n" + " -? Show this help information on stderr\n" + " -R Restart dmeventd\n" + " -V Show version of dmeventd\n\n", prog); +} + +int main(int argc, char *argv[]) +{ + signed char opt; + struct dm_event_fifos fifos = { + .client = -1, + .server = -1, + .client_path = DM_EVENT_FIFO_CLIENT, + .server_path = DM_EVENT_FIFO_SERVER + }; + time_t now, idle_exit_timeout = DMEVENTD_IDLE_EXIT_TIMEOUT; + opterr = 0; + optind = 0; + + while ((opt = getopt(argc, argv, "?fhVdlR")) != EOF) { + switch (opt) { + case 'h': + _usage(argv[0], stdout); + exit(EXIT_SUCCESS); + case '?': + _usage(argv[0], stderr); + exit(EXIT_SUCCESS); + case 'R': + _restart++; + break; + case 'f': + _foreground++; + break; + case 'd': + _debug_level++; + break; + case 'l': + _use_syslog = 0; + break; + case 'V': + printf("dmeventd version: %s\n", DM_LIB_VERSION); + exit(EXIT_SUCCESS); + } + } + + if (!_foreground && !_use_syslog) { + printf("WARNING: Ignoring logging to stdout, needs options -f\n"); + _use_syslog = 1; + } + /* + * Switch to C locale to avoid reading large locale-archive file + * used by some glibc (on some distributions it takes over 100MB). + * Daemon currently needs to use mlockall(). + */ + if (setenv("LC_ALL", "C", 1)) + perror("Cannot set LC_ALL to C"); + + if (_restart) + _restart_dmeventd(); + +#ifdef __linux__ + _systemd_activation = _systemd_handover(&fifos); +#endif + + if (!_foreground) + _daemonize(); + + if (_use_syslog) + openlog("dmeventd", LOG_PID, LOG_DAEMON); + + dm_event_log_set(_debug_level, _use_syslog); + dm_log_init(_dmeventd_log); + + (void) dm_prepare_selinux_context(DMEVENTD_PIDFILE, S_IFREG); + if (dm_create_lockfile(DMEVENTD_PIDFILE) == 0) + exit(EXIT_FAILURE); + + atexit(_remove_files_on_exit); + (void) dm_prepare_selinux_context(NULL, 0); + + /* Set the rest of the signals to cause '_exit_now' to be set */ + signal(SIGTERM, &_exit_handler); + signal(SIGINT, &_exit_handler); + signal(SIGHUP, &_exit_handler); + signal(SIGQUIT, &_exit_handler); + +#ifdef __linux__ + /* Systemd has adjusted oom killer for us already */ + if (!_systemd_activation && !_protect_against_oom_killer()) + log_warn("WARNING: Failed to protect against OOM killer."); +#endif + + _init_thread_signals(); + + pthread_mutex_init(&_global_mutex, NULL); + + if (!_systemd_activation && !_open_fifos(&fifos)) + exit(EXIT_FIFO_FAILURE); + + /* Signal parent, letting them know we are ready to go. */ + if (!_foreground) + kill(getppid(), SIGTERM); + + log_notice("dmeventd ready for processing."); + + _idle_since = time(NULL); + + if (_initial_registrations) + _process_initial_registrations(); + + for (;;) { + if (_idle_since) { + if (_exit_now) { + log_info("dmeventd detected break while being idle " + "for %ld second(s), exiting.", + (long) (time(NULL) - _idle_since)); + break; + } else if (idle_exit_timeout) { + now = time(NULL); + if (now < _idle_since) + _idle_since = now; /* clock change? */ + now -= _idle_since; + if (now >= idle_exit_timeout) { + log_info("dmeventd was idle for %ld second(s), " + "exiting.", (long) now); + break; + } + } + } else if (_exit_now) { + _exit_now = 0; + /* + * When '_exit_now' is set, signal has been received, + * but can not simply exit unless all + * threads are done processing. + */ + log_warn("WARNING: There are still devices being monitored."); + log_warn("WARNING: Refusing to exit."); + } + _process_request(&fifos); + _cleanup_unused_threads(); + } + + pthread_mutex_destroy(&_global_mutex); + + log_notice("dmeventd shutting down."); + + if (fifos.client >= 0 && close(fifos.client)) + log_sys_error("client close", fifos.client_path); + if (fifos.server >= 0 && close(fifos.server)) + log_sys_error("server close", fifos.server_path); + + if (_use_syslog) + closelog(); + + _exit_dm_lib(); + + exit(EXIT_SUCCESS); +}
diff --git a/daemons/dmeventd/dmeventd.h b/daemons/dmeventd/dmeventd.h new file mode 100644 index 0000000..afe0b0c --- /dev/null +++ b/daemons/dmeventd/dmeventd.h
@@ -0,0 +1,76 @@ +/* + * Copyright (C) 2005-2007 Red Hat, Inc. All rights reserved. + * + * This file is part of the device-mapper userspace tools. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef __DMEVENTD_DOT_H__ +#define __DMEVENTD_DOT_H__ + +/* FIXME This stuff must be configurable. */ + +#define DM_EVENT_FIFO_CLIENT DEFAULT_DM_RUN_DIR "/dmeventd-client" +#define DM_EVENT_FIFO_SERVER DEFAULT_DM_RUN_DIR "/dmeventd-server" + +#define DM_EVENT_DEFAULT_TIMEOUT 10 + +/* Commands for the daemon passed in the message below. */ +enum dm_event_command { + DM_EVENT_CMD_ACTIVE = 1, + DM_EVENT_CMD_REGISTER_FOR_EVENT, + DM_EVENT_CMD_UNREGISTER_FOR_EVENT, + DM_EVENT_CMD_GET_REGISTERED_DEVICE, + DM_EVENT_CMD_GET_NEXT_REGISTERED_DEVICE, + DM_EVENT_CMD_SET_TIMEOUT, + DM_EVENT_CMD_GET_TIMEOUT, + DM_EVENT_CMD_HELLO, + DM_EVENT_CMD_DIE, + DM_EVENT_CMD_GET_STATUS, + DM_EVENT_CMD_GET_PARAMETERS, +}; + +/* Message passed between client and daemon. */ +struct dm_event_daemon_message { + uint32_t cmd; + uint32_t size; + char *data; +}; + +/* FIXME Is this meant to be exported? I can't see where the + interface uses it. */ +/* Fifos for client/daemon communication. */ +struct dm_event_fifos { + int client; + int server; + const char *client_path; + const char *server_path; +}; + +/* EXIT_SUCCESS 0 -- stdlib.h */ +/* EXIT_FAILURE 1 -- stdlib.h */ +/* EXIT_LOCKFILE_INUSE 2 -- obsoleted */ +#define EXIT_DESC_CLOSE_FAILURE 3 +#define EXIT_DESC_OPEN_FAILURE 4 +/* EXIT_OPEN_PID_FAILURE 5 -- obsoleted */ +#define EXIT_FIFO_FAILURE 6 +#define EXIT_CHDIR_FAILURE 7 + +/* Implemented in libdevmapper-event.c, but not part of public API. */ +// FIXME misuse of bitmask as enum +int daemon_talk(struct dm_event_fifos *fifos, + struct dm_event_daemon_message *msg, int cmd, + const char *dso_name, const char *dev_name, + enum dm_event_mask evmask, uint32_t timeout); +int init_fifos(struct dm_event_fifos *fifos); +void fini_fifos(struct dm_event_fifos *fifos); +int dm_event_get_version(struct dm_event_fifos *fifos, int *version); + +#endif /* __DMEVENTD_DOT_H__ */
diff --git a/daemons/dmeventd/libdevmapper-event.c b/daemons/dmeventd/libdevmapper-event.c new file mode 100644 index 0000000..d395ed3 --- /dev/null +++ b/daemons/dmeventd/libdevmapper-event.c
@@ -0,0 +1,975 @@ +/* + * Copyright (C) 2005-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of the device-mapper userspace tools. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "dm-logging.h" +#include "dmlib.h" +#include "libdevmapper-event.h" +#include "dmeventd.h" + +#include <fcntl.h> +#include <sys/file.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <arpa/inet.h> /* for htonl, ntohl */ +#include <pthread.h> +#include <syslog.h> + +static int _debug_level = 0; +static int _use_syslog = 0; +static int _sequence_nr = 0; + +struct dm_event_handler { + char *dso; + + char *dmeventd_path; + + char *dev_name; + + char *uuid; + int major; + int minor; + uint32_t timeout; + + enum dm_event_mask mask; +}; + +static void _dm_event_handler_clear_dev_info(struct dm_event_handler *dmevh) +{ + dm_free(dmevh->dev_name); + dm_free(dmevh->uuid); + dmevh->dev_name = dmevh->uuid = NULL; + dmevh->major = dmevh->minor = 0; +} + +struct dm_event_handler *dm_event_handler_create(void) +{ + struct dm_event_handler *dmevh; + + if (!(dmevh = dm_zalloc(sizeof(*dmevh)))) { + log_error("Failed to allocate event handler."); + return NULL; + } + + return dmevh; +} + +void dm_event_handler_destroy(struct dm_event_handler *dmevh) +{ + _dm_event_handler_clear_dev_info(dmevh); + dm_free(dmevh->dso); + dm_free(dmevh->dmeventd_path); + dm_free(dmevh); +} + +int dm_event_handler_set_dmeventd_path(struct dm_event_handler *dmevh, const char *dmeventd_path) +{ + if (!dmeventd_path) /* noop */ + return 0; + + dm_free(dmevh->dmeventd_path); + + if (!(dmevh->dmeventd_path = dm_strdup(dmeventd_path))) + return -ENOMEM; + + return 0; +} + +int dm_event_handler_set_dso(struct dm_event_handler *dmevh, const char *path) +{ + if (!path) /* noop */ + return 0; + + dm_free(dmevh->dso); + + if (!(dmevh->dso = dm_strdup(path))) + return -ENOMEM; + + return 0; +} + +int dm_event_handler_set_dev_name(struct dm_event_handler *dmevh, const char *dev_name) +{ + if (!dev_name) + return 0; + + _dm_event_handler_clear_dev_info(dmevh); + + if (!(dmevh->dev_name = dm_strdup(dev_name))) + return -ENOMEM; + + return 0; +} + +int dm_event_handler_set_uuid(struct dm_event_handler *dmevh, const char *uuid) +{ + if (!uuid) + return 0; + + _dm_event_handler_clear_dev_info(dmevh); + + if (!(dmevh->uuid = dm_strdup(uuid))) + return -ENOMEM; + + return 0; +} + +void dm_event_handler_set_major(struct dm_event_handler *dmevh, int major) +{ + int minor = dmevh->minor; + + _dm_event_handler_clear_dev_info(dmevh); + + dmevh->major = major; + dmevh->minor = minor; +} + +void dm_event_handler_set_minor(struct dm_event_handler *dmevh, int minor) +{ + int major = dmevh->major; + + _dm_event_handler_clear_dev_info(dmevh); + + dmevh->major = major; + dmevh->minor = minor; +} + +void dm_event_handler_set_event_mask(struct dm_event_handler *dmevh, + enum dm_event_mask evmask) +{ + dmevh->mask = evmask; +} + +void dm_event_handler_set_timeout(struct dm_event_handler *dmevh, int timeout) +{ + dmevh->timeout = timeout; +} + +const char *dm_event_handler_get_dso(const struct dm_event_handler *dmevh) +{ + return dmevh->dso; +} + +const char *dm_event_handler_get_dev_name(const struct dm_event_handler *dmevh) +{ + return dmevh->dev_name; +} + +const char *dm_event_handler_get_uuid(const struct dm_event_handler *dmevh) +{ + return dmevh->uuid; +} + +int dm_event_handler_get_major(const struct dm_event_handler *dmevh) +{ + return dmevh->major; +} + +int dm_event_handler_get_minor(const struct dm_event_handler *dmevh) +{ + return dmevh->minor; +} + +int dm_event_handler_get_timeout(const struct dm_event_handler *dmevh) +{ + return dmevh->timeout; +} + +enum dm_event_mask dm_event_handler_get_event_mask(const struct dm_event_handler *dmevh) +{ + return dmevh->mask; +} + +static int _check_message_id(struct dm_event_daemon_message *msg) +{ + int pid, seq_nr; + + if ((sscanf(msg->data, "%d:%d", &pid, &seq_nr) != 2) || + (pid != getpid()) || (seq_nr != _sequence_nr)) { + log_error("Ignoring out-of-sequence reply from dmeventd. " + "Expected %d:%d but received %s.", getpid(), + _sequence_nr, msg->data); + return 0; + } + + return 1; +} + +/* + * daemon_read + * @fifos + * @msg + * + * Read message from daemon. + * + * Returns: 0 on failure, 1 on success + */ +static int _daemon_read(struct dm_event_fifos *fifos, + struct dm_event_daemon_message *msg) +{ + unsigned bytes = 0; + int ret, i; + fd_set fds; + size_t size = 2 * sizeof(uint32_t); /* status + size */ + uint32_t *header = alloca(size); + char *buf = (char *)header; + + while (bytes < size) { + for (i = 0, ret = 0; (i < 20) && (ret < 1); i++) { + /* Watch daemon read FIFO for input. */ + struct timeval tval = { .tv_sec = 1 }; + FD_ZERO(&fds); + FD_SET(fifos->server, &fds); + ret = select(fifos->server + 1, &fds, NULL, NULL, &tval); + if (ret < 0 && errno != EINTR) { + log_error("Unable to read from event server."); + return 0; + } + if ((ret == 0) && (i > 4) && !bytes) { + log_error("No input from event server."); + return 0; + } + } + if (ret < 1) { + log_error("Unable to read from event server."); + return 0; + } + + ret = read(fifos->server, buf + bytes, size); + if (ret < 0) { + if ((errno == EINTR) || (errno == EAGAIN)) + continue; + else { + log_error("Unable to read from event server."); + return 0; + } + } + + bytes += ret; + if (header && (bytes == 2 * sizeof(uint32_t))) { + msg->cmd = ntohl(header[0]); + msg->size = ntohl(header[1]); + buf = msg->data = dm_malloc(msg->size); + size = msg->size; + bytes = 0; + header = 0; + } + } + + if (bytes != size) { + dm_free(msg->data); + msg->data = NULL; + } + return bytes == size; +} + +/* Write message to daemon. */ +static int _daemon_write(struct dm_event_fifos *fifos, + struct dm_event_daemon_message *msg) +{ + int ret; + fd_set fds; + size_t bytes = 0; + size_t size = 2 * sizeof(uint32_t) + msg->size; + uint32_t *header = alloca(size); + char *buf = (char *)header; + char drainbuf[128]; + + header[0] = htonl(msg->cmd); + header[1] = htonl(msg->size); + memcpy(buf + 2 * sizeof(uint32_t), msg->data, msg->size); + + /* drain the answer fifo */ + while (1) { + struct timeval tval = { .tv_usec = 100 }; + FD_ZERO(&fds); + FD_SET(fifos->server, &fds); + ret = select(fifos->server + 1, &fds, NULL, NULL, &tval); + if (ret < 0) { + if (errno == EINTR) + continue; + log_error("Unable to talk to event daemon."); + return 0; + } + if (ret == 0) + break; + ret = read(fifos->server, drainbuf, sizeof(drainbuf)); + if (ret < 0) { + if ((errno == EINTR) || (errno == EAGAIN)) + continue; + log_error("Unable to talk to event daemon."); + return 0; + } + } + + while (bytes < size) { + do { + /* Watch daemon write FIFO to be ready for output. */ + FD_ZERO(&fds); + FD_SET(fifos->client, &fds); + ret = select(fifos->client + 1, NULL, &fds, NULL, NULL); + if ((ret < 0) && (errno != EINTR)) { + log_error("Unable to talk to event daemon."); + return 0; + } + } while (ret < 1); + + ret = write(fifos->client, buf + bytes, size - bytes); + if (ret < 0) { + if ((errno == EINTR) || (errno == EAGAIN)) + continue; + else { + log_error("Unable to talk to event daemon."); + return 0; + } + } + + bytes += ret; + } + + return bytes == size; +} + +int daemon_talk(struct dm_event_fifos *fifos, + struct dm_event_daemon_message *msg, int cmd, + const char *dso_name, const char *dev_name, + enum dm_event_mask evmask, uint32_t timeout) +{ + int msg_size; + memset(msg, 0, sizeof(*msg)); + + /* + * Set command and pack the arguments + * into ASCII message string. + */ + if ((msg_size = + ((cmd == DM_EVENT_CMD_HELLO) ? + dm_asprintf(&(msg->data), "%d:%d HELLO", getpid(), _sequence_nr) : + dm_asprintf(&(msg->data), "%d:%d %s %s %u %" PRIu32, + getpid(), _sequence_nr, + dso_name ? : "-", dev_name ? : "-", evmask, timeout))) + < 0) { + log_error("_daemon_talk: message allocation failed."); + return -ENOMEM; + } + msg->cmd = cmd; + msg->size = msg_size; + + /* + * Write command and message to and + * read status return code from daemon. + */ + if (!_daemon_write(fifos, msg)) { + stack; + dm_free(msg->data); + msg->data = NULL; + return -EIO; + } + + do { + dm_free(msg->data); + msg->data = NULL; + + if (!_daemon_read(fifos, msg)) { + stack; + return -EIO; + } + } while (!_check_message_id(msg)); + + _sequence_nr++; + + return (int32_t) msg->cmd; +} + +/* + * start_daemon + * + * This function forks off a process (dmeventd) that will handle + * the events. I am currently test opening one of the fifos to + * ensure that the daemon is running and listening... I thought + * this would be less expensive than fork/exec'ing every time. + * Perhaps there is an even quicker/better way (no, checking the + * lock file is _not_ a better way). + * + * Returns: 1 on success, 0 otherwise + */ +static int _start_daemon(char *dmeventd_path, struct dm_event_fifos *fifos) +{ + int pid, ret = 0; + int status; + struct stat statbuf; + char default_dmeventd_path[] = DMEVENTD_PATH; + char *args[] = { dmeventd_path ? : default_dmeventd_path, NULL }; + + /* + * FIXME Explicitly verify the code's requirement that client_path is secure: + * - All parent directories owned by root without group/other write access unless sticky. + */ + + /* If client fifo path exists, only use it if it is root-owned fifo mode 0600 */ + if ((lstat(fifos->client_path, &statbuf) < 0)) { + if (errno == ENOENT) + /* Jump ahead if fifo does not already exist. */ + goto start_server; + else { + log_sys_error("stat", fifos->client_path); + return 0; + } + } else if (!S_ISFIFO(statbuf.st_mode)) { + log_error("%s must be a fifo.", fifos->client_path); + return 0; + } else if (statbuf.st_uid) { + log_error("%s must be owned by uid 0.", fifos->client_path); + return 0; + } else if (statbuf.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO)) { + log_error("%s must have mode 0600.", fifos->client_path); + return 0; + } + + /* Anyone listening? If not, errno will be ENXIO */ + fifos->client = open(fifos->client_path, O_WRONLY | O_NONBLOCK); + if (fifos->client >= 0) { + /* Should never happen if all the above checks passed. */ + if ((fstat(fifos->client, &statbuf) < 0) || + !S_ISFIFO(statbuf.st_mode) || statbuf.st_uid || + (statbuf.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO))) { + log_error("%s is no longer a secure root-owned fifo with mode 0600.", fifos->client_path); + if (close(fifos->client)) + log_sys_debug("close", fifos->client_path); + return 0; + } + + /* server is running and listening */ + if (close(fifos->client)) + log_sys_debug("close", fifos->client_path); + return 1; + } else if (errno != ENXIO && errno != ENOENT) { + /* problem */ + log_sys_error("open", fifos->client_path); + return 0; + } + +start_server: + /* server is not running */ + + if ((args[0][0] == '/') && stat(args[0], &statbuf)) { + log_sys_error("stat", args[0]); + return 0; + } + + pid = fork(); + + if (pid < 0) + log_sys_error("fork", ""); + + else if (!pid) { + execvp(args[0], args); + log_error("Unable to exec dmeventd: %s.", strerror(errno)); + _exit(EXIT_FAILURE); + } else { + if (waitpid(pid, &status, 0) < 0) + log_error("Unable to start dmeventd: %s.", + strerror(errno)); + else if (WEXITSTATUS(status)) + log_error("Unable to start dmeventd."); + else + ret = 1; + } + + return ret; +} + +int init_fifos(struct dm_event_fifos *fifos) +{ + /* FIXME? Is fifo the most suitable method? Why not share + comms/daemon code with something else e.g. multipath? */ + + /* Open the fifo used to read from the daemon. */ + if ((fifos->server = open(fifos->server_path, O_RDWR)) < 0) { + log_sys_error("open", fifos->server_path); + return 0; + } + + /* Lock out anyone else trying to do communication with the daemon. */ + if (flock(fifos->server, LOCK_EX) < 0) { + log_sys_error("flock", fifos->server_path); + goto bad; + } + +/* if ((fifos->client = open(fifos->client_path, O_WRONLY | O_NONBLOCK)) < 0) {*/ + if ((fifos->client = open(fifos->client_path, O_RDWR | O_NONBLOCK)) < 0) { + log_sys_error("open", fifos->client_path); + goto bad; + } + + return 1; +bad: + if (close(fifos->server)) + log_sys_debug("close", fifos->server_path); + fifos->server = -1; + + return 0; +} + +/* Initialize client. */ +static int _init_client(char *dmeventd_path, struct dm_event_fifos *fifos) +{ + if (!_start_daemon(dmeventd_path, fifos)) + return_0; + + return init_fifos(fifos); +} + +void fini_fifos(struct dm_event_fifos *fifos) +{ + if (fifos->client >= 0 && close(fifos->client)) + log_sys_debug("close", fifos->client_path); + + if (fifos->server >= 0) { + if (flock(fifos->server, LOCK_UN)) + log_sys_debug("flock unlock", fifos->server_path); + + if (close(fifos->server)) + log_sys_debug("close", fifos->server_path); + } +} + +/* Get uuid of a device */ +static struct dm_task *_get_device_info(const struct dm_event_handler *dmevh) +{ + struct dm_task *dmt; + struct dm_info info; + + if (!(dmt = dm_task_create(DM_DEVICE_INFO))) { + log_error("_get_device_info: dm_task creation for info failed."); + return NULL; + } + + if (dmevh->uuid) { + if (!dm_task_set_uuid(dmt, dmevh->uuid)) + goto_bad; + } else if (dmevh->dev_name) { + if (!dm_task_set_name(dmt, dmevh->dev_name)) + goto_bad; + } else if (dmevh->major && dmevh->minor) { + if (!dm_task_set_major(dmt, dmevh->major) || + !dm_task_set_minor(dmt, dmevh->minor)) + goto_bad; + } + + /* FIXME Add name or uuid or devno to messages */ + if (!dm_task_run(dmt)) { + log_error("_get_device_info: dm_task_run() failed."); + goto bad; + } + + if (!dm_task_get_info(dmt, &info)) { + log_error("_get_device_info: failed to get info for device."); + goto bad; + } + + if (!info.exists) { + log_error("_get_device_info: %s%s%s%.0d%s%.0d%s%s: device not found.", + dmevh->uuid ? : "", + (!dmevh->uuid && dmevh->dev_name) ? dmevh->dev_name : "", + (!dmevh->uuid && !dmevh->dev_name && dmevh->major > 0) ? "(" : "", + (!dmevh->uuid && !dmevh->dev_name && dmevh->major > 0) ? dmevh->major : 0, + (!dmevh->uuid && !dmevh->dev_name && dmevh->major > 0) ? ":" : "", + (!dmevh->uuid && !dmevh->dev_name && dmevh->minor > 0) ? dmevh->minor : 0, + (!dmevh->uuid && !dmevh->dev_name && dmevh->major > 0) && dmevh->minor == 0 ? "0" : "", + (!dmevh->uuid && !dmevh->dev_name && dmevh->major > 0) ? ") " : ""); + goto bad; + } + + return dmt; + + bad: + dm_task_destroy(dmt); + return NULL; +} + +/* Handle the event (de)registration call and return negative error codes. */ +static int _do_event(int cmd, char *dmeventd_path, struct dm_event_daemon_message *msg, + const char *dso_name, const char *dev_name, + enum dm_event_mask evmask, uint32_t timeout) +{ + int ret; + struct dm_event_fifos fifos = { + .server = -1, + .client = -1, + /* FIXME Make these either configurable or depend directly on dmeventd_path */ + .client_path = DM_EVENT_FIFO_CLIENT, + .server_path = DM_EVENT_FIFO_SERVER + }; + + if (!_init_client(dmeventd_path, &fifos)) { + ret = -ESRCH; + goto_out; + } + + ret = daemon_talk(&fifos, msg, DM_EVENT_CMD_HELLO, NULL, NULL, 0, 0); + + dm_free(msg->data); + msg->data = 0; + + if (!ret) + ret = daemon_talk(&fifos, msg, cmd, dso_name, dev_name, evmask, timeout); +out: + /* what is the opposite of init? */ + fini_fifos(&fifos); + + return ret; +} + +/* External library interface. */ +int dm_event_register_handler(const struct dm_event_handler *dmevh) +{ + int ret = 1, err; + const char *uuid; + struct dm_task *dmt; + struct dm_event_daemon_message msg = { 0 }; + + if (!(dmt = _get_device_info(dmevh))) + return_0; + + uuid = dm_task_get_uuid(dmt); + + if (!strstr(dmevh->dso, "libdevmapper-event-lvm2thin.so") && + !strstr(dmevh->dso, "libdevmapper-event-lvm2snapshot.so") && + !strstr(dmevh->dso, "libdevmapper-event-lvm2mirror.so") && + !strstr(dmevh->dso, "libdevmapper-event-lvm2raid.so")) + log_warn("WARNING: %s: dmeventd plugins are deprecated.", dmevh->dso); + + + if ((err = _do_event(DM_EVENT_CMD_REGISTER_FOR_EVENT, dmevh->dmeventd_path, &msg, + dmevh->dso, uuid, dmevh->mask, dmevh->timeout)) < 0) { + log_error("%s: event registration failed: %s.", + dm_task_get_name(dmt), + msg.data ? msg.data : strerror(-err)); + ret = 0; + } + + dm_free(msg.data); + + dm_task_destroy(dmt); + + return ret; +} + +int dm_event_unregister_handler(const struct dm_event_handler *dmevh) +{ + int ret = 1, err; + const char *uuid; + struct dm_task *dmt; + struct dm_event_daemon_message msg = { 0 }; + + if (!(dmt = _get_device_info(dmevh))) + return_0; + + uuid = dm_task_get_uuid(dmt); + + if ((err = _do_event(DM_EVENT_CMD_UNREGISTER_FOR_EVENT, dmevh->dmeventd_path, &msg, + dmevh->dso, uuid, dmevh->mask, dmevh->timeout)) < 0) { + log_error("%s: event deregistration failed: %s.", + dm_task_get_name(dmt), + msg.data ? msg.data : strerror(-err)); + ret = 0; + } + + dm_free(msg.data); + + dm_task_destroy(dmt); + + return ret; +} + +/* Fetch a string off src and duplicate it into *dest. */ +/* FIXME: move to separate module to share with the daemon. */ +static char *_fetch_string(char **src, const int delimiter) +{ + char *p, *ret; + + if ((p = strchr(*src, delimiter))) + *p = 0; + + if ((ret = dm_strdup(*src))) + *src += strlen(ret) + 1; + + if (p) + *p = delimiter; + + return ret; +} + +/* Parse a device message from the daemon. */ +static int _parse_message(struct dm_event_daemon_message *msg, char **dso_name, + char **uuid, enum dm_event_mask *evmask) +{ + char *id; + char *p = msg->data; + + if ((id = _fetch_string(&p, ' ')) && + (*dso_name = _fetch_string(&p, ' ')) && + (*uuid = _fetch_string(&p, ' '))) { + *evmask = atoi(p); + dm_free(id); + return 0; + } + + dm_free(id); + return -ENOMEM; +} + +/* + * Returns 0 if handler found; error (-ENOMEM, -ENOENT) otherwise. + */ +int dm_event_get_registered_device(struct dm_event_handler *dmevh, int next) +{ + int ret = 0; + const char *uuid = NULL; + char *reply_dso = NULL, *reply_uuid = NULL; + enum dm_event_mask reply_mask = 0; + struct dm_task *dmt = NULL; + struct dm_event_daemon_message msg = { 0 }; + struct dm_info info; + + if (!(dmt = _get_device_info(dmevh))) { + log_debug("Device does not exists (uuid=%s, name=%s, %d:%d).", + dmevh->uuid, dmevh->dev_name, + dmevh->major, dmevh->minor); + ret = -ENODEV; + goto fail; + } + + uuid = dm_task_get_uuid(dmt); + + /* FIXME Distinguish errors connecting to daemon */ + if (_do_event(next ? DM_EVENT_CMD_GET_NEXT_REGISTERED_DEVICE : + DM_EVENT_CMD_GET_REGISTERED_DEVICE, dmevh->dmeventd_path, + &msg, dmevh->dso, uuid, dmevh->mask, 0)) { + log_debug("%s: device not registered.", dm_task_get_name(dmt)); + ret = -ENOENT; + goto fail; + } + + /* FIXME this will probably horribly break if we get + ill-formatted reply */ + ret = _parse_message(&msg, &reply_dso, &reply_uuid, &reply_mask); + + dm_task_destroy(dmt); + dmt = NULL; + + dm_free(msg.data); + msg.data = NULL; + + _dm_event_handler_clear_dev_info(dmevh); + if (!reply_uuid) { + ret = -ENXIO; /* dmeventd probably gave us bogus uuid back */ + goto fail; + } + + if (!(dmevh->uuid = dm_strdup(reply_uuid))) { + ret = -ENOMEM; + goto fail; + } + + if (!(dmt = _get_device_info(dmevh))) { + ret = -ENXIO; /* dmeventd probably gave us bogus uuid back */ + goto fail; + } + + dm_event_handler_set_dso(dmevh, reply_dso); + dm_event_handler_set_event_mask(dmevh, reply_mask); + + dm_free(reply_dso); + reply_dso = NULL; + + dm_free(reply_uuid); + reply_uuid = NULL; + + if (!(dmevh->dev_name = dm_strdup(dm_task_get_name(dmt)))) { + ret = -ENOMEM; + goto fail; + } + + if (!dm_task_get_info(dmt, &info)) { + ret = -1; + goto fail; + } + + dmevh->major = info.major; + dmevh->minor = info.minor; + + dm_task_destroy(dmt); + + return ret; + + fail: + dm_free(msg.data); + dm_free(reply_dso); + dm_free(reply_uuid); + _dm_event_handler_clear_dev_info(dmevh); + if (dmt) + dm_task_destroy(dmt); + return ret; +} + +/* + * You can (and have to) call this at the stage of the protocol where + * daemon_talk(fifos, &msg, DM_EVENT_CMD_HELLO, NULL, NULL, 0, 0) + * + * would be normally sent. This call will parse the version reply from + * dmeventd, in addition to above call. It is not safe to call this at any + * other place in the protocol. + * + * This is an internal function, not exposed in the public API. + */ + +int dm_event_get_version(struct dm_event_fifos *fifos, int *version) { + char *p; + struct dm_event_daemon_message msg = { 0 }; + + if (daemon_talk(fifos, &msg, DM_EVENT_CMD_HELLO, NULL, NULL, 0, 0)) + return 0; + p = msg.data; + *version = 0; + + if (!p || !(p = strchr(p, ' '))) /* Message ID */ + return 0; + if (!(p = strchr(p + 1, ' '))) /* HELLO */ + return 0; + if ((p = strchr(p + 1, ' '))) /* HELLO, once more */ + *version = atoi(p); + + return 1; +} + +void dm_event_log_set(int debug_log_level, int use_syslog) +{ + _debug_level = debug_log_level; + _use_syslog = use_syslog; +} + +void dm_event_log(const char *subsys, int level, const char *file, + int line, int dm_errno_or_class, + const char *format, va_list ap) +{ + static pthread_mutex_t _log_mutex = PTHREAD_MUTEX_INITIALIZER; + static time_t start = 0; + const char *indent = ""; + FILE *stream = stdout; + int prio; + time_t now; + + switch (level & ~(_LOG_STDERR | _LOG_ONCE)) { + case _LOG_DEBUG: + if (_debug_level < 3) + return; + prio = LOG_DEBUG; + indent = " "; + break; + case _LOG_INFO: + if (_debug_level < 2) + return; + prio = LOG_INFO; + indent = " "; + break; + case _LOG_NOTICE: + if (_debug_level < 1) + return; + prio = LOG_NOTICE; + indent = " "; + break; + case _LOG_WARN: + prio = LOG_WARNING; + break; + case _LOG_ERR: + prio = LOG_ERR; + stream = stderr; + break; + default: + prio = LOG_CRIT; + } + + /* Serialize to keep lines readable */ + pthread_mutex_lock(&_log_mutex); + + if (_use_syslog) { + vsyslog(prio, format, ap); + } else { + now = time(NULL); + if (!start) + start = now; + now -= start; + fprintf(stream, "[%2d:%02d] %8x:%-6s%s", + (int)now / 60, (int)now % 60, + // TODO: Maybe use shorter ID + // ((int)(pthread_self()) >> 6) & 0xffff, + (int)pthread_self(), subsys, + (_debug_level > 3) ? "" : indent); + if (_debug_level > 3) + fprintf(stream, "%28s:%4d %s", file, line, indent); + vfprintf(stream, _(format), ap); + fputc('\n', stream); + fflush(stream); + } + + pthread_mutex_unlock(&_log_mutex); +} + +#if 0 /* left out for now */ + +static char *_skip_string(char *src, const int delimiter) +{ + src = srtchr(src, delimiter); + if (src && *(src + 1)) + return src + 1; + return NULL; +} + +int dm_event_set_timeout(const char *device_path, uint32_t timeout) +{ + struct dm_event_daemon_message msg = { 0 }; + + if (!device_exists(device_path)) + return -ENODEV; + + return _do_event(DM_EVENT_CMD_SET_TIMEOUT, &msg, + NULL, device_path, 0, timeout); +} + +int dm_event_get_timeout(const char *device_path, uint32_t *timeout) +{ + int ret; + struct dm_event_daemon_message msg = { 0 }; + + if (!device_exists(device_path)) + return -ENODEV; + + if (!(ret = _do_event(DM_EVENT_CMD_GET_TIMEOUT, &msg, NULL, device_path, + 0, 0))) { + char *p = _skip_string(msg.data, ' '); + if (!p) { + log_error("Malformed reply from dmeventd '%s'.", + msg.data); + dm_free(msg.data); + return -EIO; + } + *timeout = atoi(p); + } + dm_free(msg.data); + + return ret; +} +#endif
diff --git a/daemons/dmeventd/libdevmapper-event.h b/daemons/dmeventd/libdevmapper-event.h new file mode 100644 index 0000000..4c97223 --- /dev/null +++ b/daemons/dmeventd/libdevmapper-event.h
@@ -0,0 +1,135 @@ +/* + * Copyright (C) 2005-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of the device-mapper userspace tools. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * Note that this file is released only as part of a technology preview + * and its contents may change in future updates in ways that do not + * preserve compatibility. + */ + +#ifndef LIB_DMEVENT_H +#define LIB_DMEVENT_H + +#include <stdint.h> + +/* + * Event library interface. + */ + +enum dm_event_mask { + DM_EVENT_SETTINGS_MASK = 0x0000FF, + DM_EVENT_SINGLE = 0x000001, /* Report multiple errors just once. */ + DM_EVENT_MULTI = 0x000002, /* Report all of them. */ + + DM_EVENT_ERROR_MASK = 0x00FF00, + DM_EVENT_SECTOR_ERROR = 0x000100, /* Failure on a particular sector. */ + DM_EVENT_DEVICE_ERROR = 0x000200, /* Device failure. */ + DM_EVENT_PATH_ERROR = 0x000400, /* Failure on an io path. */ + DM_EVENT_ADAPTOR_ERROR = 0x000800, /* Failure of a host adaptor. */ + + DM_EVENT_STATUS_MASK = 0xFF0000, + DM_EVENT_SYNC_STATUS = 0x010000, /* Mirror synchronization completed/failed. */ + DM_EVENT_TIMEOUT = 0x020000, /* Timeout has occured */ + + DM_EVENT_REGISTRATION_PENDING = 0x1000000, /* Monitor thread is setting-up/shutting-down */ +}; + +#define DM_EVENT_ALL_ERRORS DM_EVENT_ERROR_MASK +#define DM_EVENT_PROTOCOL_VERSION 2 + +struct dm_task; +struct dm_event_handler; + +struct dm_event_handler *dm_event_handler_create(void); +void dm_event_handler_destroy(struct dm_event_handler *dmevh); + +/* + * Path of shared library to handle events. + * + * All of dmeventd, dso, device_name and uuid strings are duplicated so + * you do not need to keep the pointers valid after the call succeeds. + * They may return -ENOMEM though. + */ +int dm_event_handler_set_dso(struct dm_event_handler *dmevh, const char *path); + +/* + * Path of dmeventd binary. + */ +int dm_event_handler_set_dmeventd_path(struct dm_event_handler *dmevh, const char *dmeventd_path); + +/* + * Identify the device to monitor by exactly one of device_name, uuid or + * device number. String arguments are duplicated, see above. + */ +int dm_event_handler_set_dev_name(struct dm_event_handler *dmevh, const char *device_name); + +int dm_event_handler_set_uuid(struct dm_event_handler *dmevh, const char *uuid); + +void dm_event_handler_set_major(struct dm_event_handler *dmevh, int major); +void dm_event_handler_set_minor(struct dm_event_handler *dmevh, int minor); +void dm_event_handler_set_timeout(struct dm_event_handler *dmevh, int timeout); + +/* + * Specify mask for events to monitor. + */ +// FIXME misuse of bitmask as enum +void dm_event_handler_set_event_mask(struct dm_event_handler *dmevh, + enum dm_event_mask evmask); + +const char *dm_event_handler_get_dso(const struct dm_event_handler *dmevh); +const char *dm_event_handler_get_dev_name(const struct dm_event_handler *dmevh); +const char *dm_event_handler_get_uuid(const struct dm_event_handler *dmevh); +int dm_event_handler_get_major(const struct dm_event_handler *dmevh); +int dm_event_handler_get_minor(const struct dm_event_handler *dmevh); +int dm_event_handler_get_timeout(const struct dm_event_handler *dmevh); +// FIXME misuse of bitmask as enum +enum dm_event_mask dm_event_handler_get_event_mask(const struct dm_event_handler *dmevh); + +/* FIXME Review interface (what about this next thing?) */ +int dm_event_get_registered_device(struct dm_event_handler *dmevh, int next); + +/* + * Initiate monitoring using dmeventd. + */ +int dm_event_register_handler(const struct dm_event_handler *dmevh); +int dm_event_unregister_handler(const struct dm_event_handler *dmevh); + +/* Set debug level for logging, and whether to log on stdout/stderr or syslog */ +void dm_event_log_set(int debug_log_level, int use_syslog); + +/* Log messages acroding to current debug level */ +__attribute__((format(printf, 6, 0))) +void dm_event_log(const char *subsys, int level, const char *file, + int line, int dm_errno_or_class, + const char *format, va_list ap); +/* Macro to route print_log do dm_event_log() */ +#define DM_EVENT_LOG_FN(subsys) \ +void print_log(int level, const char *file, int line, int dm_errno_or_class,\ + const char *format, ...)\ +{\ + va_list ap;\ + va_start(ap, format);\ + dm_event_log(subsys, level, file, line, dm_errno_or_class, format, ap);\ + va_end(ap);\ +} + +/* Prototypes for DSO interface, see dmeventd.c, struct dso_data for + detailed descriptions. */ +// FIXME misuse of bitmask as enum +void process_event(struct dm_task *dmt, enum dm_event_mask evmask, void **user); +int register_device(const char *device_name, const char *uuid, int major, int minor, void **user); +int unregister_device(const char *device_name, const char *uuid, int major, + int minor, void **user); + +#endif
diff --git a/daemons/dmeventd/libdevmapper-event.pc.in b/daemons/dmeventd/libdevmapper-event.pc.in new file mode 100644 index 0000000..839433f --- /dev/null +++ b/daemons/dmeventd/libdevmapper-event.pc.in
@@ -0,0 +1,11 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: devmapper-event +Description: device-mapper event library +Version: @DM_LIB_PATCHLEVEL@ +Cflags: -I${includedir} +Libs: -L${libdir} -ldevmapper-event +Requires.private: devmapper
diff --git a/daemons/dmeventd/plugins/Makefile.in b/daemons/dmeventd/plugins/Makefile.in new file mode 100644 index 0000000..b164153 --- /dev/null +++ b/daemons/dmeventd/plugins/Makefile.in
@@ -0,0 +1,46 @@ +# +# Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. +# Copyright (C) 2004-2005, 2011 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +SUBDIRS += lvm2 + +ifneq ("@MIRRORS@", "none") + SUBDIRS += mirror +endif + +ifneq ("@SNAPSHOTS@", "none") + SUBDIRS += snapshot +endif + +ifneq ("@RAID@", "none") + SUBDIRS += raid +endif + +ifneq ("@THIN@", "none") + SUBDIRS += thin +endif + +ifeq ($(MAKECMDGOALS),distclean) + SUBDIRS = lvm2 mirror snapshot raid thin +endif + +include $(top_builddir)/make.tmpl + +snapshot: lvm2 +mirror: lvm2 +raid: lvm2 +thin: lvm2
diff --git a/daemons/dmeventd/plugins/lvm2/.exported_symbols b/daemons/dmeventd/plugins/lvm2/.exported_symbols new file mode 100644 index 0000000..646e4cf --- /dev/null +++ b/daemons/dmeventd/plugins/lvm2/.exported_symbols
@@ -0,0 +1,7 @@ +dmeventd_lvm2_init +dmeventd_lvm2_exit +dmeventd_lvm2_lock +dmeventd_lvm2_unlock +dmeventd_lvm2_pool +dmeventd_lvm2_run +dmeventd_lvm2_command
diff --git a/daemons/dmeventd/plugins/lvm2/Makefile.in b/daemons/dmeventd/plugins/lvm2/Makefile.in new file mode 100644 index 0000000..956d31e --- /dev/null +++ b/daemons/dmeventd/plugins/lvm2/Makefile.in
@@ -0,0 +1,31 @@ +# +# Copyright (C) 2010-2014 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +CLDFLAGS += -L$(top_builddir)/tools + +SOURCES = dmeventd_lvm.c + +LIB_SHARED = libdevmapper-event-lvm2.$(LIB_SUFFIX) +LIB_VERSION = $(LIB_VERSION_LVM) + +include $(top_builddir)/make.tmpl + +LIBS += @LVM2CMD_LIB@ -ldevmapper $(PTHREAD_LIBS) + +install_lvm2: install_lib_shared + +install: install_lvm2
diff --git a/daemons/dmeventd/plugins/lvm2/dmeventd_lvm.c b/daemons/dmeventd/plugins/lvm2/dmeventd_lvm.c new file mode 100644 index 0000000..f36feb4 --- /dev/null +++ b/daemons/dmeventd/plugins/lvm2/dmeventd_lvm.c
@@ -0,0 +1,148 @@ +/* + * Copyright (C) 2010-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lib.h" +#include "dmeventd_lvm.h" +#include "libdevmapper-event.h" +#include "lvm2cmd.h" + +#include <pthread.h> + +/* + * register_device() is called first and performs initialisation. + * Only one device may be registered or unregistered at a time. + */ +static pthread_mutex_t _register_mutex = PTHREAD_MUTEX_INITIALIZER; + +/* + * Number of active registrations. + */ +static int _register_count = 0; +static struct dm_pool *_mem_pool = NULL; +static void *_lvm_handle = NULL; + +DM_EVENT_LOG_FN("lvm") + +static void _lvm2_print_log(int level, const char *file, int line, + int dm_errno_or_class, const char *msg) +{ + print_log(level, file, line, dm_errno_or_class, "%s", msg); +} + +/* + * Currently only one event can be processed at a time. + */ +static pthread_mutex_t _event_mutex = PTHREAD_MUTEX_INITIALIZER; + +void dmeventd_lvm2_lock(void) +{ + pthread_mutex_lock(&_event_mutex); +} + +void dmeventd_lvm2_unlock(void) +{ + pthread_mutex_unlock(&_event_mutex); +} + +int dmeventd_lvm2_init(void) +{ + int r = 0; + + pthread_mutex_lock(&_register_mutex); + + if (!_lvm_handle) { + lvm2_log_fn(_lvm2_print_log); + + if (!(_lvm_handle = lvm2_init())) + goto out; + + /* + * Need some space for allocations. 1024 should be more + * than enough for what we need (device mapper name splitting) + */ + if (!_mem_pool && !(_mem_pool = dm_pool_create("mirror_dso", 1024))) { + lvm2_exit(_lvm_handle); + _lvm_handle = NULL; + goto out; + } + + lvm2_disable_dmeventd_monitoring(_lvm_handle); + /* FIXME Temporary: move to dmeventd core */ + lvm2_run(_lvm_handle, "_memlock_inc"); + log_debug("lvm plugin initilized."); + } + + _register_count++; + r = 1; + +out: + pthread_mutex_unlock(&_register_mutex); + return r; +} + +void dmeventd_lvm2_exit(void) +{ + pthread_mutex_lock(&_register_mutex); + + if (!--_register_count) { + log_debug("lvm plugin shuting down."); + lvm2_run(_lvm_handle, "_memlock_dec"); + dm_pool_destroy(_mem_pool); + _mem_pool = NULL; + lvm2_exit(_lvm_handle); + _lvm_handle = NULL; + log_debug("lvm plugin exited."); + } + + pthread_mutex_unlock(&_register_mutex); +} + +struct dm_pool *dmeventd_lvm2_pool(void) +{ + return _mem_pool; +} + +int dmeventd_lvm2_run(const char *cmdline) +{ + return (lvm2_run(_lvm_handle, cmdline) == LVM2_COMMAND_SUCCEEDED); +} + +int dmeventd_lvm2_command(struct dm_pool *mem, char *buffer, size_t size, + const char *cmd, const char *device) +{ + char *vg = NULL, *lv = NULL, *layer; + int r; + + if (!dm_split_lvm_name(mem, device, &vg, &lv, &layer)) { + log_error("Unable to determine VG name from %s.", + device); + return 0; + } + + /* strip off the mirror component designations */ + if ((layer = strstr(lv, "_mimagetmp")) || + (layer = strstr(lv, "_mlog"))) + *layer = '\0'; + + r = dm_snprintf(buffer, size, "%s %s/%s", cmd, vg, lv); + + dm_pool_free(mem, vg); + + if (r < 0) { + log_error("Unable to form LVM command. (too long)."); + return 0; + } + + return 1; +}
diff --git a/daemons/dmeventd/plugins/lvm2/dmeventd_lvm.h b/daemons/dmeventd/plugins/lvm2/dmeventd_lvm.h new file mode 100644 index 0000000..353a03d --- /dev/null +++ b/daemons/dmeventd/plugins/lvm2/dmeventd_lvm.h
@@ -0,0 +1,74 @@ +/* + * Copyright (C) 2010-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * Wrappers around liblvm2cmd functions for dmeventd plug-ins. + * + * liblvm2cmd is not thread-safe so the locking in this library helps dmeventd + * threads to co-operate in sharing a single instance. + * + * FIXME Either support this properly as a generic liblvm2cmd wrapper or make + * liblvm2cmd thread-safe so this can go away. + */ + +#ifndef _DMEVENTD_LVMWRAP_H +#define _DMEVENTD_LVMWRAP_H + +struct dm_pool; + +int dmeventd_lvm2_init(void); +void dmeventd_lvm2_exit(void); +int dmeventd_lvm2_run(const char *cmdline); + +void dmeventd_lvm2_lock(void); +void dmeventd_lvm2_unlock(void); + +struct dm_pool *dmeventd_lvm2_pool(void); + +int dmeventd_lvm2_command(struct dm_pool *mem, char *buffer, size_t size, + const char *cmd, const char *device); + +#define dmeventd_lvm2_run_with_lock(cmdline) \ + ({\ + int rc;\ + dmeventd_lvm2_lock();\ + rc = dmeventd_lvm2_run(cmdline);\ + dmeventd_lvm2_unlock();\ + rc;\ + }) + +#define dmeventd_lvm2_init_with_pool(name, st) \ + ({\ + struct dm_pool *mem;\ + st = NULL;\ + if (dmeventd_lvm2_init()) {\ + if ((mem = dm_pool_create(name, 2048)) &&\ + (st = dm_pool_zalloc(mem, sizeof(*st))))\ + st->mem = mem;\ + else {\ + if (mem)\ + dm_pool_destroy(mem);\ + dmeventd_lvm2_exit();\ + }\ + }\ + st;\ + }) + +#define dmeventd_lvm2_exit_with_pool(pool) \ + do {\ + dm_pool_destroy(pool->mem);\ + dmeventd_lvm2_exit();\ + } while(0) + +#endif /* _DMEVENTD_LVMWRAP_H */
diff --git a/daemons/dmeventd/plugins/mirror/.exported_symbols b/daemons/dmeventd/plugins/mirror/.exported_symbols new file mode 100644 index 0000000..b88c705 --- /dev/null +++ b/daemons/dmeventd/plugins/mirror/.exported_symbols
@@ -0,0 +1,3 @@ +process_event +register_device +unregister_device
diff --git a/daemons/dmeventd/plugins/mirror/Makefile.in b/daemons/dmeventd/plugins/mirror/Makefile.in new file mode 100644 index 0000000..1d9666d --- /dev/null +++ b/daemons/dmeventd/plugins/mirror/Makefile.in
@@ -0,0 +1,37 @@ +# +# Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. +# Copyright (C) 2004-2005, 2008-2014 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +INCLUDES += -I$(top_srcdir)/daemons/dmeventd/plugins/lvm2 +CLDFLAGS += -L$(top_builddir)/daemons/dmeventd/plugins/lvm2 + +SOURCES = dmeventd_mirror.c + +LIB_NAME = libdevmapper-event-lvm2mirror +LIB_SHARED = $(LIB_NAME).$(LIB_SUFFIX) +LIB_VERSION = $(LIB_VERSION_LVM) + +CFLOW_LIST = $(SOURCES) +CFLOW_LIST_TARGET = $(LIB_NAME).cflow + +include $(top_builddir)/make.tmpl + +LIBS += -ldevmapper-event-lvm2 -ldevmapper + +install_lvm2: install_dm_plugin + +install: install_lvm2
diff --git a/daemons/dmeventd/plugins/mirror/dmeventd_mirror.c b/daemons/dmeventd/plugins/mirror/dmeventd_mirror.c new file mode 100644 index 0000000..ee10874 --- /dev/null +++ b/daemons/dmeventd/plugins/mirror/dmeventd_mirror.c
@@ -0,0 +1,223 @@ +/* + * Copyright (C) 2005-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lib.h" +#include "libdevmapper-event.h" +#include "dmeventd_lvm.h" +#include "activate.h" /* For TARGET_NAME* */ + +/* FIXME Reformat to 80 char lines. */ + +#define ME_IGNORE 0 +#define ME_INSYNC 1 +#define ME_FAILURE 2 + +struct dso_state { + struct dm_pool *mem; + char cmd_lvscan[512]; + char cmd_lvconvert[512]; +}; + +DM_EVENT_LOG_FN("mirr") + +static void _process_status_code(dm_status_mirror_health_t health, + uint32_t major, uint32_t minor, + const char *dev_type, int *r) +{ + /* + * A => Alive - No failures + * D => Dead - A write failure occurred leaving mirror out-of-sync + * F => Flush failed. + * S => Sync - A sychronization failure occurred, mirror out-of-sync + * R => Read - A read failure occurred, mirror data unaffected + * U => Unclassified failure (bug) + */ + switch (health) { + case DM_STATUS_MIRROR_ALIVE: + return; + case DM_STATUS_MIRROR_FLUSH_FAILED: + log_error("%s device %u:%u flush failed.", + dev_type, major, minor); + *r = ME_FAILURE; + break; + case DM_STATUS_MIRROR_SYNC_FAILED: + log_error("%s device %u:%u sync failed.", + dev_type, major, minor); + break; + case DM_STATUS_MIRROR_READ_FAILED: + log_error("%s device %u:%u read failed.", + dev_type, major, minor); + break; + default: + log_error("%s device %u:%u has failed (%c).", + dev_type, major, minor, (char)health); + *r = ME_FAILURE; + break; + } +} + +static int _get_mirror_event(struct dso_state *state, char *params) +{ + int r = ME_INSYNC; + unsigned i; + struct dm_status_mirror *ms; + + if (!dm_get_status_mirror(state->mem, params, &ms)) + goto_out; + + /* Check for bad mirror devices */ + for (i = 0; i < ms->dev_count; ++i) + _process_status_code(ms->devs[i].health, + ms->devs[i].major, ms->devs[i].minor, + i ? "Secondary mirror" : "Primary mirror", &r); + + /* Check for bad disk log device */ + for (i = 0; i < ms->log_count; ++i) + _process_status_code(ms->logs[i].health, + ms->logs[i].major, ms->logs[i].minor, + "Log", &r); + + /* Ignore if not in-sync */ + if ((r == ME_INSYNC) && (ms->insync_regions != ms->total_regions)) + r = ME_IGNORE; + + dm_pool_free(state->mem, ms); + + return r; + +out: + log_error("Unable to parse mirror status string."); + + return ME_IGNORE; +} + +static int _remove_failed_devices(const char *cmd_lvscan, const char *cmd_lvconvert) +{ + int r; + + if (!dmeventd_lvm2_run_with_lock(cmd_lvscan)) + log_info("Re-scan of mirrored device failed."); + + /* if repair goes OK, report success even if lvscan has failed */ + r = dmeventd_lvm2_run_with_lock(cmd_lvconvert); + + log_info("Repair of mirrored device %s.", + (r) ? "finished successfully" : "failed"); + + return r; +} + +void process_event(struct dm_task *dmt, + enum dm_event_mask event __attribute__((unused)), + void **user) +{ + struct dso_state *state = *user; + void *next = NULL; + uint64_t start, length; + char *target_type = NULL; + char *params; + const char *device = dm_task_get_name(dmt); + + do { + next = dm_get_next_target(dmt, next, &start, &length, + &target_type, ¶ms); + + if (!target_type) { + log_info("%s mapping lost.", device); + continue; + } + + if (strcmp(target_type, TARGET_NAME_MIRROR)) { + log_info("%s has unmirrored portion.", device); + continue; + } + + switch(_get_mirror_event(state, params)) { + case ME_INSYNC: + /* FIXME: all we really know is that this + _part_ of the device is in sync + Also, this is not an error + */ + log_notice("%s is now in-sync.", device); + break; + case ME_FAILURE: + log_error("Device failure in %s.", device); + if (!_remove_failed_devices(state->cmd_lvscan, + state->cmd_lvconvert)) + /* FIXME Why are all the error return codes unused? Get rid of them? */ + log_error("Failed to remove faulty devices in %s.", + device); + /* Should check before warning user that device is now linear + else + log_notice("%s is now a linear device.", + device); + */ + break; + case ME_IGNORE: + break; + default: + /* FIXME Provide value then! */ + log_info("Unknown event received."); + } + } while (next); +} + +int register_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state; + + if (!dmeventd_lvm2_init_with_pool("mirror_state", state)) + goto_bad; + + if (!dmeventd_lvm2_command(state->mem, state->cmd_lvscan, sizeof(state->cmd_lvscan), + "lvscan --cache", device)) { + dmeventd_lvm2_exit_with_pool(state); + goto_bad; + } + + if (!dmeventd_lvm2_command(state->mem, state->cmd_lvconvert, sizeof(state->cmd_lvconvert), + "lvconvert --repair --use-policies", device)) { + dmeventd_lvm2_exit_with_pool(state); + goto_bad; + } + + *user = state; + + log_info("Monitoring mirror device %s for events.", device); + + return 1; +bad: + log_error("Failed to monitor mirror %s.", device); + + return 0; +} + +int unregister_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state = *user; + + dmeventd_lvm2_exit_with_pool(state); + log_info("No longer monitoring mirror device %s for events.", + device); + + return 1; +}
diff --git a/daemons/dmeventd/plugins/raid/.exported_symbols b/daemons/dmeventd/plugins/raid/.exported_symbols new file mode 100644 index 0000000..b88c705 --- /dev/null +++ b/daemons/dmeventd/plugins/raid/.exported_symbols
@@ -0,0 +1,3 @@ +process_event +register_device +unregister_device
diff --git a/daemons/dmeventd/plugins/raid/Makefile.in b/daemons/dmeventd/plugins/raid/Makefile.in new file mode 100644 index 0000000..1bca8b2 --- /dev/null +++ b/daemons/dmeventd/plugins/raid/Makefile.in
@@ -0,0 +1,36 @@ +# +# Copyright (C) 2011-2014 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +INCLUDES += -I$(top_srcdir)/daemons/dmeventd/plugins/lvm2 +CLDFLAGS += -L$(top_builddir)/daemons/dmeventd/plugins/lvm2 + +SOURCES = dmeventd_raid.c + +LIB_NAME = libdevmapper-event-lvm2raid +LIB_SHARED = $(LIB_NAME).$(LIB_SUFFIX) +LIB_VERSION = $(LIB_VERSION_LVM) + +CFLOW_LIST = $(SOURCES) +CFLOW_LIST_TARGET = $(LIB_NAME).cflow + +include $(top_builddir)/make.tmpl + +LIBS += -ldevmapper-event-lvm2 -ldevmapper + +install_lvm2: install_dm_plugin + +install: install_lvm2
diff --git a/daemons/dmeventd/plugins/raid/dmeventd_raid.c b/daemons/dmeventd/plugins/raid/dmeventd_raid.c new file mode 100644 index 0000000..770fbc6 --- /dev/null +++ b/daemons/dmeventd/plugins/raid/dmeventd_raid.c
@@ -0,0 +1,145 @@ +/* + * Copyright (C) 2005-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lib.h" +#include "dmeventd_lvm.h" +#include "libdevmapper-event.h" + +struct dso_state { + struct dm_pool *mem; + char cmd_lvscan[512]; + char cmd_lvconvert[512]; + int failed; +}; + +DM_EVENT_LOG_FN("raid") + +/* FIXME Reformat to 80 char lines. */ + +static int _process_raid_event(struct dso_state *state, char *params, const char *device) +{ + struct dm_status_raid *status; + const char *d; + + if (!dm_get_status_raid(state->mem, params, &status)) { + log_error("Failed to process status line for %s.", device); + return 0; + } + + if ((d = strchr(status->dev_health, 'D'))) { + if (state->failed) + goto out; /* already reported */ + + log_error("Device #%d of %s array, %s, has failed.", + (int)(d - status->dev_health), + status->raid_type, device); + + state->failed = 1; + if (!dmeventd_lvm2_run_with_lock(state->cmd_lvscan)) + log_warn("WARNING: Re-scan of RAID device %s failed.", device); + + /* if repair goes OK, report success even if lvscan has failed */ + if (!dmeventd_lvm2_run_with_lock(state->cmd_lvconvert)) { + log_info("Repair of RAID device %s failed.", device); + dm_pool_free(state->mem, status); + return 0; + } + } else { + state->failed = 0; + log_info("%s array, %s, is %s in-sync.", + status->raid_type, device, + (status->insync_regions == status->total_regions) ? "now" : "not"); + } +out: + dm_pool_free(state->mem, status); + + return 1; +} + +void process_event(struct dm_task *dmt, + enum dm_event_mask event __attribute__((unused)), + void **user) +{ + struct dso_state *state = *user; + void *next = NULL; + uint64_t start, length; + char *target_type = NULL; + char *params; + const char *device = dm_task_get_name(dmt); + + do { + next = dm_get_next_target(dmt, next, &start, &length, + &target_type, ¶ms); + + if (!target_type) { + log_info("%s mapping lost.", device); + continue; + } + + if (strcmp(target_type, "raid")) { + log_info("%s has non-raid portion.", device); + continue; + } + + if (!_process_raid_event(state, params, device)) + log_error("Failed to process event for %s.", + device); + } while (next); +} + +int register_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state; + + if (!dmeventd_lvm2_init_with_pool("raid_state", state)) + goto_bad; + + if (!dmeventd_lvm2_command(state->mem, state->cmd_lvscan, sizeof(state->cmd_lvscan), + "lvscan --cache", device) || + !dmeventd_lvm2_command(state->mem, state->cmd_lvconvert, sizeof(state->cmd_lvconvert), + "lvconvert --config devices{ignore_suspended_devices=1} " + "--repair --use-policies", device)) { + dmeventd_lvm2_exit_with_pool(state); + goto_bad; + } + + *user = state; + + log_info("Monitoring RAID device %s for events.", device); + + return 1; +bad: + log_error("Failed to monitor RAID %s.", device); + + return 0; +} + +int unregister_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state = *user; + + dmeventd_lvm2_exit_with_pool(state); + log_info("No longer monitoring RAID device %s for events.", + device); + + return 1; +}
diff --git a/daemons/dmeventd/plugins/snapshot/.exported_symbols b/daemons/dmeventd/plugins/snapshot/.exported_symbols new file mode 100644 index 0000000..b88c705 --- /dev/null +++ b/daemons/dmeventd/plugins/snapshot/.exported_symbols
@@ -0,0 +1,3 @@ +process_event +register_device +unregister_device
diff --git a/daemons/dmeventd/plugins/snapshot/Makefile.in b/daemons/dmeventd/plugins/snapshot/Makefile.in new file mode 100644 index 0000000..5eb7a47 --- /dev/null +++ b/daemons/dmeventd/plugins/snapshot/Makefile.in
@@ -0,0 +1,33 @@ +# +# Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. +# Copyright (C) 2004-2014 Red Hat, Inc. All rights reserved. +# +# This file is part of the LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +INCLUDES += -I$(top_srcdir)/daemons/dmeventd/plugins/lvm2 +CLDFLAGS += -L$(top_builddir)/daemons/dmeventd/plugins/lvm2 + +SOURCES = dmeventd_snapshot.c + +LIB_SHARED = libdevmapper-event-lvm2snapshot.$(LIB_SUFFIX) +LIB_VERSION = $(LIB_VERSION_LVM) + +include $(top_builddir)/make.tmpl + +LIBS += -ldevmapper-event-lvm2 -ldevmapper + +install_lvm2: install_dm_plugin + +install: install_lvm2
diff --git a/daemons/dmeventd/plugins/snapshot/dmeventd_snapshot.c b/daemons/dmeventd/plugins/snapshot/dmeventd_snapshot.c new file mode 100644 index 0000000..7b060ed --- /dev/null +++ b/daemons/dmeventd/plugins/snapshot/dmeventd_snapshot.c
@@ -0,0 +1,285 @@ +/* + * Copyright (C) 2007-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lib.h" +#include "dmeventd_lvm.h" +#include "libdevmapper-event.h" + +#include <sys/wait.h> +#include <stdarg.h> +#include <pthread.h> + +/* First warning when snapshot is 80% full. */ +#define WARNING_THRESH (DM_PERCENT_1 * 80) +/* Run a check every 5%. */ +#define CHECK_STEP (DM_PERCENT_1 * 5) +/* Do not bother checking snapshots less than 50% full. */ +#define CHECK_MINIMUM (DM_PERCENT_1 * 50) + +#define UMOUNT_COMMAND "/bin/umount" + +struct dso_state { + struct dm_pool *mem; + dm_percent_t percent_check; + uint64_t known_size; + char cmd_lvextend[512]; +}; + +DM_EVENT_LOG_FN("snap") + +static int _run(const char *cmd, ...) +{ + va_list ap; + int argc = 1; /* for argv[0], i.e. cmd */ + int i = 0; + const char **argv; + pid_t pid = fork(); + int status; + + if (pid == 0) { /* child */ + va_start(ap, cmd); + while (va_arg(ap, const char *)) + ++ argc; + va_end(ap); + + /* + 1 for the terminating NULL */ + argv = alloca(sizeof(const char *) * (argc + 1)); + + argv[0] = cmd; + va_start(ap, cmd); + while ((argv[++i] = va_arg(ap, const char *))); + va_end(ap); + + execvp(cmd, (char **)argv); + log_sys_error("exec", cmd); + exit(127); + } + + if (pid > 0) { /* parent */ + if (waitpid(pid, &status, 0) != pid) + return 0; /* waitpid failed */ + if (!WIFEXITED(status) || WEXITSTATUS(status)) + return 0; /* the child failed */ + } + + if (pid < 0) + return 0; /* fork failed */ + + return 1; /* all good */ +} + +static int _extend(const char *cmd) +{ + log_debug("Extending snapshot via %s.", cmd); + return dmeventd_lvm2_run_with_lock(cmd); +} + +#ifdef SNAPSHOT_REMOVE +/* Remove invalid snapshot from dm-table */ +/* Experimental for now and not used by default */ +static int _remove(const char *uuid) +{ + int r = 1; + uint32_t cookie = 0; + struct dm_task *dmt; + + if (!(dmt = dm_task_create(DM_DEVICE_REMOVE))) + return 0; + + if (!dm_task_set_uuid(dmt, uuid)) { + r = 0; + goto_out; + } + + dm_task_retry_remove(dmt); + + if (!dm_task_set_cookie(dmt, &cookie, 0)) { + r = 0; + goto_out; + } + + if (!dm_task_run(dmt)) { + r = 0; + goto_out; + } +out: + dm_task_destroy(dmt); + + return r; +} +#endif /* SNAPSHOT_REMOVE */ + +static void _umount(const char *device, int major, int minor) +{ + FILE *mounts; + char buffer[4096]; + char *words[3]; + struct stat st; + const char procmounts[] = "/proc/mounts"; + + if (!(mounts = fopen(procmounts, "r"))) { + log_sys_error("fopen", procmounts); + log_error("Not umounting %s.", device); + return; + } + + while (!feof(mounts)) { + /* read a line of /proc/mounts */ + if (!fgets(buffer, sizeof(buffer), mounts)) + break; /* eof, likely */ + + /* words[0] is the mount point and words[1] is the device path */ + if (dm_split_words(buffer, 3, 0, words) < 2) + continue; + + /* find the major/minor of the device */ + if (stat(words[0], &st)) + continue; /* can't stat, skip this one */ + + if (S_ISBLK(st.st_mode) && + (int) major(st.st_rdev) == major && + (int) minor(st.st_rdev) == minor) { + log_error("Unmounting invalid snapshot %s from %s.", device, words[1]); + if (!_run(UMOUNT_COMMAND, "-fl", words[1], NULL)) + log_error("Failed to umount snapshot %s from %s: %s.", + device, words[1], strerror(errno)); + } + } + + if (fclose(mounts)) + log_sys_error("close", procmounts); +} + +void process_event(struct dm_task *dmt, + enum dm_event_mask event __attribute__((unused)), + void **user) +{ + struct dso_state *state = *user; + void *next = NULL; + uint64_t start, length; + char *target_type = NULL; + char *params; + struct dm_status_snapshot *status = NULL; + const char *device = dm_task_get_name(dmt); + int percent; + struct dm_info info; + + /* No longer monitoring, waiting for remove */ + if (!state->percent_check) + return; + + dm_get_next_target(dmt, next, &start, &length, &target_type, ¶ms); + if (!target_type || strcmp(target_type, "snapshot")) { + log_error("Target %s is not snapshot.", target_type); + return; + } + + if (!dm_get_status_snapshot(state->mem, params, &status)) { + log_error("Cannot parse snapshot %s state: %s.", device, params); + return; + } + + /* + * If the snapshot has been invalidated or we failed to parse + * the status string. Report the full status string to syslog. + */ + if (status->invalid || status->overflow || !status->total_sectors) { + log_warn("WARNING: Snapshot %s changed state to: %s and should be removed.", + device, params); + state->percent_check = 0; + if (dm_task_get_info(dmt, &info)) + _umount(device, info.major, info.minor); +#ifdef SNAPSHOT_REMOVE + /* Maybe configurable ? */ + _remove(dm_task_get_uuid(dmt)); +#endif + pthread_kill(pthread_self(), SIGALRM); + goto out; + } + + if (length <= (status->used_sectors - status->metadata_sectors)) { + /* TODO eventually recognize earlier when room is enough */ + log_info("Dropping monitoring of fully provisioned snapshot %s.", + device); + pthread_kill(pthread_self(), SIGALRM); + goto out; + } + + /* Snapshot size had changed. Clear the threshold. */ + if (state->known_size != status->total_sectors) { + state->percent_check = CHECK_MINIMUM; + state->known_size = status->total_sectors; + } + + percent = dm_make_percent(status->used_sectors, status->total_sectors); + if (percent >= state->percent_check) { + /* Usage has raised more than CHECK_STEP since the last + time. Run actions. */ + state->percent_check = (percent / CHECK_STEP) * CHECK_STEP + CHECK_STEP; + + if (percent >= WARNING_THRESH) /* Print a warning to syslog. */ + log_warn("WARNING: Snapshot %s is now %.2f%% full.", + device, dm_percent_to_float(percent)); + + /* Try to extend the snapshot, in accord with user-set policies */ + if (!_extend(state->cmd_lvextend)) + log_error("Failed to extend snapshot %s.", device); + } +out: + dm_pool_free(state->mem, status); +} + +int register_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state; + + if (!dmeventd_lvm2_init_with_pool("snapshot_state", state)) + goto_bad; + + if (!dmeventd_lvm2_command(state->mem, state->cmd_lvextend, + sizeof(state->cmd_lvextend), + "lvextend --use-policies", device)) { + dmeventd_lvm2_exit_with_pool(state); + goto_bad; + } + + state->percent_check = CHECK_MINIMUM; + *user = state; + + log_info("Monitoring snapshot %s.", device); + + return 1; +bad: + log_error("Failed to monitor snapshot %s.", device); + + return 0; +} + +int unregister_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state = *user; + + dmeventd_lvm2_exit_with_pool(state); + log_info("No longer monitoring snapshot %s.", device); + + return 1; +}
diff --git a/daemons/dmeventd/plugins/thin/.exported_symbols b/daemons/dmeventd/plugins/thin/.exported_symbols new file mode 100644 index 0000000..b88c705 --- /dev/null +++ b/daemons/dmeventd/plugins/thin/.exported_symbols
@@ -0,0 +1,3 @@ +process_event +register_device +unregister_device
diff --git a/daemons/dmeventd/plugins/thin/Makefile.in b/daemons/dmeventd/plugins/thin/Makefile.in new file mode 100644 index 0000000..f54ee2d --- /dev/null +++ b/daemons/dmeventd/plugins/thin/Makefile.in
@@ -0,0 +1,36 @@ +# +# Copyright (C) 2011-2014 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +INCLUDES += -I$(top_srcdir)/daemons/dmeventd/plugins/lvm2 +CLDFLAGS += -L$(top_builddir)/daemons/dmeventd/plugins/lvm2 + +SOURCES = dmeventd_thin.c + +LIB_NAME = libdevmapper-event-lvm2thin +LIB_SHARED = $(LIB_NAME).$(LIB_SUFFIX) +LIB_VERSION = $(LIB_VERSION_LVM) + +CFLOW_LIST = $(SOURCES) +CFLOW_LIST_TARGET = $(LIB_NAME).cflow + +include $(top_builddir)/make.tmpl + +LIBS += -ldevmapper-event-lvm2 -ldevmapper + +install_lvm2: install_dm_plugin + +install: install_lvm2
diff --git a/daemons/dmeventd/plugins/thin/dmeventd_thin.c b/daemons/dmeventd/plugins/thin/dmeventd_thin.c new file mode 100644 index 0000000..622910f --- /dev/null +++ b/daemons/dmeventd/plugins/thin/dmeventd_thin.c
@@ -0,0 +1,482 @@ +/* + * Copyright (C) 2011-2016 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lib.h" /* using here lvm log */ +#include "dmeventd_lvm.h" +#include "libdevmapper-event.h" + +#include <sys/wait.h> +#include <stdarg.h> +#include <pthread.h> + +/* TODO - move this mountinfo code into library to be reusable */ +#ifdef __linux__ +# include "kdev_t.h" +#else +# define MAJOR(x) major((x)) +# define MINOR(x) minor((x)) +#endif + +/* First warning when thin data or metadata is 80% full. */ +#define WARNING_THRESH (DM_PERCENT_1 * 80) +/* Umount thin LVs when thin data or metadata LV is >= + * and lvextend --use-policies has failed. */ +#define UMOUNT_THRESH (DM_PERCENT_1 * 95) +/* Run a check every 5%. */ +#define CHECK_STEP (DM_PERCENT_1 * 5) +/* Do not bother checking thin data or metadata is less than 50% full. */ +#define CHECK_MINIMUM (DM_PERCENT_1 * 50) + +#define UMOUNT_COMMAND "/bin/umount" + +#define MAX_FAILS (10) + +#define THIN_DEBUG 0 + +struct dso_state { + struct dm_pool *mem; + int metadata_percent_check; + int data_percent_check; + uint64_t known_metadata_size; + uint64_t known_data_size; + unsigned fails; + char cmd_str[1024]; +}; + +DM_EVENT_LOG_FN("thin") + +#define UUID_PREFIX "LVM-" + +/* Figure out device UUID has LVM- prefix and is OPEN */ +static int _has_unmountable_prefix(int major, int minor) +{ + struct dm_task *dmt; + struct dm_info info; + const char *uuid; + int r = 0; + + if (!(dmt = dm_task_create(DM_DEVICE_INFO))) + return_0; + + if (!dm_task_set_major_minor(dmt, major, minor, 1)) + goto_out; + + if (!dm_task_no_flush(dmt)) + stack; + + if (!dm_task_run(dmt)) + goto out; + + if (!dm_task_get_info(dmt, &info)) + goto out; + + if (!info.exists || !info.open_count) + goto out; /* Not open -> not mounted */ + + if (!(uuid = dm_task_get_uuid(dmt))) + goto out; + + /* Check it's public mountable LV + * has prefix LVM- and UUID size is 68 chars */ + if (memcmp(uuid, UUID_PREFIX, sizeof(UUID_PREFIX) - 1) || + strlen(uuid) != 68) + goto out; + +#if THIN_DEBUG + log_debug("Found logical volume %s (%u:%u).", uuid, major, minor); +#endif + r = 1; +out: + dm_task_destroy(dmt); + + return r; +} + +/* Get dependencies for device, and try to find matching device */ +static int _has_deps(const char *name, int tp_major, int tp_minor, int *dev_minor) +{ + struct dm_task *dmt; + const struct dm_deps *deps; + struct dm_info info; + int major, minor; + int r = 0; + + if (!(dmt = dm_task_create(DM_DEVICE_DEPS))) + return 0; + + if (!dm_task_set_name(dmt, name)) + goto out; + + if (!dm_task_no_open_count(dmt)) + goto out; + + if (!dm_task_run(dmt)) + goto out; + + if (!dm_task_get_info(dmt, &info)) + goto out; + + if (!(deps = dm_task_get_deps(dmt))) + goto out; + + if (!info.exists || deps->count != 1) + goto out; + + major = (int) MAJOR(deps->device[0]); + minor = (int) MINOR(deps->device[0]); + if ((major != tp_major) || (minor != tp_minor)) + goto out; + + *dev_minor = info.minor; + + if (!_has_unmountable_prefix(major, info.minor)) + goto out; + +#if THIN_DEBUG + { + char dev_name[PATH_MAX]; + if (dm_device_get_name(major, minor, 0, dev_name, sizeof(dev_name))) + log_debug("Found %s (%u:%u) depends on %s.", + name, major, *dev_minor, dev_name); + } +#endif + r = 1; +out: + dm_task_destroy(dmt); + + return r; +} + +/* Get all active devices */ +static int _find_all_devs(dm_bitset_t bs, int tp_major, int tp_minor) +{ + struct dm_task *dmt; + struct dm_names *names; + unsigned next = 0; + int minor, r = 1; + + if (!(dmt = dm_task_create(DM_DEVICE_LIST))) + return 0; + + if (!dm_task_run(dmt)) { + r = 0; + goto out; + } + + if (!(names = dm_task_get_names(dmt))) { + r = 0; + goto out; + } + + if (!names->dev) + goto out; + + do { + names = (struct dm_names *)((char *) names + next); + if (_has_deps(names->name, tp_major, tp_minor, &minor)) + dm_bit_set(bs, minor); + next = names->next; + } while (next); + +out: + dm_task_destroy(dmt); + + return r; +} + +static int _run(const char *cmd, ...) +{ + va_list ap; + int argc = 1; /* for argv[0], i.e. cmd */ + int i = 0; + const char **argv; + pid_t pid = fork(); + int status; + + if (pid == 0) { /* child */ + va_start(ap, cmd); + while (va_arg(ap, const char *)) + ++argc; + va_end(ap); + + /* + 1 for the terminating NULL */ + argv = alloca(sizeof(const char *) * (argc + 1)); + + argv[0] = cmd; + va_start(ap, cmd); + while ((argv[++i] = va_arg(ap, const char *))); + va_end(ap); + + execvp(cmd, (char **)argv); + log_sys_error("exec", cmd); + exit(127); + } + + if (pid > 0) { /* parent */ + if (waitpid(pid, &status, 0) != pid) + return 0; /* waitpid failed */ + if (!WIFEXITED(status) || WEXITSTATUS(status)) + return 0; /* the child failed */ + } + + if (pid < 0) + return 0; /* fork failed */ + + return 1; /* all good */ +} + +struct mountinfo_s { + const char *device; + struct dm_info info; + dm_bitset_t minors; /* Bitset for active thin pool minors */ +}; + +static int _umount_device(char *buffer, unsigned major, unsigned minor, + char *target, void *cb_data) +{ + struct mountinfo_s *data = cb_data; + char *words[10]; + + if ((major == data->info.major) && dm_bit(data->minors, minor)) { + if (dm_split_words(buffer, DM_ARRAY_SIZE(words), 0, words) < DM_ARRAY_SIZE(words)) + words[9] = NULL; /* just don't show device name */ + log_info("Unmounting thin %s (%d:%d) of thin-pool %s (%u:%u) from mount point \"%s\".", + words[9] ? : "", major, minor, data->device, + data->info.major, data->info.minor, + target); + if (!_run(UMOUNT_COMMAND, "-fl", target, NULL)) + log_error("Failed to lazy umount thin %s (%d:%d) from %s: %s.", + words[9], major, minor, target, strerror(errno)); + } + + return 1; +} + +/* + * Find all thin pool LV users and try to umount them. + * TODO: work with read-only thin pool support + */ +static void _umount(struct dm_task *dmt) +{ + /* TODO: Convert to use hash to reduce memory usage */ + static const size_t MINORS = (1U << 20); /* 20 bit */ + struct mountinfo_s data = { NULL }; + + if (!dm_task_get_info(dmt, &data.info)) + return; + + data.device = dm_task_get_name(dmt); + + if (!(data.minors = dm_bitset_create(NULL, MINORS))) { + log_error("Failed to allocate bitset. Not unmounting %s.", data.device); + goto out; + } + + if (!_find_all_devs(data.minors, data.info.major, data.info.minor)) { + log_error("Failed to detect mounted volumes for %s.", data.device); + goto out; + } + + if (!dm_mountinfo_read(_umount_device, &data)) { + log_error("Could not parse mountinfo file."); + goto out; + } + +out: + if (data.minors) + dm_bitset_destroy(data.minors); +} + +static int _use_policy(struct dm_task *dmt, struct dso_state *state) +{ +#if THIN_DEBUG + log_info("dmeventd executes: %s.", state->cmd_str); +#endif + if (!dmeventd_lvm2_run_with_lock(state->cmd_str)) { + log_error("Failed to extend thin pool %s.", + dm_task_get_name(dmt)); + state->fails++; + return 0; + } + + state->fails = 0; + return 1; +} + +void process_event(struct dm_task *dmt, + enum dm_event_mask event __attribute__((unused)), + void **user) +{ + const char *device = dm_task_get_name(dmt); + int percent; + struct dso_state *state = *user; + struct dm_status_thin_pool *tps = NULL; + void *next = NULL; + uint64_t start, length; + char *target_type = NULL; + char *params; + int needs_policy = 0; + int needs_umount = 0; + +#if THIN_DEBUG + log_debug("Watch for tp-data:%.2f%% tp-metadata:%.2f%%.", + dm_percent_to_float(state->data_percent_check), + dm_percent_to_float(state->metadata_percent_check)); +#endif + +#if 0 + /* No longer monitoring, waiting for remove */ + if (!state->meta_percent_check && !state->data_percent_check) + return; +#endif + if (event & DM_EVENT_DEVICE_ERROR) { + /* Error -> no need to check and do instant resize */ + if (_use_policy(dmt, state)) + goto out; + + stack; + } + + dm_get_next_target(dmt, next, &start, &length, &target_type, ¶ms); + + if (!target_type || (strcmp(target_type, "thin-pool") != 0)) { + log_error("Invalid target type."); + goto out; + } + + if (!dm_get_status_thin_pool(state->mem, params, &tps)) { + log_error("Failed to parse status."); + needs_umount = 1; + goto out; + } + +#if THIN_DEBUG + log_debug("Thin pool status " FMTu64 "/" FMTu64 " " + FMTu64 "/" FMTu64 ".", + tps->used_metadata_blocks, tps->total_metadata_blocks, + tps->used_data_blocks, tps->total_data_blocks); +#endif + + /* Thin pool size had changed. Clear the threshold. */ + if (state->known_metadata_size != tps->total_metadata_blocks) { + state->metadata_percent_check = CHECK_MINIMUM; + state->known_metadata_size = tps->total_metadata_blocks; + } + + if (state->known_data_size != tps->total_data_blocks) { + state->data_percent_check = CHECK_MINIMUM; + state->known_data_size = tps->total_data_blocks; + } + + percent = dm_make_percent(tps->used_metadata_blocks, tps->total_metadata_blocks); + if (percent >= state->metadata_percent_check) { + /* + * Usage has raised more than CHECK_STEP since the last + * time. Run actions. + */ + state->metadata_percent_check = (percent / CHECK_STEP) * CHECK_STEP + CHECK_STEP; + + /* FIXME: extension of metadata needs to be written! */ + if (percent >= WARNING_THRESH) /* Print a warning to syslog. */ + log_warn("WARNING: Thin pool %s metadata is now %.2f%% full.", + device, dm_percent_to_float(percent)); + needs_policy = 1; + + if (percent >= UMOUNT_THRESH) + needs_umount = 1; + } + + percent = dm_make_percent(tps->used_data_blocks, tps->total_data_blocks); + if (percent >= state->data_percent_check) { + /* + * Usage has raised more than CHECK_STEP since + * the last time. Run actions. + */ + state->data_percent_check = (percent / CHECK_STEP) * CHECK_STEP + CHECK_STEP; + + if (percent >= WARNING_THRESH) /* Print a warning to syslog. */ + log_warn("WARNING: Thin pool %s data is now %.2f%% full.", + device, dm_percent_to_float(percent)); + needs_policy = 1; + + if (percent >= UMOUNT_THRESH) + needs_umount = 1; + } + + if (needs_policy && + _use_policy(dmt, state)) + needs_umount = 0; /* No umount when command was successful */ +out: + if (needs_umount) { + _umount(dmt); + /* Until something changes, do not retry any more actions */ + state->data_percent_check = state->metadata_percent_check = (DM_PERCENT_1 * 101); + } + + if (tps) + dm_pool_free(state->mem, tps); + + if (state->fails >= MAX_FAILS) { + log_warn("WARNING: Dropping monitoring of %s. " + "lvm2 command fails too often (%u times in raw).", + device, state->fails); + pthread_kill(pthread_self(), SIGALRM); + } +} + +int register_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state; + + if (!dmeventd_lvm2_init_with_pool("thin_pool_state", state)) + goto_bad; + + if (!dmeventd_lvm2_command(state->mem, state->cmd_str, + sizeof(state->cmd_str), + "lvextend --use-policies", + device)) { + dmeventd_lvm2_exit_with_pool(state); + goto_bad; + } + + state->metadata_percent_check = CHECK_MINIMUM; + state->data_percent_check = CHECK_MINIMUM; + *user = state; + + log_info("Monitoring thin %s.", device); + + return 1; +bad: + log_error("Failed to monitor thin %s.", device); + + return 0; +} + +int unregister_device(const char *device, + const char *uuid __attribute__((unused)), + int major __attribute__((unused)), + int minor __attribute__((unused)), + void **user) +{ + struct dso_state *state = *user; + + dmeventd_lvm2_exit_with_pool(state); + log_info("No longer monitoring thin %s.", device); + + return 1; +}
diff --git a/daemons/lvmdbusd/Makefile.in b/daemons/lvmdbusd/Makefile.in new file mode 100644 index 0000000..c781452 --- /dev/null +++ b/daemons/lvmdbusd/Makefile.in
@@ -0,0 +1,67 @@ +# +# Copyright (C) 2016 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +lvmdbusdir = $(python3dir)/lvmdbusd + +LVMDBUS_SRCDIR_FILES = \ + automatedproperties.py \ + background.py \ + cfg.py \ + cmdhandler.py \ + fetch.py \ + __init__.py \ + job.py \ + loader.py \ + lvmdb.py \ + main.py \ + lvm_shell_proxy.py \ + lv.py \ + manager.py \ + objectmanager.py \ + pv.py \ + refresh.py \ + request.py \ + state.py \ + udevwatch.py \ + utils.py \ + vg.py + +LVMDBUS_BUILDDIR_FILES = \ + path.py + +LVMDBUSD = $(srcdir)/lvmdbusd + +include $(top_builddir)/make.tmpl + +.PHONY: install_lvmdbusd + +install_lvmdbusd: + $(INSTALL_DIR) $(sbindir) + $(INSTALL_SCRIPT) $(LVMDBUSD) $(sbindir) + $(INSTALL_DIR) $(DESTDIR)$(lvmdbusdir) + (cd $(srcdir); $(INSTALL_DATA) $(LVMDBUS_SRCDIR_FILES) $(DESTDIR)$(lvmdbusdir)) + $(INSTALL_DATA) $(LVMDBUS_BUILDDIR_FILES) $(DESTDIR)$(lvmdbusdir) + PYTHON=$(PYTHON3) $(PYCOMPILE) --destdir "$(DESTDIR)" --basedir "$(lvmdbusdir)" $(LVMDBUS_SRCDIR_FILES) $(LVMDBUS_BUILDDIR_FILES) + $(CHMOD) 755 $(DESTDIR)$(lvmdbusdir)/__pycache__ + $(CHMOD) 444 $(DESTDIR)$(lvmdbusdir)/__pycache__/*.py[co] + +install_lvm2: install_lvmdbusd + +install: install_lvm2 + +DISTCLEAN_TARGETS+= \ + $(LVMDBUS_BUILDDIR_FILES)
diff --git a/daemons/lvmdbusd/__init__.py b/daemons/lvmdbusd/__init__.py new file mode 100644 index 0000000..25dcfdf --- /dev/null +++ b/daemons/lvmdbusd/__init__.py
@@ -0,0 +1,10 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from .main import main
diff --git a/daemons/lvmdbusd/automatedproperties.py b/daemons/lvmdbusd/automatedproperties.py new file mode 100644 index 0000000..aff920c --- /dev/null +++ b/daemons/lvmdbusd/automatedproperties.py
@@ -0,0 +1,175 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import dbus +from . import cfg +from .utils import get_properties, add_properties, get_object_property_diff, \ + log_debug +from .state import State + + +# noinspection PyPep8Naming,PyUnresolvedReferences +class AutomatedProperties(dbus.service.Object): + """ + This class implements the needed interfaces for: + org.freedesktop.DBus.Properties + + Other classes inherit from it to get the same behavior + """ + + def __init__(self, object_path, search_method=None): + dbus.service.Object.__init__(self, cfg.bus, object_path) + self._ap_interface = [] + self._ap_o_path = object_path + self._ap_search_method = search_method + self.state = None + + def dbus_object_path(self): + return self._ap_o_path + + def emit_data(self): + props = {} + + for i in self.interface(): + props[i] = self.GetAll(i) + + return self._ap_o_path, props + + def set_interface(self, interface): + """ + With inheritance we can't easily tell what interfaces a class provides + so we will have each class that implements an interface tell the + base AutomatedProperties what it is they do provide. This is kind of + clunky and perhaps we can figure out a better way to do this later. + :param interface: An interface the object supports + :return: + """ + if interface not in self._ap_interface: + self._ap_interface.append(interface) + + # noinspection PyUnusedLocal + def interface(self, all_interfaces=False): + if all_interfaces: + cpy = list(self._ap_interface) + cpy.extend( + ["org.freedesktop.DBus.Introspectable", + "org.freedesktop.DBus.Properties"]) + return cpy + + return self._ap_interface + + # Properties + # noinspection PyUnusedLocal + @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, + in_signature='ss', out_signature='v') + def Get(self, interface_name, property_name): + value = getattr(self, property_name) + # Note: If we get an exception in this handler we won't know about it, + # only the side effect of no returned value! + log_debug('Get (%s), type (%s), value(%s)' % + (property_name, str(type(value)), str(value))) + return value + + @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, + in_signature='s', out_signature='a{sv}') + def GetAll(self, interface_name): + if interface_name in self.interface(True): + # Using introspection, lets build this dynamically + properties = get_properties(self) + if interface_name in properties: + return properties[interface_name][1] + return {} + raise dbus.exceptions.DBusException( + self._ap_interface, + 'The object %s does not implement the %s interface' + % (self.__class__, interface_name)) + + @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, + in_signature='ssv') + def Set(self, interface_name, property_name, new_value): + setattr(self, property_name, new_value) + self.PropertiesChanged(interface_name, + {property_name: new_value}, []) + + # As dbus-python does not support introspection for properties we will + # get the autogenerated xml and then add our wanted properties to it. + @dbus.service.method(dbus_interface=dbus.INTROSPECTABLE_IFACE, + out_signature='s') + def Introspect(self): + r = dbus.service.Object.Introspect(self, self._ap_o_path, cfg.bus) + # Look at the properties in the class + props = get_properties(self) + + for int_f, v in props.items(): + r = add_properties(r, int_f, v[0]) + + return r + + @dbus.service.signal(dbus_interface=dbus.PROPERTIES_IFACE, + signature='sa{sv}as') + def PropertiesChanged(self, interface_name, changed_properties, + invalidated_properties): + log_debug(('SIGNAL: PropertiesChanged(%s, %s, %s, %s)' % + (str(self._ap_o_path), str(interface_name), + str(changed_properties), str(invalidated_properties)))) + + def refresh(self, search_key=None, object_state=None): + """ + Take the values (properties) of an object and update them with what + lvm currently has. You can either fetch the new ones or supply the + new state to be updated with + :param search_key: The value to use to search for + :param object_state: Use this as the new object state + """ + num_changed = 0 + + # If we can't do a lookup, bail now, this happens if we blindly walk + # through all dbus objects as some don't have a search method, like + # 'Manager' object. + if not self._ap_search_method: + return + + search = self.lvm_id + if search_key: + search = search_key + + # Either we have the new object state or we need to go fetch it + if object_state: + new_state = object_state + else: + new_state = self._ap_search_method([search])[0] + assert isinstance(new_state, State) + + assert new_state + + # When we refresh an object the object identifiers might have changed + # because LVM allows the user to change them (name & uuid), thus if + # they have changed we need to update the object manager so that + # look-ups will happen correctly + old_id = self.state.identifiers() + new_id = new_state.identifiers() + if old_id[0] != new_id[0] or old_id[1] != new_id[1]: + cfg.om.lookup_update(self, new_id[0], new_id[1]) + + # Grab the properties values, then replace the state of the object + # and retrieve the new values + # TODO: We need to add locking to prevent concurrent access to the + # properties so that a client is not accessing while we are + # replacing. + o_prop = get_properties(self) + self.state = new_state + n_prop = get_properties(self) + + changed = get_object_property_diff(o_prop, n_prop) + + if changed: + for int_f, v in changed.items(): + self.PropertiesChanged(int_f, v, []) + num_changed += 1 + return num_changed
diff --git a/daemons/lvmdbusd/background.py b/daemons/lvmdbusd/background.py new file mode 100644 index 0000000..8078b66 --- /dev/null +++ b/daemons/lvmdbusd/background.py
@@ -0,0 +1,201 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import threading +import subprocess +from . import cfg +import time +from .cmdhandler import options_to_cli_args +import dbus +from .utils import pv_range_append, pv_dest_ranges, log_error, log_debug +import traceback + +_rlock = threading.RLock() +_thread_list = list() + + +def pv_move_lv_cmd(move_options, lv_full_name, + pv_source, pv_source_range, pv_dest_range_list): + cmd = ['pvmove', '-i', '1'] + cmd.extend(options_to_cli_args(move_options)) + + if lv_full_name: + cmd.extend(['-n', lv_full_name]) + + pv_range_append(cmd, pv_source, *pv_source_range) + pv_dest_ranges(cmd, pv_dest_range_list) + + return cmd + + +def lv_merge_cmd(merge_options, lv_full_name): + cmd = ['lvconvert', '--merge', '-i', '1'] + cmd.extend(options_to_cli_args(merge_options)) + cmd.append(lv_full_name) + return cmd + + +def _move_merge(interface_name, cmd, job_state): + add(cmd, job_state) + + done = job_state.Wait(-1) + if not done: + ec, err_msg = job_state.GetError + raise dbus.exceptions.DBusException( + interface_name, + 'Exit code %s, stderr = %s' % (str(ec), err_msg)) + + cfg.load() + return '/' + + +def move(interface_name, lv_name, pv_src_obj, pv_source_range, + pv_dests_and_ranges, move_options, job_state): + """ + Common code for the pvmove handling. + :param interface_name: What dbus interface we are providing for + :param lv_name: Optional (None or name of LV to move) + :param pv_src_obj: dbus object patch for source PV + :param pv_source_range: (0,0 to ignore, else start, end segments) + :param pv_dests_and_ranges: Array of PV object paths and start/end segs + :param move_options: Hash with optional arguments + :param job_state: Used to convey information about jobs between processes + :return: '/' When complete, the empty object path + """ + pv_dests = [] + pv_src = cfg.om.get_object_by_path(pv_src_obj) + if pv_src: + + # Check to see if we are handling a move to a specific + # destination(s) + if len(pv_dests_and_ranges): + for pr in pv_dests_and_ranges: + pv_dbus_obj = cfg.om.get_object_by_path(pr[0]) + if not pv_dbus_obj: + raise dbus.exceptions.DBusException( + interface_name, + 'PV Destination (%s) not found' % pr[0]) + + pv_dests.append((pv_dbus_obj.lvm_id, pr[1], pr[2])) + + # Generate the command line for this command, but don't + # execute it. + cmd = pv_move_lv_cmd(move_options, + lv_name, + pv_src.lvm_id, + pv_source_range, + pv_dests) + + return _move_merge(interface_name, cmd, job_state) + else: + raise dbus.exceptions.DBusException( + interface_name, 'pv_src_obj (%s) not found' % pv_src_obj) + + +def merge(interface_name, lv_uuid, lv_name, merge_options, job_state): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + if dbo: + cmd = lv_merge_cmd(merge_options, dbo.lvm_id) + return _move_merge(interface_name, cmd, job_state) + else: + raise dbus.exceptions.DBusException( + interface_name, + 'LV with uuid %s and name %s not present!' % (lv_uuid, lv_name)) + + +def background_reaper(): + while cfg.run.value != 0: + with _rlock: + num_threads = len(_thread_list) - 1 + if num_threads >= 0: + for i in range(num_threads, -1, -1): + _thread_list[i].join(0) + if not _thread_list[i].is_alive(): + log_debug("Removing thread: %s" % _thread_list[i].name) + _thread_list.pop(i) + + time.sleep(3) + + +def background_execute(command, background_job): + + # Wrap this whole operation in an exception handler, otherwise if we + # hit a code bug we will silently exit this thread without anyone being + # the wiser. + try: + process = subprocess.Popen(command, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, close_fds=True) + lines_iterator = iter(process.stdout.readline, b"") + for line in lines_iterator: + line_str = line.decode("utf-8") + + # Check to see if the line has the correct number of separators + try: + if line_str.count(':') == 2: + (device, ignore, percentage) = line_str.split(':') + background_job.Percent = \ + round(float(percentage.strip()[:-1]), 1) + except ValueError: + log_error("Trying to parse percentage which failed for %s" % + line_str) + + out = process.communicate() + + if process.returncode == 0: + background_job.Percent = 100 + + background_job.set_result(process.returncode, out[1]) + + except Exception: + # In the unlikely event that we blow up, we need to unblock caller which + # is waiting on an answer. + st = traceback.format_exc() + error = "Exception in background thread: \n%s" % st + log_error(error) + background_job.set_result(1, error) + + +def add(command, reporting_job): + # Create the thread, get it running and then add it to the list + t = threading.Thread( + target=background_execute, + name="thread: " + ' '.join(command), + args=(command, reporting_job)) + t.start() + + with _rlock: + _thread_list.append(t) + + +def wait_thread(job, timeout, cb, cbe): + # We need to put the wait on it's own thread, so that we don't block the + # entire dbus queue processing thread + try: + cb(job.state.Wait(timeout)) + except Exception as e: + cbe("Wait exception: %s" % str(e)) + return 0 + + +def add_wait(job, timeout, cb, cbe): + + if timeout == 0: + # Users are basically polling, do not create thread + cb(job.Complete) + else: + t = threading.Thread( + target=wait_thread, + name="thread job.Wait: %s" % job.dbus_object_path(), + args=(job, timeout, cb, cbe) + ) + + t.start() + with _rlock: + _thread_list.append(t)
diff --git a/daemons/lvmdbusd/cfg.py b/daemons/lvmdbusd/cfg.py new file mode 100644 index 0000000..8aec8ae --- /dev/null +++ b/daemons/lvmdbusd/cfg.py
@@ -0,0 +1,83 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import os +import multiprocessing +import queue +import itertools +try: + from . import path +except SystemError: + import path + +LVM_CMD = os.getenv('LVM_BINARY', path.LVM_BINARY) + +# This is the global object manager +om = None + +# This is the global bus connection +bus = None + +# Shared state variable across all processes +run = multiprocessing.Value('i', 1) + +# Debug +DEBUG = True + +# Use lvm shell +USE_SHELL = False + +# Lock used by pprint +stdout_lock = multiprocessing.Lock() + +kick_q = multiprocessing.Queue() +worker_q = queue.Queue() + +# Main event loop +loop = None + +BASE_INTERFACE = 'com.redhat.lvmdbus1' +PV_INTERFACE = BASE_INTERFACE + '.Pv' +VG_INTERFACE = BASE_INTERFACE + '.Vg' +LV_INTERFACE = BASE_INTERFACE + '.Lv' +LV_COMMON_INTERFACE = BASE_INTERFACE + '.LvCommon' +THIN_POOL_INTERFACE = BASE_INTERFACE + '.ThinPool' +CACHE_POOL_INTERFACE = BASE_INTERFACE + '.CachePool' +LV_CACHED = BASE_INTERFACE + '.CachedLv' +SNAPSHOT_INTERFACE = BASE_INTERFACE + '.Snapshot' +MANAGER_INTERFACE = BASE_INTERFACE + '.Manager' +JOB_INTERFACE = BASE_INTERFACE + '.Job' + +BASE_OBJ_PATH = '/' + BASE_INTERFACE.replace('.', '/') +PV_OBJ_PATH = BASE_OBJ_PATH + '/Pv' +VG_OBJ_PATH = BASE_OBJ_PATH + '/Vg' +LV_OBJ_PATH = BASE_OBJ_PATH + '/Lv' +THIN_POOL_PATH = BASE_OBJ_PATH + "/ThinPool" +CACHE_POOL_PATH = BASE_OBJ_PATH + "/CachePool" +HIDDEN_LV_PATH = BASE_OBJ_PATH + "/HiddenLv" +MANAGER_OBJ_PATH = BASE_OBJ_PATH + '/Manager' +JOB_OBJ_PATH = BASE_OBJ_PATH + '/Job' + +# Counters for object path generation +pv_id = itertools.count() +vg_id = itertools.count() +lv_id = itertools.count() +thin_id = itertools.count() +cache_pool_id = itertools.count() +job_id = itertools.count() +hidden_lv = itertools.count() + +# Used to prevent circular imports... +load = None + +# Global cached state +db = None + +# lvm flight recorder +blackbox = None
diff --git a/daemons/lvmdbusd/cmdhandler.py b/daemons/lvmdbusd/cmdhandler.py new file mode 100644 index 0000000..fac582c --- /dev/null +++ b/daemons/lvmdbusd/cmdhandler.py
@@ -0,0 +1,724 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from subprocess import Popen, PIPE +import time +import threading +from itertools import chain +import collections + +try: + from . import cfg + from .utils import pv_dest_ranges, log_debug, log_error + from .lvm_shell_proxy import LVMShellProxy +except SystemError: + import cfg + from utils import pv_dest_ranges, log_debug, log_error + from lvm_shell_proxy import LVMShellProxy + +try: + import simplejson as json +except ImportError: + import json + +SEP = '{|}' + +total_time = 0.0 +total_count = 0 + +# We need to prevent different threads from using the same lvm shell +# at the same time. +cmd_lock = threading.RLock() + +# The actual method which gets called to invoke the lvm command, can vary +# from forking a new process to using lvm shell +_t_call = None + + +class LvmExecutionMeta(object): + + def __init__(self, start, ended, cmd, ec, stdout_txt, stderr_txt): + self.start = start + self.ended = ended + self.cmd = cmd + self.ec = ec + self.stdout_txt = stdout_txt + self.stderr_txt = stderr_txt + + def __str__(self): + return "EC= %d for %s\n" \ + "STARTED: %f, ENDED: %f\n" \ + "STDOUT=%s\n" \ + "STDERR=%s\n" % \ + (self.ec, str(self.cmd), self.start, self.ended, self.stdout_txt, + self.stderr_txt) + + +class LvmFlightRecorder(object): + + def __init__(self): + self.queue = collections.deque(maxlen=16) + + def add(self, lvm_exec_meta): + self.queue.append(lvm_exec_meta) + + def dump(self): + with cmd_lock: + log_error("LVM dbus flight recorder START") + for c in self.queue: + log_error(str(c)) + log_error("LVM dbus flight recorder END") + + +cfg.blackbox = LvmFlightRecorder() + + +def _debug_c(cmd, exit_code, out): + log_error('CMD= %s' % ' '.join(cmd)) + log_error(("EC= %d" % exit_code)) + log_error(("STDOUT=\n %s\n" % out[0])) + log_error(("STDERR=\n %s\n" % out[1])) + + +def call_lvm(command, debug=False): + """ + Call an executable and return a tuple of exitcode, stdout, stderr + :param command: Command to execute + :param debug: Dump debug to stdout + """ + # print 'STACK:' + # for line in traceback.format_stack(): + # print line.strip() + + # Prepend the full lvm executable so that we can run different versions + # in different locations on the same box + command.insert(0, cfg.LVM_CMD) + + process = Popen(command, stdout=PIPE, stderr=PIPE, close_fds=True) + out = process.communicate() + + stdout_text = bytes(out[0]).decode("utf-8") + stderr_text = bytes(out[1]).decode("utf-8") + + if debug or process.returncode != 0: + _debug_c(command, process.returncode, (stdout_text, stderr_text)) + + if process.returncode == 0: + if cfg.DEBUG and out[1] and len(out[1]) and 'help' not in command: + log_error('WARNING: lvm is out-putting text to STDERR on success!') + _debug_c(command, process.returncode, (stdout_text, stderr_text)) + + return process.returncode, stdout_text, stderr_text + + +def _shell_cfg(): + global _t_call + log_debug('Using lvm shell!') + lvm_shell = LVMShellProxy() + _t_call = lvm_shell.call_lvm + + +if cfg.USE_SHELL: + _shell_cfg() +else: + _t_call = call_lvm + + +def set_execution(shell): + global _t_call + with cmd_lock: + _t_call = None + if shell: + log_debug('Using lvm shell!') + lvm_shell = LVMShellProxy() + _t_call = lvm_shell.call_lvm + else: + _t_call = call_lvm + + +def time_wrapper(command, debug=False): + global total_time + global total_count + + with cmd_lock: + start = time.time() + results = _t_call(command, debug) + ended = time.time() + total_time += (ended - start) + total_count += 1 + cfg.blackbox.add(LvmExecutionMeta(start, ended, command, *results)) + return results + + +call = time_wrapper + + +# Default cmd +# Place default arguments for every command here. +def _dc(cmd, args): + c = [cmd, '--noheading', '--separator', '%s' % SEP, '--nosuffix', + '--unbuffered', '--units', 'b'] + c.extend(args) + return c + + +def parse(out): + rc = [] + + for line in out.split('\n'): + # This line includes separators, so process them + if SEP in line: + elem = line.split(SEP) + cleaned_elem = [] + for e in elem: + e = e.strip() + cleaned_elem.append(e) + + if len(cleaned_elem) > 1: + rc.append(cleaned_elem) + else: + t = line.strip() + if len(t) > 0: + rc.append(t) + return rc + + +def parse_column_names(out, column_names): + lines = parse(out) + rc = [] + + for i in range(0, len(lines)): + d = dict(list(zip(column_names, lines[i]))) + rc.append(d) + + return rc + + +def options_to_cli_args(options): + rc = [] + for k, v in list(dict(options).items()): + if k.startswith("-"): + rc.append(k) + else: + rc.append("--%s" % k) + if v != "": + rc.append(str(v)) + return rc + + +def pv_remove(device, remove_options): + cmd = ['pvremove'] + cmd.extend(options_to_cli_args(remove_options)) + cmd.append(device) + return call(cmd) + + +def _tag(operation, what, add, rm, tag_options): + cmd = [operation] + cmd.extend(options_to_cli_args(tag_options)) + + if isinstance(what, list): + cmd.extend(what) + else: + cmd.append(what) + + if add: + cmd.extend(list(chain.from_iterable(('--addtag', x) for x in add))) + if rm: + cmd.extend(list(chain.from_iterable(('--deltag', x) for x in rm))) + + return call(cmd, False) + + +def pv_tag(pv_devices, add, rm, tag_options): + return _tag('pvchange', pv_devices, add, rm, tag_options) + + +def vg_tag(vg_name, add, rm, tag_options): + return _tag('vgchange', vg_name, add, rm, tag_options) + + +def lv_tag(lv_name, add, rm, tag_options): + return _tag('lvchange', lv_name, add, rm, tag_options) + + +def vg_rename(vg, new_name, rename_options): + cmd = ['vgrename'] + cmd.extend(options_to_cli_args(rename_options)) + cmd.extend([vg, new_name]) + return call(cmd) + + +def vg_remove(vg_name, remove_options): + cmd = ['vgremove'] + cmd.extend(options_to_cli_args(remove_options)) + cmd.extend(['-f', vg_name]) + return call(cmd) + + +def vg_lv_create(vg_name, create_options, name, size_bytes, pv_dests): + cmd = ['lvcreate'] + cmd.extend(options_to_cli_args(create_options)) + cmd.extend(['--size', str(size_bytes) + 'B']) + cmd.extend(['--name', name, vg_name]) + pv_dest_ranges(cmd, pv_dests) + return call(cmd) + + +def vg_lv_snapshot(vg_name, snapshot_options, name, size_bytes): + cmd = ['lvcreate'] + cmd.extend(options_to_cli_args(snapshot_options)) + cmd.extend(["-s"]) + + if size_bytes != 0: + cmd.extend(['--size', str(size_bytes) + 'B']) + + cmd.extend(['--name', name, vg_name]) + return call(cmd) + + +def vg_lv_create_linear(vg_name, create_options, name, size_bytes, thin_pool): + cmd = ['lvcreate'] + cmd.extend(options_to_cli_args(create_options)) + + if not thin_pool: + cmd.extend(['--size', str(size_bytes) + 'B']) + else: + cmd.extend(['--thin', '--size', str(size_bytes) + 'B']) + cmd.extend(['--name', name, vg_name]) + return call(cmd) + + +def vg_lv_create_striped(vg_name, create_options, name, size_bytes, + num_stripes, stripe_size_kb, thin_pool): + cmd = ['lvcreate'] + cmd.extend(options_to_cli_args(create_options)) + + if not thin_pool: + cmd.extend(['--size', str(size_bytes) + 'B']) + else: + cmd.extend(['--thin', '--size', str(size_bytes) + 'B']) + + cmd.extend(['--stripes', str(num_stripes)]) + + if stripe_size_kb != 0: + cmd.extend(['--stripesize', str(stripe_size_kb)]) + + cmd.extend(['--name', name, vg_name]) + return call(cmd) + + +def _vg_lv_create_raid(vg_name, create_options, name, raid_type, size_bytes, + num_stripes, stripe_size_kb): + cmd = ['lvcreate'] + + cmd.extend(options_to_cli_args(create_options)) + + cmd.extend(['--type', raid_type]) + cmd.extend(['--size', str(size_bytes) + 'B']) + + if num_stripes != 0: + cmd.extend(['--stripes', str(num_stripes)]) + + if stripe_size_kb != 0: + cmd.extend(['--stripesize', str(stripe_size_kb)]) + + cmd.extend(['--name', name, vg_name]) + return call(cmd) + + +def vg_lv_create_raid(vg_name, create_options, name, raid_type, size_bytes, + num_stripes, stripe_size_kb): + cmd = ['lvcreate'] + cmd.extend(options_to_cli_args(create_options)) + + return _vg_lv_create_raid(vg_name, create_options, name, raid_type, + size_bytes, num_stripes, stripe_size_kb) + + +def vg_lv_create_mirror(vg_name, create_options, name, size_bytes, num_copies): + cmd = ['lvcreate'] + cmd.extend(options_to_cli_args(create_options)) + + cmd.extend(['--type', 'mirror']) + cmd.extend(['--mirrors', str(num_copies)]) + cmd.extend(['--size', str(size_bytes) + 'B']) + cmd.extend(['--name', name, vg_name]) + return call(cmd) + + +def vg_create_cache_pool(md_full_name, data_full_name, create_options): + cmd = ['lvconvert'] + cmd.extend(options_to_cli_args(create_options)) + cmd.extend(['--type', 'cache-pool', '--force', '-y', + '--poolmetadata', md_full_name, data_full_name]) + return call(cmd) + + +def vg_create_thin_pool(md_full_name, data_full_name, create_options): + cmd = ['lvconvert'] + cmd.extend(options_to_cli_args(create_options)) + cmd.extend(['--type', 'thin-pool', '--force', '-y', + '--poolmetadata', md_full_name, data_full_name]) + return call(cmd) + + +def lv_remove(lv_path, remove_options): + cmd = ['lvremove'] + cmd.extend(options_to_cli_args(remove_options)) + cmd.extend(['-f', lv_path]) + return call(cmd) + + +def lv_rename(lv_path, new_name, rename_options): + cmd = ['lvrename'] + cmd.extend(options_to_cli_args(rename_options)) + cmd.extend([lv_path, new_name]) + return call(cmd) + + +def lv_resize(lv_full_name, size_change, pv_dests, + resize_options): + cmd = ['lvresize', '--force'] + + cmd.extend(options_to_cli_args(resize_options)) + + if size_change < 0: + cmd.append("-L-%dB" % (-size_change)) + else: + cmd.append("-L+%dB" % (size_change)) + + cmd.append(lv_full_name) + pv_dest_ranges(cmd, pv_dests) + return call(cmd) + + +def lv_lv_create(lv_full_name, create_options, name, size_bytes): + cmd = ['lvcreate'] + cmd.extend(options_to_cli_args(create_options)) + cmd.extend(['--virtualsize', str(size_bytes) + 'B', '-T']) + cmd.extend(['--name', name, lv_full_name]) + return call(cmd) + + +def lv_cache_lv(cache_pool_full_name, lv_full_name, cache_options): + # lvconvert --type cache --cachepool VG/CachePoolLV VG/OriginLV + cmd = ['lvconvert'] + cmd.extend(options_to_cli_args(cache_options)) + cmd.extend(['-y', '--type', 'cache', '--cachepool', + cache_pool_full_name, lv_full_name]) + return call(cmd) + + +def lv_detach_cache(lv_full_name, detach_options, destroy_cache): + cmd = ['lvconvert'] + if destroy_cache: + option = '--uncache' + else: + # Currently fairly dangerous + # see: https://bugzilla.redhat.com/show_bug.cgi?id=1248972 + option = '--splitcache' + cmd.extend(options_to_cli_args(detach_options)) + # needed to prevent interactive questions + cmd.extend(["--yes", "--force"]) + cmd.extend([option, lv_full_name]) + return call(cmd) + + +def supports_json(): + cmd = ['help'] + rc, out, err = call(cmd) + if rc == 0: + if 'fullreport' in err: + return True + return False + + +def lvm_full_report_json(): + pv_columns = ['pv_name', 'pv_uuid', 'pv_fmt', 'pv_size', 'pv_free', + 'pv_used', 'dev_size', 'pv_mda_size', 'pv_mda_free', + 'pv_ba_start', 'pv_ba_size', 'pe_start', 'pv_pe_count', + 'pv_pe_alloc_count', 'pv_attr', 'pv_tags', 'vg_name', + 'vg_uuid'] + + pv_seg_columns = ['pvseg_start', 'pvseg_size', 'segtype', + 'pv_uuid', 'lv_uuid', 'pv_name'] + + vg_columns = ['vg_name', 'vg_uuid', 'vg_fmt', 'vg_size', 'vg_free', + 'vg_sysid', 'vg_extent_size', 'vg_extent_count', + 'vg_free_count', 'vg_profile', 'max_lv', 'max_pv', + 'pv_count', 'lv_count', 'snap_count', 'vg_seqno', + 'vg_mda_count', 'vg_mda_free', 'vg_mda_size', + 'vg_mda_used_count', 'vg_attr', 'vg_tags'] + + lv_columns = ['lv_uuid', 'lv_name', 'lv_path', 'lv_size', + 'vg_name', 'pool_lv_uuid', 'pool_lv', 'origin_uuid', + 'origin', 'data_percent', + 'lv_attr', 'lv_tags', 'vg_uuid', 'lv_active', 'data_lv', + 'metadata_lv', 'lv_parent', 'lv_role', 'lv_layout'] + + lv_seg_columns = ['seg_pe_ranges', 'segtype', 'lv_uuid'] + + cmd = _dc('fullreport', [ + '-a', # Need hidden too + '--configreport', 'pv', '-o', ','.join(pv_columns), + '--configreport', 'vg', '-o', ','.join(vg_columns), + '--configreport', 'lv', '-o', ','.join(lv_columns), + '--configreport', 'seg', '-o', ','.join(lv_seg_columns), + '--configreport', 'pvseg', '-o', ','.join(pv_seg_columns), + '--reportformat', 'json' + ]) + + rc, out, err = call(cmd) + if rc == 0: + return json.loads(out) + return None + + +def pv_retrieve_with_segs(device=None): + d = [] + err = "" + out = "" + rc = 0 + + columns = ['pv_name', 'pv_uuid', 'pv_fmt', 'pv_size', 'pv_free', + 'pv_used', 'dev_size', 'pv_mda_size', 'pv_mda_free', + 'pv_ba_start', 'pv_ba_size', 'pe_start', 'pv_pe_count', + 'pv_pe_alloc_count', 'pv_attr', 'pv_tags', 'vg_name', + 'vg_uuid', 'pvseg_start', 'pvseg_size', 'segtype'] + + # Lvm has some issues where it returns failure when querying pvs when other + # operations are in process, see: + # https://bugzilla.redhat.com/show_bug.cgi?id=1274085 + for i in range(0, 10): + cmd = _dc('pvs', ['-o', ','.join(columns)]) + + if device: + cmd.extend(device) + + rc, out, err = call(cmd) + + if rc == 0: + d = parse_column_names(out, columns) + break + else: + time.sleep(0.2) + log_debug("LVM Bug workaround, retrying pvs command...") + + if rc != 0: + msg = "We were unable to get pvs to return without error after " \ + "trying 10 times, RC=%d, STDERR=(%s), STDOUT=(%s)" % \ + (rc, err, out) + log_error(msg) + raise RuntimeError(msg) + + return d + + +def pv_resize(device, size_bytes, create_options): + cmd = ['pvresize'] + + cmd.extend(options_to_cli_args(create_options)) + + if size_bytes != 0: + cmd.extend(['--setphysicalvolumesize', str(size_bytes) + 'B']) + + cmd.extend([device]) + return call(cmd) + + +def pv_create(create_options, devices): + cmd = ['pvcreate', '-ff'] + cmd.extend(options_to_cli_args(create_options)) + cmd.extend(devices) + return call(cmd) + + +def pv_allocatable(device, yes, allocation_options): + yn = 'n' + + if yes: + yn = 'y' + + cmd = ['pvchange'] + cmd.extend(options_to_cli_args(allocation_options)) + cmd.extend(['-x', yn, device]) + return call(cmd) + + +def pv_scan(activate, cache, device_paths, major_minors, scan_options): + cmd = ['pvscan'] + cmd.extend(options_to_cli_args(scan_options)) + + if activate: + cmd.extend(['--activate', "ay"]) + + if cache: + cmd.append('--cache') + + if len(device_paths) > 0: + for d in device_paths: + cmd.append(d) + + if len(major_minors) > 0: + for mm in major_minors: + cmd.append("%s:%s" % (mm)) + + return call(cmd) + + +def vg_create(create_options, pv_devices, name): + cmd = ['vgcreate'] + cmd.extend(options_to_cli_args(create_options)) + cmd.append(name) + cmd.extend(pv_devices) + return call(cmd) + + +def vg_change(change_options, name): + cmd = ['vgchange'] + cmd.extend(options_to_cli_args(change_options)) + cmd.append(name) + return call(cmd) + + +def vg_reduce(vg_name, missing, pv_devices, reduce_options): + cmd = ['vgreduce'] + cmd.extend(options_to_cli_args(reduce_options)) + + if len(pv_devices) == 0: + cmd.append('--all') + if missing: + cmd.append('--removemissing') + + cmd.append(vg_name) + cmd.extend(pv_devices) + return call(cmd) + + +def vg_extend(vg_name, extend_devices, extend_options): + cmd = ['vgextend'] + cmd.extend(options_to_cli_args(extend_options)) + cmd.append(vg_name) + cmd.extend(extend_devices) + return call(cmd) + + +def _vg_value_set(name, arguments, options): + cmd = ['vgchange'] + cmd.extend(options_to_cli_args(options)) + cmd.append(name) + cmd.extend(arguments) + return call(cmd) + + +def vg_allocation_policy(vg_name, policy, policy_options): + return _vg_value_set(vg_name, ['--alloc', policy], policy_options) + + +def vg_max_pv(vg_name, number, max_options): + return _vg_value_set(vg_name, ['--maxphysicalvolumes', str(number)], + max_options) + + +def vg_max_lv(vg_name, number, max_options): + return _vg_value_set(vg_name, ['-l', str(number)], max_options) + + +def vg_uuid_gen(vg_name, ignore, options): + assert ignore is None + return _vg_value_set(vg_name, ['--uuid'], options) + + +def activate_deactivate(op, name, activate, control_flags, options): + cmd = [op] + cmd.extend(options_to_cli_args(options)) + + op = '-a' + + if control_flags: + # Autoactivation + if (1 << 0) & control_flags: + op += 'a' + # Exclusive locking (Cluster) + if (1 << 1) & control_flags: + op += 'e' + + # Local node activation + if (1 << 2) & control_flags: + op += 'l' + + # Activation modes + if (1 << 3) & control_flags: + cmd.extend(['--activationmode', 'complete']) + elif (1 << 4) & control_flags: + cmd.extend(['--activationmode', 'partial']) + + # Ignore activation skip + if (1 << 5) & control_flags: + cmd.append('--ignoreactivationskip') + + if activate: + op += 'y' + else: + op += 'n' + + cmd.append(op) + cmd.append(name) + return call(cmd) + + +def vg_retrieve(vg_specific): + if vg_specific: + assert isinstance(vg_specific, list) + + columns = ['vg_name', 'vg_uuid', 'vg_fmt', 'vg_size', 'vg_free', + 'vg_sysid', 'vg_extent_size', 'vg_extent_count', + 'vg_free_count', 'vg_profile', 'max_lv', 'max_pv', + 'pv_count', 'lv_count', 'snap_count', 'vg_seqno', + 'vg_mda_count', 'vg_mda_free', 'vg_mda_size', + 'vg_mda_used_count', 'vg_attr', 'vg_tags'] + + cmd = _dc('vgs', ['-o', ','.join(columns)]) + + if vg_specific: + cmd.extend(vg_specific) + + d = [] + rc, out, err = call(cmd) + if rc == 0: + d = parse_column_names(out, columns) + + return d + + +def lv_retrieve_with_segments(): + columns = ['lv_uuid', 'lv_name', 'lv_path', 'lv_size', + 'vg_name', 'pool_lv_uuid', 'pool_lv', 'origin_uuid', + 'origin', 'data_percent', + 'lv_attr', 'lv_tags', 'vg_uuid', 'lv_active', 'data_lv', + 'metadata_lv', 'seg_pe_ranges', 'segtype', 'lv_parent', + 'lv_role', 'lv_layout'] + + cmd = _dc('lvs', ['-a', '-o', ','.join(columns)]) + rc, out, err = call(cmd) + + d = [] + + if rc == 0: + d = parse_column_names(out, columns) + + return d + + +if __name__ == '__main__': + pv_data = pv_retrieve_with_segs() + + for p in pv_data: + log_debug(str(p))
diff --git a/daemons/lvmdbusd/fetch.py b/daemons/lvmdbusd/fetch.py new file mode 100644 index 0000000..51f130f --- /dev/null +++ b/daemons/lvmdbusd/fetch.py
@@ -0,0 +1,30 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from .pv import load_pvs +from .vg import load_vgs +from .lv import load_lvs +from . import cfg + + +def load(refresh=True, emit_signal=True, cache_refresh=True, log=True): + num_total_changes = 0 + + # Go through and load all the PVs, VGs and LVs + if cache_refresh: + cfg.db.refresh(log) + + num_total_changes += load_pvs(refresh=refresh, emit_signal=emit_signal, + cache_refresh=False)[1] + num_total_changes += load_vgs(refresh=refresh, emit_signal=emit_signal, + cache_refresh=False)[1] + num_total_changes += load_lvs(refresh=refresh, emit_signal=emit_signal, + cache_refresh=False)[1] + + return num_total_changes
diff --git a/daemons/lvmdbusd/job.py b/daemons/lvmdbusd/job.py new file mode 100644 index 0000000..520f9a8 --- /dev/null +++ b/daemons/lvmdbusd/job.py
@@ -0,0 +1,172 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from .automatedproperties import AutomatedProperties +from .utils import job_obj_path_generate +from . import cfg +from .cfg import JOB_INTERFACE +import dbus +import threading +from . import background + + +# noinspection PyPep8Naming +class JobState(object): + def __init__(self, request=None): + self.rlock = threading.RLock() + + self._percent = 0 + self._complete = False + self._request = request + self._cond = threading.Condition(self.rlock) + self._ec = 0 + self._stderr = '' + + # This is an lvm command that is just taking too long and doesn't + # support background operation + if self._request: + # Faking the percentage when we don't have one + self._percent = 1 + + @property + def Percent(self): + with self.rlock: + return self._percent + + @Percent.setter + def Percent(self, value): + with self.rlock: + self._percent = value + + @property + def Complete(self): + with self.rlock: + if self._request: + self._complete = self._request.is_done() + if self._complete: + self._percent = 100 + + return self._complete + + @Complete.setter + def Complete(self, value): + with self.rlock: + self._complete = value + self._cond.notify_all() + + @property + def GetError(self): + with self.rlock: + if self.Complete: + if self._request: + (rc, error) = self._request.get_errors() + return (rc, str(error)) + else: + return (self._ec, self._stderr) + else: + return (-1, 'Job is not complete!') + + def set_result(self, ec, msg): + with self.rlock: + self.Complete = True + self._ec = ec + self._stderr = msg + + def dtor(self): + with self.rlock: + self._request = None + + def Wait(self, timeout): + try: + with self._cond: + # Check to see if we are done, before we wait + if not self.Complete: + if timeout != -1: + self._cond.wait(timeout) + else: + self._cond.wait() + return self.Complete + except RuntimeError: + return False + + @property + def Result(self): + with self.rlock: + if self._request: + return self._request.result() + return '/' + + +# noinspection PyPep8Naming +class Job(AutomatedProperties): + _Percent_meta = ('y', JOB_INTERFACE) + _Complete_meta = ('b', JOB_INTERFACE) + _Result_meta = ('o', JOB_INTERFACE) + _GetError_meta = ('(is)', JOB_INTERFACE) + + def __init__(self, request, job_state=None): + super(Job, self).__init__(job_obj_path_generate()) + self.set_interface(JOB_INTERFACE) + + if job_state: + self.state = job_state + else: + self.state = JobState(request) + + @property + def Percent(self): + return self.state.Percent + + @Percent.setter + def Percent(self, value): + self.state.Percent = value + + @property + def Complete(self): + return self.state.Complete + + @Complete.setter + def Complete(self, value): + self.state.Complete = value + + @property + def GetError(self): + return self.state.GetError + + def set_result(self, ec, msg): + self.state.set_result(ec, msg) + + @dbus.service.method(dbus_interface=JOB_INTERFACE) + def Remove(self): + if self.state.Complete: + cfg.om.remove_object(self, True) + self.state.dtor() + else: + raise dbus.exceptions.DBusException( + JOB_INTERFACE, 'Job is not complete!') + + @dbus.service.method(dbus_interface=JOB_INTERFACE, + in_signature='i', + out_signature='b', + async_callbacks=('cb', 'cbe')) + def Wait(self, timeout, cb, cbe): + background.add_wait(self, timeout, cb, cbe) + + @property + def Result(self): + return self.state.Result + + @property + def lvm_id(self): + return str(id(self)) + + @property + def Uuid(self): + import uuid + return uuid.uuid1()
diff --git a/daemons/lvmdbusd/loader.py b/daemons/lvmdbusd/loader.py new file mode 100644 index 0000000..f0462ef --- /dev/null +++ b/daemons/lvmdbusd/loader.py
@@ -0,0 +1,85 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from . import cfg + + +def _compare_construction(o_state, new_state): + # We need to check to see if the objects would get constructed + # the same + existing_ctor, existing_path = o_state.creation_signature() + new_ctor, new_path = new_state.creation_signature() + + # print("%s == %s and %s == %s" % (str(existing_ctor), str(new_ctor), + # str(existing_path), str(new_path))) + + return ((existing_ctor == new_ctor) and (existing_path == new_path)) + + +def common(retrieve, o_type, search_keys, + object_path, refresh, emit_signal, cache_refresh): + num_changes = 0 + existing_paths = [] + rc = [] + + if search_keys: + assert isinstance(search_keys, list) + + if cache_refresh: + cfg.db.refresh() + + objects = retrieve(search_keys, cache_refresh=False) + + # If we are doing a refresh we need to know what we have in memory, what's + # in lvm and add those that are new and remove those that are gone! + if refresh: + existing_paths = cfg.om.object_paths_by_type(o_type) + + for o in objects: + # Assume we need to add this one to dbus, unless we are refreshing + # and it's already present + return_object = True + + if refresh: + # We are refreshing all the PVs from LVM, if this one exists + # we need to refresh our state. + dbus_object = cfg.om.get_object_by_uuid_lvm_id(*o.identifiers()) + + if dbus_object: + del existing_paths[dbus_object.dbus_object_path()] + + # If the old object state and new object state wouldn't be + # created with the same path and same object constructor we + # need to remove the old object and construct the new one + # instead! + if not _compare_construction(dbus_object.state, o): + # Remove existing and construct new one + cfg.om.remove_object(dbus_object, emit_signal) + dbus_object = o.create_dbus_object(None) + cfg.om.register_object(dbus_object, emit_signal) + num_changes += 1 + else: + num_changes += dbus_object.refresh(object_state=o) + return_object = False + + if return_object: + dbus_object = o.create_dbus_object(object_path) + cfg.om.register_object(dbus_object, emit_signal) + rc.append(dbus_object) + + object_path = None + + if refresh: + for k in list(existing_paths.keys()): + cfg.om.remove_object(cfg.om.get_object_by_path(k), True) + num_changes += 1 + + num_changes += len(rc) + + return rc, num_changes
diff --git a/daemons/lvmdbusd/lv.py b/daemons/lvmdbusd/lv.py new file mode 100644 index 0000000..5658d29 --- /dev/null +++ b/daemons/lvmdbusd/lv.py
@@ -0,0 +1,893 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from .automatedproperties import AutomatedProperties + +from . import utils +from .utils import vg_obj_path_generate +import dbus +from . import cmdhandler +from . import cfg +from .cfg import LV_INTERFACE, THIN_POOL_INTERFACE, SNAPSHOT_INTERFACE, \ + LV_COMMON_INTERFACE, CACHE_POOL_INTERFACE, LV_CACHED +from .request import RequestEntry +from .utils import n, n32 +from .loader import common +from .state import State +from . import background +from .utils import round_size +from .job import JobState + + +# Try and build a key for a LV, so that we sort the LVs with least dependencies +# first. This may be error prone because of the flexibility LVM +# provides and what you can stack. +def get_key(i): + + name = i['lv_name'] + parent = i['lv_parent'] + pool = i['pool_lv'] + a1 = "" + a2 = "" + + if name[0] == '[': + a1 = '#' + + # We have a parent + if parent: + # Check if parent is hidden + if parent[0] == '[': + a2 = '##' + else: + a2 = '#' + + # If a LV has a pool, then it should be sorted/loaded after the pool + # lv, unless it's a hidden too, then after other hidden, but before visible + if pool: + if pool[0] != '[': + a2 += '~' + else: + a1 = '$' + a1 + + return "%s%s%s" % (a1, a2, name) + + +# noinspection PyUnusedLocal +def lvs_state_retrieve(selection, cache_refresh=True): + rc = [] + + if cache_refresh: + cfg.db.refresh() + + # When building up the model, it's best to process LVs with the least + # dependencies to those that are dependant upon other LVs. Otherwise, when + # we are trying to gather information we could be in a position where we + # don't have information available yet. + lvs = sorted(cfg.db.fetch_lvs(selection), key=get_key) + + for l in lvs: + rc.append(LvState( + l['lv_uuid'], l['lv_name'], + l['lv_path'], n(l['lv_size']), + l['vg_name'], + l['vg_uuid'], l['pool_lv_uuid'], + l['pool_lv'], l['origin_uuid'], l['origin'], + n32(l['data_percent']), l['lv_attr'], + l['lv_tags'], l['lv_active'], l['data_lv'], + l['metadata_lv'], l['segtype'], l['lv_role'], + l['lv_layout'])) + return rc + + +def load_lvs(lv_name=None, object_path=None, refresh=False, emit_signal=False, + cache_refresh=True): + # noinspection PyUnresolvedReferences + return common( + lvs_state_retrieve, + (LvCommon, Lv, LvThinPool, LvSnapShot), + lv_name, object_path, refresh, emit_signal, cache_refresh) + + +# noinspection PyPep8Naming,PyUnresolvedReferences,PyUnusedLocal +class LvState(State): + @staticmethod + def _pv_devices(uuid): + rc = [] + for pv in sorted(cfg.db.lv_contained_pv(uuid)): + (pv_uuid, pv_name, pv_segs) = pv + pv_obj = cfg.om.get_object_path_by_uuid_lvm_id( + pv_uuid, pv_name, gen_new=False) + rc.append((pv_obj, pv_segs)) + + return dbus.Array(rc, signature="(oa(tts))") + + def vg_name_lookup(self): + return cfg.om.get_object_by_path(self.Vg).Name + + @property + def lvm_id(self): + return "%s/%s" % (self.vg_name_lookup(), self.Name) + + def identifiers(self): + return (self.Uuid, self.lvm_id) + + def _get_hidden_lv(self): + rc = dbus.Array([], "o") + + vg_name = self.vg_name_lookup() + + for l in cfg.db.hidden_lvs(self.Uuid): + full_name = "%s/%s" % (vg_name, l[1]) + op = cfg.om.get_object_path_by_uuid_lvm_id( + l[0], full_name, gen_new=False) + assert op + rc.append(op) + return rc + + def __init__(self, Uuid, Name, Path, SizeBytes, + vg_name, vg_uuid, pool_lv_uuid, PoolLv, + origin_uuid, OriginLv, DataPercent, Attr, Tags, active, + data_lv, metadata_lv, segtypes, role, layout): + utils.init_class_from_arguments(self) + + # The segtypes is possibly an array with potentially dupes or a single + # value + self._segs = dbus.Array([], signature='s') + if not isinstance(segtypes, list): + self._segs.append(segtypes) + else: + self._segs.extend(set(segtypes)) + + self.Vg = cfg.om.get_object_path_by_uuid_lvm_id( + vg_uuid, vg_name, vg_obj_path_generate) + + self.Devices = LvState._pv_devices(self.Uuid) + + if PoolLv: + gen = utils.lv_object_path_method(Name, (Attr, layout, role)) + + self.PoolLv = cfg.om.get_object_path_by_uuid_lvm_id( + pool_lv_uuid, '%s/%s' % (vg_name, PoolLv), + gen) + else: + self.PoolLv = '/' + + if OriginLv: + self.OriginLv = \ + cfg.om.get_object_path_by_uuid_lvm_id( + origin_uuid, '%s/%s' % (vg_name, OriginLv), + vg_obj_path_generate) + else: + self.OriginLv = '/' + + self.HiddenLvs = self._get_hidden_lv() + + @property + def SegType(self): + return self._segs + + def _object_path_create(self): + return utils.lv_object_path_method( + self.Name, (self.Attr, self.layout, self.role)) + + def _object_type_create(self): + if self.Attr[0] == 't': + return LvThinPool + elif self.Attr[0] == 'C': + if 'pool' in self.layout: + return LvCachePool + else: + return LvCacheLv + elif self.Name[0] == '[': + return LvCommon + elif self.OriginLv != '/': + return LvSnapShot + else: + return Lv + + def create_dbus_object(self, path): + if not path: + path = cfg.om.get_object_path_by_uuid_lvm_id( + self.Uuid, self.lvm_id, self._object_path_create()) + + obj_ctor = self._object_type_create() + return obj_ctor(path, self) + + def creation_signature(self): + klass = self._object_type_create() + path_method = self._object_path_create() + return (klass, path_method) + + +# noinspection PyPep8Naming +@utils.dbus_property(LV_COMMON_INTERFACE, 'Uuid', 's') +@utils.dbus_property(LV_COMMON_INTERFACE, 'Name', 's') +@utils.dbus_property(LV_COMMON_INTERFACE, 'Path', 's') +@utils.dbus_property(LV_COMMON_INTERFACE, 'SizeBytes', 't') +@utils.dbus_property(LV_COMMON_INTERFACE, 'DataPercent', 'u') +@utils.dbus_property(LV_COMMON_INTERFACE, 'SegType', 'as') +@utils.dbus_property(LV_COMMON_INTERFACE, 'Vg', 'o') +@utils.dbus_property(LV_COMMON_INTERFACE, 'OriginLv', 'o') +@utils.dbus_property(LV_COMMON_INTERFACE, 'PoolLv', 'o') +@utils.dbus_property(LV_COMMON_INTERFACE, 'Devices', "a(oa(tts))") +@utils.dbus_property(LV_COMMON_INTERFACE, 'HiddenLvs', "ao") +class LvCommon(AutomatedProperties): + _Tags_meta = ("as", LV_COMMON_INTERFACE) + _Roles_meta = ("as", LV_COMMON_INTERFACE) + _IsThinVolume_meta = ("b", LV_COMMON_INTERFACE) + _IsThinPool_meta = ("b", LV_COMMON_INTERFACE) + _Active_meta = ("b", LV_COMMON_INTERFACE) + _VolumeType_meta = ("(ss)", LV_COMMON_INTERFACE) + _Permissions_meta = ("(ss)", LV_COMMON_INTERFACE) + _AllocationPolicy_meta = ("(ss)", LV_COMMON_INTERFACE) + _State_meta = ("(ss)", LV_COMMON_INTERFACE) + _TargetType_meta = ("(ss)", LV_COMMON_INTERFACE) + _Health_meta = ("(ss)", LV_COMMON_INTERFACE) + _FixedMinor_meta = ('b', LV_COMMON_INTERFACE) + _ZeroBlocks_meta = ('b', LV_COMMON_INTERFACE) + _SkipActivation_meta = ('b', LV_COMMON_INTERFACE) + + # noinspection PyUnusedLocal,PyPep8Naming + def __init__(self, object_path, object_state): + super(LvCommon, self).__init__(object_path, lvs_state_retrieve) + self.set_interface(LV_COMMON_INTERFACE) + self.state = object_state + + @property + def VolumeType(self): + type_map = {'C': 'Cache', 'm': 'mirrored', + 'M': 'Mirrored without initial sync', 'o': 'origin', + 'O': 'Origin with merging snapshot', 'r': 'raid', + 'R': 'Raid without initial sync', 's': 'snapshot', + 'S': 'merging Snapshot', 'p': 'pvmove', + 'v': 'virtual', 'i': 'mirror or raid image', + 'I': 'mirror or raid Image out-of-sync', + 'l': 'mirror log device', 'c': 'under conversion', + 'V': 'thin Volume', 't': 'thin pool', 'T': 'Thin pool data', + 'e': 'raid or pool metadata or pool metadata spare', + '-': 'Unspecified'} + return (self.state.Attr[0], type_map[self.state.Attr[0]]) + + @property + def Permissions(self): + type_map = {'w': 'writable', 'r': 'read-only', + 'R': 'Read-only activation of non-read-only volume', + '-': 'Unspecified'} + return (self.state.Attr[1], type_map[self.state.Attr[1]]) + + @property + def AllocationPolicy(self): + type_map = {'a': 'anywhere', 'A': 'anywhere locked', + 'c': 'contiguous', 'C': 'contiguous locked', + 'i': 'inherited', 'I': 'inherited locked', + 'l': 'cling', 'L': 'cling locked', + 'n': 'normal', 'N': 'normal locked', '-': 'Unspecified'} + return (self.state.Attr[2], type_map[self.state.Attr[2]]) + + @property + def FixedMinor(self): + return self.state.Attr[3] == 'm' + + @property + def State(self): + type_map = {'a': 'active', 's': 'suspended', 'I': 'Invalid snapshot', + 'S': 'invalid Suspended snapshot', + 'm': 'snapshot merge failed', + 'M': 'suspended snapshot (M)erge failed', + 'd': 'mapped device present without tables', + 'i': 'mapped device present with inactive table', + 'X': 'unknown', '-': 'Unspecified'} + return (self.state.Attr[4], type_map[self.state.Attr[4]]) + + @property + def TargetType(self): + type_map = {'C': 'Cache', 'm': 'mirror', 'r': 'raid', + 's': 'snapshot', 't': 'thin', 'u': 'unknown', + 'v': 'virtual', '-': 'Unspecified'} + return (self.state.Attr[6], type_map[self.state.Attr[6]]) + + @property + def ZeroBlocks(self): + return self.state.Attr[7] == 'z' + + @property + def Health(self): + type_map = {'p': 'partial', 'r': 'refresh', + 'm': 'mismatches', 'w': 'writemostly', + 'X': 'X unknown', '-': 'Unspecified'} + return (self.state.Attr[8], type_map[self.state.Attr[8]]) + + @property + def SkipActivation(self): + return self.state.Attr[9] == 'k' + + def vg_name_lookup(self): + return self.state.vg_name_lookup() + + def lv_full_name(self): + return "%s/%s" % (self.state.vg_name_lookup(), self.state.Name) + + @property + def identifiers(self): + return self.state.identifiers + + @property + def Tags(self): + return utils.parse_tags(self.state.Tags) + + @property + def Roles(self): + return utils.parse_tags(self.state.role) + + @property + def lvm_id(self): + return self.state.lvm_id + + @property + def IsThinVolume(self): + return self.state.Attr[0] == 'V' + + @property + def IsThinPool(self): + return self.state.Attr[0] == 't' + + @property + def Active(self): + return self.state.active == "active" + + @dbus.service.method( + dbus_interface=LV_COMMON_INTERFACE, + in_signature='ia{sv}', + out_signature='o') + def _Future(self, tmo, open_options): + raise dbus.exceptions.DBusException(LV_COMMON_INTERFACE, 'Do not use!') + + +# noinspection PyPep8Naming +class Lv(LvCommon): + def _fetch_hidden(self, name): + + # The name is vg/name + full_name = "%s/%s" % (self.vg_name_lookup(), name) + return cfg.om.get_object_path_by_lvm_id(full_name) + + def _get_data_meta(self): + + # Get the data + return (self._fetch_hidden(self.state.data_lv), + self._fetch_hidden(self.state.metadata_lv)) + + # noinspection PyUnusedLocal,PyPep8Naming + def __init__(self, object_path, object_state): + super(Lv, self).__init__(object_path, object_state) + self.set_interface(LV_INTERFACE) + self.state = object_state + + @staticmethod + def _remove(lv_uuid, lv_name, remove_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + + if dbo: + # Remove the LV, if successful then remove from the model + rc, out, err = cmdhandler.lv_remove(lv_name, remove_options) + + if rc == 0: + cfg.om.remove_object(dbo, True) + cfg.load() + else: + # Need to work on error handling, need consistent + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (lv_uuid, lv_name)) + return '/' + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Remove(self, tmo, remove_options, cb, cbe): + r = RequestEntry( + tmo, Lv._remove, + (self.Uuid, self.lvm_id, remove_options), + cb, cbe, False) + cfg.worker_q.put(r) + + @staticmethod + def _rename(lv_uuid, lv_name, new_name, rename_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + + if dbo: + # Rename the logical volume + rc, out, err = cmdhandler.lv_rename(lv_name, new_name, + rename_options) + if rc == 0: + cfg.load() + else: + # Need to work on error handling, need consistent + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (lv_uuid, lv_name)) + return '/' + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='sia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Rename(self, name, tmo, rename_options, cb, cbe): + utils.validate_lv_name(LV_INTERFACE, self.vg_name_lookup(), name) + + r = RequestEntry( + tmo, Lv._rename, + (self.Uuid, self.lvm_id, name, rename_options), + cb, cbe, False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='o(tt)a(ott)ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Move(self, pv_src_obj, pv_source_range, + pv_dests_and_ranges, + tmo, move_options, cb, cbe): + + job_state = JobState() + + r = RequestEntry( + tmo, background.move, + (LV_INTERFACE, self.lvm_id, pv_src_obj, pv_source_range, + pv_dests_and_ranges, move_options, job_state), cb, cbe, False, + job_state) + + cfg.worker_q.put(r) + + @staticmethod + def _snap_shot(lv_uuid, lv_name, name, optional_size, + snapshot_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + + if dbo: + # If you specify a size you get a 'thick' snapshot even if + # it is a thin lv + if not dbo.IsThinVolume: + if optional_size == 0: + space = dbo.SizeBytes / 80 + remainder = space % 512 + optional_size = space + 512 - remainder + + rc, out, err = cmdhandler.vg_lv_snapshot( + lv_name, snapshot_options, name, optional_size) + if rc == 0: + return_path = '/' + full_name = "%s/%s" % (dbo.vg_name_lookup(), name) + lvs = load_lvs([full_name], emit_signal=True)[0] + for l in lvs: + return_path = l.dbus_object_path() + + # Refresh self and all included PVs + cfg.load(cache_refresh=False) + return return_path + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (lv_uuid, lv_name)) + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='stia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def Snapshot(self, name, optional_size, tmo, + snapshot_options, cb, cbe): + + utils.validate_lv_name(LV_INTERFACE, self.vg_name_lookup(), name) + + r = RequestEntry( + tmo, Lv._snap_shot, + (self.Uuid, self.lvm_id, name, + optional_size, snapshot_options), cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _resize(lv_uuid, lv_name, new_size_bytes, pv_dests_and_ranges, + resize_options): + # Make sure we have a dbus object representing it + pv_dests = [] + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + + if dbo: + # If we have PVs, verify them + if len(pv_dests_and_ranges): + for pr in pv_dests_and_ranges: + pv_dbus_obj = cfg.om.get_object_by_path(pr[0]) + if not pv_dbus_obj: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'PV Destination (%s) not found' % pr[0]) + + pv_dests.append((pv_dbus_obj.lvm_id, pr[1], pr[2])) + + size_change = new_size_bytes - dbo.SizeBytes + + rc, out, err = cmdhandler.lv_resize(dbo.lvm_id, size_change, + pv_dests, resize_options) + + if rc == 0: + # Refresh what's changed + cfg.load() + return "/" + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (lv_uuid, lv_name)) + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='ta(ott)ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Resize(self, new_size_bytes, pv_dests_and_ranges, tmo, + resize_options, cb, cbe): + """ + Resize a LV + :param new_size_bytes: The requested final size in bytes + :param pv_dests_and_ranges: An array of pv object paths and src & + dst. segment ranges + :param tmo: -1 to wait forever, 0 to return job immediately, else + number of seconds to wait for operation to complete + before getting a job + :param resize_options: key/value hash of options + :param cb: Used by framework not client facing API + :param cbe: Used by framework not client facing API + :return: '/' if complete, else job object path + """ + r = RequestEntry( + tmo, Lv._resize, + (self.Uuid, self.lvm_id, round_size(new_size_bytes), + pv_dests_and_ranges, + resize_options), cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @staticmethod + def _lv_activate_deactivate(uuid, lv_name, activate, control_flags, + options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, lv_name) + + if dbo: + rc, out, err = cmdhandler.activate_deactivate( + 'lvchange', lv_name, activate, control_flags, options) + if rc == 0: + dbo.refresh() + return '/' + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (uuid, lv_name)) + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='tia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Activate(self, control_flags, tmo, activate_options, cb, cbe): + r = RequestEntry( + tmo, Lv._lv_activate_deactivate, + (self.state.Uuid, self.state.lvm_id, True, + control_flags, activate_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + # noinspection PyProtectedMember + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='tia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Deactivate(self, control_flags, tmo, activate_options, cb, cbe): + r = RequestEntry( + tmo, Lv._lv_activate_deactivate, + (self.state.Uuid, self.state.lvm_id, False, + control_flags, activate_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @staticmethod + def _add_rm_tags(uuid, lv_name, tags_add, tags_del, tag_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, lv_name) + + if dbo: + + rc, out, err = cmdhandler.lv_tag( + lv_name, tags_add, tags_del, tag_options) + if rc == 0: + dbo.refresh() + return '/' + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (uuid, lv_name)) + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='asia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def TagsAdd(self, tags, tmo, tag_options, cb, cbe): + + for t in tags: + utils.validate_tag(LV_INTERFACE, t) + + r = RequestEntry( + tmo, Lv._add_rm_tags, + (self.state.Uuid, self.state.lvm_id, + tags, None, tag_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=LV_INTERFACE, + in_signature='asia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def TagsDel(self, tags, tmo, tag_options, cb, cbe): + + for t in tags: + utils.validate_tag(LV_INTERFACE, t) + + r = RequestEntry( + tmo, Lv._add_rm_tags, + (self.state.Uuid, self.state.lvm_id, + None, tags, tag_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + +# noinspection PyPep8Naming +class LvThinPool(Lv): + _DataLv_meta = ("o", THIN_POOL_INTERFACE) + _MetaDataLv_meta = ("o", THIN_POOL_INTERFACE) + + def __init__(self, object_path, object_state): + super(LvThinPool, self).__init__(object_path, object_state) + self.set_interface(THIN_POOL_INTERFACE) + self._data_lv, self._metadata_lv = self._get_data_meta() + + @property + def DataLv(self): + return self._data_lv + + @property + def MetaDataLv(self): + return self._metadata_lv + + @staticmethod + def _lv_create(lv_uuid, lv_name, name, size_bytes, create_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + + lv_created = '/' + + if dbo: + rc, out, err = cmdhandler.lv_lv_create( + lv_name, create_options, name, size_bytes) + if rc == 0: + full_name = "%s/%s" % (dbo.vg_name_lookup(), name) + lvs = load_lvs([full_name], emit_signal=True)[0] + for l in lvs: + lv_created = l.dbus_object_path() + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (lv_uuid, lv_name)) + return lv_created + + @dbus.service.method( + dbus_interface=THIN_POOL_INTERFACE, + in_signature='stia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def LvCreate(self, name, size_bytes, tmo, create_options, cb, cbe): + utils.validate_lv_name(THIN_POOL_INTERFACE, self.vg_name_lookup(), name) + + r = RequestEntry( + tmo, LvThinPool._lv_create, + (self.Uuid, self.lvm_id, name, + round_size(size_bytes), create_options), cb, cbe) + cfg.worker_q.put(r) + + +# noinspection PyPep8Naming +class LvCachePool(Lv): + _DataLv_meta = ("o", CACHE_POOL_INTERFACE) + _MetaDataLv_meta = ("o", CACHE_POOL_INTERFACE) + + def __init__(self, object_path, object_state): + super(LvCachePool, self).__init__(object_path, object_state) + self.set_interface(CACHE_POOL_INTERFACE) + self._data_lv, self._metadata_lv = self._get_data_meta() + + @property + def DataLv(self): + return self._data_lv + + @property + def MetaDataLv(self): + return self._metadata_lv + + @staticmethod + def _cache_lv(lv_uuid, lv_name, lv_object_path, cache_options): + + # Make sure we have a dbus object representing cache pool + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + + # Make sure we have dbus object representing lv to cache + lv_to_cache = cfg.om.get_object_by_path(lv_object_path) + + if dbo and lv_to_cache: + fcn = lv_to_cache.lv_full_name() + rc, out, err = cmdhandler.lv_cache_lv( + dbo.lv_full_name(), fcn, cache_options) + if rc == 0: + # When we cache an LV, the cache pool and the lv that is getting + # cached need to be removed from the object manager and + # re-created as their interfaces have changed! + cfg.om.remove_object(dbo, emit_signal=True) + cfg.om.remove_object(lv_to_cache, emit_signal=True) + cfg.load() + + lv_converted = cfg.om.get_object_path_by_lvm_id(fcn) + + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + msg = "" + if not dbo: + dbo += 'CachePool LV with uuid %s and name %s not present!' % \ + (lv_uuid, lv_name) + + if not lv_to_cache: + dbo += 'LV to cache with object path %s not present!' % \ + (lv_object_path) + + raise dbus.exceptions.DBusException(LV_INTERFACE, msg) + return lv_converted + + @dbus.service.method( + dbus_interface=CACHE_POOL_INTERFACE, + in_signature='oia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def CacheLv(self, lv_object, tmo, cache_options, cb, cbe): + r = RequestEntry( + tmo, LvCachePool._cache_lv, + (self.Uuid, self.lvm_id, lv_object, + cache_options), cb, cbe) + cfg.worker_q.put(r) + + +# noinspection PyPep8Naming +class LvCacheLv(Lv): + _CachePool_meta = ("o", LV_CACHED) + + def __init__(self, object_path, object_state): + super(LvCacheLv, self).__init__(object_path, object_state) + self.set_interface(LV_CACHED) + + @property + def CachePool(self): + return self.state.PoolLv + + @staticmethod + def _detach_lv(lv_uuid, lv_name, detach_options, destroy_cache): + # Make sure we have a dbus object representing cache pool + dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name) + + if dbo: + + # Get current cache name + cache_pool = cfg.om.get_object_by_path(dbo.CachePool) + + rc, out, err = cmdhandler.lv_detach_cache( + dbo.lv_full_name(), detach_options, destroy_cache) + if rc == 0: + # The cache pool gets removed as hidden and put back to + # visible, so lets delete + cfg.om.remove_object(cache_pool, emit_signal=True) + cfg.om.remove_object(dbo, emit_signal=True) + cfg.load() + + uncached_lv_path = cfg.om.get_object_path_by_lvm_id(lv_name) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + LV_INTERFACE, + 'LV with uuid %s and name %s not present!' % + (lv_uuid, lv_name)) + return uncached_lv_path + + @dbus.service.method( + dbus_interface=LV_CACHED, + in_signature='bia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def DetachCachePool(self, destroy_cache, tmo, detach_options, cb, cbe): + r = RequestEntry( + tmo, LvCacheLv._detach_lv, + (self.Uuid, self.lvm_id, detach_options, + destroy_cache), cb, cbe) + cfg.worker_q.put(r) + + +# noinspection PyPep8Naming +class LvSnapShot(Lv): + def __init__(self, object_path, object_state): + super(LvSnapShot, self).__init__(object_path, object_state) + self.set_interface(SNAPSHOT_INTERFACE) + + @dbus.service.method( + dbus_interface=SNAPSHOT_INTERFACE, + in_signature='ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Merge(self, tmo, merge_options, cb, cbe): + job_state = JobState() + + r = RequestEntry(tmo, background.merge, + (SNAPSHOT_INTERFACE, self.Uuid, self.lvm_id, + merge_options, job_state), cb, cbe, False, + job_state) + cfg.worker_q.put(r)
diff --git a/daemons/lvmdbusd/lvm_shell_proxy.py b/daemons/lvmdbusd/lvm_shell_proxy.py new file mode 100755 index 0000000..3835c74 --- /dev/null +++ b/daemons/lvmdbusd/lvm_shell_proxy.py
@@ -0,0 +1,184 @@ +#!/usr/bin/env python3 + +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +# Copyright 2015-2016, Vratislav Podzimek <vpodzime@redhat.com> + +import subprocess +import shlex +from fcntl import fcntl, F_GETFL, F_SETFL +from os import O_NONBLOCK +import traceback +import sys +import re + +try: + from .cfg import LVM_CMD + from .utils import log_debug, log_error +except: + from cfg import LVM_CMD + from utils import log_debug, log_error + +SHELL_PROMPT = "lvm> " + + +def _quote_arg(arg): + if len(shlex.split(arg)) > 1: + return '"%s"' % arg + else: + return arg + + +class LVMShellProxy(object): + def _read_until_prompt(self): + prev_ec = None + stdout = "" + while not stdout.endswith(SHELL_PROMPT): + try: + tmp = self.lvm_shell.stdout.read() + if tmp: + stdout += tmp.decode("utf-8") + except IOError: + # nothing written yet + pass + + # strip the prompt from the STDOUT before returning and grab the exit + # code if it's available + m = self.re.match(stdout) + if m: + prev_ec = int(m.group(2)) + strip_idx = -1 * len(m.group(1)) + else: + strip_idx = -1 * len(SHELL_PROMPT) + + return stdout[:strip_idx], prev_ec + + def _read_line(self): + while True: + try: + tmp = self.lvm_shell.stdout.readline() + if tmp: + return tmp.decode("utf-8") + except IOError: + pass + + def _discard_echo(self, expected): + line = "" + while line != expected: + # GNU readline inserts some interesting characters at times... + line += self._read_line().replace(' \r', '') + + def _write_cmd(self, cmd): + cmd_bytes = bytes(cmd, "utf-8") + num_written = self.lvm_shell.stdin.write(cmd_bytes) + assert (num_written == len(cmd_bytes)) + self.lvm_shell.stdin.flush() + + def _lvm_echos(self): + echo = False + cmd = "version\n" + self._write_cmd(cmd) + line = self._read_line() + + if line == cmd: + echo = True + + self._read_until_prompt() + + return echo + + def __init__(self): + self.re = re.compile(".*(\[(-?[0-9]+)\] lvm> $)", re.DOTALL) + + # run the lvm shell + self.lvm_shell = subprocess.Popen( + [LVM_CMD], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, close_fds=True) + flags = fcntl(self.lvm_shell.stdout, F_GETFL) + fcntl(self.lvm_shell.stdout, F_SETFL, flags | O_NONBLOCK) + flags = fcntl(self.lvm_shell.stderr, F_GETFL) + fcntl(self.lvm_shell.stderr, F_SETFL, flags | O_NONBLOCK) + + # wait for the first prompt + self._read_until_prompt() + + # Check to see if the version of LVM we are using is running with + # gnu readline which will echo our writes from stdin to stdout + self.echo = self._lvm_echos() + + def call_lvm(self, argv, debug=False): + # create the command string + cmd = " ".join(_quote_arg(arg) for arg in argv) + cmd += "\n" + + # run the command by writing it to the shell's STDIN + self._write_cmd(cmd) + + # If lvm is utilizing gnu readline, it echos stdin to stdout + if self.echo: + self._discard_echo(cmd) + + # read everything from the STDOUT to the next prompt + stdout, exit_code = self._read_until_prompt() + + # read everything from STDERR if there's something (we waited for the + # prompt on STDOUT so there should be all or nothing at this point on + # STDERR) + stderr = None + try: + t_error = self.lvm_shell.stderr.read() + if t_error: + stderr = t_error.decode("utf-8") + except IOError: + # nothing on STDERR + pass + + if exit_code is not None: + rc = exit_code + else: + # LVM does write to stderr even when it did complete successfully, + # so without having the exit code in the prompt we can never be + # sure. + if stderr: + rc = 1 + else: + rc = 0 + + if debug or rc != 0: + log_error(('CMD: %s' % cmd)) + log_error(("EC = %d" % rc)) + log_error(("STDOUT=\n %s\n" % stdout)) + log_error(("STDERR=\n %s\n" % stderr)) + + return (rc, stdout, stderr) + + def __del__(self): + self.lvm_shell.terminate() + + +if __name__ == "__main__": + shell = LVMShellProxy() + in_line = "start" + try: + while in_line: + in_line = input("lvm> ") + if in_line: + ret, out, err, = shell.call_lvm(in_line.split()) + print(("RET: %d" % ret)) + print(("OUT:\n%s" % out)) + print(("ERR:\n%s" % err)) + except KeyboardInterrupt: + pass + except EOFError: + pass + except Exception: + traceback.print_exc(file=sys.stdout) + finally: + print()
diff --git a/daemons/lvmdbusd/lvmdb.py b/daemons/lvmdbusd/lvmdb.py new file mode 100755 index 0000000..2dc593b --- /dev/null +++ b/daemons/lvmdbusd/lvmdb.py
@@ -0,0 +1,544 @@ +#!/usr/bin/env python3 + +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from collections import OrderedDict + +import pprint as prettyprint +import os +import sys + +try: + from . import cmdhandler + from .utils import log_debug, log_error +except SystemError: + import cmdhandler + from utils import log_debug + + +class DataStore(object): + def __init__(self, usejson=None): + self.pvs = {} + self.vgs = {} + self.lvs = {} + self.pv_lvs = {} + self.lv_pvs = {} + self.lvs_hidden = {} + + self.pv_path_to_uuid = {} + self.vg_name_to_uuid = {} + self.lv_full_name_to_uuid = {} + + self.lvs_in_vgs = {} + self.pvs_in_vgs = {} + + # self.refresh() + self.num_refreshes = 0 + + if usejson is None: + self.json = cmdhandler.supports_json() + else: + self.json = usejson + + @staticmethod + def _insert_record(table, key, record, allowed_multiple): + if key in table: + existing = table[key] + + for rec_k, rec_v in record.items(): + if rec_k in allowed_multiple: + # This column name allows us to store multiple value for + # each type + if not isinstance(existing[rec_k], list): + existing_value = existing[rec_k] + existing[rec_k] = [existing_value, rec_v] + else: + existing[rec_k].append(rec_v) + else: + # If something is not expected to have changing values + # lets ensure that + if existing[rec_k] != rec_v: + raise RuntimeError( + "existing[%s]=%s != %s" % + (rec_k, str(existing[rec_k]), + str(rec_v))) + else: + table[key] = record + + @staticmethod + def _parse_pvs(_pvs): + pvs = sorted(_pvs, key=lambda pk: pk['pv_name']) + + c_pvs = OrderedDict() + c_lookup = {} + c_pvs_in_vgs = {} + + for p in pvs: + DataStore._insert_record( + c_pvs, p['pv_uuid'], p, + ['pvseg_start', 'pvseg_size', 'segtype']) + + for p in c_pvs.values(): + # Capture which PVs are associated with which VG + if p['vg_uuid'] not in c_pvs_in_vgs: + c_pvs_in_vgs[p['vg_uuid']] = [] + + if p['vg_name']: + c_pvs_in_vgs[p['vg_uuid']].append( + (p['pv_name'], p['pv_uuid'])) + + # Lookup for translating between /dev/<name> and pv uuid + c_lookup[p['pv_name']] = p['pv_uuid'] + + return c_pvs, c_lookup, c_pvs_in_vgs + + @staticmethod + def _parse_pvs_json(_all): + + c_pvs = OrderedDict() + c_lookup = {} + c_pvs_in_vgs = {} + + # Each item item in the report is a collection of information pertaining + # to the vg + for r in _all['report']: + tmp_pv = [] + + # Get the pv data for this VG. + if 'pv' in r: + tmp_pv.extend(r['pv']) + + # Sort them + sorted_tmp_pv = sorted(tmp_pv, key=lambda pk: pk['pv_name']) + + # Add them to result set + for p in sorted_tmp_pv: + c_pvs[p['pv_uuid']] = p + + if 'pvseg' in r: + for s in r['pvseg']: + r = c_pvs[s['pv_uuid']] + r.setdefault('pvseg_start', []).append(s['pvseg_start']) + r.setdefault('pvseg_size', []).append(s['pvseg_size']) + r.setdefault('segtype', []).append(s['segtype']) + + # TODO: Remove this bug work around when we have orphan segs. + for i in c_pvs.values(): + if 'pvseg_start' not in i: + i['pvseg_start'] = '0' + i['pvseg_size'] = i['pv_pe_count'] + i['segtype'] = 'free' + + for p in c_pvs.values(): + # Capture which PVs are associated with which VG + if p['vg_uuid'] not in c_pvs_in_vgs: + c_pvs_in_vgs[p['vg_uuid']] = [] + + if p['vg_name']: + c_pvs_in_vgs[p['vg_uuid']].append( + (p['pv_name'], p['pv_uuid'])) + + # Lookup for translating between /dev/<name> and pv uuid + c_lookup[p['pv_name']] = p['pv_uuid'] + + return c_pvs, c_lookup, c_pvs_in_vgs + + @staticmethod + def _parse_vgs(_vgs): + vgs = sorted(_vgs, key=lambda vk: vk['vg_name']) + + c_vgs = OrderedDict() + c_lookup = {} + + for i in vgs: + c_lookup[i['vg_name']] = i['vg_uuid'] + DataStore._insert_record(c_vgs, i['vg_uuid'], i, []) + + return c_vgs, c_lookup + + @staticmethod + def _parse_vgs_json(_all): + + tmp_vg = [] + for r in _all['report']: + # Get the pv data for this VG. + if 'vg' in r: + tmp_vg.extend(r['vg']) + + # Sort for consistent output, however this is optional + vgs = sorted(tmp_vg, key=lambda vk: vk['vg_name']) + + c_vgs = OrderedDict() + c_lookup = {} + + for i in vgs: + c_lookup[i['vg_name']] = i['vg_uuid'] + c_vgs[i['vg_uuid']] = i + + return c_vgs, c_lookup + + @staticmethod + def _parse_lvs_common(c_lvs, c_lv_full_lookup): + + c_lvs_in_vgs = OrderedDict() + c_lvs_hidden = OrderedDict() + + for i in c_lvs.values(): + if i['vg_uuid'] not in c_lvs_in_vgs: + c_lvs_in_vgs[i['vg_uuid']] = [] + + c_lvs_in_vgs[ + i['vg_uuid']].append( + (i['lv_name'], + (i['lv_attr'], i['lv_layout'], i['lv_role']), + i['lv_uuid'])) + + if i['lv_parent']: + # Lookup what the parent refers too + parent_name = i['lv_parent'] + full_parent_name = "%s/%s" % (i['vg_name'], parent_name) + if full_parent_name not in c_lv_full_lookup: + parent_name = '[%s]' % (parent_name) + full_parent_name = "%s/%s" % (i['vg_name'], parent_name) + + parent_uuid = c_lv_full_lookup[full_parent_name] + + if parent_uuid not in c_lvs_hidden: + c_lvs_hidden[parent_uuid] = [] + + c_lvs_hidden[parent_uuid].append( + (i['lv_uuid'], i['lv_name'])) + + return c_lvs, c_lvs_in_vgs, c_lvs_hidden, c_lv_full_lookup + + @staticmethod + def _parse_lvs(_lvs): + lvs = sorted(_lvs, key=lambda vk: vk['lv_name']) + + c_lvs = OrderedDict() + c_lv_full_lookup = OrderedDict() + + for i in lvs: + full_name = "%s/%s" % (i['vg_name'], i['lv_name']) + c_lv_full_lookup[full_name] = i['lv_uuid'] + DataStore._insert_record( + c_lvs, i['lv_uuid'], i, + ['seg_pe_ranges', 'segtype']) + + return DataStore._parse_lvs_common(c_lvs, c_lv_full_lookup) + + @staticmethod + def _parse_lvs_json(_all): + + c_lvs = OrderedDict() + c_lv_full_lookup = {} + + # Each item item in the report is a collection of information pertaining + # to the vg + for r in _all['report']: + # Get the lv data for this VG. + if 'lv' in r: + # Add them to result set + for i in r['lv']: + full_name = "%s/%s" % (i['vg_name'], i['lv_name']) + c_lv_full_lookup[full_name] = i['lv_uuid'] + c_lvs[i['lv_uuid']] = i + + # Add in the segment data + if 'seg' in r: + for s in r['seg']: + r = c_lvs[s['lv_uuid']] + r.setdefault('seg_pe_ranges', []).append(s['seg_pe_ranges']) + r.setdefault('segtype', []).append(s['segtype']) + + return DataStore._parse_lvs_common(c_lvs, c_lv_full_lookup) + + @staticmethod + def _make_list(l): + if not isinstance(l, list): + l = [l] + return l + + @staticmethod + def _parse_seg_entry(se, segtype): + if se: + # print("_parse_seg_entry %s %s" % (str(se), str(segtype))) + device, segs = se.split(":") + start, end = segs.split('-') + return (device, (start, end), segtype) + else: + return ("", (), segtype) + + @staticmethod + def _build_segments(l, seg_types): + rc = [] + l = DataStore._make_list(l) + s = DataStore._make_list(seg_types) + + assert len(l) == len(s) + ls = list(zip(l, s)) + + for i in ls: + if ' ' in i[0]: + tmp = i[0].split(' ') + for t in tmp: + rc.append(DataStore._parse_seg_entry(t, i[1])) + else: + rc.append(DataStore._parse_seg_entry(*i)) + return rc + + @staticmethod + def _pv_device_lv_entry(table, pv_device, lv_uuid, meta, lv_attr, + segment_info): + + if pv_device not in table: + table[pv_device] = {} + + if lv_uuid not in table[pv_device]: + table[pv_device][lv_uuid] = {} + table[pv_device][lv_uuid]['segs'] = [segment_info] + table[pv_device][lv_uuid]['name'] = meta + table[pv_device][lv_uuid]['meta'] = lv_attr + else: + table[pv_device][lv_uuid]['segs'].append(segment_info) + + @staticmethod + def _pv_device_lv_format(pv_device_lvs): + rc = {} + + for pv_device, pd in pv_device_lvs.items(): + lvs = [] + for lv_uuid, ld in sorted(pd.items()): + lvs.append((lv_uuid, ld['name'], ld['meta'], ld['segs'])) + + rc[pv_device] = lvs + return rc + + @staticmethod + def _lvs_device_pv_entry(table, lv_uuid, pv_device, pv_uuid, segment_info): + if lv_uuid not in table: + table[lv_uuid] = {} + + if pv_device not in table[lv_uuid]: + table[lv_uuid][pv_device] = {} + table[lv_uuid][pv_device]['segs'] = [segment_info] + table[lv_uuid][pv_device]['pv_uuid'] = pv_uuid + else: + table[lv_uuid][pv_device]['segs'].append(segment_info) + + @staticmethod + def _lvs_device_pv_format(lvs_device_pvs): + rc = {} + + for lv_uuid, ld in lvs_device_pvs.items(): + pvs = [] + for pv_device, pd in sorted(ld.items()): + pvs.append((pd['pv_uuid'], pv_device, pd['segs'])) + + rc[lv_uuid] = pvs + return rc + + def _parse_pv_in_lvs(self): + pv_device_lvs = {} # What LVs are stored on a PV + lvs_device_pv = {} # Where LV data is stored + + for i in self.lvs.values(): + segs = self._build_segments(i['seg_pe_ranges'], i['segtype']) + for s in segs: + # We are referring to physical device + if '/dev/' in s[0]: + device, r, seg_type = s + + DataStore._pv_device_lv_entry( + pv_device_lvs, device, i['lv_uuid'], i['lv_name'], + (i['lv_attr'], i['lv_layout'], i['lv_role']), + (r[0], r[1], seg_type)) + + # (pv_name, pv_segs, pv_uuid) + DataStore._lvs_device_pv_entry( + lvs_device_pv, i['lv_uuid'], device, + self.pv_path_to_uuid[device], (r[0], r[1], seg_type)) + else: + # TODO Handle the case where the segments refer to a LV + # and not a PV + pass + # print("Handle this %s %s %s" % (s[0], s[1], s[2])) + + # Convert form to needed result for consumption + pv_device_lvs_result = DataStore._pv_device_lv_format(pv_device_lvs) + lvs_device_pv_result = DataStore._lvs_device_pv_format(lvs_device_pv) + + return pv_device_lvs_result, lvs_device_pv_result + + def refresh(self, log=True): + """ + Go out and query lvm for the latest data in as few trips as possible + :param log Add debug log entry/exit messages + :return: None + """ + self.num_refreshes += 1 + if log: + log_debug("lvmdb - refresh entry") + + # Grab everything first then parse it + if self.json: + # Do a single lvm retrieve for everything in json + a = cmdhandler.lvm_full_report_json() + + _pvs, _pvs_lookup, _pvs_in_vgs = self._parse_pvs_json(a) + _vgs, _vgs_lookup = self._parse_vgs_json(a) + _lvs, _lvs_in_vgs, _lvs_hidden, _lvs_lookup = self._parse_lvs_json(a) + + else: + _raw_pvs = cmdhandler.pv_retrieve_with_segs() + _raw_vgs = cmdhandler.vg_retrieve(None) + _raw_lvs = cmdhandler.lv_retrieve_with_segments() + + _pvs, _pvs_lookup, _pvs_in_vgs = self._parse_pvs(_raw_pvs) + _vgs, _vgs_lookup = self._parse_vgs(_raw_vgs) + _lvs, _lvs_in_vgs, _lvs_hidden, _lvs_lookup = self._parse_lvs(_raw_lvs) + + # Set all + self.pvs = _pvs + self.pv_path_to_uuid = _pvs_lookup + self.vg_name_to_uuid = _vgs_lookup + self.lv_full_name_to_uuid = _lvs_lookup + + self.vgs = _vgs + self.lvs = _lvs + self.lvs_in_vgs = _lvs_in_vgs + self.pvs_in_vgs = _pvs_in_vgs + self.lvs_hidden = _lvs_hidden + + # Create lookup table for which LV and segments are on each PV + self.pv_lvs, self.lv_pvs = self._parse_pv_in_lvs() + + if log: + log_debug("lvmdb - refresh exit") + + def fetch_pvs(self, pv_name): + if not pv_name: + return self.pvs.values() + else: + rc = [] + for s in pv_name: + # Ths user could be using a symlink instead of the actual + # block device, make sure we are using actual block device file + # if the pv name isn't in the lookup + if s not in self.pv_path_to_uuid: + s = os.path.realpath(s) + rc.append(self.pvs[self.pv_path_to_uuid[s]]) + return rc + + def fetch_vgs(self, vg_name): + if not vg_name: + return self.vgs.values() + else: + rc = [] + for s in vg_name: + rc.append(self.vgs[self.vg_name_to_uuid[s]]) + return rc + + def fetch_lvs(self, lv_names): + try: + if not lv_names: + return self.lvs.values() + else: + rc = [] + for s in lv_names: + rc.append(self.lvs[self.lv_full_name_to_uuid[s]]) + return rc + except KeyError as ke: + log_error("Key %s not found!" % (str(lv_names))) + log_error("lv name to uuid lookup") + for keys in sorted(self.lv_full_name_to_uuid.keys()): + log_error("%s" % (keys)) + log_error("lvs entries by uuid") + for keys in sorted(self.lvs.keys()): + log_error("%s" % (keys)) + raise ke + + def pv_pe_segments(self, pv_uuid): + pv = self.pvs[pv_uuid] + return list(zip(pv['pvseg_start'], pv['pvseg_size'])) + + def pv_contained_lv(self, pv_device): + rc = [] + if pv_device in self.pv_lvs: + rc = self.pv_lvs[pv_device] + return rc + + def lv_contained_pv(self, lv_uuid): + rc = [] + if lv_uuid in self.lv_pvs: + rc = self.lv_pvs[lv_uuid] + return rc + + def lvs_in_vg(self, vg_uuid): + # Return an array of + # (lv_name, (lv_attr, lv_layout, lv_role), lv_uuid) + rc = [] + if vg_uuid in self.lvs_in_vgs: + rc = self.lvs_in_vgs[vg_uuid] + return rc + + def pvs_in_vg(self, vg_uuid): + # Returns an array of (pv_name, pv_uuid) + rc = [] + if vg_uuid in self.pvs_in_vgs: + rc = self.pvs_in_vgs[vg_uuid] + return rc + + def hidden_lvs(self, lv_uuid): + # For a specified LV, return a list of hidden lv_uuid, lv_name + # for it + rc = [] + if lv_uuid in self.lvs_hidden: + rc = self.lvs_hidden[lv_uuid] + return rc + + +if __name__ == "__main__": + pp = prettyprint.PrettyPrinter(indent=4) + + use_json = False + + if len(sys.argv) != 1: + print(len(sys.argv)) + use_json = True + + ds = DataStore(use_json) + ds.refresh() + + print("PVS") + for v in ds.pvs.values(): + pp.pprint(v) + + print("VGS") + for v in ds.vgs.values(): + pp.pprint(v) + + print("LVS") + for v in ds.lvs.values(): + pp.pprint(v) + + print("LVS in VG") + for k, v in ds.lvs_in_vgs.items(): + print("VG uuid = %s" % (k)) + pp.pprint(v) + + print("pv_in_lvs") + for k, v in ds.pv_lvs.items(): + print("PV %s contains LVS:" % (k)) + pp.pprint(v) + + for k, v in ds.lv_pvs.items(): + print("LV device = %s" % (k)) + pp.pprint(v)
diff --git a/daemons/lvmdbusd/lvmdbusd b/daemons/lvmdbusd/lvmdbusd new file mode 100755 index 0000000..7ea243b --- /dev/null +++ b/daemons/lvmdbusd/lvmdbusd
@@ -0,0 +1,16 @@ +#!/usr/bin/env python3 + +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import sys +import lvmdbusd + +if __name__ == '__main__': + sys.exit(lvmdbusd.main())
diff --git a/daemons/lvmdbusd/main.py b/daemons/lvmdbusd/main.py new file mode 100644 index 0000000..f28b402 --- /dev/null +++ b/daemons/lvmdbusd/main.py
@@ -0,0 +1,182 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from . import cfg +from . import objectmanager +from . import utils +from .cfg import BASE_INTERFACE, BASE_OBJ_PATH, MANAGER_OBJ_PATH +import threading +from . import cmdhandler +import time +import signal +import dbus +from . import lvmdb +# noinspection PyUnresolvedReferences +from gi.repository import GLib +from .fetch import load +from .manager import Manager +from .background import background_reaper +import traceback +import queue +from . import udevwatch +from .utils import log_debug +import argparse +import os +from .refresh import handle_external_event, event_complete + + +class Lvm(objectmanager.ObjectManager): + def __init__(self, object_path): + super(Lvm, self).__init__(object_path, BASE_INTERFACE) + + +def _discard_pending_refreshes(): + # We just handled a refresh, if we have any in the queue they can be + # removed because by definition they are older than the refresh we just did. + # As we limit the number of refreshes getting into the queue + # we should only ever have one to remove. + requests = [] + while not cfg.worker_q.empty(): + try: + r = cfg.worker_q.get(block=False) + if r.method != handle_external_event: + requests.append(r) + else: + # Make sure we make this event complete even though it didn't + # run, otherwise no other events will get processed + event_complete() + break + except queue.Empty: + break + + # Any requests we removed, but did not discard need to be re-queued + for r in requests: + cfg.worker_q.put(r) + + +def process_request(): + while cfg.run.value != 0: + try: + req = cfg.worker_q.get(True, 5) + + start = cfg.db.num_refreshes + + log_debug( + "Running method: %s with args %s" % + (str(req.method), str(req.arguments))) + req.run_cmd() + + end = cfg.db.num_refreshes + + num_refreshes = end - start + + if num_refreshes > 0: + _discard_pending_refreshes() + + if num_refreshes > 1: + log_debug( + "Inspect method %s for too many refreshes" % + (str(req.method))) + log_debug("Complete ") + except queue.Empty: + pass + except Exception: + st = traceback.format_exc() + utils.log_error("process_request exception: \n%s" % st) + + +def main(): + # Add simple command line handling + parser = argparse.ArgumentParser() + parser.add_argument("--udev", action='store_true', + help="Use udev for updating state", default=False, + dest='use_udev') + parser.add_argument("--debug", action='store_true', + help="Dump debug messages", default=False, + dest='debug') + + parser.add_argument("--nojson", action='store_false', + help="Do not use LVM JSON output", default=None, + dest='use_json') + + use_session = os.getenv('LVMDBUSD_USE_SESSION', False) + + # Ensure that we get consistent output for parsing stdout/stderr + os.environ["LC_ALL"] = "C" + + args = parser.parse_args() + + cfg.DEBUG = args.debug + + # List of threads that we start up + thread_list = [] + + start = time.time() + + # Install signal handlers + for s in [signal.SIGHUP, signal.SIGINT]: + try: + signal.signal(s, utils.handler) + except RuntimeError: + pass + + dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + dbus.mainloop.glib.threads_init() + + if use_session: + cfg.bus = dbus.SessionBus() + else: + cfg.bus = dbus.SystemBus() + # The base name variable needs to exist for things to work. + # noinspection PyUnusedLocal + base_name = dbus.service.BusName(BASE_INTERFACE, cfg.bus) + cfg.om = Lvm(BASE_OBJ_PATH) + cfg.om.register_object(Manager(MANAGER_OBJ_PATH)) + + cfg.load = load + + cfg.db = lvmdb.DataStore(args.use_json) + + # Start up thread to monitor pv moves + thread_list.append( + threading.Thread(target=background_reaper, name="pv_move_reaper")) + + # Using a thread to process requests. + thread_list.append(threading.Thread(target=process_request)) + + cfg.load(refresh=False, emit_signal=False) + cfg.loop = GLib.MainLoop() + + for process in thread_list: + process.damon = True + process.start() + + end = time.time() + log_debug( + 'Service ready! total time= %.2f, lvm time= %.2f count= %d' % + (end - start, cmdhandler.total_time, cmdhandler.total_count), + 'bg_black', 'fg_light_green') + + # Add udev watching + if args.use_udev: + log_debug('Utilizing udev to trigger updates') + udevwatch.add() + + try: + if cfg.run.value != 0: + cfg.loop.run() + + if args.use_udev: + udevwatch.remove() + + for process in thread_list: + process.join() + except KeyboardInterrupt: + utils.handler(signal.SIGINT, None) + return 0
diff --git a/daemons/lvmdbusd/manager.py b/daemons/lvmdbusd/manager.py new file mode 100644 index 0000000..2388d8a --- /dev/null +++ b/daemons/lvmdbusd/manager.py
@@ -0,0 +1,246 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from .automatedproperties import AutomatedProperties + +from . import utils +from .cfg import MANAGER_INTERFACE +import dbus +from . import cfg +from . import cmdhandler +from .fetch import load_pvs, load_vgs +from .request import RequestEntry +from .refresh import event_add + + +# noinspection PyPep8Naming +class Manager(AutomatedProperties): + _Version_meta = ("t", MANAGER_INTERFACE) + + def __init__(self, object_path): + super(Manager, self).__init__(object_path) + self.set_interface(MANAGER_INTERFACE) + + @property + def Version(self): + return '1.0.0' + + @staticmethod + def _pv_create(device, create_options): + + # Check to see if we are already trying to create a PV for an existing + # PV + pv = cfg.om.get_object_path_by_uuid_lvm_id( + device, device, None, False) + if pv: + raise dbus.exceptions.DBusException( + MANAGER_INTERFACE, "PV Already exists!") + + created_pv = [] + rc, out, err = cmdhandler.pv_create(create_options, [device]) + if rc == 0: + pvs = load_pvs([device], emit_signal=True)[0] + for p in pvs: + created_pv = p.dbus_object_path() + else: + raise dbus.exceptions.DBusException( + MANAGER_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + return created_pv + + @dbus.service.method( + dbus_interface=MANAGER_INTERFACE, + in_signature='sia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def PvCreate(self, device, tmo, create_options, cb, cbe): + utils.validate_device_path(MANAGER_INTERFACE, device) + r = RequestEntry( + tmo, Manager._pv_create, + (device, create_options), cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _create_vg(name, pv_object_paths, create_options): + pv_devices = [] + + for p in pv_object_paths: + pv = cfg.om.get_object_by_path(p) + if pv: + pv_devices.append(pv.Name) + else: + raise dbus.exceptions.DBusException( + MANAGER_INTERFACE, 'object path = %s not found' % p) + + rc, out, err = cmdhandler.vg_create(create_options, pv_devices, name) + created_vg = "/" + + if rc == 0: + vgs = load_vgs([name], emit_signal=True)[0] + for v in vgs: + created_vg = v.dbus_object_path() + + # Update the PVS + load_pvs(refresh=True, emit_signal=True, cache_refresh=False) + else: + raise dbus.exceptions.DBusException( + MANAGER_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + return created_vg + + @dbus.service.method( + dbus_interface=MANAGER_INTERFACE, + in_signature='saoia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def VgCreate(self, name, pv_object_paths, tmo, create_options, cb, cbe): + utils.validate_vg_name(MANAGER_INTERFACE, name) + r = RequestEntry( + tmo, Manager._create_vg, + (name, pv_object_paths, create_options,), + cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _refresh(): + utils.log_debug('Manager.Refresh - entry') + + # This is a diagnostic and should not be run in normal operation, so + # lets remove the log entries for refresh as it's implied. + rc = cfg.load(log=False) + + if rc != 0: + utils.log_debug('Manager.Refresh - exit %d' % (rc), + 'bg_black', 'fg_light_red') + else: + utils.log_debug('Manager.Refresh - exit %d' % (rc)) + return rc + + @dbus.service.method( + dbus_interface=MANAGER_INTERFACE, + out_signature='t', + async_callbacks=('cb', 'cbe')) + def Refresh(self, cb, cbe): + """ + Take all the objects we know about and go out and grab the latest + more of a test method at the moment to make sure we are handling object + paths correctly. + + :param cb Callback for result + :param cbe Callback for errors + + Returns the number of changes, object add/remove/properties changed + """ + r = RequestEntry(-1, Manager._refresh, (), cb, cbe, False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=MANAGER_INTERFACE, + in_signature='s', + out_signature='o') + def LookUpByLvmId(self, key): + """ + Given a lvm id in one of the forms: + + /dev/sda + some_vg + some_vg/some_lv + Oe1rPX-Pf0W-15E5-n41N-ZmtF-jXS0-Osg8fn + + return the object path in O(1) time. + + :param key: The lookup value + :return: Return the object path. If object not found you will get '/' + """ + p = cfg.om.get_object_path_by_uuid_lvm_id( + key, key, gen_new=False) + if p: + return p + return '/' + + @dbus.service.method( + dbus_interface=MANAGER_INTERFACE, + in_signature='b') + def UseLvmShell(self, yes_no): + """ + Allow the client to enable/disable lvm shell, used for testing + :param yes_no: + :return: Nothing + """ + cmdhandler.set_execution(yes_no) + + @dbus.service.method( + dbus_interface=MANAGER_INTERFACE, + in_signature='s', out_signature='i') + def ExternalEvent(self, command): + + event_add((command,)) + return dbus.Int32(0) + + @staticmethod + def _pv_scan(activate, cache, device_path, major_minor, scan_options): + + rc, out, err = cmdhandler.pv_scan( + activate, cache, device_path, + major_minor, scan_options) + + if rc == 0: + # This could potentially change the state quite a bit, so lets + # update everything to be safe + cfg.load() + return '/' + else: + raise dbus.exceptions.DBusException( + MANAGER_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + @dbus.service.method( + dbus_interface=MANAGER_INTERFACE, + in_signature='bbasa(ii)ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def PvScan(self, activate, cache, device_paths, major_minors, + tmo, scan_options, cb, cbe): + """ + Scan all supported LVM block devices in the system for physical volumes + NOTE: major_minors & device_paths only usable when cache == True + :param activate: If True, activate any newly found LVs + :param cache: If True, update lvmetad + :param device_paths: Array of device paths or empty + :param major_minors: Array of structures (major,minor) + :param tmo: Timeout for operation + :param scan_options: Additional options to pvscan + :param cb: Not visible in API (used for async. callback) + :param cbe: Not visible in API (used for async. error callback) + :return: '/' if operation done, else job path + """ + for d in device_paths: + utils.validate_device_path(MANAGER_INTERFACE, d) + + r = RequestEntry( + tmo, Manager._pv_scan, + (activate, cache, device_paths, major_minors, + scan_options), cb, cbe, False) + cfg.worker_q.put(r) + + @property + def lvm_id(self): + """ + Intended to be overridden by classes that inherit + """ + return str(id(self)) + + @property + def Uuid(self): + """ + Intended to be overridden by classes that inherit + """ + import uuid + return uuid.uuid1()
diff --git a/daemons/lvmdbusd/objectmanager.py b/daemons/lvmdbusd/objectmanager.py new file mode 100644 index 0000000..178003e --- /dev/null +++ b/daemons/lvmdbusd/objectmanager.py
@@ -0,0 +1,308 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import sys +import threading +import traceback +import dbus +import os +from . import cfg +from .utils import log_debug +from .automatedproperties import AutomatedProperties + + +# noinspection PyPep8Naming +class ObjectManager(AutomatedProperties): + """ + Implements the org.freedesktop.DBus.ObjectManager interface + """ + + def __init__(self, object_path, interface): + super(ObjectManager, self).__init__(object_path, interface) + self.set_interface(interface) + self._ap_o_path = object_path + self._objects = {} + self._id_to_object_path = {} + self.rlock = threading.RLock() + + @dbus.service.method( + dbus_interface="org.freedesktop.DBus.ObjectManager", + out_signature='a{oa{sa{sv}}}') + def GetManagedObjects(self): + with self.rlock: + rc = {} + try: + for k, v in list(self._objects.items()): + path, props = v[0].emit_data() + rc[path] = props + except Exception: + traceback.print_exc(file=sys.stdout) + sys.exit(1) + return rc + + def locked(self): + """ + If some external code need to run across a number of different + calls into ObjectManager while blocking others they can use this method + to lock others out. + :return: + """ + return ObjectManagerLock(self.rlock) + + @dbus.service.signal( + dbus_interface="org.freedesktop.DBus.ObjectManager", + signature='oa{sa{sv}}') + def InterfacesAdded(self, object_path, int_name_prop_dict): + log_debug( + ('SIGNAL: InterfacesAdded(%s, %s)' % + (str(object_path), str(int_name_prop_dict)))) + + @dbus.service.signal( + dbus_interface="org.freedesktop.DBus.ObjectManager", + signature='oas') + def InterfacesRemoved(self, object_path, interface_list): + log_debug(('SIGNAL: InterfacesRemoved(%s, %s)' % + (str(object_path), str(interface_list)))) + + def _lookup_add(self, obj, path, lvm_id, uuid): + """ + Store information about what we added to the caches so that we + can remove it cleanly + :param obj: The dbus object we are storing + :param lvm_id: The user name for the asset + :param uuid: The uuid for the asset + :return: + """ + # Note: Only called internally, lock implied + + # We could have a temp entry from the forward creation of a path + self._lookup_remove(path) + + self._objects[path] = (obj, lvm_id, uuid) + self._id_to_object_path[lvm_id] = path + + if uuid: + self._id_to_object_path[uuid] = path + + def _lookup_remove(self, obj_path): + # Note: Only called internally, lock implied + if obj_path in self._objects: + (obj, lvm_id, uuid) = self._objects[obj_path] + del self._id_to_object_path[lvm_id] + del self._id_to_object_path[uuid] + del self._objects[obj_path] + + def lookup_update(self, dbus_obj, new_uuid, new_lvm_id): + with self.rlock: + obj_path = dbus_obj.dbus_object_path() + self._lookup_remove(obj_path) + self._lookup_add( + dbus_obj, obj_path, + new_lvm_id, new_uuid) + + def object_paths_by_type(self, o_type): + with self.rlock: + rc = {} + + for k, v in list(self._objects.items()): + if isinstance(v[0], o_type): + rc[k] = True + return rc + + def register_object(self, dbus_object, emit_signal=False): + """ + Given a dbus object add it to the collection + :param dbus_object: Dbus object to register + :param emit_signal: If true emit a signal for interfaces added + """ + with self.rlock: + path, props = dbus_object.emit_data() + + # print('Registering object path %s for %s' % + # (path, dbus_object.lvm_id)) + + # We want fast access to the object by a number of different ways + # so we use multiple hashs with different keys + self._lookup_add(dbus_object, path, dbus_object.lvm_id, + dbus_object.Uuid) + + if emit_signal: + self.InterfacesAdded(path, props) + + def remove_object(self, dbus_object, emit_signal=False): + """ + Given a dbus object, remove it from the collection and remove it + from the dbus framework as well + :param dbus_object: Dbus object to remove + :param emit_signal: If true emit the interfaces removed signal + """ + with self.rlock: + # Store off the object path and the interface first + path = dbus_object.dbus_object_path() + interfaces = dbus_object.interface() + + # print 'UN-Registering object path %s for %s' % \ + # (path, dbus_object.lvm_id) + + self._lookup_remove(path) + + # Remove from dbus library + dbus_object.remove_from_connection(cfg.bus, path) + + # Optionally emit a signal + if emit_signal: + self.InterfacesRemoved(path, interfaces) + + def get_object_by_path(self, path): + """ + Given a dbus path return the object registered for it + :param path: The dbus path + :return: The object + """ + with self.rlock: + if path in self._objects: + return self._objects[path][0] + return None + + def get_object_by_uuid_lvm_id(self, uuid, lvm_id): + with self.rlock: + return self.get_object_by_path( + self.get_object_path_by_uuid_lvm_id(uuid, lvm_id, None, False)) + + def get_object_by_lvm_id(self, lvm_id): + """ + Given an lvm identifier, return the object registered for it + :param lvm_id: The lvm identifier + """ + with self.rlock: + if lvm_id in self._id_to_object_path: + return self.get_object_by_path(self._id_to_object_path[lvm_id]) + return None + + def get_object_path_by_lvm_id(self, lvm_id): + """ + Given an lvm identifier, return the object path for it + :param lvm_id: The lvm identifier + :return: Object path or '/' if not found + """ + with self.rlock: + if lvm_id in self._id_to_object_path: + return self._id_to_object_path[lvm_id] + return '/' + + def _uuid_verify(self, path, uuid, lvm_id): + """ + Ensure uuid is present for a successful lvm_id lookup + NOTE: Internal call, assumes under object manager lock + :param path: Path to object we looked up + :param uuid: lvm uuid to verify + :param lvm_id: lvm_id used to find object + :return: None + """ + # This gets called when we found an object based on lvm_id, ensure + # uuid is correct too, as they can change + if lvm_id != uuid: + if uuid not in self._id_to_object_path: + obj = self.get_object_by_path(path) + self._lookup_add(obj, path, lvm_id, uuid) + + def _return_lookup(self, uuid, lvm_identifier): + """ + We found an identifier, so lets return the path to the found object + :param uuid: The lvm uuid + :param lvm_identifier: The lvm_id used to find object + :return: + """ + path = self._id_to_object_path[lvm_identifier] + self._uuid_verify(path, uuid, lvm_identifier) + return path + + def get_object_path_by_uuid_lvm_id(self, uuid, lvm_id, path_create=None, + gen_new=True): + """ + For a given lvm asset return the dbus object registered to it. If the + object is not found and gen_new == True and path_create is a valid + function we will create a new path, register it and return it. + :param uuid: The uuid for the lvm object + :param lvm_id: The lvm name + :param path_create: If true create an object path if not found + :param gen_new: The function used to create the new path + """ + with self.rlock: + assert lvm_id + assert uuid + + if gen_new: + assert path_create + + path = None + + if lvm_id in self._id_to_object_path: + self._return_lookup(uuid, lvm_id) + + if "/" in lvm_id: + vg, lv = lvm_id.split("/", 1) + int_lvm_id = vg + "/" + ("[%s]" % lv) + if int_lvm_id in self._id_to_object_path: + self._return_lookup(uuid, int_lvm_id) + elif lvm_id.startswith('/'): + # We could have a pv device path lookup that failed, + # lets try canonical form and try again. + canonical = os.path.realpath(lvm_id) + if canonical in self._id_to_object_path: + self._return_lookup(uuid, canonical) + + if uuid and uuid in self._id_to_object_path: + # If we get here it indicates that we found the object, but + # the lvm_id lookup failed. In the case of a rename, the uuid + # will be correct, but the lvm_id will be wrong and vise versa. + # If the lvm_id does not equal the uuid, lets fix up the table + # so that lookups will be handled correctly. + path = self._id_to_object_path[uuid] + + # In some cases we are looking up by one or the other, don't + # update when they are the same. + if uuid != lvm_id: + obj = self.get_object_by_path(path) + self._lookup_add(obj, path, lvm_id, uuid) + else: + if gen_new: + path = path_create() + self._lookup_add(None, path, lvm_id, uuid) + + # pprint('get_object_path_by_lvm_id(%s, %s, %s, %s: return %s' % + # (uuid, lvm_id, str(path_create), str(gen_new), path)) + + return path + + +class ObjectManagerLock(object): + """ + The sole purpose of this class is to allow other code the ability to + lock the object manager using a `with` statement, eg. + + with cfg.om.locked(): + # Do stuff with object manager + + This will ensure that the lock is always released (assuming this is done + correctly) + """ + + def __init__(self, recursive_lock): + self._lock = recursive_lock + + def __enter__(self): + # Acquire lock + self._lock.acquire() + + # noinspection PyUnusedLocal + def __exit__(self, e_type, e_value, e_traceback): + # Release lock + self._lock.release() + self._lock = None
diff --git a/daemons/lvmdbusd/path.py.in b/daemons/lvmdbusd/path.py.in new file mode 100644 index 0000000..f0ef205 --- /dev/null +++ b/daemons/lvmdbusd/path.py.in
@@ -0,0 +1,10 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +LVM_BINARY = "@LVM_PATH@"
diff --git a/daemons/lvmdbusd/pv.py b/daemons/lvmdbusd/pv.py new file mode 100644 index 0000000..bbd76f1 --- /dev/null +++ b/daemons/lvmdbusd/pv.py
@@ -0,0 +1,282 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from .automatedproperties import AutomatedProperties +from . import utils +from . import cfg +import dbus +from .cfg import PV_INTERFACE +from . import cmdhandler +from .utils import vg_obj_path_generate, n, pv_obj_path_generate, \ + lv_object_path_method +from .loader import common +from .request import RequestEntry +from .state import State +from .utils import round_size + + +# noinspection PyUnusedLocal +def pvs_state_retrieve(selection, cache_refresh=True): + rc = [] + + if cache_refresh: + cfg.db.refresh() + + for p in cfg.db.fetch_pvs(selection): + rc.append( + PvState( + p["pv_name"], p["pv_uuid"], p["pv_name"], + p["pv_fmt"], n(p["pv_size"]), n(p["pv_free"]), + n(p["pv_used"]), n(p["dev_size"]), n(p["pv_mda_size"]), + n(p["pv_mda_free"]), int(p["pv_ba_start"]), + n(p["pv_ba_size"]), n(p["pe_start"]), + int(p["pv_pe_count"]), int(p["pv_pe_alloc_count"]), + p["pv_attr"], p["pv_tags"], p["vg_name"], p["vg_uuid"])) + return rc + + +def load_pvs(device=None, object_path=None, refresh=False, emit_signal=False, + cache_refresh=True): + return common( + pvs_state_retrieve, (Pv,), device, object_path, refresh, + emit_signal, cache_refresh) + + +# noinspection PyUnresolvedReferences +class PvState(State): + @property + def lvm_id(self): + return self.lvm_path + + def _lv_object_list(self, vg_name): + + # Note we are returning "a(oa(tts))" + + rc = [] + if vg_name: + for lv in sorted(cfg.db.pv_contained_lv(self.lvm_id)): + lv_uuid, lv_name, meta, segs = lv + full_name = "%s/%s" % (vg_name, lv_name) + + path_create = lv_object_path_method(lv_name, meta) + lv_path = cfg.om.get_object_path_by_uuid_lvm_id( + lv_uuid, full_name, path_create) + + rc.append((lv_path, segs)) + return dbus.Array(rc, signature="(oa(tts))") + + # noinspection PyUnusedLocal,PyPep8Naming + def __init__(self, lvm_path, Uuid, Name, + Fmt, SizeBytes, FreeBytes, UsedBytes, DevSizeBytes, + MdaSizeBytes, MdaFreeBytes, BaStart, BaSizeBytes, + PeStart, PeCount, PeAllocCount, attr, Tags, vg_name, + vg_uuid): + utils.init_class_from_arguments(self) + self.pe_segments = cfg.db.pv_pe_segments(Uuid) + + self.lv = self._lv_object_list(vg_name) + + if vg_name: + self.vg_path = cfg.om.get_object_path_by_uuid_lvm_id( + vg_uuid, vg_name, vg_obj_path_generate) + else: + self.vg_path = '/' + + def identifiers(self): + return (self.Uuid, self.lvm_path) + + def create_dbus_object(self, path): + if not path: + path = cfg.om.get_object_path_by_uuid_lvm_id(self.Uuid, self.Name, + pv_obj_path_generate) + return Pv(path, self) + + # noinspection PyMethodMayBeStatic + def creation_signature(self): + return (Pv, pv_obj_path_generate) + + +# noinspection PyPep8Naming +@utils.dbus_property(PV_INTERFACE, 'Uuid', 's') # PV UUID/pv_uuid +@utils.dbus_property(PV_INTERFACE, 'Name', 's') # PV/pv_name +@utils.dbus_property(PV_INTERFACE, 'Fmt', 's') # Fmt/pv_fmt +@utils.dbus_property(PV_INTERFACE, 'SizeBytes', 't') # PSize/pv_size +@utils.dbus_property(PV_INTERFACE, 'FreeBytes', 't') # PFree/pv_free +@utils.dbus_property(PV_INTERFACE, 'UsedBytes', 't') # Used/pv_used +@utils.dbus_property(PV_INTERFACE, 'DevSizeBytes', 't') # DevSize/dev_size +@utils.dbus_property(PV_INTERFACE, 'MdaSizeBytes', 't') # PMdaSize/pv_mda_size +@utils.dbus_property(PV_INTERFACE, 'MdaFreeBytes', 't') # PMdaFree/pv_mda_free +@utils.dbus_property(PV_INTERFACE, 'BaStart', 't') # BA start/pv_ba_start +@utils.dbus_property(PV_INTERFACE, 'BaSizeBytes', 't') # BA size/pv_ba_size +@utils.dbus_property(PV_INTERFACE, 'PeStart', 't') # 1st PE/pe_start +@utils.dbus_property(PV_INTERFACE, 'PeCount', 't') # PE/pv_pe_count +@utils.dbus_property(PV_INTERFACE, 'PeAllocCount', 't') # PE Allocation count +class Pv(AutomatedProperties): + # For properties that we need custom handlers we need these, otherwise + # we won't get our introspection data + _Tags_meta = ("as", PV_INTERFACE) + _PeSegments_meta = ("a(tt)", PV_INTERFACE) + _Exportable_meta = ("b", PV_INTERFACE) + _Allocatable_meta = ("b", PV_INTERFACE) + _Missing_meta = ("b", PV_INTERFACE) + _Lv_meta = ("a(oa(tts))", PV_INTERFACE) + _Vg_meta = ("o", PV_INTERFACE) + + # noinspection PyUnusedLocal,PyPep8Naming + def __init__(self, object_path, state_obj): + super(Pv, self).__init__(object_path, pvs_state_retrieve) + self.set_interface(PV_INTERFACE) + self.state = state_obj + + @staticmethod + def _remove(pv_uuid, pv_name, remove_options): + # Remove the PV, if successful then remove from the model + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(pv_uuid, pv_name) + + if dbo: + rc, out, err = cmdhandler.pv_remove(pv_name, remove_options) + if rc == 0: + cfg.om.remove_object(dbo, True) + else: + # Need to work on error handling, need consistent + raise dbus.exceptions.DBusException( + PV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + PV_INTERFACE, + 'PV with uuid %s and name %s not present!' % + (pv_uuid, pv_name)) + return '/' + + @dbus.service.method( + dbus_interface=PV_INTERFACE, + in_signature='ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Remove(self, tmo, remove_options, cb, cbe): + r = RequestEntry( + tmo, Pv._remove, + (self.Uuid, self.lvm_id, remove_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @staticmethod + def _resize(pv_uuid, pv_name, new_size_bytes, resize_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(pv_uuid, pv_name) + + if dbo: + rc, out, err = cmdhandler.pv_resize(pv_name, new_size_bytes, + resize_options) + if rc == 0: + dbo.refresh() + else: + raise dbus.exceptions.DBusException( + PV_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + PV_INTERFACE, + 'PV with uuid %s and name %s not present!' % + (pv_uuid, pv_name)) + return '/' + + @dbus.service.method( + dbus_interface=PV_INTERFACE, + in_signature='tia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def ReSize(self, new_size_bytes, tmo, resize_options, cb, cbe): + r = RequestEntry( + tmo, Pv._resize, + (self.Uuid, self.lvm_id, round_size(new_size_bytes), + resize_options), cb, cbe, False) + cfg.worker_q.put(r) + + @staticmethod + def _allocation_enabled(pv_uuid, pv_name, yes_no, allocation_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(pv_uuid, pv_name) + + if dbo: + rc, out, err = cmdhandler.pv_allocatable( + pv_name, yes_no, allocation_options) + if rc == 0: + cfg.load() + else: + raise dbus.exceptions.DBusException( + PV_INTERFACE, 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + PV_INTERFACE, + 'PV with uuid %s and name %s not present!' % + (pv_uuid, pv_name)) + return '/' + + @dbus.service.method( + dbus_interface=PV_INTERFACE, + in_signature='bia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def AllocationEnabled(self, yes, tmo, allocation_options, cb, cbe): + r = RequestEntry( + tmo, Pv._allocation_enabled, + (self.Uuid, self.lvm_id, + yes, allocation_options), + cb, cbe, False) + cfg.worker_q.put(r) + + @property + def Tags(self): + return utils.parse_tags(self.state.Tags) + + @property + def PeSegments(self): + if len(self.state.pe_segments): + return self.state.pe_segments + return dbus.Array([], '(tt)') + + @property + def Exportable(self): + if self.state.attr[1] == 'x': + return True + return False + + @property + def Allocatable(self): + if self.state.attr[0] == 'a': + return True + return False + + @property + def Missing(self): + if self.state.attr[2] == 'm': + return True + return False + + def object_path(self): + return self._object_path + + @property + def lvm_id(self): + return self.state.lvm_id + + @property + def identifiers(self): + return self.state.identifiers() + + @property + def Lv(self): + return self.state.lv + + @property + def Vg(self): + return self.state.vg_path
diff --git a/daemons/lvmdbusd/refresh.py b/daemons/lvmdbusd/refresh.py new file mode 100644 index 0000000..e29afd6 --- /dev/null +++ b/daemons/lvmdbusd/refresh.py
@@ -0,0 +1,45 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# Try and minimize the refreshes we do. + +import threading +from .request import RequestEntry +from . import cfg +from . import utils + +_rlock = threading.RLock() +_count = 0 + + +def handle_external_event(command): + utils.log_debug("External event: '%s'" % command) + event_complete() + cfg.load() + + +def event_add(params): + global _rlock + global _count + with _rlock: + if _count == 0: + _count += 1 + r = RequestEntry( + -1, handle_external_event, + params, None, None, False) + cfg.worker_q.put(r) + + +def event_complete(): + global _rlock + global _count + with _rlock: + if _count > 0: + _count -= 1 + return _count
diff --git a/daemons/lvmdbusd/request.py b/daemons/lvmdbusd/request.py new file mode 100644 index 0000000..ce6a6ef --- /dev/null +++ b/daemons/lvmdbusd/request.py
@@ -0,0 +1,151 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import threading +# noinspection PyUnresolvedReferences +from gi.repository import GLib +from .job import Job +from . import cfg +import traceback +from .utils import log_error + + +class RequestEntry(object): + def __init__(self, tmo, method, arguments, cb, cb_error, + return_tuple=True, job_state=None): + self.tmo = tmo + self.method = method + self.arguments = arguments + self.cb = cb + self.cb_error = cb_error + + self.timer_id = -1 + self.lock = threading.RLock() + self.done = False + self._result = None + self._job = None + self._rc = 0 + self._rc_error = None + self._return_tuple = return_tuple + self._job_state = job_state + + if self.tmo < 0: + # Client is willing to block forever + pass + elif tmo == 0: + self._return_job() + else: + self.timer_id = GLib.timeout_add_seconds( + tmo, RequestEntry._request_timeout, self) + + @staticmethod + def _request_timeout(r): + """ + Method which gets called when the timer runs out! + :param r: RequestEntry which timed out + :return: Nothing + """ + r.timer_expired() + + def _return_job(self): + self._job = Job(self, self._job_state) + cfg.om.register_object(self._job, True) + if self._return_tuple: + self.cb(('/', self._job.dbus_object_path())) + else: + self.cb(self._job.dbus_object_path()) + + def run_cmd(self): + try: + result = self.method(*self.arguments) + self.register_result(result) + except Exception as e: + # Use the request entry to return the result as the client may + # have gotten a job by the time we hit an error + # Lets get the stacktrace and set that to the error message + st = traceback.format_exc() + cfg.blackbox.dump() + log_error("Exception returned to client: \n%s" % st) + self.register_error(-1, str(e), e) + + def is_done(self): + with self.lock: + rc = self.done + return rc + + def get_errors(self): + with self.lock: + return (self._rc, self._rc_error) + + def result(self): + with self.lock: + if self.done: + return self._result + return '/' + + def _reg_ending(self, result, error_rc=0, error_msg=None, + error_exception=None): + with self.lock: + self.done = True + if self.timer_id != -1: + # Try to prevent the timer from firing + GLib.source_remove(self.timer_id) + + self._result = result + self._rc = error_rc + self._rc_error = error_msg + + if not self._job: + # We finished and there is no job, so return result or error + # now! + # Note: If we don't have a valid cb or cbe, this indicates a + # request that doesn't need a response as we already returned + # one before the request was processed. + if error_rc == 0: + if self.cb: + if self._return_tuple: + self.cb((result, '/')) + else: + self.cb(result) + else: + if self.cb_error: + if not error_exception: + if not error_msg: + error_exception = Exception( + "An error occurred, but no reason was " + "given, see service logs!") + else: + error_exception = Exception(error_msg) + + self.cb_error(error_exception) + else: + # We have a job and it's complete, indicate that it's done. + # TODO: We need to signal the job is done too. + self._job.Complete = True + self._job = None + + def register_error(self, error_rc, error_message, error_exception): + self._reg_ending(None, error_rc, error_message, error_exception) + + def register_result(self, result): + self._reg_ending(result) + + def timer_expired(self): + with self.lock: + # Set the timer back to -1 as we will get a warning if we try + # to remove a timer that doesn't exist + self.timer_id = -1 + if not self.done: + # Create dbus job object and return path to caller + self._return_job() + else: + # The job is done, we have nothing to do + pass + + return False
diff --git a/daemons/lvmdbusd/state.py b/daemons/lvmdbusd/state.py new file mode 100644 index 0000000..bbc5901 --- /dev/null +++ b/daemons/lvmdbusd/state.py
@@ -0,0 +1,27 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from abc import ABCMeta, abstractmethod + + +class State(object, metaclass=ABCMeta): + @abstractmethod + def lvm_id(self): + pass + + @abstractmethod + def identifiers(self): + pass + + @abstractmethod + def create_dbus_object(self, path): + pass + + def __str__(self): + return '*****\n' + str(self.__dict__) + '\n******\n'
diff --git a/daemons/lvmdbusd/udevwatch.py b/daemons/lvmdbusd/udevwatch.py new file mode 100644 index 0000000..c3e6e60 --- /dev/null +++ b/daemons/lvmdbusd/udevwatch.py
@@ -0,0 +1,54 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import pyudev +from .refresh import event_add +from . import cfg + +observer = None + + +# noinspection PyUnusedLocal +def filter_event(action, device): + # Filter for events of interest and add a request object to be processed + # when appropriate. + refresh = False + + if '.ID_FS_TYPE_NEW' in device: + fs_type_new = device['.ID_FS_TYPE_NEW'] + + if 'LVM' in fs_type_new: + refresh = True + elif fs_type_new == '': + # Check to see if the device was one we knew about + if 'DEVNAME' in device: + found = cfg.om.get_object_by_lvm_id(device['DEVNAME']) + if found: + refresh = True + + if 'DM_LV_NAME' in device: + refresh = True + + if refresh: + event_add(('udev',)) + + +def add(): + global observer + context = pyudev.Context() + monitor = pyudev.Monitor.from_netlink(context) + monitor.filter_by('block') + observer = pyudev.MonitorObserver(monitor, filter_event) + observer.start() + + +def remove(): + global observer + observer.stop() + observer = None
diff --git a/daemons/lvmdbusd/utils.py b/daemons/lvmdbusd/utils.py new file mode 100644 index 0000000..3dcb373 --- /dev/null +++ b/daemons/lvmdbusd/utils.py
@@ -0,0 +1,484 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import xml.etree.ElementTree as Et +import sys +import inspect +import ctypes +import os +import string + +import dbus +import dbus.service +import dbus.mainloop.glib + +try: + from . import cfg +except SystemError: + import cfg + +STDOUT_TTY = os.isatty(sys.stdout.fileno()) + + +def rtype(dbus_type): + """ + Decorator making sure that the decorated function returns a value of + specified type. + :param dbus_type: The specific dbus type to return value as + """ + + def decorator(fn): + def decorated(*args, **kwargs): + return dbus_type(fn(*args, **kwargs)) + + return decorated + + return decorator + + +# Field is expected to be a number, handle the corner cases when parsing +@rtype(dbus.UInt64) +def n(v): + if not v: + return 0 + return int(float(v)) + + +@rtype(dbus.UInt32) +def n32(v): + if not v: + return 0 + return int(float(v)) + + +# noinspection PyProtectedMember +def init_class_from_arguments(obj_instance): + for k, v in list(sys._getframe(1).f_locals.items()): + if k != 'self': + nt = k + + # If the current attribute has a value, but the incoming does + # not, don't overwrite it. Otherwise the default values on the + # property decorator don't work as expected. + cur = getattr(obj_instance, nt, v) + + # print 'Init class %s = %s' % (nt, str(v)) + if not (cur and len(str(cur)) and (v is None or len(str(v))) == 0): + setattr(obj_instance, nt, v) + + +def get_properties(f): + """ + Walks through an object instance or it's parent class(es) and determines + which attributes are properties and if they were created to be used for + dbus. + :param f: Object to inspect + :return: A dictionary of tuples with each tuple being: + 0 = An array of dicts with the keys being: p_t, p_name, + p_access(type, name, access) + 1 = Hash of property names and current value + """ + interfaces = dict() + + for c in inspect.getmro(f.__class__): + + h = vars(c) + for p, value in h.items(): + if isinstance(value, property): + # We found a property, see if it has a metadata type + key = attribute_type_name(p) + if key in h: + interface = h[key][1] + + if interface not in interfaces: + interfaces[interface] = ([], {}) + + access = '' + if getattr(f.__class__, p).fget: + access += 'read' + if getattr(f.__class__, p).fset: + access += 'write' + + interfaces[interface][0].append( + dict( + p_t=getattr(f, key)[0], + p_name=p, + p_access=access)) + + interfaces[interface][1][p] = getattr(f, p) + + return interfaces + + +def get_object_property_diff(o_prop, n_prop): + """ + Walk through each object properties and report what has changed and with + the new values + :param o_prop: Old keys/values + :param n_prop: New keys/values + :return: hash of properties that have changed and their new value + """ + rc = {} + + for intf_k, intf_v in o_prop.items(): + for k, v in list(intf_v[1].items()): + # print('Comparing %s:%s to %s:%s' % + # (k, o_prop[intf_k][1][k], k, str(n_prop[intf_k][1][k]))) + if o_prop[intf_k][1][k] != n_prop[intf_k][1][k]: + new_value = n_prop[intf_k][1][k] + + if intf_k not in rc: + rc[intf_k] = dict() + + rc[intf_k][k] = new_value + return rc + + +def add_properties(xml, interface, props): + """ + Given xml that describes the interface, add property values to the XML + for the specified interface. + :param xml: XML to edit + :param interface: Interface to add the properties too + :param props: Output from get_properties + :return: updated XML string + """ + root = Et.fromstring(xml) + + if props: + + for c in root: + # print c.attrib['name'] + if c.attrib['name'] == interface: + for p in props: + temp = '<property type="%s" name="%s" access="%s"/>\n' % \ + (p['p_t'], p['p_name'], p['p_access']) + c.append(Et.fromstring(temp)) + + return Et.tostring(root, encoding='utf8') + return xml + + +def attribute_type_name(name): + """ + Given the property name, return string of the attribute type + :param name: + :return: + """ + return "_%s_meta" % name + + +_type_map = dict( + s=dbus.String, + o=dbus.ObjectPath, + t=dbus.UInt64, + x=dbus.Int64, + u=dbus.UInt32, + i=dbus.Int32, + n=dbus.Int16, + q=dbus.UInt16, + d=dbus.Double, + y=dbus.Byte, + b=dbus.Boolean) + + +def _pass_through(v): + """ + If we have something which is not a simple type we return the original + value un-wrapped. + :param v: + :return: + """ + return v + + +def _dbus_type(t, value): + return _type_map.get(t, _pass_through)(value) + + +def dbus_property(interface_name, name, dbus_type, doc=None): + """ + Creates the get/set properties for the given name. It assumes that the + actual attribute is '_' + name and the attribute metadata is stuffed in + _name_type. + + There is probably a better way todo this. + :param interface_name: Dbus interface this property is associated with + :param name: Name of property + :param dbus_type: dbus string type eg. s,t,i,x + :param doc: Python __doc__ for the property + :return: + """ + attribute_name = '_' + name + + def getter(self): + t = getattr(self, attribute_name + '_meta')[0] + return _dbus_type(t, getattr(self.state, attribute_name[1:])) + + prop = property(getter, None, None, doc) + + def decorator(cls): + setattr(cls, attribute_name + '_meta', (dbus_type, interface_name)) + setattr(cls, name, prop) + return cls + + return decorator + + +def parse_tags(tags): + if len(tags): + if ',' in tags: + return tags.split(',') + return sorted([tags]) + return dbus.Array([], signature='s') + + +def _common_log(msg, *attributes): + cfg.stdout_lock.acquire() + tid = ctypes.CDLL('libc.so.6').syscall(186) + + msg = "%d:%d - %s" % (os.getpid(), tid, msg) + + if STDOUT_TTY and attributes: + print(color(msg, *attributes)) + else: + print(msg) + + cfg.stdout_lock.release() + sys.stdout.flush() + + +# Serializes access to stdout to prevent interleaved output +# @param msg Message to output to stdout +# @return None +def log_debug(msg, *attributes): + if cfg.DEBUG: + _common_log(msg, *attributes) + + +def log_error(msg, *attributes): + _common_log(msg, *attributes) + + +# noinspection PyUnusedLocal +def handler(signum, frame): + cfg.run.value = 0 + log_debug('Signal handler called with signal %d' % signum) + if cfg.loop is not None: + cfg.loop.quit() + + +def pv_obj_path_generate(): + return cfg.PV_OBJ_PATH + "/%d" % next(cfg.pv_id) + + +def vg_obj_path_generate(): + return cfg.VG_OBJ_PATH + "/%d" % next(cfg.vg_id) + + +def lv_object_path_method(name, meta): + if name[0] == '[': + return _hidden_lv_obj_path_generate + elif meta[0][0] == 't': + return _thin_pool_obj_path_generate + elif meta[0][0] == 'C' and 'pool' in meta[1]: + return _cache_pool_obj_path_generate + + return _lv_obj_path_generate + + +# Note: None of the individual LV path generate functions should be called +# directly, they should only be dispatched through lv_object_path_method + +def _lv_obj_path_generate(): + return cfg.LV_OBJ_PATH + "/%d" % next(cfg.lv_id) + + +def _thin_pool_obj_path_generate(): + return cfg.THIN_POOL_PATH + "/%d" % next(cfg.thin_id) + + +def _cache_pool_obj_path_generate(): + return cfg.CACHE_POOL_PATH + "/%d" % next(cfg.cache_pool_id) + + +def _hidden_lv_obj_path_generate(): + return cfg.HIDDEN_LV_PATH + "/%d" % next(cfg.hidden_lv) + + +def job_obj_path_generate(): + return cfg.JOB_OBJ_PATH + "/%d" % next(cfg.job_id) + + +def color(text, *user_styles): + styles = { + # styles + 'reset': '\033[0m', + 'bold': '\033[01m', + 'disabled': '\033[02m', + 'underline': '\033[04m', + 'reverse': '\033[07m', + 'strike_through': '\033[09m', + 'invisible': '\033[08m', + # text colors + 'fg_black': '\033[30m', + 'fg_red': '\033[31m', + 'fg_green': '\033[32m', + 'fg_orange': '\033[33m', + 'fg_blue': '\033[34m', + 'fg_purple': '\033[35m', + 'fg_cyan': '\033[36m', + 'fg_light_grey': '\033[37m', + 'fg_dark_grey': '\033[90m', + 'fg_light_red': '\033[91m', + 'fg_light_green': '\033[92m', + 'fg_yellow': '\033[93m', + 'fg_light_blue': '\033[94m', + 'fg_pink': '\033[95m', + 'fg_light_cyan': '\033[96m', + # background colors + 'bg_black': '\033[40m', + 'bg_red': '\033[41m', + 'bg_green': '\033[42m', + 'bg_orange': '\033[43m', + 'bg_blue': '\033[44m', + 'bg_purple': '\033[45m', + 'bg_cyan': '\033[46m', + 'bg_light_grey': '\033[47m' + } + + color_text = '' + for style in user_styles: + try: + color_text += styles[style] + except KeyError: + return 'def color: parameter {} does not exist'.format(style) + color_text += text + return '\033[0m{0}\033[0m'.format(color_text) + + +def pv_range_append(cmd, device, start, end): + if (start, end) == (0, 0): + cmd.append(device) + else: + if start != 0 and end == 0: + cmd.append("%s:%d-" % (device, start)) + else: + cmd.append( + "%s:%d-%d" % + (device, start, end)) + + +def pv_dest_ranges(cmd, pv_dest_range_list): + if len(pv_dest_range_list): + for i in pv_dest_range_list: + pv_range_append(cmd, *i) + + +def round_size(size_bytes): + bs = 512 + remainder = size_bytes % bs + if not remainder: + return size_bytes + return size_bytes + bs - remainder + + +_ALLOWABLE_CH = string.ascii_letters + string.digits + '#+-.:=@_\/%' +_ALLOWABLE_CH_SET = set(_ALLOWABLE_CH) + +_ALLOWABLE_VG_LV_CH = string.ascii_letters + string.digits + '.-_+' +_ALLOWABLE_VG_LV_CH_SET = set(_ALLOWABLE_VG_LV_CH) +_LV_NAME_RESERVED = ("_cdata", "_cmeta", "_corig", "_mimage", "_mlog", + "_pmspare", "_rimage", "_rmeta", "_tdata", "_tmeta", "_vorigin") + +# Tags can have the characters, based on the code +# a-zA-Z0-9._-+/=!:&# +_ALLOWABLE_TAG_CH = string.ascii_letters + string.digits + "._-+/=!:&#" +_ALLOWABLE_TAG_CH_SET = set(_ALLOWABLE_TAG_CH) + + +def _allowable_tag(tag_name): + # LVM should impose a length restriction + return set(tag_name) <= _ALLOWABLE_TAG_CH_SET + + +def _allowable_vg_name(vg_name): + if vg_name is None: + raise ValueError("VG name is None or empty") + + vg_len = len(vg_name) + if vg_len == 0 or vg_len > 127: + raise ValueError("VG name (%s) length (%d) not in the domain 1..127" % + (vg_name, vg_len)) + + if not set(vg_name) <= _ALLOWABLE_VG_LV_CH_SET: + raise ValueError("VG name (%s) contains invalid character, " + "allowable set(%s)" % (vg_name, _ALLOWABLE_VG_LV_CH)) + + if vg_name == "." or vg_name == "..": + raise ValueError('VG name (%s) cannot be "." or ".."' % (vg_name)) + + +def _allowable_lv_name(vg_name, lv_name): + + if lv_name is None: + raise ValueError("LV name is None or empty") + + lv_len = len(lv_name) + + # This length is derived from empirical testing + if lv_len == 0 or (len(vg_name) + lv_len) > 125: + raise ValueError("LV name (%s) length (%d) + VG name length " + "not in the domain 1..125" % (lv_name, lv_len)) + + if not set(lv_name) <= _ALLOWABLE_VG_LV_CH_SET: + raise ValueError("LV name (%s) contains invalid character, " + "allowable (%s)" % (lv_name, _ALLOWABLE_VG_LV_CH)) + + if any(x in lv_name for x in _LV_NAME_RESERVED): + raise ValueError("LV name (%s) contains a reserved word, " + "reserved set(%s)" % (lv_name, str(_LV_NAME_RESERVED))) + + if lv_name.startswith("snapshot") or lv_name.startswith("pvmove"): + raise ValueError("LV name (%s) starts with a reserved word, " + "reserved set(%s)" % (lv_name, str(["snapshot", "pvmove"]))) + + if lv_name[0] == '-': + raise ValueError("LV name (%s) cannot start with a '-' " + "character" % lv_name) + + +def validate_device_path(interface, device): + if not set(device) <= _ALLOWABLE_CH_SET: + raise dbus.exceptions.DBusException( + interface, 'Device path (%s) has invalid characters, ' + 'allowable (%s)' % (device, _ALLOWABLE_CH)) + + +def validate_vg_name(interface, vg_name): + try: + _allowable_vg_name(vg_name) + except ValueError as ve: + raise dbus.exceptions.DBusException( + interface, str(ve)) + + +def validate_lv_name(interface, vg_name, lv_name): + try: + _allowable_lv_name(vg_name, lv_name) + except ValueError as ve: + raise dbus.exceptions.DBusException( + interface, str(ve)) + + +def validate_tag(interface, tag): + if not _allowable_tag(tag): + raise dbus.exceptions.DBusException( + interface, 'tag (%s) contains invalid character, allowable set(%s)' + % (tag, _ALLOWABLE_TAG_CH))
diff --git a/daemons/lvmdbusd/vg.py b/daemons/lvmdbusd/vg.py new file mode 100644 index 0000000..4cc938e --- /dev/null +++ b/daemons/lvmdbusd/vg.py
@@ -0,0 +1,959 @@ +# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from .automatedproperties import AutomatedProperties + +from . import utils +from .utils import pv_obj_path_generate, vg_obj_path_generate, n +import dbus +from . import cfg +from .cfg import VG_INTERFACE +from . import cmdhandler +from .request import RequestEntry +from .loader import common +from .state import State +from . import background +from .utils import round_size +from .job import JobState + + +# noinspection PyUnusedLocal +def vgs_state_retrieve(selection, cache_refresh=True): + rc = [] + + if cache_refresh: + cfg.db.refresh() + + for v in cfg.db.fetch_vgs(selection): + rc.append( + VgState( + v['vg_uuid'], v['vg_name'], v['vg_fmt'], n(v['vg_size']), + n(v['vg_free']), v['vg_sysid'], n(v['vg_extent_size']), + n(v['vg_extent_count']), n(v['vg_free_count']), + v['vg_profile'], n(v['max_lv']), n(v['max_pv']), + n(v['pv_count']), n(v['lv_count']), n(v['snap_count']), + n(v['vg_seqno']), n(v['vg_mda_count']), + n(v['vg_mda_free']), n(v['vg_mda_size']), + n(v['vg_mda_used_count']), v['vg_attr'], v['vg_tags'])) + return rc + + +def load_vgs(vg_specific=None, object_path=None, refresh=False, + emit_signal=False, cache_refresh=True): + return common(vgs_state_retrieve, (Vg,), vg_specific, object_path, refresh, + emit_signal, cache_refresh) + + +# noinspection PyPep8Naming,PyUnresolvedReferences,PyUnusedLocal +class VgState(State): + @property + def lvm_id(self): + return self.Name + + def identifiers(self): + return (self.Uuid, self.Name) + + def _lv_paths_build(self): + rc = [] + for lv in cfg.db.lvs_in_vg(self.Uuid): + (lv_name, meta, lv_uuid) = lv + full_name = "%s/%s" % (self.Name, lv_name) + + gen = utils.lv_object_path_method(lv_name, meta) + + lv_path = cfg.om.get_object_path_by_uuid_lvm_id( + lv_uuid, full_name, gen) + rc.append(lv_path) + return dbus.Array(rc, signature='o') + + def _pv_paths_build(self): + rc = [] + for p in cfg.db.pvs_in_vg(self.Uuid): + (pv_name, pv_uuid) = p + rc.append(cfg.om.get_object_path_by_uuid_lvm_id( + pv_uuid, pv_name, pv_obj_path_generate)) + return dbus.Array(rc, signature='o') + + def __init__(self, Uuid, Name, Fmt, + SizeBytes, FreeBytes, SysId, ExtentSizeBytes, + ExtentCount, FreeCount, Profile, MaxLv, MaxPv, PvCount, + LvCount, SnapCount, Seqno, MdaCount, MdaFree, + MdaSizeBytes, MdaUsedCount, attr, tags): + utils.init_class_from_arguments(self) + self.Pvs = self._pv_paths_build() + self.Lvs = self._lv_paths_build() + + def create_dbus_object(self, path): + if not path: + path = cfg.om.get_object_path_by_uuid_lvm_id( + self.Uuid, self.Name, vg_obj_path_generate) + return Vg(path, self) + + # noinspection PyMethodMayBeStatic + def creation_signature(self): + return (Vg, vg_obj_path_generate) + + +# noinspection PyPep8Naming +@utils.dbus_property(VG_INTERFACE, 'Uuid', 's') +@utils.dbus_property(VG_INTERFACE, 'Name', 's') +@utils.dbus_property(VG_INTERFACE, 'Fmt', 's') +@utils.dbus_property(VG_INTERFACE, 'SizeBytes', 't', 0) +@utils.dbus_property(VG_INTERFACE, 'FreeBytes', 't', 0) +@utils.dbus_property(VG_INTERFACE, 'SysId', 's') +@utils.dbus_property(VG_INTERFACE, 'ExtentSizeBytes', 't') +@utils.dbus_property(VG_INTERFACE, 'ExtentCount', 't') +@utils.dbus_property(VG_INTERFACE, 'FreeCount', 't') +@utils.dbus_property(VG_INTERFACE, 'Profile', 's') +@utils.dbus_property(VG_INTERFACE, 'MaxLv', 't') +@utils.dbus_property(VG_INTERFACE, 'MaxPv', 't') +@utils.dbus_property(VG_INTERFACE, 'PvCount', 't') +@utils.dbus_property(VG_INTERFACE, 'LvCount', 't') +@utils.dbus_property(VG_INTERFACE, 'SnapCount', 't') +@utils.dbus_property(VG_INTERFACE, 'Seqno', 't') +@utils.dbus_property(VG_INTERFACE, 'MdaCount', 't') +@utils.dbus_property(VG_INTERFACE, 'MdaFree', 't') +@utils.dbus_property(VG_INTERFACE, 'MdaSizeBytes', 't') +@utils.dbus_property(VG_INTERFACE, 'MdaUsedCount', 't') +class Vg(AutomatedProperties): + _Tags_meta = ("as", VG_INTERFACE) + _Pvs_meta = ("ao", VG_INTERFACE) + _Lvs_meta = ("ao", VG_INTERFACE) + _Writeable_meta = ("b", VG_INTERFACE) + _Readable_meta = ("b", VG_INTERFACE) + _Resizeable_meta = ("b", VG_INTERFACE) + _Exportable_meta = ('b', VG_INTERFACE) + _Partial_meta = ('b', VG_INTERFACE) + _AllocContiguous_meta = ('b', VG_INTERFACE) + _AllocCling_meta = ('b', VG_INTERFACE) + _AllocNormal_meta = ('b', VG_INTERFACE) + _AllocAnywhere_meta = ('b', VG_INTERFACE) + _Clustered_meta = ('b', VG_INTERFACE) + + # noinspection PyUnusedLocal,PyPep8Naming + def __init__(self, object_path, object_state): + super(Vg, self).__init__(object_path, vgs_state_retrieve) + self.set_interface(VG_INTERFACE) + self._object_path = object_path + self.state = object_state + + @staticmethod + def fetch_new_lv(vg_name, lv_name): + cfg.load() + return cfg.om.get_object_by_lvm_id("%s/%s" % (vg_name, lv_name)) + + @staticmethod + def _rename(uuid, vg_name, new_name, rename_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = cmdhandler.vg_rename(vg_name, new_name, + rename_options) + if rc == 0: + cfg.load() + else: + # Need to work on error handling, need consistent + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + return '/' + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='sia{sv}', out_signature='o', + async_callbacks=('cb', 'cbe')) + def Rename(self, name, tmo, rename_options, cb, cbe): + utils.validate_vg_name(VG_INTERFACE, name) + r = RequestEntry(tmo, Vg._rename, + (self.state.Uuid, self.state.lvm_id, name, + rename_options), cb, cbe, False) + cfg.worker_q.put(r) + + @staticmethod + def _remove(uuid, vg_name, remove_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + # Remove the VG, if successful then remove from the model + rc, out, err = cmdhandler.vg_remove(vg_name, remove_options) + + if rc == 0: + # Remove the VG + cfg.om.remove_object(dbo, True) + + # If an LV has hidden LVs, things can get quite involved, + # especially if it's the last thin pool to get removed, so + # lets refresh all + cfg.load() + + else: + # Need to work on error handling, need consistent + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + return '/' + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='ia{sv}', out_signature='o', + async_callbacks=('cb', 'cbe')) + def Remove(self, tmo, remove_options, cb, cbe): + r = RequestEntry(tmo, Vg._remove, + (self.state.Uuid, self.state.lvm_id, remove_options), + cb, cbe, False) + cfg.worker_q.put(r) + + @staticmethod + def _change(uuid, vg_name, change_options): + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = cmdhandler.vg_change(change_options, vg_name) + + # To use an example with d-feet (Method input) + # {"activate": __import__('gi.repository.GLib', globals(), + # locals(), ['Variant']).Variant("s", "n")} + + if rc == 0: + cfg.load() + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + return '/' + + # TODO: This should be broken into a number of different methods + # instead of having one method that takes a hash for parameters. Some of + # the changes that vgchange does works on entire system, not just a + # specfic vg, thus that should be in the Manager interface. + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Change(self, tmo, change_options, cb, cbe): + r = RequestEntry(tmo, Vg._change, + (self.state.Uuid, self.state.lvm_id, change_options), + cb, cbe, False) + cfg.worker_q.put(r) + + @staticmethod + def _reduce(uuid, vg_name, missing, pv_object_paths, reduce_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + pv_devices = [] + + # If pv_object_paths is not empty, then get the device paths + if pv_object_paths and len(pv_object_paths) > 0: + for pv_op in pv_object_paths: + pv = cfg.om.get_object_by_path(pv_op) + if pv: + pv_devices.append(pv.lvm_id) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'PV Object path not found = %s!' % pv_op) + + rc, out, err = cmdhandler.vg_reduce(vg_name, missing, pv_devices, + reduce_options) + if rc == 0: + cfg.load() + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + return '/' + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='baoia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Reduce(self, missing, pv_object_paths, tmo, reduce_options, cb, cbe): + r = RequestEntry(tmo, Vg._reduce, + (self.state.Uuid, self.state.lvm_id, missing, + pv_object_paths, reduce_options), cb, cbe, False) + cfg.worker_q.put(r) + + @staticmethod + def _extend(uuid, vg_name, pv_object_paths, extend_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + extend_devices = [] + + for i in pv_object_paths: + pv = cfg.om.get_object_by_path(i) + if pv: + extend_devices.append(pv.lvm_id) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, 'PV Object path not found = %s!' % i) + + if len(extend_devices): + rc, out, err = cmdhandler.vg_extend(vg_name, extend_devices, + extend_options) + if rc == 0: + cfg.load() + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, 'No pv_object_paths provided!') + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + return '/' + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='aoia{sv}', out_signature='o', + async_callbacks=('cb', 'cbe')) + def Extend(self, pv_object_paths, tmo, extend_options, cb, cbe): + r = RequestEntry(tmo, Vg._extend, + (self.state.Uuid, self.state.lvm_id, pv_object_paths, + extend_options), + cb, cbe, False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='o(tt)a(ott)ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Move(self, pv_src_obj, pv_source_range, pv_dests_and_ranges, + tmo, move_options, cb, cbe): + + job_state = JobState() + + r = RequestEntry( + tmo, background.move, + (VG_INTERFACE, None, pv_src_obj, pv_source_range, + pv_dests_and_ranges, move_options, job_state), cb, cbe, False, + job_state) + + cfg.worker_q.put(r) + + @staticmethod + def _lv_create(uuid, vg_name, name, size_bytes, pv_dests_and_ranges, + create_options): + # Make sure we have a dbus object representing it + pv_dests = [] + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + if len(pv_dests_and_ranges): + for pr in pv_dests_and_ranges: + pv_dbus_obj = cfg.om.get_object_by_path(pr[0]) + if not pv_dbus_obj: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'PV Destination (%s) not found' % pr[0]) + + pv_dests.append((pv_dbus_obj.lvm_id, pr[1], pr[2])) + + rc, out, err = cmdhandler.vg_lv_create( + vg_name, create_options, name, size_bytes, pv_dests) + + if rc == 0: + return Vg.fetch_new_lv(vg_name, name) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='sta(ott)ia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def LvCreate(self, name, size_bytes, pv_dests_and_ranges, + tmo, create_options, cb, cbe): + """ + This one it for the advanced users that want to roll their own + :param name: Name of the LV + :param size_bytes: Size of LV in bytes + :param pv_dests_and_ranges: Optional array of PV object paths and + ranges + :param tmo: -1 == Wait forever, 0 == return job immediately, > 0 == + willing to wait that number of seconds before + getting a job + :param create_options: hash of key/value pairs + :param cb: Internal, not accessible by dbus API user + :param cbe: Internal, not accessible by dbus API user + :return: (oo) First object path is newly created object, second is + job object path if created. Each == '/' when it doesn't + apply. + """ + utils.validate_lv_name(VG_INTERFACE, self.Name, name) + r = RequestEntry(tmo, Vg._lv_create, + (self.state.Uuid, self.state.lvm_id, + name, round_size(size_bytes), pv_dests_and_ranges, + create_options), cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _lv_create_linear(uuid, vg_name, name, size_bytes, + thin_pool, create_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = cmdhandler.vg_lv_create_linear( + vg_name, create_options, name, size_bytes, thin_pool) + + if rc == 0: + created_lv = Vg.fetch_new_lv(vg_name, name) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + return created_lv + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='stbia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def LvCreateLinear(self, name, size_bytes, + thin_pool, tmo, create_options, cb, cbe): + utils.validate_lv_name(VG_INTERFACE, self.Name, name) + r = RequestEntry(tmo, Vg._lv_create_linear, + (self.state.Uuid, self.state.lvm_id, + name, round_size(size_bytes), thin_pool, + create_options), cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _lv_create_striped(uuid, vg_name, name, size_bytes, num_stripes, + stripe_size_kb, thin_pool, create_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = cmdhandler.vg_lv_create_striped( + vg_name, create_options, name, size_bytes, + num_stripes, stripe_size_kb, thin_pool) + if rc == 0: + created_lv = Vg.fetch_new_lv(vg_name, name) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + return created_lv + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='stuubia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def LvCreateStriped(self, name, size_bytes, num_stripes, + stripe_size_kb, thin_pool, tmo, create_options, + cb, cbe): + utils.validate_lv_name(VG_INTERFACE, self.Name, name) + r = RequestEntry( + tmo, Vg._lv_create_striped, + (self.state.Uuid, self.state.lvm_id, name, + round_size(size_bytes), num_stripes, stripe_size_kb, + thin_pool, create_options), + cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _lv_create_mirror(uuid, vg_name, name, size_bytes, + num_copies, create_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = cmdhandler.vg_lv_create_mirror( + vg_name, create_options, name, size_bytes, num_copies) + if rc == 0: + created_lv = Vg.fetch_new_lv(vg_name, name) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + return created_lv + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='stuia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def LvCreateMirror(self, name, size_bytes, num_copies, + tmo, create_options, cb, cbe): + utils.validate_lv_name(VG_INTERFACE, self.Name, name) + r = RequestEntry( + tmo, Vg._lv_create_mirror, + (self.state.Uuid, self.state.lvm_id, name, + round_size(size_bytes), num_copies, + create_options), cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _lv_create_raid(uuid, vg_name, name, raid_type, size_bytes, + num_stripes, stripe_size_kb, create_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = cmdhandler.vg_lv_create_raid( + vg_name, create_options, name, raid_type, size_bytes, + num_stripes, stripe_size_kb) + if rc == 0: + created_lv = Vg.fetch_new_lv(vg_name, name) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + return created_lv + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='sstuuia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def LvCreateRaid(self, name, raid_type, size_bytes, + num_stripes, stripe_size_kb, tmo, + create_options, cb, cbe): + utils.validate_lv_name(VG_INTERFACE, self.Name, name) + r = RequestEntry(tmo, Vg._lv_create_raid, + (self.state.Uuid, self.state.lvm_id, name, + raid_type, round_size(size_bytes), num_stripes, + stripe_size_kb, create_options), cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _create_pool(uuid, vg_name, meta_data_lv, data_lv, + create_options, create_method): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + # Retrieve the full names for the metadata and data lv + md = cfg.om.get_object_by_path(meta_data_lv) + data = cfg.om.get_object_by_path(data_lv) + + if dbo and md and data: + + new_name = data.Name + + rc, out, err = create_method( + md.lv_full_name(), data.lv_full_name(), create_options) + if rc == 0: + cfg.om.remove_object(md, emit_signal=True) + cfg.om.remove_object(data, emit_signal=True) + + cache_pool_lv = Vg.fetch_new_lv(vg_name, new_name) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + else: + msg = "" + + if not dbo: + msg += 'VG with uuid %s and name %s not present!' % \ + (uuid, vg_name) + + if not md: + msg += 'Meta data LV with object path %s not present!' % \ + (meta_data_lv) + + if not data_lv: + msg += 'Data LV with object path %s not present!' % \ + (meta_data_lv) + + raise dbus.exceptions.DBusException(VG_INTERFACE, msg) + + return cache_pool_lv + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='ooia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def CreateCachePool(self, meta_data_lv, data_lv, tmo, create_options, + cb, cbe): + r = RequestEntry( + tmo, Vg._create_pool, + (self.state.Uuid, self.state.lvm_id, meta_data_lv, + data_lv, create_options, cmdhandler.vg_create_cache_pool), cb, cbe) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='ooia{sv}', + out_signature='(oo)', + async_callbacks=('cb', 'cbe')) + def CreateThinPool(self, meta_data_lv, data_lv, tmo, create_options, + cb, cbe): + r = RequestEntry( + tmo, Vg._create_pool, + (self.state.Uuid, self.state.lvm_id, meta_data_lv, + data_lv, create_options, cmdhandler.vg_create_thin_pool), cb, cbe) + cfg.worker_q.put(r) + + @staticmethod + def _pv_add_rm_tags(uuid, vg_name, pv_object_paths, tags_add, + tags_del, tag_options): + pv_devices = [] + + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + # Check for existence of pv object paths + for p in pv_object_paths: + pv = cfg.om.get_object_by_path(p) + if pv: + pv_devices.append(pv.Name) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, 'PV object path = %s not found' % p) + + rc, out, err = cmdhandler.pv_tag( + pv_devices, tags_add, tags_del, tag_options) + if rc == 0: + cfg.load() + return '/' + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='aoasia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def PvTagsAdd(self, pvs, tags, tmo, tag_options, cb, cbe): + + for t in tags: + utils.validate_tag(VG_INTERFACE, t) + + r = RequestEntry(tmo, Vg._pv_add_rm_tags, + (self.state.Uuid, self.state.lvm_id, + pvs, tags, None, tag_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='aoasia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def PvTagsDel(self, pvs, tags, tmo, tag_options, cb, cbe): + + for t in tags: + utils.validate_tag(VG_INTERFACE, t) + + r = RequestEntry( + tmo, Vg._pv_add_rm_tags, + (self.state.Uuid, self.state.lvm_id, + pvs, None, tags, tag_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @staticmethod + def _vg_add_rm_tags(uuid, vg_name, tags_add, tags_del, tag_options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + + rc, out, err = cmdhandler.vg_tag( + vg_name, tags_add, tags_del, tag_options) + if rc == 0: + dbo.refresh() + return '/' + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='asia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def TagsAdd(self, tags, tmo, tag_options, cb, cbe): + + for t in tags: + utils.validate_tag(VG_INTERFACE, t) + + r = RequestEntry(tmo, Vg._vg_add_rm_tags, + (self.state.Uuid, self.state.lvm_id, + tags, None, tag_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='asia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def TagsDel(self, tags, tmo, tag_options, cb, cbe): + + for t in tags: + utils.validate_tag(VG_INTERFACE, t) + + r = RequestEntry(tmo, Vg._vg_add_rm_tags, + (self.state.Uuid, self.state.lvm_id, + None, tags, tag_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @staticmethod + def _vg_change_set(uuid, vg_name, method, value, options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = method(vg_name, value, options) + if rc == 0: + dbo.refresh() + return '/' + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='sia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def AllocationPolicySet(self, policy, tmo, policy_options, cb, cbe): + r = RequestEntry(tmo, Vg._vg_change_set, + (self.state.Uuid, self.state.lvm_id, + cmdhandler.vg_allocation_policy, + policy, policy_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='tia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def MaxPvSet(self, number, tmo, max_options, cb, cbe): + r = RequestEntry(tmo, Vg._vg_change_set, + (self.state.Uuid, self.state.lvm_id, + cmdhandler.vg_max_pv, number, max_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='ia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def UuidGenerate(self, tmo, options, cb, cbe): + r = RequestEntry(tmo, Vg._vg_change_set, + (self.state.Uuid, self.state.lvm_id, + cmdhandler.vg_uuid_gen, None, options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + def _attribute(self, pos, ch): + if self.state.attr[pos] == ch: + return True + return False + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='tia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def MaxLvSet(self, number, tmo, max_options, cb, cbe): + r = RequestEntry(tmo, Vg._vg_change_set, + (self.state.Uuid, self.state.lvm_id, + cmdhandler.vg_max_lv, number, max_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @staticmethod + def _vg_activate_deactivate(uuid, vg_name, activate, control_flags, + options): + # Make sure we have a dbus object representing it + dbo = cfg.om.get_object_by_uuid_lvm_id(uuid, vg_name) + + if dbo: + rc, out, err = cmdhandler.activate_deactivate( + 'vgchange', vg_name, activate, control_flags, options) + if rc == 0: + cfg.load() + return '/' + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'Exit code %s, stderr = %s' % (str(rc), err)) + else: + raise dbus.exceptions.DBusException( + VG_INTERFACE, + 'VG with uuid %s and name %s not present!' % + (uuid, vg_name)) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='tia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Activate(self, control_flags, tmo, activate_options, cb, cbe): + r = RequestEntry(tmo, Vg._vg_activate_deactivate, + (self.state.Uuid, self.state.lvm_id, True, + control_flags, activate_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @dbus.service.method( + dbus_interface=VG_INTERFACE, + in_signature='tia{sv}', + out_signature='o', + async_callbacks=('cb', 'cbe')) + def Deactivate(self, control_flags, tmo, activate_options, cb, cbe): + r = RequestEntry(tmo, Vg._vg_activate_deactivate, + (self.state.Uuid, self.state.lvm_id, False, + control_flags, activate_options), + cb, cbe, return_tuple=False) + cfg.worker_q.put(r) + + @property + def Tags(self): + return utils.parse_tags(self.state.tags) + + @property + def Pvs(self): + return self.state.Pvs + + @property + def Lvs(self): + return self.state.Lvs + + @property + def lvm_id(self): + return self.state.lvm_id + + @property + def Writeable(self): + return self._attribute(0, 'w') + + @property + def Readable(self): + return self._attribute(0, 'r') + + @property + def Resizeable(self): + return self._attribute(1, 'z') + + @property + def Exportable(self): + return self._attribute(2, 'x') + + @property + def Partial(self): + return self._attribute(3, 'p') + + @property + def AllocContiguous(self): + return self._attribute(4, 'c') + + @property + def AllocCling(self): + return self._attribute(4, 'l') + + @property + def AllocNormal(self): + return self._attribute(4, 'n') + + @property + def AllocAnywhere(self): + return self._attribute(4, 'a') + + @property + def Clustered(self): + return self._attribute(5, 'c')
diff --git a/daemons/lvmetad/.gitignore b/daemons/lvmetad/.gitignore new file mode 100644 index 0000000..773097e --- /dev/null +++ b/daemons/lvmetad/.gitignore
@@ -0,0 +1,2 @@ +lvmetad +lvmetactl
diff --git a/daemons/lvmetad/Makefile.in b/daemons/lvmetad/Makefile.in new file mode 100644 index 0000000..fa3bdf1 --- /dev/null +++ b/daemons/lvmetad/Makefile.in
@@ -0,0 +1,65 @@ +# +# Copyright (C) 2011-2012 Red Hat, Inc. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU Lesser General Public License v.2.1. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +SOURCES = lvmetad-core.c +SOURCES2 = testclient.c + +TARGETS = lvmetad lvmetactl + +.PHONY: install_lvmetad + +CFLOW_LIST = $(SOURCES) +CFLOW_LIST_TARGET = $(LIB_NAME).cflow +CFLOW_TARGET = lvmetad + +include $(top_builddir)/make.tmpl + +INCLUDES += -I$(top_srcdir)/libdaemon/server +LVMLIBS = -ldaemonserver $(LVMINTERNAL_LIBS) -ldevmapper + +LIBS += $(PTHREAD_LIBS) + +LDFLAGS += -L$(top_builddir)/libdaemon/server $(EXTRA_EXEC_LDFLAGS) +CLDFLAGS += -L$(top_builddir)/libdaemon/server +CFLAGS += $(EXTRA_EXEC_CFLAGS) + +lvmetad: $(OBJECTS) $(top_builddir)/libdaemon/client/libdaemonclient.a \ + $(top_builddir)/libdaemon/server/libdaemonserver.a + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJECTS) $(LVMLIBS) $(LIBS) + +lvmetactl: lvmetactl.o $(top_builddir)/libdaemon/client/libdaemonclient.a \ + $(top_builddir)/libdaemon/server/libdaemonserver.a + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ lvmetactl.o $(LVMLIBS) + +CLEAN_TARGETS += lvmetactl.o + +# TODO: No idea. No idea how to test either. +#ifneq ("$(CFLOW_CMD)", "") +#CFLOW_SOURCES = $(addprefix $(srcdir)/, $(SOURCES)) +#-include $(top_builddir)/libdm/libdevmapper.cflow +#-include $(top_builddir)/lib/liblvm-internal.cflow +#-include $(top_builddir)/lib/liblvm2cmd.cflow +#-include $(top_builddir)/daemons/dmeventd/$(LIB_NAME).cflow +#-include $(top_builddir)/daemons/dmeventd/plugins/mirror/$(LIB_NAME)-lvm2mirror.cflow +#endif + +install_lvmetad: lvmetad + $(INSTALL_PROGRAM) -D $< $(sbindir)/$(<F) + +install_lvm2: install_lvmetad + +install: install_lvm2
diff --git a/daemons/lvmetad/lvmetactl.c b/daemons/lvmetad/lvmetactl.c new file mode 100644 index 0000000..dd2ee1e --- /dev/null +++ b/daemons/lvmetad/lvmetactl.c
@@ -0,0 +1,249 @@ +/* + * Copyright (C) 2014 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ + +#include "tool.h" + +#include "lvmetad-client.h" + +daemon_handle h; + +static void print_reply(daemon_reply reply) +{ + const char *a = daemon_reply_str(reply, "response", NULL); + const char *b = daemon_reply_str(reply, "status", NULL); + const char *c = daemon_reply_str(reply, "reason", NULL); + + printf("response \"%s\" status \"%s\" reason \"%s\"\n", + a ? a : "", b ? b : "", c ? c : ""); +} + +int main(int argc, char **argv) +{ + daemon_reply reply; + char *cmd; + char *uuid; + char *name; + int val; + int ver; + + if (argc < 2) { + printf("lvmetactl dump\n"); + printf("lvmetactl pv_list\n"); + printf("lvmetactl vg_list\n"); + printf("lvmetactl get_global_info\n"); + printf("lvmetactl vg_lookup_name <name>\n"); + printf("lvmetactl vg_lookup_uuid <uuid>\n"); + printf("lvmetactl pv_lookup_uuid <uuid>\n"); + printf("lvmetactl set_global_invalid 0|1\n"); + printf("lvmetactl set_global_disable 0|1\n"); + printf("lvmetactl set_vg_version <uuid> <name> <version>\n"); + printf("lvmetactl vg_lock_type <uuid>\n"); + return -1; + } + + cmd = argv[1]; + + h = lvmetad_open(NULL); + + if (!strcmp(cmd, "dump")) { + reply = daemon_send_simple(h, "dump", + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + printf("%s\n", reply.buffer.mem); + + } else if (!strcmp(cmd, "pv_list")) { + reply = daemon_send_simple(h, "pv_list", + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + printf("%s\n", reply.buffer.mem); + + } else if (!strcmp(cmd, "vg_list")) { + reply = daemon_send_simple(h, "vg_list", + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + printf("%s\n", reply.buffer.mem); + + } else if (!strcmp(cmd, "get_global_info")) { + reply = daemon_send_simple(h, "get_global_info", + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + printf("%s\n", reply.buffer.mem); + + } else if (!strcmp(cmd, "set_global_invalid")) { + if (argc < 3) { + printf("set_global_invalid 0|1\n"); + return -1; + } + val = atoi(argv[2]); + + reply = daemon_send_simple(h, "set_global_info", + "global_invalid = " FMTd64, (int64_t) val, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + print_reply(reply); + + } else if (!strcmp(cmd, "set_global_disable")) { + if (argc < 3) { + printf("set_global_disable 0|1\n"); + return -1; + } + val = atoi(argv[2]); + + reply = daemon_send_simple(h, "set_global_info", + "global_disable = " FMTd64, (int64_t) val, + "disable_reason = %s", LVMETAD_DISABLE_REASON_DIRECT, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + print_reply(reply); + + } else if (!strcmp(cmd, "set_vg_version")) { + if (argc < 5) { + printf("set_vg_version <uuid> <name> <ver>\n"); + return -1; + } + uuid = argv[2]; + name = argv[3]; + ver = atoi(argv[4]); + + if ((strlen(uuid) == 1) && (uuid[0] == '-')) + uuid = NULL; + if ((strlen(name) == 1) && (name[0] == '-')) + name = NULL; + + if (uuid && name) { + reply = daemon_send_simple(h, "set_vg_info", + "uuid = %s", uuid, + "name = %s", name, + "version = " FMTd64, (int64_t) ver, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + } else if (uuid) { + reply = daemon_send_simple(h, "set_vg_info", + "uuid = %s", uuid, + "version = " FMTd64, (int64_t) ver, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + } else if (name) { + reply = daemon_send_simple(h, "set_vg_info", + "name = %s", name, + "version = " FMTd64, (int64_t) ver, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + } else { + printf("name or uuid required\n"); + return -1; + } + + print_reply(reply); + + } else if (!strcmp(cmd, "vg_lookup_name")) { + if (argc < 3) { + printf("vg_lookup_name <name>\n"); + return -1; + } + name = argv[2]; + + reply = daemon_send_simple(h, "vg_lookup", + "name = %s", name, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + printf("%s\n", reply.buffer.mem); + + } else if (!strcmp(cmd, "vg_lookup_uuid")) { + if (argc < 3) { + printf("vg_lookup_uuid <uuid>\n"); + return -1; + } + uuid = argv[2]; + + reply = daemon_send_simple(h, "vg_lookup", + "uuid = %s", uuid, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + printf("%s\n", reply.buffer.mem); + + } else if (!strcmp(cmd, "vg_lock_type")) { + struct dm_config_node *metadata; + const char *lock_type; + + if (argc < 3) { + printf("vg_lock_type <uuid>\n"); + return -1; + } + uuid = argv[2]; + + reply = daemon_send_simple(h, "vg_lookup", + "uuid = %s", uuid, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + /* printf("%s\n", reply.buffer.mem); */ + + metadata = dm_config_find_node(reply.cft->root, "metadata"); + if (!metadata) { + printf("no metadata\n"); + goto out; + } + + lock_type = dm_config_find_str(metadata, "metadata/lock_type", NULL); + if (!lock_type) { + printf("no lock_type\n"); + goto out; + } + printf("lock_type %s\n", lock_type); + + } else if (!strcmp(cmd, "pv_lookup_uuid")) { + if (argc < 3) { + printf("pv_lookup_uuid <uuid>\n"); + return -1; + } + uuid = argv[2]; + + reply = daemon_send_simple(h, "pv_lookup", + "uuid = %s", uuid, + "token = %s", "skip", + "pid = " FMTd64, (int64_t)getpid(), + "cmd = %s", "lvmetactl", + NULL); + printf("%s\n", reply.buffer.mem); + + } else { + printf("unknown command\n"); + goto out_close; + } +out: + daemon_reply_destroy(reply); +out_close: + daemon_close(h); + return 0; +}
diff --git a/daemons/lvmetad/lvmetad-client.h b/daemons/lvmetad/lvmetad-client.h new file mode 100644 index 0000000..dd6a379 --- /dev/null +++ b/daemons/lvmetad/lvmetad-client.h
@@ -0,0 +1,90 @@ +/* + * Copyright (C) 2011-2012 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _LVM_LVMETAD_CLIENT_H +#define _LVM_LVMETAD_CLIENT_H + +#include "daemon-client.h" + +#define LVMETAD_SOCKET DEFAULT_RUN_DIR "/lvmetad.socket" + +#define LVMETAD_TOKEN_UPDATE_IN_PROGRESS "update in progress" + +#define LVMETAD_DISABLE_REASON_DIRECT "DIRECT" +#define LVMETAD_DISABLE_REASON_LVM1 "LVM1" +#define LVMETAD_DISABLE_REASON_DUPLICATES "DUPLICATES" +#define LVMETAD_DISABLE_REASON_VGRESTORE "VGRESTORE" + +struct volume_group; + +/* Different types of replies we may get from lvmetad. */ + +typedef struct { + daemon_reply r; + const char **uuids; /* NULL terminated array */ +} lvmetad_uuidlist; + +typedef struct { + daemon_reply r; + struct dm_config_tree *cft; +} lvmetad_vg; + +/* Get a list of VG UUIDs that match a given VG name. */ +lvmetad_uuidlist lvmetad_lookup_vgname(daemon_handle h, const char *name); + +/* Get the metadata of a single VG, identified by UUID. */ +lvmetad_vg lvmetad_get_vg(daemon_handle h, const char *uuid); + +/* + * Add and remove PVs on demand. Udev-driven systems will use this interface + * instead of scanning. + */ +daemon_reply lvmetad_add_pv(daemon_handle h, const char *pv_uuid, const char *mda_content); +daemon_reply lvmetad_remove_pv(daemon_handle h, const char *pv_uuid); + +/* Trigger a full disk scan, throwing away all caches. XXX do we eventually want + * this? Probably not yet, anyway. + * daemon_reply lvmetad_rescan(daemon_handle h); + */ + +/* + * Update the version of metadata of a volume group. The VG has to be locked for + * writing for this, and the VG metadata here has to match whatever has been + * written to the disk (under this lock). This initially avoids the requirement + * for lvmetad to write to disk (in later revisions, lvmetad_supersede_vg may + * also do the writing, or we probably add another function to do that). + */ +daemon_reply lvmetad_supersede_vg(daemon_handle h, struct volume_group *vg); + +/* Wrappers to open/close connection */ + +static inline daemon_handle lvmetad_open(const char *socket) +{ + daemon_info lvmetad_info = { + .path = "lvmetad", + .socket = socket ?: LVMETAD_SOCKET, + .protocol = "lvmetad", + .protocol_version = 1, + .autostart = 0 + }; + + return daemon_open(lvmetad_info); +} + +static inline void lvmetad_close(daemon_handle h) +{ + return daemon_close(h); +} + +#endif
diff --git a/daemons/lvmetad/lvmetad-core.c b/daemons/lvmetad/lvmetad-core.c new file mode 100644 index 0000000..ebaca78 --- /dev/null +++ b/daemons/lvmetad/lvmetad-core.c
@@ -0,0 +1,3009 @@ +/* + * Copyright (C) 2012-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define _XOPEN_SOURCE 500 /* pthread */ + +#define _REENTRANT + +#include "tool.h" + +#include "daemon-io.h" +#include "daemon-server.h" +#include "daemon-log.h" +#include "lvm-version.h" +#include "lvmetad-client.h" + +#include <assert.h> +#include <errno.h> +#include <pthread.h> + +#define LVMETAD_SOCKET DEFAULT_RUN_DIR "/lvmetad.socket" + +/* + * cache states: + * . Empty: no devices visible to the system have been added to lvmetad + * . Scanning: some devices visible to the system have been added to lvmetad + * . Initialized: all devices visible to the system have been added to lvmetad + * . Outdated: event on system or storage is not yet processed by lvmetad + * Outdated variations: + * - MissingDev: device added to system, not yet added to lvmetad + * - RemovedDev: device removed from system, not yet removed from lvmetad + * - MissingVG: new vg is written on disk, not yet added to lvmetad + * - RemovedVG: vg is removed on disk, not yet removed in lvmetad + * - ChangedVG: vg metadata is changed on disk, not yet updated in lvmetad + * - MissingPV: new pv is written on disk, not yet added to in lvmetad + * - RemovedPV: pv is removed on disk, not yet removed in lvmetad + * - ChangedPV: pv metadata is changed on disk, not yet updated in lvmetad + * . Updated: events have been processed by lvmetad + * + * state transitions: + * . Empty -> Scanning + * . Scanning -> Initialized + * . Initialized -> Scanning + * . Initialized -> Outdated + * . Outdated -> Updated + * . Updated -> Outdated + * . Updated -> Scanning + * . Outdated -> Scanning + * + * state transitions caused by: + * . Empty is caused by: + * - starting/restarting lvmetad + * . Scanning is caused by: + * - running pvscan --cache + * - running any command with different global_filter (token mismatch) + * - running any command while lvmetad is Empty + * - running a report/display command with --foreign + * - running a report/display command with --shared + * - running a command using lvmlockd global lock where global state is changed + * . Initialized is caused by: + * - completion of Scanning + * . Outdated is caused by: + * - device being added or removed on the system + * - creating/removing/changing a VG + * - creating/removing/changing a PV + * . Updated is caused by: + * - receiving and processing all events + * + * request handling: + * . Empty: short period during startup, token error returned + * . Scanning: should be very short, lvmetad responds to requests with + * the token error "updating" + * . Initialized: lvmetad responds to requests + * . Updated: lvmetad responds to requests + * . Outdated: should be very short, lvmetad responds to requests + * + * In general, the cache state before and after the transition + * "Updated -> Scanning -> Initialized" should match, unless + * events occur during that transition. + * + * The Scanning state includes: + * . receive a request to set the token to "updating" (Scanning state begins.) + * . receive a pv_clear_all request to clear current cache + * . receive a number of pv_found events to repopulate cache + * . receive a request to set the token to a hash value (Initialized state begins.) + * + * The transition from Outdated to Updated depends on lvm commands + * sending events to lvmetad, i.e. pv_found, pv_gone, vg_update, + * vg_remove. Prior to receiving these events, lvmetad is not aware + * that it is in the Outdated state. + * + * When using a shared VG with lvmlockd, the Outdated state can last a + * longer time, but it won't be used in that state. lvmlockd forces a + * transition "Outdated -> Scanning -> Initialized" before the cache + * is used. + */ + + +/* + * valid/invalid state of cached metadata + * + * Normally when using lvmetad, the state is kept up-to-date through a + * combination of notifications from clients and updates triggered by uevents. + * When using lvmlockd, the lvmetad state is expected to become out of + * date (invalid/stale) when other hosts make changes to the metadata on disk. + * + * To deal with this, the metadata cached in lvmetad can be flagged as invalid. + * This invalid flag is returned along with the metadata when read by a + * command. The command can check for the invalid flag and decide that it + * should either use the stale metadata (uncommon), or read the latest metadata + * from disk rather than using the invalid metadata that was returned. If the + * command reads the latest metadata from disk, it can choose to send it to + * lvmetad to update the cached copy and clear the invalid flag in lvmetad. + * Otherwise, the next command to read the metadata from lvmetad will also + * receive the invalid metadata with the invalid flag (and like the previous + * command, it too may choose to read the latest metadata from disk and can + * then also choose to update the lvmetad copy.) + * + * For purposes of tracking the invalid state, LVM metadata is considered + * to be either VG-specific or global. VG-specific metadata is metadata + * that is isolated to a VG, such as the LVs it contains. Global + * metadata is metadata that is not isolated to a single VG. Global + * metdata includes: + * . the VG namespace (which VG names are used) + * . the set of orphan PVs (which PVs are in VGs and which are not) + * . properties of orphan PVs (the size of an orphan PV) + * + * If the metadata for a single VG becomes invalid, the VGFL_INVALID + * flag can be set in the vg_info struct for that VG. If the global + * metdata becomes invalid, the GLFL_INVALID flag can be set in the + * lvmetad daemon state. + * + * If a command reads VG metadata and VGFL_INVALID is set, an + * extra config node called "vg_invalid" is added to the config + * data returned to the command. + * + * If a command reads global metdata and GLFL_INVALID is set, an + * extra config node called "global_invalid" is added to the + * config data returned to the command. + * + * If a command sees vg_invalid, and wants the latest VG metadata, + * it only needs to scan disks of the PVs in that VG. + * It can then use vg_update to send the latest metadata to lvmetad + * which clears the VGFL_INVALID flag. + * + * If a command sees global_invalid, and wants the latest metadata, + * it should scan all devices to update lvmetad, and then send + * lvmetad the "set_global_info global_invalid=0" message to clear + * GLFL_INVALID. + * + * (When rescanning devices to update lvmetad, the command must use + * the global filter cmd->lvmetad_filter so that it processes the same + * devices that are seen by lvmetad.) + * + * The lvmetad INVALID flags can be set by sending lvmetad the messages: + * + * . set_vg_info with the latest VG seqno. If the VG seqno is larger + * than the cached VG seqno, VGFL_INVALID is set for the VG. + * + * . set_global_info with global_invalid=1 sets GLFL_INVALID. + * + * Different entities could use these functions to invalidate metadata + * if/when they detected that the cache is stale. How they detect that + * the cache is stale depends on the details of the specific entity. + * + * In the case of lvmlockd, it embeds values into its locks to keep track + * of when other nodes have changed metadata on disk related to those locks. + * When acquring locks it can look at these values and detect that + * the metadata associated with the lock has been changed. + * When the values change, it uses set_vg_info/set_global_info to + * invalidate the lvmetad cache. + * + * The values that lvmlockd distributes through its locks are the + * latest VG seqno in VG locks and a global counter in the global lock. + * When a host acquires a VG lock and sees that the embedded seqno is + * larger than it was previously, it knows that it should invalidate the + * lvmetad cache for the VG. If the host acquires the global lock + * and sees that the counter is larger than previously, it knows that + * it should invalidate the global info in lvmetad. This invalidation + * is done before the lock is returned to the command. This way the + * invalid flag will be set on the metadata before the command reads + * it from lvmetad. + */ + +struct vg_info { + int64_t external_version; + uint32_t flags; /* VGFL_ */ +}; + +#define GLFL_INVALID 0x00000001 +#define GLFL_DISABLE 0x00000002 +#define GLFL_DISABLE_REASON_DIRECT 0x00000004 +#define GLFL_DISABLE_REASON_LVM1 0x00000008 +#define GLFL_DISABLE_REASON_DUPLICATES 0x00000010 +#define GLFL_DISABLE_REASON_VGRESTORE 0x00000020 + +#define GLFL_DISABLE_REASON_ALL (GLFL_DISABLE_REASON_DIRECT | GLFL_DISABLE_REASON_LVM1 | GLFL_DISABLE_REASON_DUPLICATES | GLFL_DISABLE_REASON_VGRESTORE) + +#define VGFL_INVALID 0x00000001 + +#define CMD_NAME_SIZE 32 + +typedef struct { + daemon_idle *idle; + log_state *log; /* convenience */ + const char *log_config; + + struct dm_hash_table *pvid_to_pvmeta; + struct dm_hash_table *device_to_pvid; /* shares locks with above */ + + struct dm_hash_table *vgid_to_metadata; + struct dm_hash_table *vgid_to_vgname; + struct dm_hash_table *vgid_to_outdated_pvs; + struct dm_hash_table *vgid_to_info; + struct dm_hash_table *vgname_to_vgid; + struct dm_hash_table *pvid_to_vgid; + char token[128]; + char update_cmd[CMD_NAME_SIZE]; + int update_pid; + int update_timeout; + uint64_t update_begin; + uint32_t flags; /* GLFL_ */ + pthread_mutex_t token_lock; + pthread_mutex_t info_lock; + pthread_rwlock_t cache_lock; +} lvmetad_state; + +static uint64_t _monotonic_seconds(void) +{ + struct timespec ts; + + if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) + return 0; + return ts.tv_sec; +} + +static void destroy_metadata_hashes(lvmetad_state *s) +{ + struct dm_hash_node *n = NULL; + + dm_hash_iterate(n, s->vgid_to_metadata) + dm_config_destroy(dm_hash_get_data(s->vgid_to_metadata, n)); + + dm_hash_iterate(n, s->vgid_to_outdated_pvs) + dm_config_destroy(dm_hash_get_data(s->vgid_to_outdated_pvs, n)); + + dm_hash_iterate(n, s->pvid_to_pvmeta) + dm_config_destroy(dm_hash_get_data(s->pvid_to_pvmeta, n)); + + dm_hash_destroy(s->pvid_to_pvmeta); + dm_hash_destroy(s->vgid_to_metadata); + dm_hash_destroy(s->vgid_to_vgname); + dm_hash_destroy(s->vgid_to_outdated_pvs); + dm_hash_destroy(s->vgid_to_info); + dm_hash_destroy(s->vgname_to_vgid); + + dm_hash_destroy(s->device_to_pvid); + dm_hash_destroy(s->pvid_to_vgid); +} + +static void create_metadata_hashes(lvmetad_state *s) +{ + s->pvid_to_pvmeta = dm_hash_create(32); + s->device_to_pvid = dm_hash_create(32); + s->vgid_to_metadata = dm_hash_create(32); + s->vgid_to_vgname = dm_hash_create(32); + s->vgid_to_outdated_pvs = dm_hash_create(32); + s->vgid_to_info = dm_hash_create(32); + s->pvid_to_vgid = dm_hash_create(32); + s->vgname_to_vgid = dm_hash_create(32); +} + +static response reply_fail(const char *reason) +{ + return daemon_reply_simple("failed", "reason = %s", reason, NULL); +} + +static response reply_unknown(const char *reason) +{ + return daemon_reply_simple("unknown", "reason = %s", reason, NULL); +} + +static struct dm_config_node *pvs(struct dm_config_node *vg) +{ + struct dm_config_node *pv = dm_config_find_node(vg, "metadata/physical_volumes"); + if (pv) + pv = pv->child; + return pv; +} + +static void filter_metadata(struct dm_config_node *vg) { + struct dm_config_node *pv = pvs(vg); + while (pv) { + struct dm_config_node *item = pv->child; + while (item) { + /* Remove the advisory device nodes. */ + if (item->sib && !strcmp(item->sib->key, "device")) + item->sib = item->sib->sib; + item = item->sib; + } + pv = pv->sib; + } + vg->sib = NULL; /* Drop any trailing garbage. */ +} + +static void merge_pvmeta(struct dm_config_node *pv, struct dm_config_node *pvmeta) +{ + struct dm_config_node *tmp; + + if (!pvmeta) + return; + + tmp = pvmeta; + while (tmp->sib) { + /* drop the redundant ID and dev_size nodes */ + if (!strcmp(tmp->sib->key, "id") || !strcmp(tmp->sib->key, "dev_size")) + tmp->sib = tmp->sib->sib; + if (!tmp->sib) break; + tmp = tmp->sib; + tmp->parent = pv; + } + tmp->sib = pv->child; + pv->child = pvmeta; + pvmeta->parent = pv; +} + +/* + * Either the "big" vgs lock, or a per-vg lock needs to be held before entering + * this function. + * + * cft and vg is data being sent to the caller. + */ + +static int update_pv_status(lvmetad_state *s, + struct dm_config_tree *cft, + struct dm_config_node *vg) +{ + struct dm_config_node *pv; + const char *uuid; + struct dm_config_tree *pvmeta; + struct dm_config_node *pvmeta_cn; + int ret = 1; + + for (pv = pvs(vg); pv; pv = pv->sib) { + if (!(uuid = dm_config_find_str(pv->child, "id", NULL))) { + ERROR(s, "update_pv_status found no uuid for PV"); + continue; + } + + pvmeta = dm_hash_lookup(s->pvid_to_pvmeta, uuid); + + set_flag(cft, pv, "status", "MISSING", !pvmeta); + + if (pvmeta) { + if (!(pvmeta_cn = dm_config_clone_node(cft, pvmeta->root->child, 1))) { + ERROR(s, "update_pv_status out of memory"); + ret = 0; + goto out; + } + + merge_pvmeta(pv, pvmeta_cn); + } + } +out: + return ret; +} + +static struct dm_config_node *add_last_node(struct dm_config_tree *cft, const char *node_name) +{ + struct dm_config_node *cn, *last; + + cn = cft->root; + last = cn; + + while (cn->sib) { + last = cn->sib; + cn = last; + } + + cn = dm_config_create_node(cft, node_name); + if (!cn) + return NULL; + + cn->v = NULL; + cn->sib = NULL; + cn->parent = cft->root; + last->sib = cn; + + return cn; +} + +static struct dm_config_node *make_pv_node(lvmetad_state *s, const char *pvid, + struct dm_config_tree *cft, + struct dm_config_node *parent, + struct dm_config_node *pre_sib) +{ + struct dm_config_tree *pvmeta = dm_hash_lookup(s->pvid_to_pvmeta, pvid); + const char *vgid = dm_hash_lookup(s->pvid_to_vgid, pvid), *vgname = NULL; + struct dm_config_node *pv; + struct dm_config_node *cn = NULL; + + if (!pvmeta) + return NULL; + + if (vgid) { + vgname = dm_hash_lookup(s->vgid_to_vgname, vgid); + } + + /* Nick the pvmeta config tree. */ + if (!(pv = dm_config_clone_node(cft, pvmeta->root, 0))) + return 0; + + if (pre_sib) + pre_sib->sib = pv; + if (parent && !parent->child) + parent->child = pv; + pv->parent = parent; + pv->key = pvid; + + /* Add the "variable" bits to it. */ + + if (vgid && strcmp(vgid, "#orphan")) + cn = make_text_node(cft, "vgid", vgid, pv, cn); + if (vgname) + cn = make_text_node(cft, "vgname", vgname, pv, cn); + + return pv; +} + +static response pv_list(lvmetad_state *s, request r) +{ + struct dm_config_node *cn = NULL, *cn_pvs; + struct dm_hash_node *n; + const char *id; + response res = { 0 }; + + DEBUGLOG(s, "pv_list"); + + buffer_init( &res.buffer ); + + if (!(res.cft = dm_config_create())) + return res; /* FIXME error reporting */ + + /* The response field */ + if (!(res.cft->root = make_text_node(res.cft, "response", "OK", NULL, NULL))) + return res; /* FIXME doomed */ + + cn_pvs = make_config_node(res.cft, "physical_volumes", NULL, res.cft->root); + + dm_hash_iterate(n, s->pvid_to_pvmeta) { + id = dm_hash_get_key(s->pvid_to_pvmeta, n); + cn = make_pv_node(s, id, res.cft, cn_pvs, cn); + } + + if (s->flags & GLFL_INVALID) + add_last_node(res.cft, "global_invalid"); + + return res; +} + +static response pv_lookup(lvmetad_state *s, request r) +{ + const char *pvid = daemon_request_str(r, "uuid", NULL); + int64_t devt = daemon_request_int(r, "device", 0); + response res = { 0 }; + struct dm_config_node *pv; + + DEBUGLOG(s, "pv_lookup pvid %s", pvid); + + buffer_init( &res.buffer ); + + if (!pvid && !devt) + return reply_fail("need PVID or device"); + + if (!(res.cft = dm_config_create())) + return reply_fail("out of memory"); + + if (!(res.cft->root = make_text_node(res.cft, "response", "OK", NULL, NULL))) + return reply_fail("out of memory"); + + if (!pvid && devt) + pvid = dm_hash_lookup_binary(s->device_to_pvid, &devt, sizeof(devt)); + + if (!pvid) { + WARN(s, "pv_lookup: could not find device %" PRIu64, devt); + dm_config_destroy(res.cft); + return reply_unknown("device not found"); + } + + pv = make_pv_node(s, pvid, res.cft, NULL, res.cft->root); + if (!pv) { + dm_config_destroy(res.cft); + return reply_unknown("PV not found"); + } + + pv->key = "physical_volume"; + + if (s->flags & GLFL_INVALID) + add_last_node(res.cft, "global_invalid"); + + return res; +} + +static response vg_list(lvmetad_state *s, request r) +{ + struct dm_config_node *cn, *cn_vgs, *cn_last = NULL; + struct dm_hash_node *n; + const char *id; + const char *name; + response res = { 0 }; + + DEBUGLOG(s, "vg_list"); + + buffer_init( &res.buffer ); + + if (!(res.cft = dm_config_create())) + goto bad; /* FIXME: better error reporting */ + + /* The response field */ + res.cft->root = cn = dm_config_create_node(res.cft, "response"); + if (!cn) + goto bad; /* FIXME */ + cn->parent = res.cft->root; + if (!(cn->v = dm_config_create_value(res.cft))) + goto bad; /* FIXME */ + + cn->v->type = DM_CFG_STRING; + cn->v->v.str = "OK"; + + cn_vgs = cn = cn->sib = dm_config_create_node(res.cft, "volume_groups"); + if (!cn_vgs) + goto bad; /* FIXME */ + + cn->parent = res.cft->root; + cn->v = NULL; + cn->child = NULL; + + dm_hash_iterate(n, s->vgid_to_vgname) { + id = dm_hash_get_key(s->vgid_to_vgname, n), + name = dm_hash_get_data(s->vgid_to_vgname, n); + + if (!(cn = dm_config_create_node(res.cft, id))) + goto bad; /* FIXME */ + + if (cn_last) + cn_last->sib = cn; + + cn->parent = cn_vgs; + cn->sib = NULL; + cn->v = NULL; + + if (!(cn->child = dm_config_create_node(res.cft, "name"))) + goto bad; /* FIXME */ + + cn->child->parent = cn; + cn->child->sib = 0; + if (!(cn->child->v = dm_config_create_value(res.cft))) + goto bad; /* FIXME */ + + cn->child->v->type = DM_CFG_STRING; + cn->child->v->v.str = name; + + if (!cn_vgs->child) + cn_vgs->child = cn; + cn_last = cn; + } + + if (s->flags & GLFL_INVALID) + add_last_node(res.cft, "global_invalid"); +bad: + return res; +} + +static void mark_outdated_pv(lvmetad_state *s, const char *vgid, const char *pvid) +{ + struct dm_config_tree *pvmeta, *outdated_pvs; + struct dm_config_node *list, *cft_vgid; + struct dm_config_value *v; + + pvmeta = dm_hash_lookup(s->pvid_to_pvmeta, pvid); + + /* if the MDA exists and is used, it will have ignore=0 set */ + if (!pvmeta || + (dm_config_find_int64(pvmeta->root, "pvmeta/mda0/ignore", 1) && + dm_config_find_int64(pvmeta->root, "pvmeta/mda1/ignore", 1))) + return; + + ERROR(s, "PV %s has outdated metadata for VG %s", pvid, vgid); + + outdated_pvs = dm_hash_lookup(s->vgid_to_outdated_pvs, vgid); + if (!outdated_pvs) { + if (!(outdated_pvs = dm_config_from_string("outdated_pvs/pv_list = []")) || + !(cft_vgid = make_text_node(outdated_pvs, "vgid", dm_pool_strdup(outdated_pvs->mem, vgid), + outdated_pvs->root, NULL))) + abort(); + if (!dm_hash_insert(s->vgid_to_outdated_pvs, cft_vgid->v->v.str, outdated_pvs)) + abort(); + DEBUGLOG(s, "created outdated_pvs list for VG %s", vgid); + } + + list = dm_config_find_node(outdated_pvs->root, "outdated_pvs/pv_list"); + v = list->v; + while (v) { + if (v->type != DM_CFG_EMPTY_ARRAY && !strcmp(v->v.str, pvid)) + return; + v = v->next; + } + if (!(v = dm_config_create_value(outdated_pvs))) + abort(); + v->type = DM_CFG_STRING; + v->v.str = dm_pool_strdup(outdated_pvs->mem, pvid); + v->next = list->v; + list->v = v; +} + +static void chain_outdated_pvs(lvmetad_state *s, const char *vgid, struct dm_config_tree *metadata_cft, struct dm_config_node *metadata) +{ + struct dm_config_tree *cft = dm_hash_lookup(s->vgid_to_outdated_pvs, vgid), *pvmeta; + struct dm_config_node *pv, *res, *out_pvs = cft ? dm_config_find_node(cft->root, "outdated_pvs/pv_list") : NULL; + struct dm_config_value *pvs_v = out_pvs ? out_pvs->v : NULL; + if (!pvs_v) + return; + if (!(res = make_config_node(metadata_cft, "outdated_pvs", metadata_cft->root, 0))) + return; /* oops */ + res->sib = metadata->child; + metadata->child = res; + for (; pvs_v && pvs_v->type != DM_CFG_EMPTY_ARRAY; pvs_v = pvs_v->next) { + pvmeta = dm_hash_lookup(s->pvid_to_pvmeta, pvs_v->v.str); + if (!pvmeta) { + WARN(s, "metadata for PV %s not found", pvs_v->v.str); + continue; + } + if (!(pv = dm_config_clone_node(metadata_cft, pvmeta->root, 0))) + continue; + pv->key = dm_config_find_str(pv, "pvmeta/id", NULL); + pv->sib = res->child; + res->child = pv; + } +} + +static response vg_lookup(lvmetad_state *s, request r) +{ + struct dm_config_tree *cft; + struct dm_config_node *metadata, *n; + struct vg_info *info; + response res = { 0 }; + const char *uuid = daemon_request_str(r, "uuid", NULL); + const char *name = daemon_request_str(r, "name", NULL); + int count = 0; + + buffer_init( &res.buffer ); + + if (!uuid && !name) { + ERROR(s, "vg_lookup with no uuid or name"); + return reply_unknown("VG not found"); + + } else if (!uuid || !name) { + DEBUGLOG(s, "vg_lookup vgid %s name %s needs lookup", + uuid ?: "none", name ?: "none"); + + if (name && !uuid) + uuid = dm_hash_lookup_with_count(s->vgname_to_vgid, name, &count); + else if (uuid && !name) + name = dm_hash_lookup(s->vgid_to_vgname, uuid); + + if (name && uuid && (count > 1)) { + DEBUGLOG(s, "vg_lookup name %s vgid %s found %d vgids", + name, uuid, count); + return daemon_reply_simple("multiple", "reason = %s", "Multiple VGs found with same name", NULL); + } + + if (!uuid || !name) + return reply_unknown("VG not found"); + + } else { + char *name_lookup = dm_hash_lookup(s->vgid_to_vgname, uuid); + char *uuid_lookup = dm_hash_lookup_with_val(s->vgname_to_vgid, name, uuid, strlen(uuid) + 1); + + /* FIXME: comment out these sanity checks when not testing */ + + if (!name_lookup || !uuid_lookup) { + ERROR(s, "vg_lookup vgid %s name %s found incomplete mapping uuid %s name %s", + uuid, name, uuid_lookup ?: "none", name_lookup ?: "none"); + return reply_unknown("VG mapping incomplete"); + } else if (strcmp(name_lookup, name) || strcmp(uuid_lookup, uuid)) { + ERROR(s, "vg_lookup vgid %s name %s found inconsistent mapping uuid %s name %s", + uuid, name, uuid_lookup, name_lookup); + return reply_unknown("VG mapping inconsistent"); + } + } + + DEBUGLOG(s, "vg_lookup vgid %s name %s", uuid ?: "none", name ?: "none"); + + cft = dm_hash_lookup(s->vgid_to_metadata, uuid); + if (!cft || !cft->root) { + return reply_unknown("UUID not found"); + } + + metadata = cft->root; + if (!(res.cft = dm_config_create())) + goto nomem_un; + + /* The response field */ + if (!(res.cft->root = n = dm_config_create_node(res.cft, "response"))) + goto nomem_un; + + if (!(n->v = dm_config_create_value(cft))) + goto nomem_un; + + n->parent = res.cft->root; + n->v->type = DM_CFG_STRING; + n->v->v.str = "OK"; + + if (!(n = n->sib = dm_config_create_node(res.cft, "name"))) + goto nomem_un; + + if (!(n->v = dm_config_create_value(res.cft))) + goto nomem_un; + + n->parent = res.cft->root; + n->v->type = DM_CFG_STRING; + n->v->v.str = name; + + /* The metadata section */ + if (!(n = n->sib = dm_config_clone_node(res.cft, metadata, 1))) + goto nomem_un; + n->parent = res.cft->root; + + if (!update_pv_status(s, res.cft, n)) + goto nomem; + chain_outdated_pvs(s, uuid, res.cft, n); + + if (s->flags & GLFL_INVALID) + add_last_node(res.cft, "global_invalid"); + + info = dm_hash_lookup(s->vgid_to_info, uuid); + if (info && (info->flags & VGFL_INVALID)) { + if (!add_last_node(res.cft, "vg_invalid")) + goto nomem; + } + + return res; + +nomem_un: +nomem: + reply_fail("out of memory"); + ERROR(s, "vg_lookup vgid %s name %s out of memory.", uuid ?: "none", name ?: "none"); + ERROR(s, "lvmetad could not be updated and is aborting."); + exit(EXIT_FAILURE); +} + +static int vg_remove_if_missing(lvmetad_state *s, const char *vgid, int update_pvids); + +enum update_pvid_mode { UPDATE_ONLY, REMOVE_EMPTY, MARK_OUTDATED }; + +/* You need to be holding the pvid_to_vgid lock already to call this. */ +static int _update_pvid_to_vgid(lvmetad_state *s, struct dm_config_tree *vg, + const char *vgid, int mode) +{ + struct dm_config_node *pv; + struct dm_hash_table *to_check; + struct dm_hash_node *n; + const char *pvid; + char *vgid_old; + char *vgid_dup; + const char *check_vgid; + int r = 0; + + if (!vgid) + return 0; + + if (!(to_check = dm_hash_create(32))) + goto abort_daemon; + + for (pv = pvs(vg->root); pv; pv = pv->sib) { + if (!(pvid = dm_config_find_str(pv->child, "id", NULL))) { + ERROR(s, "PV has no id for update_pvid_to_vgid"); + continue; + } + + vgid_old = dm_hash_lookup(s->pvid_to_vgid, pvid); + + if ((mode == REMOVE_EMPTY) && vgid_old) { + /* This copies the vgid_old string, doesn't reference it. */ + if (!dm_hash_insert(to_check, vgid_old, (void*) 1)) { + ERROR(s, "update_pvid_to_vgid out of memory for hash insert vgid_old %s", vgid_old); + goto abort_daemon; + } + } + + if (mode == MARK_OUTDATED) + mark_outdated_pv(s, vgid, pvid); + + if (!(vgid_dup = dm_strdup(vgid))) { + ERROR(s, "update_pvid_to_vgid out of memory for vgid %s", vgid); + goto abort_daemon; + } + + if (!dm_hash_insert(s->pvid_to_vgid, pvid, vgid_dup)) { + ERROR(s, "update_pvid_to_vgid out of memory for hash insert vgid %s", vgid_dup); + dm_free(vgid_dup); + goto abort_daemon; + } + + /* pvid_to_vgid no longer references vgid_old */ + dm_free(vgid_old); + + DEBUGLOG(s, "moving PV %s to VG %s", pvid, vgid); + } + + dm_hash_iterate(n, to_check) { + check_vgid = dm_hash_get_key(to_check, n); + vg_remove_if_missing(s, check_vgid, 0); + } + + r = 1; + dm_hash_destroy(to_check); + + return r; + +abort_daemon: + ERROR(s, "lvmetad could not be updated and is aborting."); + if (to_check) + dm_hash_destroy(to_check); + exit(EXIT_FAILURE); +} + +/* A pvid map lock needs to be held if update_pvids = 1. */ +static int remove_metadata(lvmetad_state *s, const char *vgid, int update_pvids) +{ + struct dm_config_tree *meta_lookup; + struct dm_config_tree *outdated_pvs_lookup; + struct vg_info *info_lookup; + char *name_lookup = NULL; + char *vgid_lookup = NULL; + + /* get data pointers from hash table so they can be freed */ + + info_lookup = dm_hash_lookup(s->vgid_to_info, vgid); + meta_lookup = dm_hash_lookup(s->vgid_to_metadata, vgid); + name_lookup = dm_hash_lookup(s->vgid_to_vgname, vgid); + outdated_pvs_lookup = dm_hash_lookup(s->vgid_to_outdated_pvs, vgid); + if (name_lookup) + vgid_lookup = dm_hash_lookup_with_val(s->vgname_to_vgid, name_lookup, vgid, strlen(vgid) + 1); + + /* remove hash table mappings */ + + dm_hash_remove(s->vgid_to_info, vgid); + dm_hash_remove(s->vgid_to_metadata, vgid); + dm_hash_remove(s->vgid_to_vgname, vgid); + dm_hash_remove(s->vgid_to_outdated_pvs, vgid); + if (name_lookup) + dm_hash_remove_with_val(s->vgname_to_vgid, name_lookup, vgid, strlen(vgid) + 1); + + /* update_pvid_to_vgid will clear/free the pvid_to_vgid hash */ + if (update_pvids && meta_lookup) + (void) _update_pvid_to_vgid(s, meta_lookup, "#orphan", 0); + + /* free the unmapped data */ + + if (info_lookup) + dm_free(info_lookup); + if (meta_lookup) + dm_config_destroy(meta_lookup); + if (name_lookup) + dm_free(name_lookup); + if (outdated_pvs_lookup) + dm_config_destroy(outdated_pvs_lookup); + if (vgid_lookup) + dm_free(vgid_lookup); + return 1; +} + +/* The VG must be locked. */ +static int vg_remove_if_missing(lvmetad_state *s, const char *vgid, int update_pvids) +{ + struct dm_config_tree *vg; + struct dm_config_node *pv; + const char *vgid_check; + const char *pvid; + int missing = 1; + + if (!vgid) + return 0; + + if (!(vg = dm_hash_lookup(s->vgid_to_metadata, vgid))) + return 1; + + for (pv = pvs(vg->root); pv; pv = pv->sib) { + if (!(pvid = dm_config_find_str(pv->child, "id", NULL))) + continue; + + if ((vgid_check = dm_hash_lookup(s->pvid_to_vgid, pvid)) && + dm_hash_lookup(s->pvid_to_pvmeta, pvid) && + !strcmp(vgid, vgid_check)) + missing = 0; /* at least one PV is around */ + } + + if (missing) { + DEBUGLOG(s, "removing empty VG %s", vgid); + remove_metadata(s, vgid, update_pvids); + } + + return 1; +} + +/* + * Remove all hash table references to arg_name and arg_vgid + * so that new metadata using this name and/or vgid can be added + * without interference previous data. + * + * This is used if a command updates metadata in the cache, + * but update_metadata finds that what's in the cache is not + * consistent with a normal transition between old and new + * metadata. If this happens, it assumes that the command + * is providing the correct metadata, so it first calls this + * function to purge all records of the old metadata so the + * new metadata can be added. + */ + +static void _purge_metadata(lvmetad_state *s, const char *arg_name, const char *arg_vgid) +{ + char *rem_vgid; + + remove_metadata(s, arg_vgid, 1); + + if ((rem_vgid = dm_hash_lookup_with_val(s->vgname_to_vgid, arg_name, arg_vgid, strlen(arg_vgid) + 1))) { + dm_hash_remove_with_val(s->vgname_to_vgid, arg_name, arg_vgid, strlen(arg_vgid) + 1); + dm_free(rem_vgid); + } +} + +/* + * Updates for new vgid and new metadata. + * + * Remove any existing vg_info struct since it will be + * recreated by lvmlockd if/when needed. + * + * Remove any existing outdated pvs since their metadata + * will no longer be associated with this VG. + */ + +static int _update_metadata_new_vgid(lvmetad_state *s, + const char *arg_name, + const char *old_vgid, + const char *new_vgid, + struct dm_config_tree *old_meta, + struct dm_config_tree *new_meta) +{ + struct vg_info *rem_info; + struct dm_config_tree *rem_outdated; + char *new_vgid_dup = NULL; + char *arg_name_dup = NULL; + int abort_daemon = 0; + int retval = 0; + + if (!(new_vgid_dup = dm_strdup(new_vgid))) + goto ret; + + if (!(arg_name_dup = dm_strdup(arg_name))) + goto ret; + + /* + * Temporarily orphan the PVs in the old metadata. + */ + if (!_update_pvid_to_vgid(s, old_meta, "#orphan", 0)) { + ERROR(s, "update_metadata_new_vgid failed to move PVs for %s old_vgid %s", arg_name, old_vgid); + abort_daemon = 1; + goto ret; + } + + /* + * Remove things related to the old vgid. (like remove_metadata) + */ + + if ((rem_info = dm_hash_lookup(s->vgid_to_info, old_vgid))) { + dm_hash_remove(s->vgid_to_info, old_vgid); + dm_free(rem_info); + } + + if ((rem_outdated = dm_hash_lookup(s->vgid_to_outdated_pvs, old_vgid))) { + dm_hash_remove(s->vgid_to_outdated_pvs, old_vgid); + dm_config_destroy(rem_outdated); + } + + dm_hash_remove(s->vgid_to_metadata, old_vgid); + dm_config_destroy(old_meta); + old_meta = NULL; + + dm_hash_remove_with_val(s->vgname_to_vgid, arg_name, old_vgid, strlen(old_vgid) + 1); + dm_hash_remove(s->vgid_to_vgname, old_vgid); + dm_free((char *)old_vgid); + old_vgid = NULL; + + /* + * Insert things with the new vgid. + */ + + if (!dm_hash_insert(s->vgid_to_metadata, new_vgid, new_meta)) { + ERROR(s, "update_metadata_new_vgid out of memory for meta hash insert for %s %s", arg_name, new_vgid); + abort_daemon = 1; + goto out; + } + + if (!dm_hash_insert(s->vgid_to_vgname, new_vgid, arg_name_dup)) { + ERROR(s, "update_metadata_new_vgid out of memory for name hash insert for %s %s", arg_name, new_vgid); + abort_daemon = 1; + goto out; + } + + if (!dm_hash_insert_allow_multiple(s->vgname_to_vgid, arg_name, new_vgid_dup, strlen(new_vgid_dup) + 1)) { + ERROR(s, "update_metadata_new_vgid out of memory for vgid hash insert for %s %s", arg_name, new_vgid); + abort_daemon = 1; + goto out; + } + + /* + * Reassign PVs based on the new metadata. + */ + if (!_update_pvid_to_vgid(s, new_meta, new_vgid, 1)) { + ERROR(s, "update_metadata_new_name failed to update PVs for %s %s", arg_name, new_vgid); + abort_daemon = 1; + goto out; + } + + DEBUGLOG(s, "update_metadata_new_vgid is done for %s %s", arg_name, new_vgid); + retval = 1; +out: +ret: + if (!new_vgid_dup || !arg_name_dup || abort_daemon) { + ERROR(s, "lvmetad could not be updated and is aborting."); + exit(EXIT_FAILURE); + } + + if (!retval && new_meta) + dm_config_destroy(new_meta); + return retval; +} + +/* + * Updates for new name and new metadata. + * + * Remove any existing vg_info struct since it will be + * recreated by lvmlockd if/when needed. + * + * Remove any existing outdated pvs since their metadata + * will no longer be associated with this VG. + */ + +static int _update_metadata_new_name(lvmetad_state *s, + const char *arg_vgid, + const char *old_name, + const char *new_name, + struct dm_config_tree *old_meta, + struct dm_config_tree *new_meta) +{ + struct vg_info *rem_info; + struct dm_config_tree *rem_outdated; + char *new_name_dup = NULL; + char *arg_vgid_dup = NULL; + int abort_daemon = 0; + int retval = 0; + + if (!(new_name_dup = dm_strdup(new_name))) + goto ret; + + if (!(arg_vgid_dup = dm_strdup(arg_vgid))) + goto ret; + + /* + * Temporarily orphan the PVs in the old metadata. + */ + if (!_update_pvid_to_vgid(s, old_meta, "#orphan", 0)) { + ERROR(s, "update_metadata_new_name failed to move PVs for old_name %s %s", old_name, arg_vgid); + abort_daemon = 1; + goto ret; + } + + /* + * Remove things related to the old name. + */ + + if ((rem_info = dm_hash_lookup(s->vgid_to_info, arg_vgid))) { + dm_hash_remove(s->vgid_to_info, arg_vgid); + dm_free(rem_info); + } + + if ((rem_outdated = dm_hash_lookup(s->vgid_to_outdated_pvs, arg_vgid))) { + dm_hash_remove(s->vgid_to_outdated_pvs, arg_vgid); + dm_config_destroy(rem_outdated); + } + + dm_hash_remove(s->vgid_to_metadata, arg_vgid); + dm_config_destroy(old_meta); + old_meta = NULL; + + dm_hash_remove(s->vgid_to_vgname, arg_vgid); + dm_hash_remove_with_val(s->vgname_to_vgid, old_name, arg_vgid, strlen(arg_vgid) + 1); + dm_free((char *)old_name); + old_name = NULL; + + /* + * Insert things with the new name. + */ + + if (!dm_hash_insert(s->vgid_to_metadata, arg_vgid, new_meta)) { + ERROR(s, "update_metadata_new_name out of memory for meta hash insert for %s %s", new_name, arg_vgid); + abort_daemon = 1; + goto out; + } + + if (!dm_hash_insert(s->vgid_to_vgname, arg_vgid, new_name_dup)) { + ERROR(s, "update_metadata_new_name out of memory for name hash insert for %s %s", new_name, arg_vgid); + abort_daemon = 1; + goto out; + } + + if (!dm_hash_insert_allow_multiple(s->vgname_to_vgid, new_name, arg_vgid_dup, strlen(arg_vgid_dup) + 1)) { + ERROR(s, "update_metadata_new_name out of memory for vgid hash insert for %s %s", new_name, arg_vgid); + abort_daemon = 1; + goto out; + } + + /* + * Reassign PVs based on the new metadata. + */ + if (!_update_pvid_to_vgid(s, new_meta, arg_vgid, 1)) { + ERROR(s, "update_metadata_new_name failed to update PVs for %s %s", new_name, arg_vgid); + abort_daemon = 1; + goto out; + } + + DEBUGLOG(s, "update_metadata_new_name is done for %s %s", new_name, arg_vgid); + retval = 1; +out: +ret: + if (!new_name_dup || !arg_vgid_dup || abort_daemon) { + ERROR(s, "lvmetad could not be updated and is aborting."); + exit(EXIT_FAILURE); + } + + if (!retval && new_meta) + dm_config_destroy(new_meta); + return retval; +} + + +/* + * Add new entries to all hash tables. + */ + +static int _update_metadata_add_new(lvmetad_state *s, const char *new_name, const char *new_vgid, + struct dm_config_tree *new_meta) +{ + char *new_name_dup = NULL; + char *new_vgid_dup = NULL; + int abort_daemon = 0; + int retval = 0; + + DEBUGLOG(s, "update_metadata_add_new for %s %s", new_name, new_vgid); + + if (!(new_name_dup = dm_strdup(new_name))) + goto out_free; + + if (!(new_vgid_dup = dm_strdup(new_vgid))) + goto out_free; + + if (!dm_hash_insert(s->vgid_to_metadata, new_vgid, new_meta)) { + ERROR(s, "update_metadata_add_new out of memory for meta hash insert for %s %s", new_name, new_vgid); + abort_daemon = 1; + goto out; + } + + if (!dm_hash_insert(s->vgid_to_vgname, new_vgid, new_name_dup)) { + ERROR(s, "update_metadata_add_new out of memory for name hash insert for %s %s", new_name, new_vgid); + abort_daemon = 1; + goto out; + } + + if (!dm_hash_insert_allow_multiple(s->vgname_to_vgid, new_name, new_vgid_dup, strlen(new_vgid_dup) + 1)) { + ERROR(s, "update_metadata_add_new out of memory for vgid hash insert for %s %s", new_name, new_vgid); + abort_daemon = 1; + goto out; + } + + if (!_update_pvid_to_vgid(s, new_meta, new_vgid, 1)) { + ERROR(s, "update_metadata_add_new failed to update PVs for %s %s", new_name, new_vgid); + abort_daemon = 1; + goto out; + } + + DEBUGLOG(s, "update_metadata_add_new is done for %s %s", new_name, new_vgid); + retval = 1; +out: +out_free: + if (!new_name_dup || !new_vgid_dup || abort_daemon) { + if (new_name_dup) + dm_free(new_name_dup); + if (new_vgid_dup) + dm_free(new_vgid_dup); + ERROR(s, "lvmetad could not be updated and is aborting."); + exit(EXIT_FAILURE); + } + + if (!retval && new_meta) + dm_config_destroy(new_meta); + return retval; +} + +/* + * No locks need to be held. The pointers are never used outside of the scope of + * this function, so they can be safely destroyed after update_metadata returns + * (anything that might have been retained is copied). + * + * When this is called from pv_found, the metadata was read from a single + * PV specified by the pvid arg and ret_old_seq is not NULL. The metadata + * should match the existing metadata (matching seqno). If the metadata + * from pv_found has a smaller seqno, it means that the PV is outdated + * (was previously used in the VG and now reappeared after changes to the VG). + * The next command to access the VG will erase the outdated PV and then clear + * the outdated pv record here. If the metadata from pv_found has a larger + * seqno than the existing metadata, it means ... (existing pvs are outdated?) + * + * When this is caleld from vg_update, the metadata is from a command that + * has new metadata that should replace the existing metadata. + * pvid and ret_old_seq are both NULL. + */ + +static int _update_metadata(lvmetad_state *s, const char *arg_name, const char *arg_vgid, + struct dm_config_node *new_metadata, int *ret_old_seq, + const char *pvid) +{ + struct dm_config_tree *old_meta = NULL; + struct dm_config_tree *new_meta = NULL; + const char *arg_name_lookup; /* name lookup result from arg_vgid */ + const char *arg_vgid_lookup; /* vgid lookup result from arg_name */ + const char *old_name = NULL; + const char *new_name = NULL; + const char *old_vgid = NULL; + const char *new_vgid = NULL; + const char *new_metadata_vgid; + int old_seq = -1; + int new_seq = -1; + int needs_repair = 0; + int abort_daemon = 0; + int retval = 0; + int count = 0; + + if (!arg_vgid || !arg_name) { + ERROR(s, "update_metadata missing args arg_vgid %s arg_name %s pvid %s", + arg_vgid ?: "none", arg_name ?: "none", pvid ?: "none"); + return 0; + } + + DEBUGLOG(s, "update_metadata begin arg_vgid %s arg_name %s pvid %s", + arg_vgid, arg_name, pvid ?: "none"); + + /* + * Begin by figuring out what has changed: + * . the VG could be new - found no existing record of the vgid or name. + * . the VG could have a new vgid - found an existing record of the name. + * . the VG could have a new name - found an existing record of the vgid. + * . the VG could have unchanged vgid and name - found existing record of both. + */ + + arg_name_lookup = dm_hash_lookup(s->vgid_to_vgname, arg_vgid); + arg_vgid_lookup = dm_hash_lookup_with_val(s->vgname_to_vgid, arg_name, arg_vgid, strlen(arg_vgid) + 1); + + /* + * A new VG when there is no existing record of the name or vgid args. + */ + if (!arg_name_lookup && !arg_vgid_lookup) { + new_vgid = arg_vgid; + new_name = arg_name; + + DEBUGLOG(s, "update_metadata new name %s and new vgid %s", + new_name, new_vgid); + goto update; + } + + /* + * An existing name has a new vgid (new_vgid = arg_vgid). + * A lookup of the name arg was successful in finding arg_vgid_lookup, + * but that resulting vgid doesn't match the arg_vgid. + */ + if (arg_vgid_lookup && strcmp(arg_vgid_lookup, arg_vgid)) { + if (arg_name_lookup) { + /* + * This shouldn't happen. + * arg_vgid should be new and should not map to any name. + */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s unexpected arg_name_lookup %s", + arg_vgid, arg_name, arg_name_lookup); + needs_repair = 1; + goto update; + } + + new_vgid = arg_vgid; + old_vgid = dm_hash_lookup_with_count(s->vgname_to_vgid, arg_name, &count); + + /* + * FIXME: this ensures that arg_name maps to only one existing + * VG (old_vgid), because if it maps to multiple vgids, then we + * don't know which one should get the new vgid (arg_vgid). If + * this function was given both the existing name and existing + * vgid to identify the VG, then this wouldn't be a problem. + * But as it is now, the vgid arg to this function is the new + * vgid and the existing VG is specified only by name. + */ + if (old_vgid && (count > 1)) { + ERROR(s, "update_metadata arg_vgid %s arg_name %s found %d vgids for name", + arg_vgid, arg_name, count); + old_vgid = NULL; + } + + if (!old_vgid) { + /* This shouldn't happen. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s no old_vgid", + arg_vgid, arg_name); + needs_repair = 1; + goto update; + } + + if (!(old_meta = dm_hash_lookup(s->vgid_to_metadata, old_vgid))) { + /* This shouldn't happen. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s old_vgid %s no old_meta", + arg_vgid, arg_name, old_vgid); + needs_repair = 1; + goto update; + } + + DEBUGLOG(s, "update_metadata existing name %s has new vgid %s old vgid %s", + arg_name, new_vgid, old_vgid); + goto update; + } + + /* + * An existing vgid has a new name (new_name = arg_name). + * A lookup of the vgid arg was successful in finding arg_name_lookup, + * but that resulting name doesn't match the arg_name. + */ + if (arg_name_lookup && strcmp(arg_name_lookup, arg_name)) { + if (arg_vgid_lookup) { + /* + * This shouldn't happen. + * arg_name should be new and should not map to any vgid. + */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s unexpected arg_vgid_lookup %s", + arg_vgid, arg_name, arg_vgid_lookup); + needs_repair = 1; + goto update; + } + + new_name = arg_name; + old_name = dm_hash_lookup(s->vgid_to_vgname, arg_vgid); + + if (!old_name) { + /* This shouldn't happen. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s no old_name", + arg_vgid, arg_name); + needs_repair = 1; + goto update; + } + + if (!(old_meta = dm_hash_lookup(s->vgid_to_metadata, arg_vgid))) { + /* This shouldn't happen. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s old_name %s no old_meta", + arg_vgid, arg_name, old_name); + needs_repair = 1; + goto update; + } + + DEBUGLOG(s, "update_metadata existing vgid %s has new name %s old name %s", + arg_vgid, new_name, old_name); + goto update; + } + + /* + * An existing VG has unchanged name and vgid. + */ + if (!new_vgid && !new_name) { + if (!arg_vgid_lookup || !arg_name_lookup) { + /* This shouldn't happen. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s missing lookups vgid %s name %s", + arg_vgid ?: "none", arg_name ?: "none", arg_vgid_lookup ?: "none", arg_name_lookup ?: "none"); + needs_repair = 1; + goto update; + } + + if (strcmp(arg_name_lookup, arg_name)) { + /* This shouldn't happen. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s mismatch arg_name_lookup %s", + arg_vgid, arg_name, arg_name_lookup); + needs_repair = 1; + goto update; + } + + if (strcmp(arg_vgid_lookup, arg_vgid)) { + /* This shouldn't happen. Two VGs with the same name is handled above. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s mismatch arg_vgid_lookup %s", + arg_vgid, arg_name, arg_vgid_lookup); + needs_repair = 1; + goto update; + } + + /* old_vgid == arg_vgid, and old_name == arg_name */ + + if (!(old_meta = dm_hash_lookup(s->vgid_to_metadata, arg_vgid))) { + /* This shouldn't happen. */ + ERROR(s, "update_metadata arg_vgid %s arg_name %s no old_meta", + arg_vgid, arg_name); + needs_repair = 1; + goto update; + } + + DEBUGLOG(s, "update_metadata existing vgid %s and existing name %s", + arg_vgid, arg_name); + goto update; + } + + update: + filter_metadata(new_metadata); /* sanitize */ + + /* + * FIXME: verify that there's at least one PV in common between + * the old and new metadata? + */ + + if (!(new_meta = dm_config_create()) || + !(new_meta->root = dm_config_clone_node(new_meta, new_metadata, 0))) { + ERROR(s, "update_metadata out of memory for new metadata for %s %s", + arg_name, arg_vgid); + /* FIXME: should we purge the old metadata here? */ + retval = 0; + goto out; + } + + /* + * Get the seqno from existing (old) and new metadata and perform + * sanity checks for transitions that generally shouldn't happen. + * Sometimes ignore the new metadata and leave the existing metadata + * alone, and sometimes purge the existing metadata and add the new. + * This often depends on whether the new metadata comes from a single + * PV (via pv_found) that's been scanned, or a vg_update sent from a + * command. + */ + + new_seq = dm_config_find_int(new_metadata, "metadata/seqno", -1); + + if (old_meta) + old_seq = dm_config_find_int(old_meta->root, "metadata/seqno", -1); + + if (ret_old_seq) + *ret_old_seq = old_meta ? old_seq : new_seq; + + /* + * The new metadata has an invalid seqno. + * This shouldn't happen, but if it does, ignore the new metadata. + */ + if (new_seq <= 0) { + ERROR(s, "update_metadata ignore new metadata because of invalid seqno for %s %s", + arg_vgid, arg_name); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + retval = 0; + goto out; + } + + /* + * The new metadata is missing an internal vgid. + * This shouldn't happen, but if it does, ignore the new metadata. + */ + if (!(new_metadata_vgid = dm_config_find_str(new_meta->root, "metadata/id", NULL))) { + ERROR(s, "update_metadata has no internal vgid for %s %s", + arg_name, arg_vgid); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + retval = 0; + goto out; + } + + /* + * The new metadata internal vgid doesn't match the arg vgid. + * This shouldn't happen, but if it does, ignore the new metadata. + */ + if (strcmp(new_metadata_vgid, arg_vgid)) { + ERROR(s, "update_metadata has bad internal vgid %s for %s %s", + new_metadata_vgid, arg_name, arg_vgid); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + retval = 0; + goto out; + } + + /* + * A single PV appears with metadata that's inconsistent with + * existing, ignore the PV. FIXME: make it outdated? + */ + if (pvid && needs_repair) { + ERROR(s, "update_metadata ignore inconsistent metadata on PV %s seqno %d for %s %s seqno %d", + pvid, new_seq, arg_vgid, arg_name, old_seq); + if (old_meta) + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + retval = 0; + goto out; + } + + /* + * A VG update with metadata that's inconsistent with existing. + */ + if (!pvid && needs_repair) { + ERROR(s, "update_metadata inconsistent with cache for vgid %s and name %s", + arg_vgid, arg_name); + if (old_meta) + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + abort_daemon = 1; + retval = 0; + goto out; + } + + /* + * A single PV appears with metadata that's older than the existing, + * e.g. an PV that had been in the VG has reappeared after the VG changed. + * old PV: the PV that lvmetad was told about first + * new PV: the PV that lvmetad is being told about here, second + * old_seq: the larger seqno on the old PV, for the newer version of the VG + * new_seq: the smaller seqno on the new PV, for the older version of the VG + * + * So, the new PV (by notification order) is "older" (in terms of + * VG seqno) than the old PV. + * + * Make the new PV outdated so it'll be cleared and keep the existing + * metadata from the old PV. + */ + if (pvid && (old_seq > 0) && (new_seq < old_seq)) { + ERROR(s, "update_metadata ignoring outdated metadata on PV %s seqno %d for %s %s seqno %d", + pvid, new_seq, arg_vgid, arg_name, old_seq); + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + mark_outdated_pv(s, arg_vgid, pvid); + retval = 0; + goto out; + } + + /* + * A single PV appears with metadata that's newer than the existing, + * e.g. a PV has been found with VG metadata that is newer than the + * VG metdata we know about. This can happen when scanning PVs after + * an outdated PV (with an older version of the VG metadata) has + * reappeared. The rescanning may initially scan the outdated PV + * and notify lvmetad about it, and then scan a current PV from + * the VG and notify lvmetad about it. + * old PV: the PV that lvmetad was told about first + * new PV: the PV that lvmetad is being told about here, second + * old_seq: the smaller seqno on the old PV, for the older version of the VG + * new_seq: the larger seqno on the new PV, for the newer version of the VG + * + * Make the existing PVs outdated, and use the new metadata. + */ + if (pvid && (old_seq > 0) && (new_seq > old_seq)) { + ERROR(s, "update_metadata found newer metadata on PV %s seqno %d for %s %s seqno %d", + pvid, new_seq, arg_vgid, arg_name, old_seq); + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + _update_pvid_to_vgid(s, old_meta, arg_vgid, MARK_OUTDATED); + } + + /* + * The existing/old metadata has an invalid seqno. + * This shouldn't happen, but if it does, purge old and add the new. + */ + if (old_meta && (old_seq <= 0)) { + ERROR(s, "update_metadata bad old seqno %d for %s %s", + old_seq, arg_name, arg_vgid); + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + _purge_metadata(s, arg_name, arg_vgid); + new_name = arg_name; + new_vgid = arg_vgid; + old_name = NULL; + old_vgid = NULL; + old_meta = NULL; + old_seq = -1; + } + + /* + * A single PV appears with a seqno matching existing metadata, + * but unmatching metadata content. This shouldn't happen, + * but if it does, ignore the PV. FIXME: make it outdated? + */ + if (pvid && (new_seq == old_seq) && compare_config(new_metadata, old_meta->root)) { + ERROR(s, "update_metadata from pv %s same seqno %d with unmatching data for %s %s", + pvid, new_seq, arg_name, arg_vgid); + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + retval = 0; + goto out; + } + + /* + * A VG update with metadata matching existing seqno but unmatching content. + * This shouldn't happen, but if it does, purge existing and add the new. + */ + if (!pvid && (new_seq == old_seq) && compare_config(new_metadata, old_meta->root)) { + ERROR(s, "update_metadata same seqno %d with unmatching data for %s %s", + new_seq, arg_name, arg_vgid); + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + _purge_metadata(s, arg_name, arg_vgid); + new_name = arg_name; + new_vgid = arg_vgid; + old_name = NULL; + old_vgid = NULL; + old_meta = NULL; + old_seq = -1; + } + + /* + * A VG update with metadata older than existing. VG updates should + * have increasing seqno. This shouldn't happen, but if it does, + * purge existing and add the new. + */ + if (!pvid && (new_seq < old_seq)) { + ERROR(s, "update_metadata new seqno %d less than old seqno %d for %s %s", + new_seq, old_seq, arg_name, arg_vgid); + DEBUGLOG_cft(s, "OLD: ", old_meta->root); + DEBUGLOG_cft(s, "NEW: ", new_metadata); + _purge_metadata(s, arg_name, arg_vgid); + new_name = arg_name; + new_vgid = arg_vgid; + old_name = NULL; + old_vgid = NULL; + old_meta = NULL; + old_seq = -1; + } + + /* + * All the checks are done, do one of the four possible updates + * outlined above: + */ + + /* + * Add metadata for a new VG to the cache. + */ + if (new_name && new_vgid) + return _update_metadata_add_new(s, new_name, new_vgid, new_meta); + + /* + * Update cached metadata for a VG with a new vgid. + */ + if (new_vgid) + return _update_metadata_new_vgid(s, arg_name, old_vgid, new_vgid, old_meta, new_meta); + + /* + * Update cached metadata for a renamed VG. + */ + if (new_name) + return _update_metadata_new_name(s, arg_vgid, old_name, new_name, old_meta, new_meta); + + /* + * If the old and new seqnos are the same, we've already compared the + * old/new metadata and verified it's the same, so there's no reason + * to replace old meta with new meta. + */ + if (old_seq == new_seq) { + DEBUGLOG(s, "update_metadata skipped for %s %s seqno %d is unchanged", + arg_name, arg_vgid, old_seq); + dm_config_destroy(new_meta); + new_meta = NULL; + retval = 1; + goto out; + } + + /* + * Update cached metdata for a VG with unchanged name and vgid. + * Replace the old metadata with the new metadata. + * old_meta is the old copy of the metadata from the cache. + * new_meta is the new copy of the metadata from the command. + */ + DEBUGLOG(s, "update_metadata for %s %s from %d to %d", arg_name, arg_vgid, old_seq, new_seq); + + /* + * The PVs in the VG may have changed in the new metadata, so + * temporarily orphan all of the PVs in the existing VG. + * The PVs that are still in the VG will be reassigned to this + * VG below by the next call to _update_pvid_to_vgid(). + */ + if (!_update_pvid_to_vgid(s, old_meta, "#orphan", 0)) { + ERROR(s, "update_metadata failed to move PVs for %s %s", arg_name, arg_vgid); + abort_daemon = 1; + retval = 0; + goto out; + } + + /* + * The only hash table update that is needed is the actual + * metadata config tree in vgid_to_metadata. The VG name + * and vgid are unchanged. + */ + + dm_hash_remove(s->vgid_to_metadata, arg_vgid); + dm_config_destroy(old_meta); + old_meta = NULL; + + if (!dm_hash_insert(s->vgid_to_metadata, arg_vgid, new_meta)) { + ERROR(s, "update_metadata out of memory for hash insert for %s %s", arg_name, arg_vgid); + abort_daemon = 1; + retval = 0; + goto out; + } + + /* + * Map the PVs in the new metadata to the vgid. + * All pre-existing PVs were temporarily orphaned above. + * Previous PVs that were removed from the VG will not + * be remapped. New PVs that were added to the VG will + * be newly mapped to this vgid, and previous PVs that + * remain in the VG will be remapped to the VG again. + */ + if (!_update_pvid_to_vgid(s, new_meta, arg_vgid, 1)) { + ERROR(s, "update_metadata failed to update PVs for %s %s", arg_name, arg_vgid); + abort_daemon = 1; + retval = 0; + } else { + DEBUGLOG(s, "update_metadata is done for %s %s", arg_name, arg_vgid); + retval = 1; + } + +out: + if (abort_daemon) { + ERROR(s, "lvmetad could not be updated is aborting."); + exit(EXIT_FAILURE); + } + + if (!retval && new_meta) + dm_config_destroy(new_meta); + return retval; +} + +static response pv_gone(lvmetad_state *s, request r) +{ + const char *arg_pvid = NULL; + char *old_pvid = NULL; + const char *pvid; + int64_t device; + struct dm_config_tree *pvmeta; + char *vgid; + + arg_pvid = daemon_request_str(r, "uuid", NULL); + device = daemon_request_int(r, "device", 0); + + if (!arg_pvid && device > 0) + old_pvid = dm_hash_lookup_binary(s->device_to_pvid, &device, sizeof(device)); + + if (!arg_pvid && !old_pvid) { + DEBUGLOG(s, "pv_gone device %" PRIu64 " not found", device); + return reply_unknown("device not in cache"); + } + + pvid = arg_pvid ? arg_pvid : old_pvid; + + DEBUGLOG(s, "pv_gone %s device %" PRIu64, pvid ?: "none", device); + + if (!(pvmeta = dm_hash_lookup(s->pvid_to_pvmeta, pvid))) { + DEBUGLOG(s, "pv_gone %s device %" PRIu64 " has no PV metadata", + pvid ?: "none", device); + return reply_unknown("PVID does not exist"); + } + + vgid = dm_hash_lookup(s->pvid_to_vgid, pvid); + + dm_hash_remove_binary(s->device_to_pvid, &device, sizeof(device)); + dm_hash_remove(s->pvid_to_pvmeta, pvid); + + if (vgid) { + char *vgid_dup; + /* + * vg_remove_if_missing will clear and free the pvid_to_vgid + * mappings for this vg, which will free the "vgid" string that + * was returned above from the pvid_to_vgid lookup. + */ + if (!(vgid_dup = dm_strdup(vgid))) + return reply_fail("out of memory"); + + vg_remove_if_missing(s, vgid_dup, 1); + dm_free(vgid_dup); + vgid_dup = NULL; + vgid = NULL; + } + + dm_config_destroy(pvmeta); + if (old_pvid) + dm_free(old_pvid); + + return daemon_reply_simple("OK", NULL ); +} + +static response pv_clear_all(lvmetad_state *s, request r) +{ + DEBUGLOG(s, "pv_clear_all"); + + destroy_metadata_hashes(s); + create_metadata_hashes(s); + + return daemon_reply_simple("OK", NULL); +} + +/* + * Returns 1 if PV metadata exists for all PVs in a VG. + */ +static int _vg_is_complete(lvmetad_state *s, struct dm_config_tree *vgmeta) +{ + struct dm_config_node *vg = vgmeta->root; + struct dm_config_node *pv; + int complete = 1; + const char *pvid; + + for (pv = pvs(vg); pv; pv = pv->sib) { + if (!(pvid = dm_config_find_str(pv->child, "id", NULL))) + continue; + + if (!dm_hash_lookup(s->pvid_to_pvmeta, pvid)) { + complete = 0; + break; + } + } + + return complete; +} + +/* + * pv_found: a PV has appeared and been scanned + * It contains PV metadata, and optionally VG metadata. + * Both kinds of metadata should be added to the cache + * and hash table mappings related to the PV and device + * should be updated. + * + * Input values from request: + * . arg_pvmeta: PV metadata from the found pv + * . arg_pvid: pvid from arg_pvmeta (pvmeta/id) + * . arg_device: device from arg_pvmeta (pvmeta/device) + * . arg_vgmeta: VG metadata from the found pv (optional) + * . arg_name: VG name from found pv (optional) + * . arg_vgid: VG vgid from arg_vgmeta (optional) + * + * Search for existing mappings in hash tables: + * . pvid_to_pvmeta (which produces pvid to device) + * . device_to_pvid + * . pvid_to_vgid + * + * Existing data from cache: + * . old_pvmeta: result of pvid_to_pvmeta(arg_pvid) + * . arg_device_lookup: result of old_pvmeta:pvmeta/device using arg_pvid + * . arg_pvid_lookup: result of device_to_pvid(arg_device) + * . arg_vgid_lookup: result of pvid_to_vgid(arg_pvid) + * + * When arg_pvid doesn't match arg_pvid_lookup: + * . a new PV replaces a previous PV on arg_device + * . prev_pvid_on_dev: set to arg_pvid_lookup, pvid of the prev PV + * . prev_pvmeta_on_dev: result pvid_to_pvmeta(prev_pvid_on_dev) + * . prev_vgid_on_dev: result of pvid_to_vgid(prev_pvid_on_dev) + * + * Old PV on old device + * . no PV/device mappings have changed + * . arg_pvid_lookup == arg_pvid && arg_device_lookup == arg_device + * . arg_device was used to look up a PV and found a PV with + * the same pvid as arg_pvid + * . arg_pvid was used to look up a PV and found a PV on the + * same device as arg_device + * . new_pvmeta may be more recent than old_pvmeta + * + * New PV on new device + * . add new mappings in hash tables + * . !arg_pvid_lookup && !arg_device_lookup + * . arg_device was used to look up a PV and found nothing + * . arg_pvid was used to look up a PV and found nothing + * + * New PV on old device + * . a new PV replaces a previous PV on a device + * . arg_pvid_lookup != arg_pvid + * . arg_device was used to look up a PV and found a PV with + * a different pvid than arg_pvid + * . replace existing mappings for arg_device and arg_pvid + * . replace existing old_pvmeta with new_pvmeta + * . remove arg_device association with prev PV (prev_pvid_on_dev) + * . possibly remove prev PV (if arg_device was previously a duplicate) + * + * Old PV on new device + * . a duplicate PV + * . arg_device_lookup != arg_device + * . arg_pvid was used to look up a PV, and found that the PV + * has a different device than arg_device. + */ + +static response pv_found(lvmetad_state *s, request r) +{ + struct dm_config_node *arg_vgmeta = NULL; + struct dm_config_node *arg_pvmeta = NULL; + struct dm_config_tree *old_pvmeta = NULL; + struct dm_config_tree *new_pvmeta = NULL; + struct dm_config_tree *prev_pvmeta_on_dev = NULL; + struct dm_config_tree *vgmeta = NULL; + const char *arg_pvid = NULL; + const char *arg_pvid_lookup = NULL; + const char *new_pvid = NULL; + const char *new_pvid_dup = NULL; + const char *arg_name = NULL; + const char *arg_vgid = NULL; + const char *arg_vgid_lookup = NULL; + const char *prev_pvid_on_dev = NULL; + const char *prev_vgid_on_dev = NULL; + const char *vg_status = NULL; + uint64_t arg_device = 0; + uint64_t arg_device_lookup = 0; + uint64_t new_device = 0; + uint64_t old_device = 0; + int arg_seqno = -1; + int old_seqno = -1; + int vg_status_seqno = -1; + int changed = 0; + + /* + * New input values. + */ + + if (!(arg_pvmeta = dm_config_find_node(r.cft->root, "pvmeta"))) { + ERROR(s, "Ignore PV without PV metadata"); + return reply_fail("Ignore PV without PV metadata"); + } + + if (!(arg_pvid = daemon_request_str(r, "pvmeta/id", NULL))) { + ERROR(s, "Ignore PV without PV UUID"); + return reply_fail("Ignore PV without PV UUID"); + } + + if (!dm_config_get_uint64(arg_pvmeta, "pvmeta/device", &arg_device)) { + ERROR(s, "Ignore PV without device pvid %s", arg_pvid); + return reply_fail("Ignore PV without device"); + } + + if ((arg_vgmeta = dm_config_find_node(r.cft->root, "metadata"))) { + arg_name = daemon_request_str(r, "vgname", NULL); + arg_vgid = daemon_request_str(r, "metadata/id", NULL); + arg_seqno = daemon_request_int(r, "metadata/seqno", -1); + + if (!arg_name || !arg_vgid || (arg_seqno < 0)) + ERROR(s, "Ignore VG metadata from PV %s", arg_pvid); + if (!arg_name) + return reply_fail("Ignore VG metadata from PV without VG name"); + if (!arg_vgid) + return reply_fail("Ignore VG metadata from PV without VG vgid"); + if (arg_seqno < 0) + return reply_fail("Ignore VG metadata from PV without VG seqno"); + } + + /* Make a copy of the new pvmeta that can be inserted into cache. */ + if (!(new_pvmeta = dm_config_create()) || + !(new_pvmeta->root = dm_config_clone_node(new_pvmeta, arg_pvmeta, 0))) { + ERROR(s, "pv_found out of memory for new pvmeta %s", arg_pvid); + goto nomem; + } + + /* + * Existing (old) cache values. + */ + + old_pvmeta = dm_hash_lookup(s->pvid_to_pvmeta, arg_pvid); + if (old_pvmeta) + dm_config_get_uint64(old_pvmeta->root, "pvmeta/device", &arg_device_lookup); + + arg_pvid_lookup = dm_hash_lookup_binary(s->device_to_pvid, &arg_device, sizeof(arg_device)); + + /* + * Determine which of the four possible changes is happening + * by comparing the existing/old and new values: + * old PV, old device + * new PV, new device + * new PV, old device + * old PV, new device + */ + + if (arg_pvid_lookup && arg_device_lookup && + (arg_device == arg_device_lookup) && + !strcmp(arg_pvid_lookup, arg_pvid)) { + /* + * Old PV on old device (existing values unchanged) + */ + new_pvid = NULL; + new_device = 0; + + DEBUGLOG(s, "pv_found pvid %s on device %" PRIu64 " matches existing", + arg_pvid, arg_device); + + } else if (!arg_pvid_lookup && !arg_device_lookup) { + /* + * New PV on new device (no existing values) + */ + new_pvid = arg_pvid; + new_device = arg_device; + + DEBUGLOG(s, "pv_found pvid %s on device %" PRIu64 " is new", + arg_pvid, arg_device); + + } else if (arg_pvid_lookup && strcmp(arg_pvid_lookup, arg_pvid)) { + /* + * New PV on old device (existing device reused for new PV) + */ + new_pvid = arg_pvid; + new_device = 0; + prev_pvid_on_dev = arg_pvid_lookup; + prev_pvmeta_on_dev = dm_hash_lookup(s->pvid_to_pvmeta, arg_pvid_lookup); + prev_vgid_on_dev = dm_hash_lookup(s->pvid_to_vgid, arg_pvid_lookup); + + DEBUGLOG(s, "pv_found pvid %s vgid %s on device %" PRIu64 " previous pvid %s vgid %s", + arg_pvid, arg_vgid ?: "none", arg_device, + prev_pvid_on_dev, prev_vgid_on_dev ?: "none"); + + } else if (arg_device_lookup && (arg_device_lookup != arg_device)) { + /* + * Old PV on new device (existing PV on a new device, i.e. duplicate) + */ + new_device = arg_device; + new_pvid = NULL; + old_device = arg_device_lookup; + + DEBUGLOG(s, "pv_found pvid %s vgid %s on device %" PRIu64 " duplicate %" PRIu64, + arg_pvid, arg_vgid ?: "none", arg_device, arg_device_lookup); + + } else { + ERROR(s, "pv_found pvid %s vgid %s on device %" PRIu64 " unknown lookup %s %s %" PRIu64, + arg_pvid, + arg_vgid ?: "none", + arg_device, + arg_pvid_lookup ?: "none", + arg_vgid_lookup ?: "none", + arg_device_lookup); + return reply_fail("Ignore PV for unknown state"); + } + + /* + * Make changes to hashes device_to_pvid and pvid_to_pvmeta for each case. + */ + + if (!new_pvid && !new_device) { + /* + * Old PV on old device (unchanged) + * . add new_pvmeta, replacing old_pvmeta + */ + if (compare_config(old_pvmeta->root, new_pvmeta->root)) + changed |= 1; + + if (!dm_hash_insert(s->pvid_to_pvmeta, arg_pvid, new_pvmeta)) + goto nomem_free1; + + } else if (new_pvid && new_device) { + /* + * New PV on new device (new entry) + * . add new_device/new_pvid mapping + * . add new_pvmeta + */ + changed |= 1; + + DEBUGLOG(s, "pv_found new entry device_to_pvid %" PRIu64 " to %s", + new_device, new_pvid); + + if (!(new_pvid_dup = dm_strdup(new_pvid))) + goto nomem_free1; + + if (!dm_hash_insert_binary(s->device_to_pvid, &new_device, sizeof(new_device), (char *)new_pvid_dup)) + goto nomem_free2; + + if (!dm_hash_insert(s->pvid_to_pvmeta, new_pvid, new_pvmeta)) + goto nomem_free1; + + } else if (new_pvid && !new_device) { + /* + * New PV on old device (existing device reused for new PV). + * The previous PV on arg_device is replaced by the new one. + * + * Don't free prev_pvid or prev_vgid strings because they are + * used at the end to check the VG metadata. + */ + changed |= 1; + + if (prev_pvmeta_on_dev) { + DEBUGLOG(s, "pv_found new pvid device_to_pvid %" PRIu64 " to %s removes prev pvid %s", + arg_device, new_pvid, prev_pvid_on_dev); + + dm_hash_remove(s->pvid_to_pvmeta, prev_pvid_on_dev); + dm_config_destroy(prev_pvmeta_on_dev); + prev_pvmeta_on_dev = NULL; + + /* removes arg_device/prev_pvid_on_dev mapping */ + dm_hash_remove_binary(s->device_to_pvid, &arg_device, sizeof(arg_device)); + + /* + * The new PV replacing the prev PV was copied from + * another existing PV, creating a duplicate PV which + * we ignore. + */ + if (dm_hash_lookup(s->pvid_to_pvmeta, new_pvid)) { + DEBUGLOG(s, "pv_found ignore duplicate device %" PRIu64 " of existing PV for pvid %s", + arg_device, arg_pvid); + dm_config_destroy(new_pvmeta); + s->flags |= GLFL_DISABLE; + s->flags |= GLFL_DISABLE_REASON_DUPLICATES; + return reply_fail("Ignore duplicate PV"); + } + } + + + if (!(new_pvid_dup = dm_strdup(new_pvid))) + goto nomem_free1; + + if (!dm_hash_insert_binary(s->device_to_pvid, &arg_device, sizeof(arg_device), (char *)new_pvid_dup)) + goto nomem_free2; + + if (!dm_hash_insert(s->pvid_to_pvmeta, new_pvid, new_pvmeta)) + goto nomem_free1; + + } else if (new_device && !new_pvid) { + /* + * Old PV on new device (duplicate) + * Ignore it. + */ + DEBUGLOG(s, "pv_found ignore duplicate device %" PRIu64 " of existing device %" PRIu64 " for pvid %s", + new_device, old_device, arg_pvid); + dm_config_destroy(new_pvmeta); + s->flags |= GLFL_DISABLE; + s->flags |= GLFL_DISABLE_REASON_DUPLICATES; + return reply_fail("Ignore duplicate PV"); + } + + if (old_pvmeta) + dm_config_destroy(old_pvmeta); + + /* + * Update VG metadata cache with arg_vgmeta from the PV, or + * if the PV holds no VG metadata, then look up the vgid and + * name of the VG so we can check if the VG is complete. + */ + if (arg_vgmeta) { + DEBUGLOG(s, "pv_found pvid %s has VG %s %s seqno %d", arg_pvid, arg_name, arg_vgid, arg_seqno); + + if (!_update_metadata(s, arg_name, arg_vgid, arg_vgmeta, &old_seqno, arg_pvid)) { + ERROR(s, "Cannot use VG metadata for %s %s from PV %s on %" PRIu64, + arg_name, arg_vgid, arg_pvid, arg_device); + } + + changed |= (old_seqno != arg_seqno); + } else { + arg_vgid = dm_hash_lookup(s->pvid_to_vgid, arg_pvid); + + if (arg_vgid) { + arg_name = dm_hash_lookup(s->vgid_to_vgname, arg_vgid); + } + } + + /* + * Check if the VG is complete (all PVs have been found) because + * the reply indicates if the the VG is complete or partial. + * The "vgmeta" from dm_hash_lookup will be a copy of arg_vgmeta that + * was cloned and added to the cache by update_metadata. + */ + if (!arg_vgid || !strcmp(arg_vgid, "#orphan")) { + DEBUGLOG(s, "pv_found pvid %s on %" PRIu64 " not in VG %s", + arg_pvid, arg_device, arg_vgid ?: ""); + vg_status = "orphan"; + goto prev_vals; + } + + if (!(vgmeta = dm_hash_lookup(s->vgid_to_metadata, arg_vgid))) { + ERROR(s, "pv_found %s on %" PRIu64 " vgid %s no VG metadata found", + arg_pvid, arg_device, arg_vgid); + } else { + vg_status = _vg_is_complete(s, vgmeta) ? "complete" : "partial"; + vg_status_seqno = dm_config_find_int(vgmeta->root, "metadata/seqno", -1); + } + + prev_vals: + /* + * If the device previously held a different VG (prev_vgid_on_dev), + * then that VG should be removed if no devices are left for it. + * + * The mapping from the device's previous pvid to the previous vgid + * is removed. + */ + + if (prev_pvid_on_dev || prev_vgid_on_dev) { + DEBUGLOG(s, "pv_found pvid %s on %" PRIu64 " had prev pvid %s prev vgid %s", + arg_pvid, arg_device, + prev_pvid_on_dev ?: "none", + prev_vgid_on_dev ?: "none"); + } + + if (prev_vgid_on_dev) { + char *tmp_vgid; + + if (!arg_vgid || strcmp(arg_vgid, prev_vgid_on_dev)) { + tmp_vgid = dm_strdup(prev_vgid_on_dev); + /* vg_remove_if_missing will clear and free + the string pointed to by prev_vgid_on_dev. */ + vg_remove_if_missing(s, tmp_vgid, 1); + dm_free(tmp_vgid); + } + + /* vg_remove_if_missing may have remapped prev_pvid_on_dev to orphan */ + if ((tmp_vgid = dm_hash_lookup(s->pvid_to_vgid, prev_pvid_on_dev))) { + dm_hash_remove(s->pvid_to_vgid, prev_pvid_on_dev); + dm_free(tmp_vgid); + } + } + + /* This was unhashed from device_to_pvid above. */ + if (prev_pvid_on_dev) + dm_free((void *)prev_pvid_on_dev); + + return daemon_reply_simple("OK", + "status = %s", vg_status, + "changed = " FMTd64, (int64_t) changed, + "vgid = %s", arg_vgid ? arg_vgid : "#orphan", + "vgname = %s", arg_name ? arg_name : "#orphan", + "seqno_before = " FMTd64, (int64_t) old_seqno, + "seqno_after = " FMTd64, (int64_t) vg_status_seqno, + NULL); + + nomem_free2: + dm_free((char *)new_pvid_dup); + nomem_free1: + dm_config_destroy(new_pvmeta); + nomem: + ERROR(s, "pv_found %s is out of memory.", arg_pvid); + ERROR(s, "lvmetad could not be updated is aborting."); + reply_fail("out of memory"); + exit(EXIT_FAILURE); +} + +static response vg_clear_outdated_pvs(lvmetad_state *s, request r) +{ + struct dm_config_tree *outdated_pvs; + const char *vgid = daemon_request_str(r, "vgid", NULL); + + if (!vgid) + return reply_fail("need VG UUID"); + + DEBUGLOG(s, "vg_clear_outdated_pvs vgid %s", vgid); + + if ((outdated_pvs = dm_hash_lookup(s->vgid_to_outdated_pvs, vgid))) { + dm_config_destroy(outdated_pvs); + dm_hash_remove(s->vgid_to_outdated_pvs, vgid); + } + return daemon_reply_simple("OK", NULL); +} + +static void vg_info_update(lvmetad_state *s, const char *uuid, + struct dm_config_node *metadata) +{ + struct vg_info *info; + int64_t cache_version; + + cache_version = dm_config_find_int64(metadata, "metadata/seqno", -1); + if (cache_version == -1) + return; + + info = (struct vg_info *) dm_hash_lookup(s->vgid_to_info, uuid); + if (!info) + return; + + if (cache_version >= info->external_version) + info->flags &= ~VGFL_INVALID; +} + +static response vg_update(lvmetad_state *s, request r) +{ + struct dm_config_node *metadata = dm_config_find_node(r.cft->root, "metadata"); + const char *vgid = daemon_request_str(r, "metadata/id", NULL); + const char *vgname = daemon_request_str(r, "vgname", NULL); + + DEBUGLOG(s, "vg_update vgid %s name %s", vgid ?: "none", vgname ?: "none"); + + if (metadata) { + if (!vgid) { + ERROR(s, "vg_update failed: need VG UUID"); + reply_fail("vg_update: need VG UUID"); + goto fail; + } + if (!vgname) { + ERROR(s, "vg_update failed: need VG name"); + reply_fail("vg_update: need VG name"); + goto fail; + } + if (daemon_request_int(r, "metadata/seqno", -1) < 0) { + ERROR(s, "vg_update failed: need VG seqno"); + reply_fail("vg_update: need VG seqno"); + goto fail; + } + + /* TODO defer metadata update here; add a separate vg_commit + * call; if client does not commit, die */ + + if (!_update_metadata(s, vgname, vgid, metadata, NULL, NULL)) { + ERROR(s, "vg_update failed: metadata update failed"); + reply_fail("vg_update: failed metadata update"); + goto fail; + } + + vg_info_update(s, vgid, metadata); + } + return daemon_reply_simple("OK", NULL); + +fail: + ERROR(s, "lvmetad could not be updated is aborting."); + exit(EXIT_FAILURE); +} + +static response vg_remove(lvmetad_state *s, request r) +{ + const char *vgid = daemon_request_str(r, "uuid", NULL); + + if (!vgid) + return reply_fail("need VG UUID"); + + DEBUGLOG(s, "vg_remove: %s", vgid); + + remove_metadata(s, vgid, 1); + + return daemon_reply_simple("OK", NULL); +} + +/* + * Whether lvmetad is disabled is determined only by the single + * flag GLFL_DISABLE. The REASON flags are only explanatory + * additions to GLFL_DISABLE, and do not control the disabled state. + * The REASON flags can accumulate if multiple reasons exist for + * the disabled flag. When clearing GLFL_DISABLE, all REASON flags + * are cleared. The caller clearing GLFL_DISABLE should only do so + * when all the reasons for it have gone. + */ + +static response set_global_info(lvmetad_state *s, request r) +{ + const int global_invalid = daemon_request_int(r, "global_invalid", -1); + const int global_disable = daemon_request_int(r, "global_disable", -1); + const char *reason; + uint32_t reason_flags = 0; + + if ((reason = daemon_request_str(r, "disable_reason", NULL))) { + if (strstr(reason, LVMETAD_DISABLE_REASON_DIRECT)) + reason_flags |= GLFL_DISABLE_REASON_DIRECT; + if (strstr(reason, LVMETAD_DISABLE_REASON_LVM1)) + reason_flags |= GLFL_DISABLE_REASON_LVM1; + if (strstr(reason, LVMETAD_DISABLE_REASON_DUPLICATES)) + reason_flags |= GLFL_DISABLE_REASON_DUPLICATES; + if (strstr(reason, LVMETAD_DISABLE_REASON_VGRESTORE)) + reason_flags |= GLFL_DISABLE_REASON_VGRESTORE; + } + + if (global_invalid != -1) { + DEBUGLOG(s, "set global info invalid from %d to %d", + (s->flags & GLFL_INVALID) ? 1 : 0, global_invalid); + } + + if (global_disable != -1) { + DEBUGLOG(s, "set global info disable from %d to %d %s", + (s->flags & GLFL_DISABLE) ? 1 : 0, global_disable, + reason ? reason : ""); + } + + if (global_invalid == 1) + s->flags |= GLFL_INVALID; + + else if (global_invalid == 0) + s->flags &= ~GLFL_INVALID; + + if (global_disable == 1) { + s->flags |= GLFL_DISABLE; + s->flags |= reason_flags; + + } else if (global_disable == 0) { + s->flags &= ~GLFL_DISABLE; + s->flags &= ~GLFL_DISABLE_REASON_ALL; + } + + return daemon_reply_simple("OK", NULL); +} + +#define REASON_BUF_SIZE 64 + +/* + * Save the time when "updating" begins, and the config setting for how long + * the update is allowed to take. Before returning "updating" as the token + * value in get_global_info, check if the update has exceeded the max allowed + * time. If so, then return "none" as the current token value (i.e. + * uninitialized), so that the command will repopulate our cache. + * + * This automatically clears a stuck update, where a command started to update + * the cache and then failed, leaving the token set to "update in progress". + */ + +static response get_global_info(lvmetad_state *s, request r) +{ + char reason[REASON_BUF_SIZE]; + char flag_str[64]; + int pid; + + /* This buffer should be large enough to hold all the possible reasons. */ + + memset(reason, 0, sizeof(reason)); + + pid = (int)daemon_request_int(r, "pid", 0); + + if (s->flags & GLFL_DISABLE) { + snprintf(reason, REASON_BUF_SIZE - 1, "%s%s%s%s", + (s->flags & GLFL_DISABLE_REASON_DIRECT) ? LVMETAD_DISABLE_REASON_DIRECT "," : "", + (s->flags & GLFL_DISABLE_REASON_LVM1) ? LVMETAD_DISABLE_REASON_LVM1 "," : "", + (s->flags & GLFL_DISABLE_REASON_DUPLICATES) ? LVMETAD_DISABLE_REASON_DUPLICATES "," : "", + (s->flags & GLFL_DISABLE_REASON_VGRESTORE) ? LVMETAD_DISABLE_REASON_VGRESTORE "," : ""); + } + + if (!reason[0]) + strcpy(reason, "none"); + + /* + * If the current update has timed out, then return + * token of "none" which means "uninitialized" so that + * the caller will repopulate lvmetad. + */ + if (s->update_begin && s->update_timeout) { + if (_monotonic_seconds() - s->update_begin >= s->update_timeout) { + DEBUGLOG(s, "global info cancel update after timeout %d len %d begin %llu pid %d cmd %s", + s->update_timeout, + (int)(_monotonic_seconds() - s->update_begin), + (unsigned long long)s->update_begin, + s->update_pid, s->update_cmd); + memset(s->token, 0, sizeof(s->token)); + s->update_begin = 0; + s->update_timeout = 0; + s->update_pid = 0; + memset(s->update_cmd, 0, CMD_NAME_SIZE); + } + } + + memset(flag_str, 0, sizeof(flag_str)); + if (s->flags & GLFL_INVALID) + strcat(flag_str, "Invalid"); + if (s->flags & GLFL_DISABLE) + strcat(flag_str, "Disable"); + if (!flag_str[0]) + strcat(flag_str, "none"); + + DEBUGLOG(s, "%d global info flags %s reason %s token %s update_pid %d", + pid, flag_str, reason, s->token[0] ? s->token : "none", s->update_pid); + + return daemon_reply_simple("OK", "global_invalid = " FMTd64, (int64_t)((s->flags & GLFL_INVALID) ? 1 : 0), + "global_disable = " FMTd64, (int64_t)((s->flags & GLFL_DISABLE) ? 1 : 0), + "disable_reason = %s", reason, + "daemon_pid = " FMTd64, (int64_t)getpid(), + "token = %s", s->token[0] ? s->token : "none", + "update_cmd = %s", s->update_cmd, + "update_pid = " FMTd64, (int64_t)s->update_pid, + "update_begin = " FMTd64, (int64_t)s->update_begin, + "update_timeout = " FMTd64, (int64_t)s->update_timeout, + NULL); +} + +static response set_vg_info(lvmetad_state *s, request r) +{ + struct dm_config_tree *vg; + struct vg_info *info; + const char *name = NULL; + const char *uuid = NULL; + const int64_t new_version = daemon_request_int(r, "version", -1); + int64_t cache_version = -1; + + if (new_version == -1) + goto out; + + if (!(uuid = daemon_request_str(r, "uuid", NULL))) + goto use_name; + + if ((vg = dm_hash_lookup(s->vgid_to_metadata, uuid))) + goto vers; +use_name: + if (!(name = daemon_request_str(r, "name", NULL))) + goto out; + + if (!(uuid = dm_hash_lookup(s->vgname_to_vgid, name))) + goto out; + + /* + * FIXME: if we only have the name and multiple VGs have that name, + * then invalidate each of them. + */ + + if (!(vg = dm_hash_lookup(s->vgid_to_metadata, uuid))) + goto out; +vers: + if (!new_version) + goto inval; + + cache_version = dm_config_find_int64(vg->root, "metadata/seqno", -1); + + if (cache_version != -1 && new_version != -1 && cache_version >= new_version) + goto out; +inval: + DEBUGLOG(s, "set info VG name %s uuid %s cache_version %d new_version %d", + name ?: "none", uuid ?: "none", (int)cache_version, (int)new_version); + + info = dm_hash_lookup(s->vgid_to_info, uuid); + if (!info) { + info = malloc(sizeof(struct vg_info)); + if (!info) + goto bad; + memset(info, 0, sizeof(struct vg_info)); + if (!dm_hash_insert(s->vgid_to_info, uuid, (void*)info)) + goto bad; + } + + info->external_version = new_version; + info->flags |= VGFL_INVALID; + +out: + return daemon_reply_simple("OK", NULL); +bad: + return reply_fail("out of memory"); +} + +static void _dump_cft(struct buffer *buf, struct dm_hash_table *ht, const char *key_addr) +{ + struct dm_hash_node *n; + + dm_hash_iterate(n, ht) { + struct dm_config_tree *cft = dm_hash_get_data(ht, n); + const char *key_backup = cft->root->key; + cft->root->key = dm_config_find_str(cft->root, key_addr, "unknown"); + (void) dm_config_write_node(cft->root, buffer_line, buf); + cft->root->key = key_backup; + } +} + +static void _dump_pairs(struct buffer *buf, struct dm_hash_table *ht, const char *name, int int_key) +{ + char *append; + struct dm_hash_node *n; + + buffer_append(buf, name); + buffer_append(buf, " {\n"); + + dm_hash_iterate(n, ht) { + const char *key = dm_hash_get_key(ht, n), + *val = dm_hash_get_data(ht, n); + buffer_append(buf, " "); + if (int_key) + (void) dm_asprintf(&append, "%d = \"%s\"", *(const int*)key, val); + else + (void) dm_asprintf(&append, "%s = \"%s\"", key, val); + if (append) + buffer_append(buf, append); + buffer_append(buf, "\n"); + dm_free(append); + } + buffer_append(buf, "}\n"); +} + +static void _dump_info_version(struct buffer *buf, struct dm_hash_table *ht, const char *name, int int_key) +{ + char *append; + struct dm_hash_node *n = dm_hash_get_first(ht); + struct vg_info *info; + + buffer_append(buf, name); + buffer_append(buf, " {\n"); + + while (n) { + const char *key = dm_hash_get_key(ht, n); + info = dm_hash_get_data(ht, n); + buffer_append(buf, " "); + (void) dm_asprintf(&append, "%s = %lld", key, (long long)info->external_version); + if (append) + buffer_append(buf, append); + buffer_append(buf, "\n"); + dm_free(append); + n = dm_hash_get_next(ht, n); + } + buffer_append(buf, "}\n"); +} + +static void _dump_info_flags(struct buffer *buf, struct dm_hash_table *ht, const char *name, int int_key) +{ + char *append; + struct dm_hash_node *n = dm_hash_get_first(ht); + struct vg_info *info; + + buffer_append(buf, name); + buffer_append(buf, " {\n"); + + while (n) { + const char *key = dm_hash_get_key(ht, n); + info = dm_hash_get_data(ht, n); + buffer_append(buf, " "); + (void) dm_asprintf(&append, "%s = %llx", key, (long long)info->flags); + if (append) + buffer_append(buf, append); + buffer_append(buf, "\n"); + dm_free(append); + n = dm_hash_get_next(ht, n); + } + buffer_append(buf, "}\n"); +} + +static response dump(lvmetad_state *s) +{ + response res = { 0 }; + struct buffer *b = &res.buffer; + + buffer_init(b); + + /* Lock everything so that we get a consistent dump. */ + + buffer_append(b, "# VG METADATA\n\n"); + _dump_cft(b, s->vgid_to_metadata, "metadata/id"); + + buffer_append(b, "\n# PV METADATA\n\n"); + _dump_cft(b, s->pvid_to_pvmeta, "pvmeta/id"); + + buffer_append(b, "\n# VGID to VGNAME mapping\n\n"); + _dump_pairs(b, s->vgid_to_vgname, "vgid_to_vgname", 0); + + buffer_append(b, "\n# VGID to outdated PVs mapping\n\n"); + _dump_cft(b, s->vgid_to_outdated_pvs, "outdated_pvs/vgid"); + + buffer_append(b, "\n# VGNAME to VGID mapping\n\n"); + _dump_pairs(b, s->vgname_to_vgid, "vgname_to_vgid", 0); + + buffer_append(b, "\n# PVID to VGID mapping\n\n"); + _dump_pairs(b, s->pvid_to_vgid, "pvid_to_vgid", 0); + + buffer_append(b, "\n# DEVICE to PVID mapping\n\n"); + _dump_pairs(b, s->device_to_pvid, "device_to_pvid", 1); + + buffer_append(b, "\n# VGID to INFO version mapping\n\n"); + _dump_info_version(b, s->vgid_to_info, "vgid_to_info", 0); + + buffer_append(b, "\n# VGID to INFO flags mapping\n\n"); + _dump_info_flags(b, s->vgid_to_info, "vgid_to_info", 0); + + return res; +} + +static response handler(daemon_state s, client_handle h, request r) +{ + response res; + lvmetad_state *state = s.private; + char prev_token[128] = { 0 }; + const char *rq; + const char *token; + const char *cmd; + int prev_in_progress, this_in_progress; + int update_timeout; + int pid; + int cache_lock = 0; + int info_lock = 0; + + rq = daemon_request_str(r, "request", "NONE"); + token = daemon_request_str(r, "token", "NONE"); + pid = (int)daemon_request_int(r, "pid", 0); + cmd = daemon_request_str(r, "cmd", "NONE"); + update_timeout = (int)daemon_request_int(r, "update_timeout", 0); + + pthread_mutex_lock(&state->token_lock); + + /* + * token_update: start populating the cache, i.e. a full update. + * To populate the lvmetad cache, a command does: + * + * - token_update, setting token to "update in progress" + * (further requests during the update continue using + * this same "update in progress" token) + * - pv_clear_all, to clear the current cache + * - pv_gone, for each PV + * - pv_found, for each PV to populate the cache + * - token_update, setting token to filter hash + */ + if (!strcmp(rq, "token_update")) { + prev_in_progress = !strcmp(state->token, LVMETAD_TOKEN_UPDATE_IN_PROGRESS); + this_in_progress = !strcmp(token, LVMETAD_TOKEN_UPDATE_IN_PROGRESS); + + if (!prev_in_progress && this_in_progress) { + /* New update is starting (filter token is replaced by update token) */ + + memcpy(prev_token, state->token, 128); + strncpy(state->token, token, 128); + state->token[127] = 0; + state->update_begin = _monotonic_seconds(); + state->update_timeout = update_timeout; + state->update_pid = pid; + strncpy(state->update_cmd, cmd, CMD_NAME_SIZE - 1); + + DEBUGLOG(state, "token_update begin %llu timeout %d pid %d cmd %s", + (unsigned long long)state->update_begin, + state->update_timeout, + state->update_pid, + state->update_cmd); + + } else if (prev_in_progress && this_in_progress) { + /* Current update is cancelled and replaced by a new update */ + + DEBUGLOG(state, "token_update replacing pid %d begin %llu len %d cmd %s", + state->update_pid, + (unsigned long long)state->update_begin, + (int)(_monotonic_seconds() - state->update_begin), + state->update_cmd); + + memcpy(prev_token, state->token, 128); + strncpy(state->token, token, 128); + state->token[127] = 0; + state->update_begin = _monotonic_seconds(); + state->update_timeout = update_timeout; + state->update_pid = pid; + strncpy(state->update_cmd, cmd, CMD_NAME_SIZE - 1); + + DEBUGLOG(state, "token_update begin %llu timeout %d pid %d cmd %s", + (unsigned long long)state->update_begin, + state->update_timeout, + state->update_pid, + state->update_cmd); + + } else if (prev_in_progress && !this_in_progress) { + /* Update is finished, update token is replaced by filter token */ + + if (state->update_pid != pid) { + /* If a pid doing update was cancelled, ignore its token update at the end. */ + DEBUGLOG(state, "token_update ignored from cancelled update pid %d", pid); + pthread_mutex_unlock(&state->token_lock); + + return daemon_reply_simple("token_mismatch", + "expected = %s", state->token, + "received = %s", token, + "update_pid = " FMTd64, (int64_t)state->update_pid, + "reason = %s", "another command has populated the cache"); + } + + DEBUGLOG(state, "token_update end len %d pid %d new token %s", + (int)(_monotonic_seconds() - state->update_begin), + state->update_pid, token); + + memcpy(prev_token, state->token, 128); + strncpy(state->token, token, 128); + state->token[127] = 0; + state->update_begin = 0; + state->update_timeout = 0; + state->update_pid = 0; + memset(state->update_cmd, 0, CMD_NAME_SIZE); + } + pthread_mutex_unlock(&state->token_lock); + + return daemon_reply_simple("OK", + "prev_token = %s", prev_token, + "update_pid = " FMTd64, (int64_t)state->update_pid, + NULL); + } + + if (strcmp(token, state->token) && strcmp(rq, "dump") && strcmp(token, "skip")) { + pthread_mutex_unlock(&state->token_lock); + + DEBUGLOG(state, "token_mismatch current \"%s\" got \"%s\" from pid %d cmd %s", + state->token, token, pid, cmd ?: "none"); + + return daemon_reply_simple("token_mismatch", + "expected = %s", state->token, + "received = %s", token, + "update_pid = " FMTd64, (int64_t)state->update_pid, + "reason = %s", "another command has populated the cache"); + } + + /* If a pid doing update was cancelled, ignore its update messages. */ + if (!strcmp(token, LVMETAD_TOKEN_UPDATE_IN_PROGRESS) && + state->update_pid && pid && (state->update_pid != pid)) { + pthread_mutex_unlock(&state->token_lock); + + DEBUGLOG(state, "token_mismatch ignore update from pid %d current update pid %d", + pid, state->update_pid); + + return daemon_reply_simple("token_mismatch", + "expected = %s", state->token, + "received = %s", token, + "update_pid = " FMTd64, (int64_t)state->update_pid, + "reason = %s", "another command has populated the lvmetad cache"); + } + + pthread_mutex_unlock(&state->token_lock); + + + if (!strcmp(rq, "pv_found") || + !strcmp(rq, "pv_gone") || + !strcmp(rq, "vg_update") || + !strcmp(rq, "vg_remove") || + !strcmp(rq, "set_vg_info") || + !strcmp(rq, "pv_clear_all") || + !strcmp(rq, "vg_clear_outdated_pvs")) { + pthread_rwlock_wrlock(&state->cache_lock); + cache_lock = 1; + goto do_rq; + } + + if (!strcmp(rq, "pv_lookup") || + !strcmp(rq, "vg_lookup") || + !strcmp(rq, "pv_list") || + !strcmp(rq, "vg_list") || + !strcmp(rq, "dump")) { + pthread_rwlock_rdlock(&state->cache_lock); + cache_lock = 1; + goto do_rq; + } + + if (!strcmp(rq, "set_global_info") || + !strcmp(rq, "get_global_info")) { + pthread_mutex_lock(&state->info_lock); + info_lock = 1; + goto do_rq; + } + + do_rq: + + if (!strcmp(rq, "pv_found")) + res = pv_found(state, r); + + else if (!strcmp(rq, "pv_gone")) + res = pv_gone(state, r); + + else if (!strcmp(rq, "pv_clear_all")) + res = pv_clear_all(state, r); + + else if (!strcmp(rq, "pv_lookup")) + res = pv_lookup(state, r); + + else if (!strcmp(rq, "vg_update")) + res = vg_update(state, r); + + else if (!strcmp(rq, "vg_clear_outdated_pvs")) + res = vg_clear_outdated_pvs(state, r); + + else if (!strcmp(rq, "vg_remove")) + res = vg_remove(state, r); + + else if (!strcmp(rq, "vg_lookup")) + res = vg_lookup(state, r); + + else if (!strcmp(rq, "pv_list")) + res = pv_list(state, r); + + else if (!strcmp(rq, "vg_list")) + res = vg_list(state, r); + + else if (!strcmp(rq, "set_global_info")) + res = set_global_info(state, r); + + else if (!strcmp(rq, "get_global_info")) + res = get_global_info(state, r); + + else if (!strcmp(rq, "set_vg_info")) + res = set_vg_info(state, r); + + else if (!strcmp(rq, "dump")) + res = dump(state); + + else + res = reply_fail("request not implemented"); + + if (cache_lock) + pthread_rwlock_unlock(&state->cache_lock); + if (info_lock) + pthread_mutex_unlock(&state->info_lock); + + return res; +} + +static int init(daemon_state *s) +{ + lvmetad_state *ls = s->private; + ls->log = s->log; + + pthread_mutex_init(&ls->token_lock, NULL); + pthread_mutex_init(&ls->info_lock, NULL); + pthread_rwlock_init(&ls->cache_lock, NULL); + create_metadata_hashes(ls); + + ls->token[0] = 0; + + /* Set up stderr logging depending on the -l option. */ + if (!daemon_log_parse(ls->log, DAEMON_LOG_OUTLET_STDERR, ls->log_config, 1)) + return 0; + + DEBUGLOG(s, "initialised state: vgid_to_metadata = %p", ls->vgid_to_metadata); + if (!ls->pvid_to_vgid || !ls->vgid_to_metadata) + return 0; + + /* if (ls->initial_registrations) + _process_initial_registrations(ds->initial_registrations); */ + + if (ls->idle) + ls->idle->is_idle = 1; + + return 1; +} + +static int fini(daemon_state *s) +{ + lvmetad_state *ls = s->private; + + DEBUGLOG(s, "fini"); + destroy_metadata_hashes(ls); + return 1; +} + +static int process_timeout_arg(const char *str, unsigned *max_timeouts) +{ + char *endptr; + unsigned long l; + + errno = 0; + l = strtoul(str, &endptr, 10); + if (errno || *endptr || l >= UINT_MAX) + return 0; + + *max_timeouts = (unsigned) l; + + return 1; +} + +static void usage(const char *prog, FILE *file) +{ + fprintf(file, "Usage:\n" + "%s [-V] [-h] [-f] [-l level[,level ...]] [-s path] [-t secs]\n\n" + " -V Show version of lvmetad\n" + " -h Show this help information\n" + " -f Don't fork, run in the foreground\n" + " -l Logging message levels (all,fatal,error,warn,info,wire,debug)\n" + " -p Set path to the pidfile\n" + " -s Set path to the socket to listen on\n" + " -t Time to wait in seconds before shutdown on idle (missing or 0 = inifinite)\n\n", prog); +} + +int main(int argc, char *argv[]) +{ + signed char opt; + struct timeval timeout; + daemon_idle di = { .ptimeout = &timeout }; + lvmetad_state ls = { .log_config = "" }; + daemon_state s = { + .daemon_fini = fini, + .daemon_init = init, + .handler = handler, + .name = "lvmetad", + .pidfile = getenv("LVM_LVMETAD_PIDFILE") ? : LVMETAD_PIDFILE, + .private = &ls, + .protocol = "lvmetad", + .protocol_version = 1, + .socket_path = getenv("LVM_LVMETAD_SOCKET") ? : LVMETAD_SOCKET, + }; + + // use getopt_long + while ((opt = getopt(argc, argv, "?fhVl:p:s:t:")) != EOF) { + switch (opt) { + case 'h': + usage(argv[0], stdout); + exit(0); + case '?': + usage(argv[0], stderr); + exit(0); + case 'f': + s.foreground = 1; + break; + case 'l': + ls.log_config = optarg; + break; + case 'p': + s.pidfile = optarg; + break; + case 's': // --socket + s.socket_path = optarg; + break; + case 't': + if (!process_timeout_arg(optarg, &di.max_timeouts)) { + fprintf(stderr, "Invalid value of timeout parameter.\n"); + exit(EXIT_FAILURE); + } + /* 0 equals to wait indefinitely */ + if (di.max_timeouts) + s.idle = ls.idle = &di; + break; + case 'V': + printf("lvmetad version: " LVM_VERSION "\n"); + exit(1); + } + } + + daemon_start(s); + + return 0; +}
diff --git a/daemons/lvmetad/test.sh b/daemons/lvmetad/test.sh new file mode 100755 index 0000000..f937562 --- /dev/null +++ b/daemons/lvmetad/test.sh
@@ -0,0 +1,16 @@ +#!/bin/bash + +export LD_LIBRARY_PATH="$1" + +test -n "$2" && { + rm -f /var/run/lvmetad.{socket,pid} + chmod +rx lvmetad + valgrind ./lvmetad -f & + PID=$! + sleep 1 + ./testclient + kill $PID + exit 0 +} + +sudo ./test.sh "$1" .
diff --git a/daemons/lvmetad/testclient.c b/daemons/lvmetad/testclient.c new file mode 100644 index 0000000..c9efbe6 --- /dev/null +++ b/daemons/lvmetad/testclient.c
@@ -0,0 +1,147 @@ +/* + * Copyright (C) 2011-2014 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "tool.h" + +#include "lvmetad-client.h" +#include "label.h" +#include "lvmcache.h" +#include "metadata.h" + +const char *uuid1 = "abcd-efgh"; +const char *uuid2 = "bbcd-efgh"; +const char *vgid = "yada-yada"; +const char *uuid3 = "cbcd-efgh"; + +const char *metadata2 = "{\n" + "id = \"yada-yada\"\n" + "seqno = 15\n" + "status = [\"READ\", \"WRITE\"]\n" + "flags = []\n" + "extent_size = 8192\n" + "physical_volumes {\n" + " pv0 {\n" + " id = \"abcd-efgh\"\n" + " }\n" + " pv1 {\n" + " id = \"bbcd-efgh\"\n" + " }\n" + " pv2 {\n" + " id = \"cbcd-efgh\"\n" + " }\n" + "}\n" + "}\n"; + +void _handle_reply(daemon_reply reply) { + const char *repl = daemon_reply_str(reply, "response", NULL); + const char *status = daemon_reply_str(reply, "status", NULL); + const char *vgid = daemon_reply_str(reply, "vgid", NULL); + + fprintf(stderr, "[C] REPLY: %s\n", repl); + if (!strcmp(repl, "failed")) + fprintf(stderr, "[C] REASON: %s\n", daemon_reply_str(reply, "reason", "unknown")); + if (vgid) + fprintf(stderr, "[C] VGID: %s\n", vgid); + if (status) + fprintf(stderr, "[C] STATUS: %s\n", status); + daemon_reply_destroy(reply); +} + +void _pv_add(daemon_handle h, const char *uuid, const char *metadata) +{ + daemon_reply reply = daemon_send_simple(h, "pv_add", "uuid = %s", uuid, + "metadata = %b", metadata, + NULL); + _handle_reply(reply); +} + +int scan(daemon_handle h, char *fn) { + struct device *dev = dev_cache_get(fn, NULL); + + struct label *label; + if (!label_read(dev, &label, 0)) { + fprintf(stderr, "[C] no label found on %s\n", fn); + return; + } + + char uuid[64]; + if (!id_write_format(dev->pvid, uuid, 64)) { + fprintf(stderr, "[C] Failed to format PV UUID for %s", dev_name(dev)); + return; + } + fprintf(stderr, "[C] found PV: %s\n", uuid); + struct lvmcache_info *info = (struct lvmcache_info *) label->info; + struct physical_volume pv = { 0, }; + + if (!(info->fmt->ops->pv_read(info->fmt, dev_name(dev), &pv, 0))) { + fprintf(stderr, "[C] Failed to read PV %s", dev_name(dev)); + return; + } + + struct format_instance_ctx fic; + struct format_instance *fid = info->fmt->ops->create_instance(info->fmt, &fic); + struct metadata_area *mda; + struct volume_group *vg = NULL; + dm_list_iterate_items(mda, &info->mdas) { + struct volume_group *this = mda->ops->vg_read(fid, "", mda); + if (this && !vg || this->seqno > vg->seqno) + vg = this; + } + if (vg) { + char *buf = NULL; + /* TODO. This is not entirely correct, since export_vg_to_buffer + * adds trailing garbage to the buffer. We may need to use + * export_vg_to_config_tree and format the buffer ourselves. It + * does, however, work for now, since the garbage is well + * formatted and has no conflicting keys with the rest of the + * request. */ + export_vg_to_buffer(vg, &buf); + daemon_reply reply = + daemon_send_simple(h, "pv_add", "uuid = %s", uuid, + "metadata = %b", strchr(buf, '{'), + NULL); + _handle_reply(reply); + } +} + +void _dump_vg(daemon_handle h, const char *uuid) +{ + daemon_reply reply = daemon_send_simple(h, "vg_by_uuid", "uuid = %s", uuid, NULL); + fprintf(stderr, "[C] reply buffer: %s\n", reply.buffer); + daemon_reply_destroy(reply); +} + +int main(int argc, char **argv) { + daemon_handle h = lvmetad_open(); + /* FIXME Missing error path */ + + if (argc > 1) { + int i; + struct cmd_context *cmd = create_toolcontext(0, NULL, 0, 0, 1, 1); + for (i = 1; i < argc; ++i) { + const char *uuid = NULL; + scan(h, argv[i]); + } + destroy_toolcontext(cmd); + /* FIXME Missing lvmetad_close() */ + return 0; + } + + _pv_add(h, uuid1, NULL); + _pv_add(h, uuid2, metadata2); + _dump_vg(h, vgid); + _pv_add(h, uuid3, NULL); + + daemon_close(h); /* FIXME lvmetad_close? */ + return 0; +}
diff --git a/daemons/lvmlockd/.gitignore b/daemons/lvmlockd/.gitignore new file mode 100644 index 0000000..6ba6109 --- /dev/null +++ b/daemons/lvmlockd/.gitignore
@@ -0,0 +1,2 @@ +lvmlockctl +lvmlockd
diff --git a/daemons/lvmlockd/Makefile.in b/daemons/lvmlockd/Makefile.in new file mode 100644 index 0000000..1b9d787 --- /dev/null +++ b/daemons/lvmlockd/Makefile.in
@@ -0,0 +1,66 @@ +# +# Copyright (C) 2014-2015 Red Hat, Inc. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU Lesser General Public License v.2.1. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +SOURCES = lvmlockd-core.c + +ifeq ("@BUILD_LOCKDSANLOCK@", "yes") + SOURCES += lvmlockd-sanlock.c +endif + +ifeq ("@BUILD_LOCKDDLM@", "yes") + SOURCES += lvmlockd-dlm.c +endif + +TARGETS = lvmlockd lvmlockctl + +.PHONY: install_lvmlockd + +include $(top_builddir)/make.tmpl + +INCLUDES += -I$(top_srcdir)/libdaemon/server +LVMLIBS = -ldaemonserver $(LVMINTERNAL_LIBS) -ldevmapper + +LIBS += $(PTHREAD_LIBS) + +ifeq ("@BUILD_LOCKDSANLOCK@", "yes") + LIBS += -lsanlock_client +endif + +ifeq ("@BUILD_LOCKDDLM@", "yes") + LIBS += -ldlm_lt +endif + +LDFLAGS += -L$(top_builddir)/libdaemon/server +CLDFLAGS += -L$(top_builddir)/libdaemon/server + +lvmlockd: $(OBJECTS) $(top_builddir)/libdaemon/client/libdaemonclient.a \ + $(top_builddir)/libdaemon/server/libdaemonserver.a + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJECTS) $(LVMLIBS) $(LIBS) + +lvmlockctl: lvmlockctl.o $(top_builddir)/libdaemon/client/libdaemonclient.a \ + $(top_builddir)/libdaemon/server/libdaemonserver.a + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ lvmlockctl.o $(LVMLIBS) + +install_lvmlockd: lvmlockd + $(INSTALL_PROGRAM) -D $< $(sbindir)/$(<F) + +install_lvmlockctl: lvmlockctl + $(INSTALL_PROGRAM) -D $< $(sbindir)/$(<F) + +install_lvm2: install_lvmlockd install_lvmlockctl + +install: install_lvm2
diff --git a/daemons/lvmlockd/lvmlockctl.c b/daemons/lvmlockd/lvmlockctl.c new file mode 100644 index 0000000..7d4e072 --- /dev/null +++ b/daemons/lvmlockd/lvmlockctl.c
@@ -0,0 +1,752 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ + +#include "tool.h" + +#include "lvmlockd-client.h" + +#include <stddef.h> +#include <getopt.h> +#include <signal.h> +#include <errno.h> +#include <fcntl.h> +#include <syslog.h> +#include <sys/socket.h> +#include <sys/un.h> + +static int quit = 0; +static int info = 0; +static int dump = 0; +static int wait_opt = 0; +static int force_opt = 0; +static int kill_vg = 0; +static int drop_vg = 0; +static int gl_enable = 0; +static int gl_disable = 0; +static int stop_lockspaces = 0; +static char *arg_vg_name = NULL; + +#define DUMP_SOCKET_NAME "lvmlockd-dump.sock" +#define DUMP_BUF_SIZE (1024 * 1024) +static char dump_buf[DUMP_BUF_SIZE+1]; +static int dump_len; +static struct sockaddr_un dump_addr; +static socklen_t dump_addrlen; + +daemon_handle _lvmlockd; + +#define log_error(fmt, args...) \ +do { \ + printf(fmt "\n", ##args); \ +} while (0) + +#define MAX_LINE 512 + +/* copied from lvmlockd-internal.h */ +#define MAX_NAME 64 +#define MAX_ARGS 64 + +/* + * lvmlockd dumps the client info before the lockspaces, + * so we can look up client info when printing lockspace info. + */ + +#define MAX_CLIENTS 100 + +struct client_info { + uint32_t client_id; + int pid; + char name[MAX_NAME+1]; +}; + +static struct client_info clients[MAX_CLIENTS]; +static int num_clients; + +static void save_client_info(char *line) +{ + uint32_t pid = 0; + int fd = 0; + int pi = 0; + uint32_t client_id = 0; + char name[MAX_NAME+1] = { 0 }; + + (void) sscanf(line, "info=client pid=%u fd=%d pi=%d id=%u name=%s", + &pid, &fd, &pi, &client_id, name); + + clients[num_clients].client_id = client_id; + clients[num_clients].pid = pid; + strcpy(clients[num_clients].name, name); + num_clients++; +} + +static void find_client_info(uint32_t client_id, uint32_t *pid, char *cl_name) +{ + int i; + + for (i = 0; i < num_clients; i++) { + if (clients[i].client_id == client_id) { + *pid = clients[i].pid; + strcpy(cl_name, clients[i].name); + return; + } + } +} + +static int first_ls = 1; + +static void format_info_ls(char *line) +{ + char ls_name[MAX_NAME+1] = { 0 }; + char vg_name[MAX_NAME+1] = { 0 }; + char vg_uuid[MAX_NAME+1] = { 0 }; + char vg_sysid[MAX_NAME+1] = { 0 }; + char lock_args[MAX_ARGS+1] = { 0 }; + char lock_type[MAX_NAME+1] = { 0 }; + + (void) sscanf(line, "info=ls ls_name=%s vg_name=%s vg_uuid=%s vg_sysid=%s vg_args=%s lm_type=%s", + ls_name, vg_name, vg_uuid, vg_sysid, lock_args, lock_type); + + if (!first_ls) + printf("\n"); + first_ls = 0; + + printf("VG %s lock_type=%s %s\n", vg_name, lock_type, vg_uuid); + + printf("LS %s %s\n", lock_type, ls_name); +} + +static void format_info_ls_action(char *line) +{ + uint32_t client_id = 0; + char flags[MAX_NAME+1] = { 0 }; + char version[MAX_NAME+1] = { 0 }; + char op[MAX_NAME+1] = { 0 }; + uint32_t pid = 0; + char cl_name[MAX_NAME+1] = { 0 }; + + (void) sscanf(line, "info=ls_action client_id=%u %s %s op=%s", + &client_id, flags, version, op); + + find_client_info(client_id, &pid, cl_name); + + printf("OP %s pid %u (%s)\n", op, pid, cl_name); +} + +static void format_info_r(char *line, char *r_name_out, char *r_type_out) +{ + char r_name[MAX_NAME+1] = { 0 }; + char r_type[4] = { 0 }; + char mode[4] = { 0 }; + char sh_count[MAX_NAME+1] = { 0 }; + uint32_t ver = 0; + + (void) sscanf(line, "info=r name=%s type=%s mode=%s %s version=%u", + r_name, r_type, mode, sh_count, &ver); + + strcpy(r_name_out, r_name); + strcpy(r_type_out, r_type); + + /* when mode is not un, wait and print each lk line */ + if (strcmp(mode, "un")) + return; + + /* when mode is un, there will be no lk lines, so print now */ + + if (!strcmp(r_type, "gl")) { + printf("LK GL un ver %u\n", ver); + + } else if (!strcmp(r_type, "vg")) { + printf("LK VG un ver %u\n", ver); + + } else if (!strcmp(r_type, "lv")) { + printf("LK LV un %s\n", r_name); + } +} + +static void format_info_lk(char *line, char *r_name, char *r_type) +{ + char mode[4] = { 0 }; + uint32_t ver = 0; + char flags[MAX_NAME+1] = { 0 }; + uint32_t client_id = 0; + uint32_t pid = 0; + char cl_name[MAX_NAME+1] = { 0 }; + + if (!r_name[0] || !r_type[0]) { + printf("format_info_lk error r_name %s r_type %s\n", r_name, r_type); + printf("%s\n", line); + return; + } + + (void) sscanf(line, "info=lk mode=%s version=%u %s client_id=%u", + mode, &ver, flags, &client_id); + + find_client_info(client_id, &pid, cl_name); + + if (!strcmp(r_type, "gl")) { + printf("LK GL %s ver %u pid %u (%s)\n", mode, ver, pid, cl_name); + + } else if (!strcmp(r_type, "vg")) { + printf("LK VG %s ver %u pid %u (%s)\n", mode, ver, pid, cl_name); + + } else if (!strcmp(r_type, "lv")) { + printf("LK LV %s %s\n", mode, r_name); + } +} + +static void format_info_r_action(char *line, char *r_name, char *r_type) +{ + uint32_t client_id = 0; + char flags[MAX_NAME+1] = { 0 }; + char version[MAX_NAME+1] = { 0 }; + char op[MAX_NAME+1] = { 0 }; + char rt[4] = { 0 }; + char mode[4] = { 0 }; + char lm[MAX_NAME+1] = { 0 }; + char result[MAX_NAME+1] = { 0 }; + char lm_rv[MAX_NAME+1] = { 0 }; + uint32_t pid = 0; + char cl_name[MAX_NAME+1] = { 0 }; + + if (!r_name[0] || !r_type[0]) { + printf("format_info_r_action error r_name %s r_type %s\n", r_name, r_type); + printf("%s\n", line); + return; + } + + (void) sscanf(line, "info=r_action client_id=%u %s %s op=%s rt=%s mode=%s %s %s %s", + &client_id, flags, version, op, rt, mode, lm, result, lm_rv); + + find_client_info(client_id, &pid, cl_name); + + if (strcmp(op, "lock")) { + printf("OP %s pid %u (%s)\n", op, pid, cl_name); + return; + } + + if (!strcmp(r_type, "gl")) { + printf("LW GL %s ver %u pid %u (%s)\n", mode, 0, pid, cl_name); + + } else if (!strcmp(r_type, "vg")) { + printf("LW VG %s ver %u pid %u (%s)\n", mode, 0, pid, cl_name); + + } else if (!strcmp(r_type, "lv")) { + printf("LW LV %s %s\n", mode, r_name); + } +} + +static void format_info_line(char *line, char *r_name, char *r_type) +{ + if (!strncmp(line, "info=structs ", strlen("info=structs "))) { + /* only print this in the raw info dump */ + + } else if (!strncmp(line, "info=client ", strlen("info=client "))) { + save_client_info(line); + + } else if (!strncmp(line, "info=ls ", strlen("info=ls "))) { + format_info_ls(line); + + } else if (!strncmp(line, "info=ls_action ", strlen("info=ls_action "))) { + format_info_ls_action(line); + + } else if (!strncmp(line, "info=r ", strlen("info=r "))) { + /* + * r_name/r_type are reset when a new resource is found. + * They are reused for the lock and action lines that + * follow a resource line. + */ + memset(r_name, 0, MAX_NAME+1); + memset(r_type, 0, MAX_NAME+1); + format_info_r(line, r_name, r_type); + + } else if (!strncmp(line, "info=lk ", strlen("info=lk "))) { + /* will use info from previous r */ + format_info_lk(line, r_name, r_type); + + } else if (!strncmp(line, "info=r_action ", strlen("info=r_action "))) { + /* will use info from previous r */ + format_info_r_action(line, r_name, r_type); + } else { + printf("UN %s\n", line); + } +} + +static void format_info(void) +{ + char line[MAX_LINE]; + char r_name[MAX_NAME+1]; + char r_type[MAX_NAME+1]; + int i, j; + + j = 0; + memset(line, 0, sizeof(line)); + + for (i = 0; i < dump_len; i++) { + line[j++] = dump_buf[i]; + + if ((line[j-1] == '\n') || (line[j-1] == '\0')) { + format_info_line(line, r_name, r_type); + j = 0; + memset(line, 0, sizeof(line)); + } + } +} + + +static daemon_reply _lvmlockd_send(const char *req_name, ...) +{ + va_list ap; + daemon_reply repl; + daemon_request req; + + req = daemon_request_make(req_name); + + va_start(ap, req_name); + daemon_request_extend_v(req, ap); + va_end(ap); + + repl = daemon_send(_lvmlockd, req); + + daemon_request_destroy(req); + + return repl; +} + +/* See the same in lib/locking/lvmlockd.c */ +#define NO_LOCKD_RESULT -1000 + +static int _lvmlockd_result(daemon_reply reply, int *result) +{ + int reply_result; + + if (reply.error) { + log_error("lvmlockd_result reply error %d", reply.error); + return 0; + } + + if (strcmp(daemon_reply_str(reply, "response", ""), "OK")) { + log_error("lvmlockd_result bad response"); + return 0; + } + + reply_result = daemon_reply_int(reply, "op_result", NO_LOCKD_RESULT); + if (reply_result == -1000) { + log_error("lvmlockd_result no op_result"); + return 0; + } + + *result = reply_result; + + return 1; +} + +static int do_quit(void) +{ + daemon_reply reply; + int rv = 0; + + reply = daemon_send_simple(_lvmlockd, "quit", NULL); + + if (reply.error) { + log_error("reply error %d", reply.error); + rv = reply.error; + } + + daemon_reply_destroy(reply); + return rv; +} + +static int setup_dump_socket(void) +{ + int s, rv; + + s = socket(AF_LOCAL, SOCK_DGRAM, 0); + if (s < 0) + return s; + + memset(&dump_addr, 0, sizeof(dump_addr)); + dump_addr.sun_family = AF_LOCAL; + strcpy(&dump_addr.sun_path[1], DUMP_SOCKET_NAME); + dump_addrlen = sizeof(sa_family_t) + strlen(dump_addr.sun_path+1) + 1; + + rv = bind(s, (struct sockaddr *) &dump_addr, dump_addrlen); + if (rv < 0) { + rv = -errno; + if (!close(s)) + log_error("failed to close dump socket"); + return rv; + } + + return s; +} + +static int do_dump(const char *req_name) +{ + daemon_reply reply; + int result; + int fd, rv = 0; + int count = 0; + + fd = setup_dump_socket(); + if (fd < 0) { + log_error("socket error %d", fd); + return fd; + } + + reply = daemon_send_simple(_lvmlockd, req_name, NULL); + + if (reply.error) { + log_error("reply error %d", reply.error); + rv = reply.error; + goto out; + } + + result = daemon_reply_int(reply, "result", 0); + dump_len = daemon_reply_int(reply, "dump_len", 0); + + daemon_reply_destroy(reply); + + if (result < 0) { + rv = result; + log_error("result %d", result); + } + + if (!dump_len) + goto out; + + memset(dump_buf, 0, sizeof(dump_buf)); + +retry: + rv = recvfrom(fd, dump_buf + count, dump_len - count, MSG_WAITALL, + (struct sockaddr *)&dump_addr, &dump_addrlen); + if (rv < 0) { + log_error("recvfrom error %d %d", rv, errno); + rv = -errno; + goto out; + } + count += rv; + + if (count < dump_len) + goto retry; + + rv = 0; + if ((info && dump) || !strcmp(req_name, "dump")) + printf("%s\n", dump_buf); + else + format_info(); +out: + if (close(fd)) + log_error("failed to close dump socket %d", fd); + return rv; +} + +static int do_able(const char *req_name) +{ + daemon_reply reply; + int result; + int rv; + + reply = _lvmlockd_send(req_name, + "cmd = %s", "lvmlockctl", + "pid = " FMTd64, (int64_t) getpid(), + "vg_name = %s", arg_vg_name, + NULL); + + if (!_lvmlockd_result(reply, &result)) { + log_error("lvmlockd result %d", result); + rv = result; + } else { + rv = 0; + } + + daemon_reply_destroy(reply); + return rv; +} + +static int do_stop_lockspaces(void) +{ + daemon_reply reply; + char opts[32]; + int result; + int rv; + + memset(opts, 0, sizeof(opts)); + + if (wait_opt) + strcat(opts, "wait "); + if (force_opt) + strcat(opts, "force "); + + reply = _lvmlockd_send("stop_all", + "cmd = %s", "lvmlockctl", + "pid = " FMTd64, (int64_t) getpid(), + "opts = %s", opts[0] ? opts : "none", + NULL); + + if (!_lvmlockd_result(reply, &result)) { + log_error("lvmlockd result %d", result); + rv = result; + } else { + rv = 0; + } + + daemon_reply_destroy(reply); + return rv; +} + +static int do_kill(void) +{ + daemon_reply reply; + int result; + int rv; + + syslog(LOG_EMERG, "Lost access to sanlock lease storage in VG %s.", arg_vg_name); + /* These two lines explain the manual alternative to the FIXME below. */ + syslog(LOG_EMERG, "Immediately deactivate LVs in VG %s.", arg_vg_name); + syslog(LOG_EMERG, "Once VG is unused, run lvmlockctl --drop %s.", arg_vg_name); + + /* + * It may not be strictly necessary to notify lvmlockd of the kill, but + * lvmlockd can use this information to avoid attempting any new lock + * requests in the VG (which would fail anyway), and can return an + * error indicating that the VG has been killed. + */ + + reply = _lvmlockd_send("kill_vg", + "cmd = %s", "lvmlockctl", + "pid = " FMTd64, (int64_t) getpid(), + "vg_name = %s", arg_vg_name, + NULL); + + if (!_lvmlockd_result(reply, &result)) { + log_error("lvmlockd result %d", result); + rv = result; + } else { + rv = 0; + } + + daemon_reply_destroy(reply); + + /* + * FIXME: here is where we should implement a strong form of + * blkdeactivate, and if it completes successfully, automatically call + * do_drop() afterward. (The drop step may not always be necessary + * if the lvm commands run while shutting things down release all the + * leases.) + * + * run_strong_blkdeactivate(); + * do_drop(); + */ + + return rv; +} + +static int do_drop(void) +{ + daemon_reply reply; + int result; + int rv; + + syslog(LOG_WARNING, "Dropping locks for VG %s.", arg_vg_name); + + /* + * Check for misuse by looking for any active LVs in the VG + * and refusing this operation if found? One possible way + * to kill LVs (e.g. if fs cannot be unmounted) is to suspend + * them, or replace them with the error target. In that + * case the LV will still appear to be active, but it is + * safe to release the lock. + */ + + reply = _lvmlockd_send("drop_vg", + "cmd = %s", "lvmlockctl", + "pid = " FMTd64, (int64_t) getpid(), + "vg_name = %s", arg_vg_name, + NULL); + + if (!_lvmlockd_result(reply, &result)) { + log_error("lvmlockd result %d", result); + rv = result; + } else { + rv = 0; + } + + daemon_reply_destroy(reply); + return rv; +} + +static void print_usage(void) +{ + printf("lvmlockctl options\n"); + printf("Options:\n"); + printf("--help | -h\n"); + printf(" Show this help information.\n"); + printf("--quit | -q\n"); + printf(" Tell lvmlockd to quit.\n"); + printf("--info | -i\n"); + printf(" Print lock state information from lvmlockd.\n"); + printf("--dump | -d\n"); + printf(" Print log buffer from lvmlockd.\n"); + printf("--wait | -w 0|1\n"); + printf(" Wait option for other commands.\n"); + printf("--force | -f 0|1>\n"); + printf(" Force option for other commands.\n"); + printf("--kill | -k <vgname>\n"); + printf(" Kill access to the VG when sanlock cannot renew lease.\n"); + printf("--drop | -r <vgname>\n"); + printf(" Clear locks for the VG when it is unused after kill (-k).\n"); + printf("--gl-enable | -E <vgname>\n"); + printf(" Tell lvmlockd to enable the global lock in a sanlock VG.\n"); + printf("--gl-disable | -D <vgname>\n"); + printf(" Tell lvmlockd to disable the global lock in a sanlock VG.\n"); + printf("--stop-lockspaces | -S\n"); + printf(" Stop all lockspaces.\n"); +} + +static int read_options(int argc, char *argv[]) +{ + int option_index = 0; + int c; + + static struct option long_options[] = { + {"help", no_argument, 0, 'h' }, + {"quit", no_argument, 0, 'q' }, + {"info", no_argument, 0, 'i' }, + {"dump", no_argument, 0, 'd' }, + {"wait", required_argument, 0, 'w' }, + {"force", required_argument, 0, 'f' }, + {"kill", required_argument, 0, 'k' }, + {"drop", required_argument, 0, 'r' }, + {"gl-enable", required_argument, 0, 'E' }, + {"gl-disable", required_argument, 0, 'D' }, + {"stop-lockspaces", no_argument, 0, 'S' }, + {0, 0, 0, 0 } + }; + + if (argc == 1) { + print_usage(); + exit(0); + } + + while (1) { + c = getopt_long(argc, argv, "hqidE:D:w:k:r:S", long_options, &option_index); + if (c == -1) + break; + + switch (c) { + case 'h': + /* --help */ + print_usage(); + exit(0); + case 'q': + /* --quit */ + quit = 1; + break; + case 'i': + /* --info */ + info = 1; + break; + case 'd': + /* --dump */ + dump = 1; + break; + case 'w': + wait_opt = atoi(optarg); + break; + case 'k': + kill_vg = 1; + arg_vg_name = strdup(optarg); + break; + case 'r': + drop_vg = 1; + arg_vg_name = strdup(optarg); + break; + case 'E': + gl_enable = 1; + arg_vg_name = strdup(optarg); + break; + case 'D': + gl_disable = 1; + arg_vg_name = strdup(optarg); + break; + case 'S': + stop_lockspaces = 1; + break; + default: + print_usage(); + exit(1); + } + } + + + return 0; +} + +int main(int argc, char **argv) +{ + int rv = 0; + + rv = read_options(argc, argv); + if (rv < 0) + return rv; + + _lvmlockd = lvmlockd_open(NULL); + + if (_lvmlockd.socket_fd < 0 || _lvmlockd.error) { + log_error("Cannot connect to lvmlockd."); + return -1; + } + + if (quit) { + rv = do_quit(); + goto out; + } + + if (info) { + rv = do_dump("info"); + goto out; + } + + if (dump) { + rv = do_dump("dump"); + goto out; + } + + if (kill_vg) { + rv = do_kill(); + goto out; + } + + if (drop_vg) { + rv = do_drop(); + goto out; + } + + if (gl_enable) { + syslog(LOG_INFO, "Enabling global lock in VG %s.", arg_vg_name); + rv = do_able("enable_gl"); + goto out; + } + + if (gl_disable) { + syslog(LOG_INFO, "Disabling global lock in VG %s.", arg_vg_name); + rv = do_able("disable_gl"); + goto out; + } + + if (stop_lockspaces) { + rv = do_stop_lockspaces(); + goto out; + } + +out: + lvmlockd_close(_lvmlockd); + return rv; +}
diff --git a/daemons/lvmlockd/lvmlockd-client.h b/daemons/lvmlockd/lvmlockd-client.h new file mode 100644 index 0000000..67fcbe3 --- /dev/null +++ b/daemons/lvmlockd/lvmlockd-client.h
@@ -0,0 +1,52 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ + +#ifndef _LVM_LVMLOCKD_CLIENT_H +#define _LVM_LVMLOCKD_CLIENT_H + +#include "daemon-client.h" + +#define LVMLOCKD_SOCKET DEFAULT_RUN_DIR "/lvmlockd.socket" + +/* Wrappers to open/close connection */ + +static inline daemon_handle lvmlockd_open(const char *sock) +{ + daemon_info lvmlockd_info = { + .path = "lvmlockd", + .socket = sock ?: LVMLOCKD_SOCKET, + .protocol = "lvmlockd", + .protocol_version = 1, + .autostart = 0 + }; + + return daemon_open(lvmlockd_info); +} + +static inline void lvmlockd_close(daemon_handle h) +{ + return daemon_close(h); +} + +/* + * Errors returned as the lvmlockd result value. + */ +#define ENOLS 210 /* lockspace not found */ +#define ESTARTING 211 /* lockspace is starting */ +#define EARGS 212 +#define EHOSTID 213 +#define EMANAGER 214 +#define EPREPARE 215 +#define ELOCKD 216 +#define EVGKILLED 217 /* sanlock lost access to leases and VG is killed. */ +#define ELOCKIO 218 /* sanlock io errors during lock op, may be transient. */ +#define EREMOVED 219 + +#endif /* _LVM_LVMLOCKD_CLIENT_H */
diff --git a/daemons/lvmlockd/lvmlockd-core.c b/daemons/lvmlockd/lvmlockd-core.c new file mode 100644 index 0000000..8fcbdec --- /dev/null +++ b/daemons/lvmlockd/lvmlockd-core.c
@@ -0,0 +1,6102 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ + +#define _XOPEN_SOURCE 500 /* pthread */ +#define _ISOC99_SOURCE +#define _REENTRANT + +#include "tool.h" + +#include "daemon-io.h" +#include "daemon-server.h" +#include "lvm-version.h" +#include "lvmetad-client.h" +#include "lvmlockd-client.h" + +/* #include <assert.h> */ +#include <errno.h> +#include <pthread.h> +#include <stddef.h> +#include <poll.h> +#include <signal.h> +#include <getopt.h> +#include <syslog.h> +#include <dirent.h> +#include <time.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/utsname.h> +#include <sys/un.h> + +#define EXTERN +#include "lvmlockd-internal.h" + +/* + * Basic operation of lvmlockd + * + * lvmlockd main process runs main_loop() which uses poll(). + * poll listens for new connections from lvm commands and for + * messages from existing connected lvm commands. + * + * lvm command starts and connects to lvmlockd. + * + * lvmlockd receives a connection request from command and adds a + * 'struct client' to keep track of the connection to the command. + * The client's fd is added to the set of fd's in poll(). + * + * lvm command sends a lock request to lvmlockd. The lock request + * can be for the global lock, a vg lock, or an lv lock. + * + * lvmlockd main_loop/poll sees a message from an existing client. + * It sets client.recv = 1, then wakes up client_thread_main. + * + * client_thread_main iterates through client structs (cl), looking + * for any that need processing, finds the one with cl->recv set, + * and calls client_recv_action(cl). + * + * client_recv_action(cl) reads the message/request from the client, + * allocates a new 'struct action' (act) to represent the request, + * sets the act with what is found in the request, then looks at + * the specific operation in act->op (LD_OP_FOO) to decide what to + * do with the action: + * + * . If the action is to start a lockspace, create a new thread + * to manage that lockspace: add_lockspace(act). + * + * . If the action is a lock request, pass the act to the thread + * that is managing that lockspace: add_lock_action(act). + * + * . Other misc actions are are passed to the worker_thread: + * add_work_action(act). + * + * Onec the client_thread has passed the action off to another + * thread to process, it goes back to waiting for more client + * handling work to do. + * + * The thread that was given the action by the client_thread + * now processes that action according to the operation, act->op. + * This is either a lockspace_thread (for lock ops or ops that + * add/rem a lockspace), or the worker_thread. See below for + * how these ops are processed by these threads. When the + * given thread is done processing the action, the result is + * set in act->result, and the act struct for the completed action + * is passed back to the client_thread (client_results list). + * + * The client_thread takes completed actions (from client_results + * list), and sends the result back to the client that sent the + * request represented by the action. The act struct is then freed. + * + * This completes the cycle of work between lvm commands (clients) + * and lvmlockd. In summary: + * + * - main process polls for new client connections and new requests + * from lvm commands + * - client_thread reads requests from clients + * - client_thread creates an action struct for each request + * - client_thread passes the act to another thread for processing + * - other threads pass completed act structs back to client_thread + * - client_thread sends the act result back to the client and frees the act + * + * + * Lockspace threads: + * Each lockd VG has its own lockspace that contains locks for that VG. + * Each 'struct lockspace' is managed by a separate lockspace_thread. + * When the lockspace_thread is first created, the first thing it does + * is join the lockspace in the lock manager. This can take a long time. + * If the join fails, the thread exits. After the join, the thread + * enters a loop waiting for lock actions to perform in the lockspace. + * + * The request to remove/leave a lockspace causes a flag to be set in + * the lockspace struct. When the lockspace_thread sees this flag + * set, it leaves the lockspace, and exits. + * + * When the client_thread passes a new action to a lockspace_thread, + * i.e. a new lock request, the lockspace_thread identifies which resource + * is being locked (GL, VG, LV), and gets the 'struct resource' (r) for it. + * r->type will be LD_RT_GL, LD_RT_VG, or LD_RT_LV. r->name is the + * resource name, and is fixed for GL and VG resources, but is based on + * the LV name for LV resources. The act is added to the resource's + * list of actions: r->actions, i.e. outstanding lock requests on the + * resource. + * + * The lockspace thread then iterates through each resource in the + * lockspace, processing any outstanding actions on each: res_process(ls, r). + * + * res_process() compares the outstanding actions/requests in r->actions + * against any existing locks on the resource in r->locks. If the + * action is blocked by existing locks, it's left on r->actions. If not, + * the action/request is passed to the lock manager. If the result from + * the lock manager is success, a new 'struct lock' is created for the + * action and saved on r->locks. The result is set in act->result and + * the act is passed back to the client_thread to be returned to the client. + */ + +static const char *lvmlockd_protocol = "lvmlockd"; +static const int lvmlockd_protocol_version = 1; +static int daemon_quit; +static int adopt_opt; + +static daemon_handle lvmetad_handle; +static pthread_mutex_t lvmetad_mutex; +static int lvmetad_connected; + +/* + * We use a separate socket for dumping daemon info. + * This will not interfere with normal operations, and allows + * free-form debug data to be dumped instead of the libdaemon + * protocol that wants all data in the cft format. + * 1MB should fit all the info we need to dump. + */ +#define DUMP_SOCKET_NAME "lvmlockd-dump.sock" +#define DUMP_BUF_SIZE (1024 * 1024) +static char dump_buf[DUMP_BUF_SIZE]; +static struct sockaddr_un dump_addr; +static socklen_t dump_addrlen; + +/* + * Main program polls client connections, adds new clients, + * adds work for client thread. + * + * pollfd_mutex is used for adding vs removing entries, + * and for resume vs realloc. + */ +#define POLL_FD_UNUSED -1 /* slot if free */ +#define POLL_FD_IGNORE -2 /* slot is used but ignore in poll */ +#define ADD_POLL_SIZE 16 /* increment slots by this amount */ + +static pthread_mutex_t pollfd_mutex; +static struct pollfd *pollfd; +static int pollfd_size; +static int pollfd_maxi; +static int listen_pi; +static int listen_fd; +static int restart_pi; +static int restart_fds[2]; + +/* + * Each lockspace has its own thread to do locking. + * The lockspace thread makes synchronous lock requests to dlm/sanlock. + * Every vg with a lockd type, i.e. "dlm", "sanlock", should be on this list. + */ +static pthread_mutex_t lockspaces_mutex; +static struct list_head lockspaces; + +/* + * Client thread reads client requests and writes client results. + */ +static pthread_t client_thread; +static pthread_mutex_t client_mutex; +static pthread_cond_t client_cond; +static struct list_head client_list; /* connected clients */ +static struct list_head client_results; /* actions to send back to clients */ +static uint32_t client_ids; /* 0 and INTERNAL_CLIENT_ID are skipped */ +static int client_stop; /* stop the thread */ +static int client_work; /* a client on client_list has work to do */ + +#define INTERNAL_CLIENT_ID 0xFFFFFFFF /* special client_id for internal actions */ +static struct list_head adopt_results; /* special start actions from adopt_locks() */ + +/* + * Worker thread performs misc non-locking actions, e.g. init/free. + */ +static pthread_t worker_thread; +static pthread_mutex_t worker_mutex; +static pthread_cond_t worker_cond; +static struct list_head worker_list; /* actions for worker_thread */ +static int worker_stop; /* stop the thread */ +static int worker_wake; /* wake the thread without adding work */ + +/* + * The content of every log_foo() statement is saved in the + * circular buffer, which can be dumped to a client and printed. + */ +#define LOG_LINE_SIZE 256 +#define LOG_DUMP_SIZE DUMP_BUF_SIZE +#define LOG_SYSLOG_PRIO LOG_WARNING +static char log_dump[LOG_DUMP_SIZE]; +static unsigned int log_point; +static unsigned int log_wrap; +static pthread_mutex_t log_mutex; +static int syslog_priority = LOG_SYSLOG_PRIO; + +/* + * Structure pools to avoid repeated malloc/free. + */ +#define MAX_UNUSED_ACTION 64 +#define MAX_UNUSED_CLIENT 64 +#define MAX_UNUSED_RESOURCE 64 +#define MAX_UNUSED_LOCK 64 +static pthread_mutex_t unused_struct_mutex; +static struct list_head unused_action; +static struct list_head unused_client; +static struct list_head unused_resource; +static struct list_head unused_lock; +static int unused_action_count; +static int unused_client_count; +static int unused_resource_count; +static int unused_lock_count; +static int resource_lm_data_size; /* max size of lm_data from sanlock|dlm */ +static int alloc_new_structs; /* used for initializing in setup_structs */ + +#define DO_STOP 1 +#define NO_STOP 0 +#define DO_FREE 1 +#define NO_FREE 0 +#define DO_FORCE 1 +#define NO_FORCE 0 + +static int add_lock_action(struct action *act); +static int str_to_lm(const char *str); +static int setup_dump_socket(void); +static void send_dump_buf(int fd, int dump_len); +static int dump_info(int *dump_len); +static int dump_log(int *dump_len); + +static int _syslog_name_to_num(const char *name) +{ + if (!strcmp(name, "emerg")) + return LOG_EMERG; + if (!strcmp(name, "alert")) + return LOG_ALERT; + if (!strcmp(name, "crit")) + return LOG_CRIT; + if (!strcmp(name, "err") || !strcmp(name, "error")) + return LOG_ERR; + if (!strcmp(name, "warning") || !strcmp(name, "warn")) + return LOG_WARNING; + if (!strcmp(name, "notice")) + return LOG_NOTICE; + if (!strcmp(name, "info")) + return LOG_INFO; + if (!strcmp(name, "debug")) + return LOG_DEBUG; + return LOG_WARNING; +} + +static const char *_syslog_num_to_name(int num) +{ + switch (num) { + case LOG_EMERG: + return "emerg"; + case LOG_ALERT: + return "alert"; + case LOG_CRIT: + return "crit"; + case LOG_ERR: + return "err"; + case LOG_WARNING: + return "warning"; + case LOG_NOTICE: + return "notice"; + case LOG_INFO: + return "info"; + case LOG_DEBUG: + return "debug"; + } + return "unknown"; +} + +static uint64_t monotime(void) +{ + struct timespec ts; + + if (clock_gettime(CLOCK_MONOTONIC, &ts)) { + log_error("clock_gettime failed to get timestamp %s.", + strerror(errno)); + ts.tv_sec = 0; + } + + return ts.tv_sec; +} + +static void log_save_line(int len, char *line, + char *log_buf, unsigned int *point, unsigned int *wrap) +{ + unsigned int p = *point; + unsigned int w = *wrap; + int i; + + if (len < (int) (LOG_DUMP_SIZE - p)) { + memcpy(log_buf + p, line, len); + p += len; + + if (p == LOG_DUMP_SIZE) { + p = 0; + w = 1; + } + goto out; + } + + for (i = 0; i < len; i++) { + log_buf[p++] = line[i]; + + if (p == LOG_DUMP_SIZE) { + p = 0; + w = 1; + } + } + out: + *point = p; + *wrap = w; +} + +void log_level(int level, const char *fmt, ...) +{ + char line[LOG_LINE_SIZE]; + va_list ap; + int len = LOG_LINE_SIZE - 1; + int ret, pos = 0; + + memset(line, 0, sizeof(line)); + + ret = snprintf(line, len, "%llu ", (unsigned long long)time(NULL)); + pos += ret; + + va_start(ap, fmt); + ret = vsnprintf(line + pos, len - pos, fmt, ap); + va_end(ap); + + if (ret >= len - pos) + pos = len - 1; + else + pos += ret; + + line[pos++] = '\n'; + line[pos++] = '\0'; + + pthread_mutex_lock(&log_mutex); + log_save_line(pos - 1, line, log_dump, &log_point, &log_wrap); + pthread_mutex_unlock(&log_mutex); + + if (level <= syslog_priority) + syslog(level, "%s", line); + + if (daemon_debug) + fprintf(stderr, "%s", line); +} + +static int dump_log(int *dump_len) +{ + int tail_len; + + pthread_mutex_lock(&log_mutex); + + if (!log_wrap && !log_point) { + *dump_len = 0; + } else if (log_wrap) { + tail_len = LOG_DUMP_SIZE - log_point; + memcpy(dump_buf, log_dump+log_point, tail_len); + if (log_point) + memcpy(dump_buf+tail_len, log_dump, log_point); + *dump_len = LOG_DUMP_SIZE; + } else { + memcpy(dump_buf, log_dump, log_point-1); + *dump_len = log_point-1; + } + pthread_mutex_unlock(&log_mutex); + + return 0; +} + +struct lockspace *alloc_lockspace(void) +{ + struct lockspace *ls; + + if (!(ls = malloc(sizeof(struct lockspace)))) { + log_error("out of memory for lockspace"); + return NULL; + } + + memset(ls, 0, sizeof(struct lockspace)); + INIT_LIST_HEAD(&ls->actions); + INIT_LIST_HEAD(&ls->resources); + pthread_mutex_init(&ls->mutex, NULL); + pthread_cond_init(&ls->cond, NULL); + return ls; +} + +static struct action *alloc_action(void) +{ + struct action *act; + + pthread_mutex_lock(&unused_struct_mutex); + if (!unused_action_count || alloc_new_structs) { + act = malloc(sizeof(struct action)); + } else { + act = list_first_entry(&unused_action, struct action, list); + list_del(&act->list); + unused_action_count--; + } + pthread_mutex_unlock(&unused_struct_mutex); + if (act) + memset(act, 0, sizeof(struct action)); + else + log_error("out of memory for action"); + return act; +} + +static struct client *alloc_client(void) +{ + struct client *cl; + + pthread_mutex_lock(&unused_struct_mutex); + if (!unused_client_count || alloc_new_structs) { + cl = malloc(sizeof(struct client)); + } else { + cl = list_first_entry(&unused_client, struct client, list); + list_del(&cl->list); + unused_client_count--; + } + pthread_mutex_unlock(&unused_struct_mutex); + if (cl) + memset(cl, 0, sizeof(struct client)); + else + log_error("out of memory for client"); + return cl; +} + +static struct resource *alloc_resource(void) +{ + struct resource *r; + + pthread_mutex_lock(&unused_struct_mutex); + if (!unused_resource_count || alloc_new_structs) { + r = malloc(sizeof(struct resource) + resource_lm_data_size); + } else { + r = list_first_entry(&unused_resource, struct resource, list); + list_del(&r->list); + unused_resource_count--; + } + pthread_mutex_unlock(&unused_struct_mutex); + if (r) { + memset(r, 0, sizeof(struct resource) + resource_lm_data_size); + INIT_LIST_HEAD(&r->locks); + INIT_LIST_HEAD(&r->actions); + } else { + log_error("out of memory for resource"); + } + return r; +} + +static struct lock *alloc_lock(void) +{ + struct lock *lk; + + pthread_mutex_lock(&unused_struct_mutex); + if (!unused_lock_count || alloc_new_structs) { + lk = malloc(sizeof(struct lock)); + } else { + lk = list_first_entry(&unused_lock, struct lock, list); + list_del(&lk->list); + unused_lock_count--; + } + pthread_mutex_unlock(&unused_struct_mutex); + if (lk) + memset(lk, 0, sizeof(struct lock)); + else + log_error("out of memory for lock"); + return lk; +} + +static void free_action(struct action *act) +{ + pthread_mutex_lock(&unused_struct_mutex); + if (unused_action_count >= MAX_UNUSED_ACTION) { + free(act); + } else { + list_add_tail(&act->list, &unused_action); + unused_action_count++; + } + pthread_mutex_unlock(&unused_struct_mutex); +} + +static void free_client(struct client *cl) +{ + pthread_mutex_lock(&unused_struct_mutex); + if (unused_client_count >= MAX_UNUSED_CLIENT) { + free(cl); + } else { + list_add_tail(&cl->list, &unused_client); + unused_client_count++; + } + pthread_mutex_unlock(&unused_struct_mutex); +} + +static void free_resource(struct resource *r) +{ + pthread_mutex_lock(&unused_struct_mutex); + if (unused_resource_count >= MAX_UNUSED_RESOURCE) { + free(r); + } else { + list_add_tail(&r->list, &unused_resource); + unused_resource_count++; + } + pthread_mutex_unlock(&unused_struct_mutex); +} + +static void free_lock(struct lock *lk) +{ + pthread_mutex_lock(&unused_struct_mutex); + if (unused_lock_count >= MAX_UNUSED_LOCK) { + free(lk); + } else { + list_add_tail(&lk->list, &unused_lock); + unused_lock_count++; + } + pthread_mutex_unlock(&unused_struct_mutex); +} + +static int setup_structs(void) +{ + struct action *act; + struct client *cl; + struct resource *r; + struct lock *lk; + int data_san = lm_data_size_sanlock(); + int data_dlm = lm_data_size_dlm(); + int i; + + resource_lm_data_size = data_san > data_dlm ? data_san : data_dlm; + + pthread_mutex_init(&unused_struct_mutex, NULL); + INIT_LIST_HEAD(&unused_action); + INIT_LIST_HEAD(&unused_client); + INIT_LIST_HEAD(&unused_resource); + INIT_LIST_HEAD(&unused_lock); + + /* + * For setup, force the alloc_ functions to alloc new structs instead + * of taking them unused. This allows alloc_struct/free_struct loop to + * populate the unused lists. + */ + alloc_new_structs = 1; + + for (i = 0; i < MAX_UNUSED_ACTION/2; i++) { + if (!(act = alloc_action())) + goto fail; + free_action(act); + } + + for (i = 0; i < MAX_UNUSED_CLIENT/2; i++) { + if (!(cl = alloc_client())) + goto fail; + free_client(cl); + } + + for (i = 0; i < MAX_UNUSED_RESOURCE/2; i++) { + if (!(r = alloc_resource())) + goto fail; + free_resource(r); + } + + for (i = 0; i < MAX_UNUSED_LOCK/2; i++) { + if (!(lk = alloc_lock())) + goto fail; + free_lock(lk); + } + + alloc_new_structs = 0; + return 0; +fail: + alloc_new_structs = 0; + return -ENOMEM; +} + +static int add_pollfd(int fd) +{ + int i, new_size; + struct pollfd *tmp_pollfd; + + pthread_mutex_lock(&pollfd_mutex); + for (i = 0; i < pollfd_size; i++) { + if (pollfd[i].fd != POLL_FD_UNUSED) + continue; + + pollfd[i].fd = fd; + pollfd[i].events = POLLIN; + pollfd[i].revents = 0; + + if (i > pollfd_maxi) + pollfd_maxi = i; + + pthread_mutex_unlock(&pollfd_mutex); + return i; + } + + new_size = pollfd_size + ADD_POLL_SIZE; + + tmp_pollfd = realloc(pollfd, new_size * sizeof(struct pollfd)); + if (!tmp_pollfd) { + log_error("can't alloc new size %d for pollfd", new_size); + pthread_mutex_unlock(&pollfd_mutex); + return -ENOMEM; + } + pollfd = tmp_pollfd; + + for (i = pollfd_size; i < new_size; i++) { + pollfd[i].fd = POLL_FD_UNUSED; + pollfd[i].events = 0; + pollfd[i].revents = 0; + } + + i = pollfd_size; + pollfd[i].fd = fd; + pollfd[i].events = POLLIN; + pollfd[i].revents = 0; + pollfd_maxi = i; + + pollfd_size = new_size; + + pthread_mutex_unlock(&pollfd_mutex); + return i; +} + +static void rem_pollfd(int pi) +{ + if (pi < 0) { + log_error("rem_pollfd %d", pi); + return; + } + pthread_mutex_lock(&pollfd_mutex); + pollfd[pi].fd = POLL_FD_UNUSED; + pollfd[pi].events = 0; + pollfd[pi].revents = 0; + pthread_mutex_unlock(&pollfd_mutex); +} + +static const char *lm_str(int x) +{ + switch (x) { + case LD_LM_NONE: + return "none"; + case LD_LM_DLM: + return "dlm"; + case LD_LM_SANLOCK: + return "sanlock"; + default: + return "lm_unknown"; + } +} + +static const char *rt_str(int x) +{ + switch (x) { + case LD_RT_GL: + return "gl"; + case LD_RT_VG: + return "vg"; + case LD_RT_LV: + return "lv"; + default: + return "."; + }; +} + +static const char *op_str(int x) +{ + switch (x) { + case LD_OP_INIT: + return "init"; + case LD_OP_FREE: + return "free"; + case LD_OP_START: + return "start"; + case LD_OP_STOP: + return "stop"; + case LD_OP_LOCK: + return "lock"; + case LD_OP_UPDATE: + return "update"; + case LD_OP_CLOSE: + return "close"; + case LD_OP_ENABLE: + return "enable"; + case LD_OP_DISABLE: + return "disable"; + case LD_OP_START_WAIT: + return "start_wait"; + case LD_OP_STOP_ALL: + return "stop_all"; + case LD_OP_RENAME_BEFORE: + return "rename_before"; + case LD_OP_RENAME_FINAL: + return "rename_final"; + case LD_OP_RUNNING_LM: + return "running_lm"; + case LD_OP_FIND_FREE_LOCK: + return "find_free_lock"; + case LD_OP_KILL_VG: + return "kill_vg"; + case LD_OP_DROP_VG: + return "drop_vg"; + case LD_OP_DUMP_LOG: + return "dump_log"; + case LD_OP_DUMP_INFO: + return "dump_info"; + case LD_OP_BUSY: + return "busy"; + default: + return "op_unknown"; + }; +} + +int last_string_from_args(char *args_in, char *last) +{ + const char *args = args_in; + const char *colon, *str = NULL; + + while (1) { + if (!args || (*args == '\0')) + break; + colon = strstr(args, ":"); + if (!colon) + break; + str = colon; + args = colon + 1; + } + + if (str) { + snprintf(last, MAX_ARGS, "%s", str + 1); + return 0; + } + return -1; +} + +int version_from_args(char *args, unsigned int *major, unsigned int *minor, unsigned int *patch) +{ + char version[MAX_ARGS+1]; + char *major_str, *minor_str, *patch_str; + char *n, *d1, *d2; + + memset(version, 0, sizeof(version)); + strncpy(version, args, MAX_ARGS); + version[MAX_ARGS] = '\0'; + + n = strstr(version, ":"); + if (n) + *n = '\0'; + + d1 = strstr(version, "."); + if (!d1) + return -1; + + d2 = strstr(d1 + 1, "."); + if (!d2) + return -1; + + major_str = version; + minor_str = d1 + 1; + patch_str = d2 + 1; + + *d1 = '\0'; + *d2 = '\0'; + + if (major) + *major = atoi(major_str); + if (minor) + *minor = atoi(minor_str); + if (patch) + *patch = atoi(patch_str); + + return 0; +} + +/* + * These are few enough that arrays of function pointers can + * be avoided. + */ + +static int lm_prepare_lockspace(struct lockspace *ls, struct action *act) +{ + int rv; + + if (ls->lm_type == LD_LM_DLM) + rv = lm_prepare_lockspace_dlm(ls); + else if (ls->lm_type == LD_LM_SANLOCK) + rv = lm_prepare_lockspace_sanlock(ls); + else + return -1; + + if (act) + act->lm_rv = rv; + return rv; +} + +static int lm_add_lockspace(struct lockspace *ls, struct action *act, int adopt) +{ + int rv; + + if (ls->lm_type == LD_LM_DLM) + rv = lm_add_lockspace_dlm(ls, adopt); + else if (ls->lm_type == LD_LM_SANLOCK) + rv = lm_add_lockspace_sanlock(ls, adopt); + else + return -1; + + if (act) + act->lm_rv = rv; + return rv; +} + +static int lm_rem_lockspace(struct lockspace *ls, struct action *act, int free_vg) +{ + int rv; + + if (ls->lm_type == LD_LM_DLM) + rv = lm_rem_lockspace_dlm(ls, free_vg); + else if (ls->lm_type == LD_LM_SANLOCK) + rv = lm_rem_lockspace_sanlock(ls, free_vg); + else + return -1; + + if (act) + act->lm_rv = rv; + return rv; +} + +static int lm_lock(struct lockspace *ls, struct resource *r, int mode, struct action *act, + struct val_blk *vb_out, int *retry, int adopt) +{ + int rv; + + if (ls->lm_type == LD_LM_DLM) + rv = lm_lock_dlm(ls, r, mode, vb_out, adopt); + else if (ls->lm_type == LD_LM_SANLOCK) + rv = lm_lock_sanlock(ls, r, mode, vb_out, retry, adopt); + else + return -1; + + if (act) + act->lm_rv = rv; + return rv; +} + +static int lm_convert(struct lockspace *ls, struct resource *r, + int mode, struct action *act, uint32_t r_version) +{ + int rv; + + if (ls->lm_type == LD_LM_DLM) + rv = lm_convert_dlm(ls, r, mode, r_version); + else if (ls->lm_type == LD_LM_SANLOCK) + rv = lm_convert_sanlock(ls, r, mode, r_version); + else + return -1; + + if (act) + act->lm_rv = rv; + return rv; +} + +static int lm_unlock(struct lockspace *ls, struct resource *r, struct action *act, + uint32_t r_version, uint32_t lmu_flags) +{ + int rv; + + if (ls->lm_type == LD_LM_DLM) + rv = lm_unlock_dlm(ls, r, r_version, lmu_flags); + else if (ls->lm_type == LD_LM_SANLOCK) + rv = lm_unlock_sanlock(ls, r, r_version, lmu_flags); + else + return -1; + + if (act) + act->lm_rv = rv; + return rv; +} + +static int lm_hosts(struct lockspace *ls, int notify) +{ + if (ls->lm_type == LD_LM_DLM) + return lm_hosts_dlm(ls, notify); + else if (ls->lm_type == LD_LM_SANLOCK) + return lm_hosts_sanlock(ls, notify); + return -1; +} + +static void lm_rem_resource(struct lockspace *ls, struct resource *r) +{ + if (ls->lm_type == LD_LM_DLM) + lm_rem_resource_dlm(ls, r); + else if (ls->lm_type == LD_LM_SANLOCK) + lm_rem_resource_sanlock(ls, r); +} + +static int lm_find_free_lock(struct lockspace *ls, uint64_t *free_offset) +{ + if (ls->lm_type == LD_LM_DLM) + return 0; + else if (ls->lm_type == LD_LM_SANLOCK) + return lm_find_free_lock_sanlock(ls, free_offset); + return -1; +} + +/* + * While adopting locks, actions originate from the adopt_locks() + * function, not from a client. So, these actions (flagged ADOPT), + * should be passed back to the adopt_locks() function through the + * adopt_results list, and not be sent back to a client via the + * client_list/client_thread. + */ + +static void add_client_result(struct action *act) +{ + if (act->flags & LD_AF_NO_CLIENT) { + log_debug("internal action done op %s mode %s result %d vg %s", + op_str(act->op), mode_str(act->mode), act->result, act->vg_name); + free_action(act); + return; + } + + pthread_mutex_lock(&client_mutex); + if (act->flags & LD_AF_ADOPT) + list_add_tail(&act->list, &adopt_results); + else + list_add_tail(&act->list, &client_results); + pthread_cond_signal(&client_cond); + pthread_mutex_unlock(&client_mutex); +} + +static struct lock *find_lock_client(struct resource *r, uint32_t client_id) +{ + struct lock *lk; + + list_for_each_entry(lk, &r->locks, list) { + if (lk->client_id == client_id) + return lk; + } + return NULL; +} + +static struct lock *find_lock_persistent(struct resource *r) +{ + struct lock *lk; + + list_for_each_entry(lk, &r->locks, list) { + if (lk->flags & LD_LF_PERSISTENT) + return lk; + } + return NULL; +} + +static struct action *find_action_client(struct resource *r, uint32_t client_id) +{ + struct action *act; + + list_for_each_entry(act, &r->actions, list) { + if (act->client_id != client_id) + continue; + return act; + } + return NULL; +} + +static void add_work_action(struct action *act) +{ + pthread_mutex_lock(&worker_mutex); + if (!worker_stop) { + list_add_tail(&act->list, &worker_list); + pthread_cond_signal(&worker_cond); + } + pthread_mutex_unlock(&worker_mutex); +} + +static daemon_reply send_lvmetad(const char *id, ...) +{ + daemon_reply reply; + va_list ap; + int retries = 0; + int err; + + va_start(ap, id); + + /* + * mutex is used because all threads share a single + * lvmetad connection/handle. + */ + pthread_mutex_lock(&lvmetad_mutex); +retry: + if (!lvmetad_connected) { + lvmetad_handle = lvmetad_open(NULL); + if (lvmetad_handle.error || lvmetad_handle.socket_fd < 0) { + err = lvmetad_handle.error ?: lvmetad_handle.socket_fd; + pthread_mutex_unlock(&lvmetad_mutex); + log_error("lvmetad_open reconnect error %d", err); + memset(&reply, 0, sizeof(reply)); + reply.error = err; + va_end(ap); + return reply; + } else { + log_debug("lvmetad reconnected"); + lvmetad_connected = 1; + } + } + + reply = daemon_send_simple_v(lvmetad_handle, id, ap); + + /* lvmetad may have been restarted */ + if ((reply.error == ECONNRESET) && (retries < 2)) { + daemon_close(lvmetad_handle); + lvmetad_connected = 0; + retries++; + goto retry; + } + pthread_mutex_unlock(&lvmetad_mutex); + + va_end(ap); + return reply; +} + +static int res_lock(struct lockspace *ls, struct resource *r, struct action *act, int *retry) +{ + struct lock *lk; + struct val_blk vb; + uint32_t new_version = 0; + int inval_meta; + int rv = 0; + + memset(&vb, 0, sizeof(vb)); + + r->last_client_id = act->client_id; + + if (r->type == LD_RT_LV) + log_debug("S %s R %s res_lock cl %u mode %s (%s)", ls->name, r->name, act->client_id, mode_str(act->mode), act->lv_name); + else + log_debug("S %s R %s res_lock cl %u mode %s", ls->name, r->name, act->client_id, mode_str(act->mode)); + + if (r->mode == LD_LK_SH && act->mode == LD_LK_SH) + goto add_lk; + + if (r->type == LD_RT_LV && act->lv_args[0]) + memcpy(r->lv_args, act->lv_args, MAX_ARGS); + + rv = lm_lock(ls, r, act->mode, act, &vb, retry, act->flags & LD_AF_ADOPT); + + if (r->use_vb) + log_debug("S %s R %s res_lock rv %d read vb %x %x %u", + ls->name, r->name, rv, vb.version, vb.flags, vb.r_version); + else + log_debug("S %s R %s res_lock rv %d", ls->name, r->name, rv); + + if (rv < 0) + return rv; + + if (sanlock_gl_dup && ls->sanlock_gl_enabled) + act->flags |= LD_AF_DUP_GL_LS; + + /* + * Check new lvb values to decide if lvmetad cache should + * be invalidated. When we need to invalidate the lvmetad + * cache, but don't have a usable r_version from the lvb, + * send lvmetad new_version 0 which causes it to invalidate + * the VG metdata without comparing against the currently + * cached VG seqno. + */ + + inval_meta = 0; + + if (!r->use_vb) { + /* LV locks don't use an lvb. */ + + } else if (vb.version && ((vb.version & 0xFF00) > (VAL_BLK_VERSION & 0xFF00))) { + log_error("S %s R %s res_lock invalid val_blk version %x flags %x r_version %u", + ls->name, r->name, vb.version, vb.flags, vb.r_version); + inval_meta = 1; + new_version = 0; + rv = -EINVAL; + + } else if (vb.r_version && (vb.r_version == r->version)) { + /* + * Common case when the version hasn't changed. + * Do nothing. + */ + } else if (r->version && vb.r_version && (vb.r_version > r->version)) { + /* + * Common case when the version has changed. Another host + * has changed the data protected by the lock since we last + * acquired it, and increased r_version so we know that our + * cache is invalid. + */ + log_debug("S %s R %s res_lock got version %u our %u", + ls->name, r->name, vb.r_version, r->version); + r->version = vb.r_version; + new_version = vb.r_version; + r->version_zero_valid = 0; + inval_meta = 1; + + } else if (r->version_zero_valid && !vb.r_version) { + /* + * The lvb is in a persistent zero state, which will end + * once someone uses the lock and writes a new lvb value. + * Do nothing. + */ + log_debug("S %s R %s res_lock version_zero_valid still zero", ls->name, r->name); + + } else if (r->version_zero_valid && vb.r_version) { + /* + * Someone has written to the lvb after it was in a + * persistent zero state. Begin tracking normal + * non-zero changes. We may or may not have known + * about a previous non-zero version (in r->version). + * If we did, it means the lvb content was lost and + * has now been reinitialized. + * + * If the new reinitialized value is less than the + * previous non-zero value in r->version, then something + * unusual has happened. For a VG lock, it probably + * means the VG was removed and recreated. Invalidate + * our cache and begin using the new VG version. For + * a GL lock, another host may have reinitialized a + * lost/zero lvb with a value less than we'd seen + * before. Invalidate the cache, and begin using + * the lower version (or continue using our old + * larger version?) + */ + if (r->version && (r->version >= vb.r_version)) { + log_debug("S %s R %s res_lock version_zero_valid got version %u less than our %u", + ls->name, r->name, vb.r_version, r->version); + new_version = 0; + } else { + log_debug("S %s R %s res_lock version_zero_valid got version %u our %u", + ls->name, r->name, vb.r_version, r->version); + new_version = vb.r_version; + } + r->version = vb.r_version; + r->version_zero_valid = 0; + inval_meta = 1; + + } else if (!r->version && vb.r_version) { + /* + * The first time we've acquired the lock and seen the lvb. + */ + log_debug("S %s R %s res_lock initial version %u", ls->name, r->name, vb.r_version); + r->version = vb.r_version; + inval_meta = 1; + new_version = vb.r_version; + r->version_zero_valid = 0; + + } else if (!r->version && !vb.r_version) { + /* + * The lock may have never been used to change something. + * (e.g. a new sanlock GL?) + */ + log_debug("S %s R %s res_lock all versions zero", ls->name, r->name); + if (!r->version_zero_valid) { + inval_meta = 1; + new_version = 0; + } + r->version_zero_valid = 1; + + } else if (r->version && !vb.r_version) { + /* + * The lvb content has been lost or never been initialized. + * It can be lost during dlm recovery when the master node + * is removed. + * + * If we're the next to write the lvb, reinitialze it to the + * new VG seqno, or a new GL counter larger than was seen by + * any hosts before (how to estimate that?) + * + * If we see non-zero values before we next write to it, use + * those values. + * + * While the lvb values remain zero, the data for the lock + * is unchanged and we don't need to invalidate metadata. + */ + if ((ls->lm_type == LD_LM_DLM) && !vb.version && !vb.flags) + log_debug("S %s R %s res_lock all lvb content is blank", + ls->name, r->name); + log_debug("S %s R %s res_lock our version %u got vb %x %x %u", + ls->name, r->name, r->version, vb.version, vb.flags, vb.r_version); + r->version_zero_valid = 1; + inval_meta = 1; + new_version = 0; + + } else if (r->version && vb.r_version && (vb.r_version < r->version)) { + /* + * The lvb value has gone backwards, which shouldn't generally happen, + * but could when the dlm lvb is lost and reinitialized, or the VG + * is removed and recreated. + * + * If this is a VG lock, it probably means the VG has been removed + * and recreated while we had the dlm lockspace running. + * FIXME: how does the cache validation and replacement in lvmetad + * work in this case? + */ + log_debug("S %s R %s res_lock got version %u less than our version %u", + ls->name, r->name, vb.r_version, r->version); + r->version = vb.r_version; + inval_meta = 1; + new_version = 0; + r->version_zero_valid = 0; + } else { + log_debug("S %s R %s res_lock undefined vb condition vzv %d our version %u vb %x %x %u", + ls->name, r->name, r->version_zero_valid, r->version, + vb.version, vb.flags, vb.r_version); + } + + if (vb.version && vb.r_version && (vb.flags & VBF_REMOVED)) { + /* Should we set ls->thread_stop = 1 ? */ + log_debug("S %s R %s res_lock vb flag REMOVED", + ls->name, r->name); + rv = -EREMOVED; + } + + /* + * r is vglk: tell lvmetad to set the vg invalid + * flag, and provide the new r_version. If lvmetad finds + * that its cached vg has seqno less than the value + * we send here, it will set the vg invalid flag. + * lvm commands that read the vg from lvmetad, will + * see the invalid flag returned, will reread the + * vg from disk, update the lvmetad copy, and go on. + * + * r is global: tell lvmetad to set the global invalid + * flag. When commands see this flag returned from lvmetad, + * they will reread metadata from disk, update the lvmetad + * caches, and tell lvmetad to set global invalid to 0. + */ + + if (inval_meta && (r->type == LD_RT_VG)) { + daemon_reply reply; + char *uuid; + + log_debug("S %s R %s res_lock set lvmetad vg version %u", + ls->name, r->name, new_version); + + if (!ls->vg_uuid[0] || !strcmp(ls->vg_uuid, "none")) + uuid = (char *)"none"; + else + uuid = ls->vg_uuid; + + reply = send_lvmetad("set_vg_info", + "token = %s", "skip", + "uuid = %s", uuid, + "name = %s", ls->vg_name, + "version = " FMTd64, (int64_t)new_version, + NULL); + + if (reply.error || strcmp(daemon_reply_str(reply, "response", ""), "OK")) + log_error("set_vg_info in lvmetad failed %d", reply.error); + daemon_reply_destroy(reply); + } + + if (inval_meta && (r->type == LD_RT_GL)) { + daemon_reply reply; + + log_debug("S %s R %s res_lock set lvmetad global invalid", + ls->name, r->name); + + reply = send_lvmetad("set_global_info", + "token = %s", "skip", + "global_invalid = " FMTd64, INT64_C(1), + NULL); + + if (reply.error || strcmp(daemon_reply_str(reply, "response", ""), "OK")) + log_error("set_global_info in lvmetad failed %d", reply.error); + daemon_reply_destroy(reply); + } + + /* + * Record the new lock state. + */ + + r->mode = act->mode; + +add_lk: + if (r->mode == LD_LK_SH) + r->sh_count++; + + if (!(lk = alloc_lock())) + return -ENOMEM; + + lk->client_id = act->client_id; + lk->mode = act->mode; + + if (act->flags & LD_AF_PERSISTENT) { + lk->flags |= LD_LF_PERSISTENT; + lk->client_id = 0; + } + + /* + * LV_LOCK means the action acquired the lv lock in the lock manager + * (as opposed to finding that the lv lock was already held). If + * the client for this LV_LOCK action fails before we send the result, + * then we automatically unlock the lv since the lv wasn't activated. + * (There will always be an odd chance the lv lock is held while the + * lv is not active, but this helps.) The most common case where this + * is helpful is when the lv lock operation is slow/delayed and the + * command is canceled by the user. + * + * LV_UNLOCK means the lv unlock action was generated by lvmlockd when + * it tried to send the reply for an lv lock action (with LV_LOCK set), + * and failed to send the reply to the client/command. The + * last_client_id saved on the resource is compared to this LV_UNLOCK + * action before the auto unlock is done in case another action locked + * the lv between the failed client lock action and the auto unlock. + */ + if (r->type == LD_RT_LV) + act->flags |= LD_AF_LV_LOCK; + + list_add_tail(&lk->list, &r->locks); + + return rv; +} + +static int res_convert(struct lockspace *ls, struct resource *r, + struct lock *lk, struct action *act) +{ + uint32_t r_version; + int rv; + + r->last_client_id = act->client_id; + + log_debug("S %s R %s res_convert cl %u mode %s", ls->name, r->name, act->client_id, mode_str(act->mode)); + + if (act->mode == LD_LK_EX && lk->mode == LD_LK_SH && r->sh_count > 1) + return -EAGAIN; + + /* + * lm_convert() writes new version (from ex) + * Same as lm_unlock() + */ + + if ((r->type == LD_RT_GL) && (r->mode == LD_LK_EX)) { + r->version++; + lk->version = r->version; + r_version = r->version; + r->version_zero_valid = 0; + + log_debug("S %s R %s res_convert r_version inc %u", + ls->name, r->name, r_version); + + } else if ((r->type == LD_RT_VG) && (r->mode == LD_LK_EX) && (lk->version > r->version)) { + r->version = lk->version; + r_version = r->version; + r->version_zero_valid = 0; + + log_debug("S %s R %s res_convert r_version new %u", ls->name, r->name, r_version); + } else { + r_version = 0; + } + + rv = lm_convert(ls, r, act->mode, act, r_version); + if (rv < 0) { + log_error("S %s R %s res_convert lm error %d", ls->name, r->name, rv); + return rv; + } + + log_debug("S %s R %s res_convert lm done", ls->name, r->name); + + if (lk->mode == LD_LK_EX && act->mode == LD_LK_SH) { + r->sh_count = 1; + } else if (lk->mode == LD_LK_SH && act->mode == LD_LK_EX) { + r->sh_count = 0; + } else { + /* should not be possible */ + log_error("S %s R %s res_convert invalid modes %d %d", + ls->name, r->name, lk->mode, act->mode); + return -1; + } + + r->mode = act->mode; + lk->mode = act->mode; + + return 0; +} + +static int res_cancel(struct lockspace *ls, struct resource *r, + struct action *act) +{ + struct action *cact; + + /* + * a client can cancel its own non-persistent lock requests, + * when could this happen? + * + * a client can cancel other client's persistent lock requests, + * when could this happen? + */ + + if (act->flags & LD_AF_PERSISTENT) { + list_for_each_entry(cact, &r->actions, list) { + if (!(cact->flags & LD_AF_PERSISTENT)) + continue; + goto do_cancel; + } + } else { + cact = find_action_client(r, act->client_id); + if (cact) + goto do_cancel; + } + + return -ENOENT; + +do_cancel: + log_debug("S %s R %s res_cancel cl %u", ls->name, r->name, cact->client_id); + cact->result = -ECANCELED; + list_del(&cact->list); + add_client_result(cact); + + return -ECANCELED; +} + +/* + * lm_unlock() writes new a r_version (from ex) + * + * The r_version of the vg resource is incremented if + * an "update" was received for the vg lock. The update + * contains the new vg seqno from the vg metadata which is + * used as the r_version. + * + * The r_version of the global resource is automatically + * incremented when it is unlocked from ex mode. + * + * r_version is incremented every time a command releases + * the global lock from ex. + */ + +/* + * persistent locks will not be unlocked for OP_CLOSE/act_close + * because act_close->flags does not have the PERSISTENT flag + * set, and a persistent lk->client_id is zero, which will not + * match the client in act_close->client_id. + */ + +static int res_unlock(struct lockspace *ls, struct resource *r, + struct action *act) +{ + struct lock *lk; + uint32_t r_version; + int rv; + + if (act->flags & LD_AF_PERSISTENT) { + lk = find_lock_persistent(r); + if (lk) + goto do_unlock; + } else { + lk = find_lock_client(r, act->client_id); + if (lk) + goto do_unlock; + } + + if (act->op != LD_OP_CLOSE) + log_debug("S %s R %s res_unlock cl %u no locks", ls->name, r->name, act->client_id); + return -ENOENT; + +do_unlock: + if ((act->flags & LD_AF_LV_UNLOCK) && (r->last_client_id != act->client_id)) { + log_debug("S %s R %s res_unlock cl %u for failed client ignored, last client %u", + ls->name, r->name, act->client_id, r->last_client_id); + return -ENOENT; + } + + r->last_client_id = act->client_id; + + if (act->op == LD_OP_CLOSE) + log_debug("S %s R %s res_unlock cl %u from close", ls->name, r->name, act->client_id); + else if (r->type == LD_RT_LV) + log_debug("S %s R %s res_unlock cl %u (%s)", ls->name, r->name, act->client_id, act->lv_name); + else + log_debug("S %s R %s res_unlock cl %u", ls->name, r->name, act->client_id); + + /* send unlock to lm when last sh lock is unlocked */ + if (lk->mode == LD_LK_SH) { + r->sh_count--; + if (r->sh_count > 0) { + log_debug("S %s R %s res_unlock sh_count %u", ls->name, r->name, r->sh_count); + goto rem_lk; + } + } + + if ((r->type == LD_RT_GL) && (r->mode == LD_LK_EX)) { + r->version++; + lk->version = r->version; + r_version = r->version; + r->version_zero_valid = 0; + + log_debug("S %s R %s res_unlock r_version inc %u", ls->name, r->name, r_version); + + } else if ((r->type == LD_RT_VG) && (r->mode == LD_LK_EX) && (lk->version > r->version)) { + r->version = lk->version; + r_version = r->version; + r->version_zero_valid = 0; + + log_debug("S %s R %s res_unlock r_version new %u", + ls->name, r->name, r_version); + } else { + r_version = 0; + } + + rv = lm_unlock(ls, r, act, r_version, 0); + if (rv < 0) { + /* should never happen, retry? */ + log_error("S %s R %s res_unlock lm error %d", ls->name, r->name, rv); + return rv; + } + + log_debug("S %s R %s res_unlock lm done", ls->name, r->name); + +rem_lk: + list_del(&lk->list); + free_lock(lk); + + if (list_empty(&r->locks)) + r->mode = LD_LK_UN; + + return 0; +} + +static int res_update(struct lockspace *ls, struct resource *r, + struct action *act) +{ + struct lock *lk; + + lk = find_lock_client(r, act->client_id); + if (!lk) { + log_error("S %s R %s res_update cl %u lock not found", + ls->name, r->name, act->client_id); + return -ENOENT; + } + + if (r->mode != LD_LK_EX) { + log_error("S %s R %s res_update cl %u version on non-ex lock", + ls->name, r->name, act->client_id); + return -EINVAL; + } + + /* lk version will be written to lm by unlock */ + + if (act->flags & LD_AF_NEXT_VERSION) + lk->version = r->version + 1; + else { + if (r->version >= act->version) { + /* + * This update is done from vg_write. If the metadata with + * this seqno is not committed by vg_commit, then next + * vg_write can use the same seqno, causing us to see no + * increase in seqno here as expected. + * FIXME: In this case, do something like setting the lvb + * version to 0 to instead of the same seqno which will + * force an invalidation on other hosts. The next change + * will return to using the seqno again. + */ + log_error("S %s R %s res_update cl %u old version %u new version %u too small", + ls->name, r->name, act->client_id, r->version, act->version); + } + lk->version = act->version; + } + + log_debug("S %s R %s res_update cl %u lk version to %u", ls->name, r->name, act->client_id, lk->version); + + return 0; +} + +/* + * There is nothing to deallocate when freeing a dlm LV, the LV + * will simply be unlocked by rem_resource. + */ + +static int free_lv(struct lockspace *ls, struct resource *r) +{ + if (ls->lm_type == LD_LM_SANLOCK) + return lm_free_lv_sanlock(ls, r); + else if (ls->lm_type == LD_LM_DLM) + return 0; + else + return -EINVAL; +} + +/* + * NB. we can't do this if sanlock is holding any locks on + * the resource; we'd be rewriting the resource from under + * sanlock and would confuse or break it badly. We don't + * know what another host is doing, so these must be used + * very carefully. + */ + +static int res_able(struct lockspace *ls, struct resource *r, + struct action *act) +{ + int rv; + + if (ls->lm_type != LD_LM_SANLOCK) { + log_error("enable/disable only applies to sanlock"); + return -EINVAL; + } + + if (r->type != LD_RT_GL) { + log_error("enable/disable only applies to global lock"); + return -EINVAL; + } + + if (r->mode != LD_LK_UN) { + log_error("enable/disable only allowed on unlocked resource"); + return -EINVAL; + } + + if (act->op == LD_OP_ENABLE && gl_lsname_sanlock[0]) { + log_error("disable global lock in %s before enable in %s", + gl_lsname_sanlock, ls->name); + return -EINVAL; + } + + if ((act->op == LD_OP_DISABLE) && (act->flags & LD_AF_EX_DISABLE)) { + rv = lm_ex_disable_gl_sanlock(ls); + goto out; + } + + rv = lm_able_gl_sanlock(ls, act->op == LD_OP_ENABLE); + + if (!rv && (act->op == LD_OP_ENABLE)) + gl_vg_removed = 0; +out: + return rv; +} + +/* + * Go through queued actions, and make lock/unlock calls on the resource + * based on the actions and the existing lock state. + * + * All lock operations sent to the lock manager are non-blocking. + * This is because sanlock does not support lock queueing. + * Eventually we could enhance this to take advantage of lock + * queueing when available (i.e. for the dlm). + * + * act_close_list: list of CLOSE actions, identifying clients that have + * closed/terminated their lvmlockd connection, and whose locks should + * be released. Do not remove these actions from act_close_list. + * + * retry_out: set to 1 if the lock manager said we should retry, + * meaning we should call res_process() again in a short while to retry. + */ + +static void res_process(struct lockspace *ls, struct resource *r, + struct list_head *act_close_list, int *retry_out) +{ + struct action *act, *safe, *act_close; + struct lock *lk; + int lm_retry; + int rv; + + /* + * handle version updates for ex locks + * (new version will be written by unlock) + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (act->op == LD_OP_UPDATE) { + rv = res_update(ls, r, act); + act->result = rv; + list_del(&act->list); + add_client_result(act); + } + } + + /* + * handle explicit unlock actions + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if ((act->op == LD_OP_LOCK) && + (act->mode == LD_LK_IV || act->mode == LD_LK_NL)) { + act->result = -EINVAL; + list_del(&act->list); + add_client_result(act); + } + + if (act->op == LD_OP_LOCK && act->mode == LD_LK_UN) { + rv = res_unlock(ls, r, act); + + if (rv == -ENOENT && (act->flags & LD_AF_UNLOCK_CANCEL)) + rv = res_cancel(ls, r, act); + + /* + * possible unlock results: + * 0: unlock succeeded + * -ECANCELED: cancel succeeded + * -ENOENT: nothing to unlock or cancel + */ + + act->result = rv; + list_del(&act->list); + add_client_result(act); + } + } + + /* + * handle implicit unlocks due to client exit, + * also clear any outstanding actions for the client + */ + + list_for_each_entry(act_close, act_close_list, list) { + res_unlock(ls, r, act_close); + res_cancel(ls, r, act_close); + } + + /* + * handle freeing a lock for an lv that has been removed + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (act->op == LD_OP_FREE && act->rt == LD_RT_LV) { + log_debug("S %s R %s free_lv", ls->name, r->name); + rv = free_lv(ls, r); + act->result = rv; + list_del(&act->list); + add_client_result(act); + goto r_free; + + } + } + + /* + * handle enable/disable + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (act->op == LD_OP_ENABLE || act->op == LD_OP_DISABLE) { + rv = res_able(ls, r, act); + act->result = rv; + list_del(&act->list); + add_client_result(act); + + if (!rv && act->op == LD_OP_DISABLE) { + log_debug("S %s R %s free disabled", ls->name, r->name); + goto r_free; + } + } + } + + /* + * transient requests on existing transient locks + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (act->flags & LD_AF_PERSISTENT) + continue; + + lk = find_lock_client(r, act->client_id); + if (!lk) + continue; + + if (lk->mode != act->mode) { + /* convert below */ + /* + act->result = -EEXIST; + list_del(&act->list); + add_client_result(act); + */ + continue; + } else { + /* success */ + r->last_client_id = act->client_id; + act->result = -EALREADY; + list_del(&act->list); + add_client_result(act); + } + } + + /* + * persistent requests on existing persistent locks + * + * persistent locks are not owned by a client, so any + * existing with matching mode satisfies a request. + * only one persistent lock is kept on a resource. + * a single "unowned" persistent lock satisfies + * any/multiple client requests for a persistent lock. + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (!(act->flags & LD_AF_PERSISTENT)) + continue; + + lk = find_lock_persistent(r); + if (!lk) + continue; + + if (lk->mode != act->mode) { + /* convert below */ + /* + act->result = -EEXIST; + list_del(&act->list); + add_client_result(act); + */ + continue; + } else { + /* success */ + r->last_client_id = act->client_id; + act->result = -EALREADY; + list_del(&act->list); + add_client_result(act); + } + } + + /* + * transient requests with existing persistent locks + * + * Just grant the transient request and do not + * keep a record of it. Assume that the persistent + * lock will not go away while the transient lock + * is needed. + * + * This would be used when an ex, persistent lv lock + * exists from activation, and then something like + * lvextend asks for a transient ex lock to change + * the lv. The lv could not be unlocked by deactivation + * while the lvextend was running. + * + * The logic here for mixing T/P locks is not general + * support; there are a number of cases where it will + * not work: updating version number (lv locks have + * none), ex locks from multiple clients will not + * conflict, explicit un of the transient lock will fail. + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (act->flags & LD_AF_PERSISTENT) + continue; + + lk = find_lock_persistent(r); + if (!lk) + continue; + + if ((lk->mode == LD_LK_EX) || + (lk->mode == LD_LK_SH && act->mode == LD_LK_SH)) { + r->last_client_id = act->client_id; + act->result = 0; + list_del(&act->list); + add_client_result(act); + } else { + /* persistent lock is sh, transient request is ex */ + /* FIXME: can we remove this case? do a convert here? */ + log_debug("res_process %s existing persistent lock new transient", r->name); + r->last_client_id = act->client_id; + act->result = -EEXIST; + list_del(&act->list); + add_client_result(act); + } + } + + /* + * persistent requests with existing transient locks + * + * If a client requests a P (persistent) lock for a T (transient) + * lock it already holds, we can just change T to P. Fail if the + * same happens for locks from different clients. Changing + * another client's lock from T to P may cause problems + * if that client tries to unlock or update version. + * + * I don't think this P/T combination will be used. + * It might be used if a command was able to take a P + * vg lock, in which case the T vg lock would already + * be held for reading. If the T lock was sh, it would + * be converted to P ex. If the T/P modes matched, the + * lock could just be changed from T to P. + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (!(act->flags & LD_AF_PERSISTENT)) + continue; + + lk = find_lock_client(r, act->client_id); + if (!lk) + continue; + + if (lk->mode != act->mode) { + /* FIXME: convert and change to persistent? */ + log_debug("res_process %s existing transient lock new persistent", r->name); + r->last_client_id = act->client_id; + act->result = -EEXIST; + list_del(&act->list); + add_client_result(act); + } else { + r->last_client_id = act->client_id; + lk->flags |= LD_LF_PERSISTENT; + lk->client_id = 0; + act->result = 0; + list_del(&act->list); + add_client_result(act); + } + } + + /* + * convert mode of existing locks + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (act->flags & LD_AF_PERSISTENT) + lk = find_lock_persistent(r); + else + lk = find_lock_client(r, act->client_id); + if (!lk) + continue; + + if (lk->mode == act->mode) { + /* should never happen, should be found above */ + log_error("convert same mode"); + continue; + } + + /* convert fails immediately, no EAGAIN retry */ + rv = res_convert(ls, r, lk, act); + act->result = rv; + list_del(&act->list); + add_client_result(act); + } + + /* + * Cases above are all requests addressed by existing locks. + * Below handles the rest. Transient and persistent are + * handled the same, except + * - if mode of existing lock is incompat with requested, + * leave the act on r->actions + * - if r mode is EX, any lock action is blocked, just quit + * + * Retry a lock request that fails due to a lock conflict (-EAGAIN): + * if we have not exceeded max retries and lm sets lm_retry (sanlock + * transient conflicts from shared lock implementation), or r type + * is gl or vg (transient real conflicts we want to hide from command). + * lv lock conflicts won't be transient so don't retry them. + */ + + if (r->mode == LD_LK_EX) + return; + + /* + * r mode is SH or UN, pass lock-sh actions to lm + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + /* grant in order, so break here */ + if (act->op == LD_OP_LOCK && act->mode == LD_LK_EX) + break; + + if (act->op == LD_OP_LOCK && act->mode == LD_LK_SH) { + lm_retry = 0; + + rv = res_lock(ls, r, act, &lm_retry); + if ((rv == -EAGAIN) && + (act->retries <= act->max_retries) && + (lm_retry || (r->type != LD_RT_LV))) { + /* leave act on list */ + log_debug("S %s R %s res_lock EAGAIN retry", ls->name, r->name); + act->retries++; + *retry_out = 1; + } else { + act->result = rv; + list_del(&act->list); + add_client_result(act); + } + if (rv == -EUNATCH) + goto r_free; + } + } + + /* + * r mode is SH, any ex lock action is blocked, just quit + */ + + if (r->mode == LD_LK_SH) + return; + + /* + * r mode is UN, pass lock-ex action to lm + */ + + list_for_each_entry_safe(act, safe, &r->actions, list) { + if (act->op == LD_OP_LOCK && act->mode == LD_LK_EX) { + lm_retry = 0; + + rv = res_lock(ls, r, act, &lm_retry); + if ((rv == -EAGAIN) && + (act->retries <= act->max_retries) && + (lm_retry || (r->type != LD_RT_LV))) { + /* leave act on list */ + log_debug("S %s R %s res_lock EAGAIN retry", ls->name, r->name); + act->retries++; + *retry_out = 1; + } else { + act->result = rv; + list_del(&act->list); + add_client_result(act); + } + if (rv == -EUNATCH) + goto r_free; + break; + } + } + + return; + +r_free: + /* For the EUNATCH case it may be possible there are queued actions? */ + list_for_each_entry_safe(act, safe, &r->actions, list) { + log_error("S %s R %s res_process r_free cancel %s client %d", + ls->name, r->name, op_str(act->op), act->client_id); + act->result = -ECANCELED; + list_del(&act->list); + add_client_result(act); + } + log_debug("S %s R %s res_process free", ls->name, r->name); + lm_rem_resource(ls, r); + list_del(&r->list); + free_resource(r); +} + +#define LOCKS_EXIST_ANY 1 +#define LOCKS_EXIST_GL 2 +#define LOCKS_EXIST_VG 3 +#define LOCKS_EXIST_LV 4 + +static int for_each_lock(struct lockspace *ls, int locks_do) +{ + struct resource *r; + struct lock *lk; + + list_for_each_entry(r, &ls->resources, list) { + list_for_each_entry(lk, &r->locks, list) { + if (locks_do == LOCKS_EXIST_ANY) + return 1; + + if (locks_do == LOCKS_EXIST_GL && r->type == LD_RT_GL) + return 1; + + if (locks_do == LOCKS_EXIST_VG && r->type == LD_RT_VG) + return 1; + + if (locks_do == LOCKS_EXIST_LV && r->type == LD_RT_LV) + return 1; + } + } + + return 0; +} + +static int clear_locks(struct lockspace *ls, int free_vg, int drop_vg) +{ + struct resource *r, *r_safe; + struct lock *lk, *lk_safe; + struct action *act, *act_safe; + uint32_t lk_version; + uint32_t r_version; + int lk_count = 0; + int rv; + + list_for_each_entry_safe(r, r_safe, &ls->resources, list) { + lk_version = 0; + + list_for_each_entry_safe(lk, lk_safe, &r->locks, list) { + lk_count++; + + /* + * Stopping a lockspace shouldn't happen with LV locks + * still held, but it will be stopped with GL and VG + * locks held. The drop_vg case may see LV locks. + */ + + if (lk->flags & LD_LF_PERSISTENT && !drop_vg) + log_error("S %s R %s clear lock persistent", ls->name, r->name); + else + log_debug("S %s R %s clear lock mode %s client %d", ls->name, r->name, mode_str(lk->mode), lk->client_id); + + if (lk->version > lk_version) + lk_version = lk->version; + + list_del(&lk->list); + free_lock(lk); + } + + if (r->mode == LD_LK_UN) + goto r_free; + + if ((r->type == LD_RT_GL) && (r->mode == LD_LK_EX)) { + r->version++; + r_version = r->version; + log_debug("S %s R %s clear_locks r_version inc %u", + ls->name, r->name, r_version); + + } else if ((r->type == LD_RT_VG) && (r->mode == LD_LK_EX) && (lk_version > r->version)) { + r->version = lk_version; + r_version = r->version; + log_debug("S %s R %s clear_locks r_version new %u", + ls->name, r->name, r_version); + + } else { + r_version = 0; + } + + rv = lm_unlock(ls, r, NULL, r_version, free_vg ? LMUF_FREE_VG : 0); + if (rv < 0) { + /* should never happen */ + log_error("S %s R %s clear_locks free %d drop %d lm unlock error %d", + ls->name, r->name, free_vg, drop_vg, rv); + } + + list_for_each_entry_safe(act, act_safe, &r->actions, list) { + log_error("S %s R %s clear_locks cancel %s client %d", + ls->name, r->name, op_str(act->op), act->client_id); + act->result = -ECANCELED; + list_del(&act->list); + add_client_result(act); + } + r_free: + log_debug("S %s R %s free", ls->name, r->name); + lm_rem_resource(ls, r); + list_del(&r->list); + free_resource(r); + } + + return lk_count; +} + +/* + * find and return the resource that is referenced by the action + * - there is a single gl resource per lockspace + * - there is a single vg resource per lockspace + * - there can be many lv resources per lockspace, compare names + */ + +static struct resource *find_resource_act(struct lockspace *ls, + struct action *act, + int nocreate) +{ + struct resource *r; + + list_for_each_entry(r, &ls->resources, list) { + if (r->type != act->rt) + continue; + + if (r->type == LD_RT_GL && act->rt == LD_RT_GL) + return r; + + if (r->type == LD_RT_VG && act->rt == LD_RT_VG) + return r; + + if (r->type == LD_RT_LV && act->rt == LD_RT_LV && + !strcmp(r->name, act->lv_uuid)) + return r; + } + + if (nocreate) + return NULL; + + if (!(r = alloc_resource())) + return NULL; + + r->type = act->rt; + r->mode = LD_LK_UN; + + if (r->type == LD_RT_GL) { + strncpy(r->name, R_NAME_GL, MAX_NAME); + r->use_vb = 1; + } else if (r->type == LD_RT_VG) { + strncpy(r->name, R_NAME_VG, MAX_NAME); + r->use_vb = 1; + } else if (r->type == LD_RT_LV) { + strncpy(r->name, act->lv_uuid, MAX_NAME); + r->use_vb = 0; + } + + list_add_tail(&r->list, &ls->resources); + + return r; +} + +static void free_ls_resources(struct lockspace *ls) +{ + struct resource *r, *r_safe; + + list_for_each_entry_safe(r, r_safe, &ls->resources, list) { + lm_rem_resource(ls, r); + list_del(&r->list); + free_resource(r); + } +} + +/* + * ls is the vg being removed that holds the global lock. + * check if any other vgs will be left without a global lock. + */ + +static int other_sanlock_vgs_exist(struct lockspace *ls_rem) +{ + struct lockspace *ls; + + list_for_each_entry(ls, &lockspaces, list) { + if (ls->lm_type != LD_LM_SANLOCK) + continue; + if (!strcmp(ls->name, ls_rem->name)) + continue; + log_debug("other sanlock vg exists %s", ls->name); + return 1; + } + + return 0; +} + +/* + * LOCK is the main thing we're interested in; the others are unlikely. + */ + +static int process_op_during_kill(struct action *act) +{ + if (act->op == LD_OP_LOCK && act->mode == LD_LK_UN) + return 1; + + switch (act->op) { + case LD_OP_LOCK: + case LD_OP_ENABLE: + case LD_OP_DISABLE: + case LD_OP_UPDATE: + case LD_OP_RENAME_BEFORE: + case LD_OP_RENAME_FINAL: + case LD_OP_FIND_FREE_LOCK: + return 0; + }; + return 1; +} + +/* + * Process actions queued for this lockspace by + * client_recv_action / add_lock_action. + * + * The lockspace_thread can touch its own ls struct without holding + * lockspaces_mutex until it sets ls->thread_done, after which it + * cannot touch ls without holding lockspaces_mutex. + */ + +#define LOCK_RETRY_MS 1000 /* milliseconds to delay between retry */ + +static void *lockspace_thread_main(void *arg_in) +{ + struct lockspace *ls = arg_in; + struct resource *r, *r2; + struct action *add_act, *act, *safe; + struct action *act_op_free = NULL; + struct list_head tmp_act; + struct list_head act_close; + char tmp_name[MAX_NAME+1]; + int free_vg = 0; + int drop_vg = 0; + int error = 0; + int adopt_flag = 0; + int wait_flag = 0; + int retry; + int rv; + + INIT_LIST_HEAD(&act_close); + + /* first action may be client add */ + pthread_mutex_lock(&ls->mutex); + act = NULL; + add_act = NULL; + if (!list_empty(&ls->actions)) { + act = list_first_entry(&ls->actions, struct action, list); + if (act->op == LD_OP_START) { + add_act = act; + list_del(&add_act->list); + + if (add_act->flags & LD_AF_WAIT) + wait_flag = 1; + if (add_act->flags & LD_AF_ADOPT) + adopt_flag = 1; + } + } + pthread_mutex_unlock(&ls->mutex); + + log_debug("S %s lm_add_lockspace %s wait %d adopt %d", + ls->name, lm_str(ls->lm_type), wait_flag, adopt_flag); + + /* + * The prepare step does not wait for anything and is quick; + * it tells us if the parameters are valid and the lm is running. + */ + error = lm_prepare_lockspace(ls, add_act); + + if (add_act && (!wait_flag || error)) { + /* send initial join result back to client */ + add_act->result = error; + add_client_result(add_act); + add_act = NULL; + } + + /* + * The actual lockspace join can take a while. + */ + if (!error) { + error = lm_add_lockspace(ls, add_act, adopt_flag); + + log_debug("S %s lm_add_lockspace done %d", ls->name, error); + + if (ls->sanlock_gl_enabled && gl_lsname_sanlock[0] && + strcmp(ls->name, gl_lsname_sanlock)) + sanlock_gl_dup = 1; + + if (add_act) { + /* send final join result back to client */ + add_act->result = error; + add_client_result(add_act); + } + } + + pthread_mutex_lock(&ls->mutex); + if (error) { + ls->thread_stop = 1; + ls->create_fail = 1; + } else { + ls->create_done = 1; + } + pthread_mutex_unlock(&ls->mutex); + + if (error) + goto out_act; + + while (1) { + pthread_mutex_lock(&ls->mutex); + while (!ls->thread_work) { + if (ls->thread_stop) { + pthread_mutex_unlock(&ls->mutex); + goto out_rem; + } + pthread_cond_wait(&ls->cond, &ls->mutex); + } + + /* + * Process all the actions queued for this lockspace. + * The client thread queues actions on ls->actions. + * + * Here, take all the actions off of ls->actions, and: + * + * - For lock operations, move the act to r->actions. + * These lock actions/operations processed by res_process(). + * + * - For non-lock operations, e.g. related to managing + * the lockspace, process them in this loop. + */ + + while (1) { + if (list_empty(&ls->actions)) { + ls->thread_work = 0; + break; + } + + act = list_first_entry(&ls->actions, struct action, list); + + if (act->op == LD_OP_KILL_VG && act->rt == LD_RT_VG) { + /* Continue processing until DROP_VG arrives. */ + log_debug("S %s kill_vg", ls->name); + ls->kill_vg = 1; + list_del(&act->list); + act->result = 0; + add_client_result(act); + continue; + } + + if (ls->kill_vg && !process_op_during_kill(act)) { + log_debug("S %s disallow op %s after kill_vg", ls->name, op_str(act->op)); + list_del(&act->list); + act->result = -EVGKILLED; + add_client_result(act); + continue; + } + + if (act->op == LD_OP_DROP_VG && act->rt == LD_RT_VG) { + /* + * If leases are released after i/o errors begin + * but before lvmlockctl --kill, then the VG is not + * killed, but drop is still needed to clean up the + * VG, so in that case there would be a drop op without + * a preceding kill op. + */ + if (!ls->kill_vg) + log_debug("S %s received drop without kill", ls->name); + log_debug("S %s drop_vg", ls->name); + ls->thread_work = 0; + ls->thread_stop = 1; + drop_vg = 1; + break; + } + + if (act->op == LD_OP_STOP) { + /* thread_stop is already set */ + ls->thread_work = 0; + break; + } + + if (act->op == LD_OP_FREE && act->rt == LD_RT_VG) { + /* vgremove */ + log_debug("S %s checking for lockspace hosts", ls->name); + rv = lm_hosts(ls, 1); + if (rv) { + /* + * Checking for hosts here in addition to after the + * main loop allows vgremove to fail and be rerun + * after the ls is stopped on other hosts. + */ + log_error("S %s lockspace hosts %d", ls->name, rv); + list_del(&act->list); + act->result = -EBUSY; + add_client_result(act); + continue; + } + ls->thread_work = 0; + ls->thread_stop = 1; + free_vg = 1; + break; + } + + if (act->op == LD_OP_BUSY && act->rt == LD_RT_VG) { + log_debug("S %s checking if lockspace is busy", ls->name); + rv = lm_hosts(ls, 0); + if (rv) + act->result = -EBUSY; + else + act->result = 0; + list_del(&act->list); + add_client_result(act); + continue; + } + + if (act->op == LD_OP_RENAME_BEFORE && act->rt == LD_RT_VG) { + /* vgrename */ + log_debug("S %s checking for lockspace hosts", ls->name); + rv = lm_hosts(ls, 1); + if (rv) { + log_error("S %s lockspace hosts %d", ls->name, rv); + list_del(&act->list); + act->result = -EBUSY; + add_client_result(act); + continue; + } + ls->thread_work = 0; + ls->thread_stop = 1; + /* Do we want to check hosts again below like vgremove? */ + break; + } + + if (act->op == LD_OP_FIND_FREE_LOCK && act->rt == LD_RT_VG) { + uint64_t free_offset = 0; + log_debug("S %s find free lock", ls->name); + rv = lm_find_free_lock(ls, &free_offset); + log_debug("S %s find free lock %d offset %llu", + ls->name, rv, (unsigned long long)free_offset); + ls->free_lock_offset = free_offset; + list_del(&act->list); + act->result = rv; + add_client_result(act); + continue; + } + + list_del(&act->list); + + /* applies to all resources */ + if (act->op == LD_OP_CLOSE) { + list_add(&act->list, &act_close); + continue; + } + + /* + * All the other op's are for locking. + * Find the specific resource that the lock op is for, + * and add the act to the resource's list of lock ops. + * + * (This creates a new resource if the one named in + * the act is not found.) + */ + + r = find_resource_act(ls, act, (act->op == LD_OP_FREE) ? 1 : 0); + if (!r) { + act->result = (act->op == LD_OP_FREE) ? -ENOENT : -ENOMEM; + add_client_result(act); + continue; + } + + list_add_tail(&act->list, &r->actions); + + log_debug("S %s R %s action %s %s", ls->name, r->name, + op_str(act->op), mode_str(act->mode)); + } + pthread_mutex_unlock(&ls->mutex); + + /* + * Process the lock operations that have been queued for each + * resource. + */ + + retry = 0; + + list_for_each_entry_safe(r, r2, &ls->resources, list) + res_process(ls, r, &act_close, &retry); + + list_for_each_entry_safe(act, safe, &act_close, list) { + list_del(&act->list); + free_action(act); + } + + if (retry) { + ls->thread_work = 1; + usleep(LOCK_RETRY_MS * 1000); + } + } + +out_rem: + log_debug("S %s stopping", ls->name); + + /* + * For sanlock, we need to unlock any existing locks + * before removing the lockspace, otherwise the sanlock + * daemon will kill us when the lockspace goes away. + * For dlm, we leave with force, so all locks will + * automatically be dropped when we leave the lockspace, + * so unlocking all before leaving could be skipped. + * + * Blindly dropping all existing locks must only be + * allowed in emergency/force situations, otherwise it's + * obviously dangerous, since the lock holders are still + * operating under the assumption that they hold the lock. + * drop_vg drops all existing locks, but should only + * happen when the VG access has been forcibly and + * succesfully terminated. + * + * For vgremove of a sanlock vg, the vg lock will be held, + * and possibly the gl lock if this vg holds the gl. + * sanlock vgremove wants to unlock-rename these locks. + */ + + log_debug("S %s clearing locks", ls->name); + + rv = clear_locks(ls, free_vg, drop_vg); + + /* + * Tell any other hosts in the lockspace to leave it + * before we remove it (for vgremove). We do this + * before leaving the lockspace ourself because we + * need to be in the lockspace to see others. + */ + + if (free_vg) { + log_debug("S %s checking for lockspace hosts", ls->name); + rv = lm_hosts(ls, 1); + if (rv) + log_error("S %s other lockspace hosts %d", ls->name, rv); + } + + /* + * Leave the lockspace. + */ + + rv = lm_rem_lockspace(ls, NULL, free_vg); + + log_debug("S %s rem_lockspace done %d", ls->name, rv); + +out_act: + /* + * Move remaining actions to results; this will usually (always?) + * be only the stop action. + */ + INIT_LIST_HEAD(&tmp_act); + + pthread_mutex_lock(&ls->mutex); + list_for_each_entry_safe(act, safe, &ls->actions, list) { + if (act->op == LD_OP_FREE) { + act_op_free = act; + act->result = 0; + } else if (act->op == LD_OP_STOP) + act->result = 0; + else if (act->op == LD_OP_DROP_VG) + act->result = 0; + else if (act->op == LD_OP_RENAME_BEFORE) + act->result = 0; + else + act->result = -ENOLS; + list_del(&act->list); + list_add_tail(&act->list, &tmp_act); + } + pthread_mutex_unlock(&ls->mutex); + + /* + * If this freed a sanlock vg that had gl enabled, and other sanlock + * vgs exist, return a flag so the command can warn that the gl has + * been removed and may need to be enabled in another sanlock vg. + */ + + if (free_vg && ls->sanlock_gl_enabled && act_op_free) { + pthread_mutex_lock(&lockspaces_mutex); + if (other_sanlock_vgs_exist(ls)) { + act_op_free->flags |= LD_AF_WARN_GL_REMOVED; + gl_vg_removed = 1; + } + pthread_mutex_unlock(&lockspaces_mutex); + } + + pthread_mutex_lock(&client_mutex); + list_for_each_entry_safe(act, safe, &tmp_act, list) { + list_del(&act->list); + list_add_tail(&act->list, &client_results); + } + pthread_cond_signal(&client_cond); + pthread_mutex_unlock(&client_mutex); + + pthread_mutex_lock(&lockspaces_mutex); + ls->thread_done = 1; + ls->free_vg = free_vg; + ls->drop_vg = drop_vg; + if (ls->lm_type == LD_LM_DLM && !strcmp(ls->name, gl_lsname_dlm)) + global_dlm_lockspace_exists = 0; + /* Avoid a name collision of the same lockspace is added again before this thread is cleaned up. */ + memset(tmp_name, 0, sizeof(tmp_name)); + snprintf(tmp_name, MAX_NAME, "REM:%s", ls->name); + memcpy(ls->name, tmp_name, MAX_NAME); + pthread_mutex_unlock(&lockspaces_mutex); + + /* worker_thread will join this thread, and free the ls */ + pthread_mutex_lock(&worker_mutex); + worker_wake = 1; + pthread_cond_signal(&worker_cond); + pthread_mutex_unlock(&worker_mutex); + + return NULL; +} + +int lockspaces_empty(void) +{ + int rv; + pthread_mutex_lock(&lockspaces_mutex); + rv = list_empty(&lockspaces); + pthread_mutex_unlock(&lockspaces_mutex); + return rv; +} + +/* + * lockspaces_mutex is locked + * + * When duplicate sanlock global locks have been seen, + * this function has a secondary job of counting the + * number of lockspaces that exist with the gl enabled, + * with the side effect of setting sanlock_gl_dup back to + * zero when the duplicates have been removed/disabled. + */ + +static struct lockspace *find_lockspace_name(char *ls_name) +{ + struct lockspace *ls_found = NULL; + struct lockspace *ls; + int gl_count = 0; + + list_for_each_entry(ls, &lockspaces, list) { + if (!strcmp(ls->name, ls_name)) + ls_found = ls; + + if (!sanlock_gl_dup && ls_found) + return ls_found; + + if (sanlock_gl_dup && ls->sanlock_gl_enabled) + gl_count++; + } + + /* this is the side effect we want from this function */ + if (sanlock_gl_dup && gl_count < 2) + sanlock_gl_dup = 0; + + return ls_found; +} + +/* + * If lvm_<vg_name> is longer than max lockspace name (64) we just ignore the + * extra characters. For sanlock vgs, the name is shortened further to 48 in + * the sanlock code. + */ + +static int vg_ls_name(const char *vg_name, char *ls_name) +{ + if (strlen(vg_name) + 4 > MAX_NAME) { + log_error("vg name too long %s", vg_name); + return -1; + } + + snprintf(ls_name, MAX_NAME, "%s%s", LVM_LS_PREFIX, vg_name); + return 0; +} + +/* FIXME: add mutex for gl_lsname_ ? */ + +static void gl_ls_name(char *ls_name) +{ + if (gl_use_dlm) + memcpy(ls_name, gl_lsname_dlm, MAX_NAME); + else if (gl_use_sanlock) + memcpy(ls_name, gl_lsname_sanlock, MAX_NAME); + else + memset(ls_name, 0, MAX_NAME); +} + +/* + * When this function returns an error, the caller needs to deal + * with act (in the cases where act exists). + */ + +static int add_lockspace_thread(const char *ls_name, + const char *vg_name, + const char *vg_uuid, + int lm_type, const char *vg_args, + struct action *act) +{ + struct lockspace *ls, *ls2; + struct resource *r; + int rv; + + log_debug("add_lockspace_thread %s %s version %u", + lm_str(lm_type), ls_name, act ? act->version : 0); + + if (!(ls = alloc_lockspace())) + return -ENOMEM; + + strncpy(ls->name, ls_name, MAX_NAME); + ls->lm_type = lm_type; + + if (act) + ls->start_client_id = act->client_id; + + if (vg_uuid) + strncpy(ls->vg_uuid, vg_uuid, 64); + + if (vg_name) + strncpy(ls->vg_name, vg_name, MAX_NAME); + + if (vg_args) + strncpy(ls->vg_args, vg_args, MAX_ARGS); + + if (act) + ls->host_id = act->host_id; + + if (!(r = alloc_resource())) { + free(ls); + return -ENOMEM; + } + + r->type = LD_RT_VG; + r->mode = LD_LK_UN; + r->use_vb = 1; + strncpy(r->name, R_NAME_VG, MAX_NAME); + list_add_tail(&r->list, &ls->resources); + + pthread_mutex_lock(&lockspaces_mutex); + ls2 = find_lockspace_name(ls->name); + if (ls2) { + if (ls2->thread_stop) { + log_debug("add_lockspace_thread %s exists and stopping", ls->name); + rv = -EAGAIN; + } else { + log_debug("add_lockspace_thread %s exists", ls->name); + rv = -EEXIST; + } + pthread_mutex_unlock(&lockspaces_mutex); + free_resource(r); + free(ls); + return rv; + } + + /* + * act will be null when this lockspace is added automatically/internally + * and not by an explicit client action that wants a result. + */ + if (act) + list_add(&act->list, &ls->actions); + + if (ls->lm_type == LD_LM_DLM && !strcmp(ls->name, gl_lsname_dlm)) + global_dlm_lockspace_exists = 1; + list_add_tail(&ls->list, &lockspaces); + pthread_mutex_unlock(&lockspaces_mutex); + + rv = pthread_create(&ls->thread, NULL, lockspace_thread_main, ls); + if (rv < 0) { + log_error("add_lockspace_thread %s pthread error %d %d", ls->name, rv, errno); + pthread_mutex_lock(&lockspaces_mutex); + list_del(&ls->list); + pthread_mutex_unlock(&lockspaces_mutex); + free_resource(r); + free(ls); + return rv; + } + + return 0; +} + +/* + * There is no add_sanlock_global_lockspace or + * rem_sanlock_global_lockspace because with sanlock, + * the global lockspace is one of the vg lockspaces. + */ + +static int add_dlm_global_lockspace(struct action *act) +{ + int rv; + + if (global_dlm_lockspace_exists) + return 0; + + /* + * FIXME: if the dlm global lockspace is started without a global + * lock request, insert an internal gl sh lock request? + */ + + rv = add_lockspace_thread(gl_lsname_dlm, NULL, NULL, LD_LM_DLM, NULL, act); + if (rv < 0) + log_debug("add_dlm_global_lockspace add_lockspace_thread %d", rv); + + /* + * EAGAIN may be returned for a short period because + * global_dlm_lockspace_exists is set to 0 before the + * ls is removed from the lockspaces list by the + * worker_thread. + */ + + return rv; +} + +/* + * If dlm gl lockspace is the only one left, then stop it. + * This is not used for an explicit rem_lockspace action from + * the client, only for auto remove. + */ + +static int rem_dlm_global_lockspace(void) +{ + struct lockspace *ls, *ls_gl = NULL; + int others = 0; + int rv = 0; + + pthread_mutex_lock(&lockspaces_mutex); + list_for_each_entry(ls, &lockspaces, list) { + if (!strcmp(ls->name, gl_lsname_dlm)) { + ls_gl = ls; + continue; + } + if (ls->thread_stop) + continue; + others++; + break; + } + + if (others) { + rv = -EAGAIN; + goto out; + } + + if (!ls_gl) { + rv = -ENOENT; + goto out; + } + + ls = ls_gl; + pthread_mutex_lock(&ls->mutex); + ls->thread_stop = 1; + ls->thread_work = 1; + pthread_cond_signal(&ls->cond); + pthread_mutex_unlock(&ls->mutex); + rv = 0; +out: + pthread_mutex_unlock(&lockspaces_mutex); + return rv; +} + +/* + * When the first dlm lockspace is added for a vg, automatically add a separate + * dlm lockspace for the global lock. + * + * For sanlock, a separate lockspace is not used for the global lock, but the + * gl lock lives in a vg lockspace, (although it's recommended to create a + * special vg dedicated to holding the gl). + */ + +static int add_lockspace(struct action *act) +{ + char ls_name[MAX_NAME+1]; + int rv; + + memset(ls_name, 0, sizeof(ls_name)); + + /* + * FIXME: I don't think this is used any more. + * Remove it, or add the ability to start the global + * dlm lockspace using lvmlockctl? + */ + if (act->rt == LD_RT_GL) { + if (gl_use_dlm) { + rv = add_dlm_global_lockspace(act); + return rv; + } else { + return -EINVAL; + } + } + + if (act->rt == LD_RT_VG) { + if (gl_use_dlm) + add_dlm_global_lockspace(NULL); + + vg_ls_name(act->vg_name, ls_name); + + rv = add_lockspace_thread(ls_name, act->vg_name, act->vg_uuid, + act->lm_type, act->vg_args, + act); + if (rv) + log_debug("add_lockspace %s add_lockspace_thread %d", ls_name, rv); + return rv; + } + + log_error("add_lockspace bad type %d", act->rt); + return -1; +} + +/* + * vgchange --lock-stop vgname will lock the vg ex, then send a stop, + * so we exect to find the ex vg lock held here, and will automatically + * unlock it when stopping. + * + * Should we attempt to stop the lockspace containing the gl last? + */ + +static int rem_lockspace(struct action *act) +{ + struct lockspace *ls; + char ls_name[MAX_NAME+1]; + int force = act->flags & LD_AF_FORCE; + int rt = act->rt; + + if (act->rt == LD_RT_GL && act->lm_type != LD_LM_DLM) + return -EINVAL; + + memset(ls_name, 0, sizeof(ls_name)); + + if (act->rt == LD_RT_GL) + gl_ls_name(ls_name); + else + vg_ls_name(act->vg_name, ls_name); + + pthread_mutex_lock(&lockspaces_mutex); + ls = find_lockspace_name(ls_name); + if (!ls) { + pthread_mutex_unlock(&lockspaces_mutex); + return -ENOLS; + } + + pthread_mutex_lock(&ls->mutex); + if (ls->thread_stop) { + pthread_mutex_unlock(&ls->mutex); + pthread_mutex_unlock(&lockspaces_mutex); + return -ESTALE; + } + + if (!force && for_each_lock(ls, LOCKS_EXIST_LV)) { + pthread_mutex_unlock(&ls->mutex); + pthread_mutex_unlock(&lockspaces_mutex); + return -EBUSY; + } + ls->thread_work = 1; + ls->thread_stop = 1; + list_add_tail(&act->list, &ls->actions); + pthread_cond_signal(&ls->cond); + pthread_mutex_unlock(&ls->mutex); + pthread_mutex_unlock(&lockspaces_mutex); + + /* + * The dlm global lockspace was automatically added when + * the first dlm vg lockspace was added, now reverse that + * by automatically removing the dlm global lockspace when + * the last dlm vg lockspace is removed. + */ + + if (rt == LD_RT_VG && gl_use_dlm) + rem_dlm_global_lockspace(); + + return 0; +} + +/* + * count how many lockspaces started by this client are still starting; + * the client will use this to wait for all its start operations to finish + * (START_WAIT). + */ + +static int count_lockspace_starting(uint32_t client_id) +{ + struct lockspace *ls; + int count = 0; + int done = 0; + int fail = 0; + + pthread_mutex_lock(&lockspaces_mutex); + list_for_each_entry(ls, &lockspaces, list) { + if (ls->start_client_id != client_id) + continue; + + if (!ls->create_done && !ls->create_fail) { + count++; + continue; + } + + if (ls->create_done) + done++; + if (ls->create_fail) + fail++; + } + pthread_mutex_unlock(&lockspaces_mutex); + + log_debug("count_lockspace_starting client %u count %d done %d fail %d", + client_id, count, done, fail); + + return count; +} + +/* + * Loop through all lockspaces, and: + * - if do_stop is set, stop any that are not stopped + * - if do_free is set, join any that are done stopping (and free ls) + * + * do_stop will not stop an ls with lv locks unless force is set. + * + * This function does not block or wait for anything. + * + * do_stop (no do_free): + * returns count of lockspaces that need stop (have locks and no force) + * + * do_free (no do_stop): + * returns count of lockspaces that are stopped and need freeing + * + * do_stop and do_free: + * returns sum of the previous two + */ + +static int for_each_lockspace(int do_stop, int do_free, int do_force) +{ + struct lockspace *ls, *safe; + int need_stop = 0; + int need_free = 0; + int stop_count = 0; + int free_count = 0; + int done; + int stop; + int perrno; + + pthread_mutex_lock(&lockspaces_mutex); + + if (do_stop) { + list_for_each_entry(ls, &lockspaces, list) { + + pthread_mutex_lock(&ls->mutex); + if (ls->thread_stop) { + pthread_mutex_unlock(&ls->mutex); + continue; + } + + if (!do_force && for_each_lock(ls, LOCKS_EXIST_ANY)) { + need_stop++; + } else { + ls->thread_work = 1; + ls->thread_stop = 1; + pthread_cond_signal(&ls->cond); + stop_count++; + } + pthread_mutex_unlock(&ls->mutex); + } + } + + if (do_free) { + list_for_each_entry_safe(ls, safe, &lockspaces, list) { + + pthread_mutex_lock(&ls->mutex); + done = ls->thread_done; + stop = ls->thread_stop; + pthread_mutex_unlock(&ls->mutex); + + /* This ls has locks and force is not set. */ + if (!stop) + continue; + + /* + * Once thread_done is set, we know that the lockspace_thread + * will not be using/touching the ls struct. Any other + * thread touches the ls struct under lockspaces_mutex. + */ + if (done) { + if ((perrno = pthread_join(ls->thread, NULL))) + log_error("pthread_join error %d", perrno); + + list_del(&ls->list); + + /* FIXME: will free_vg ever not be set? */ + + log_debug("free ls %s", ls->name); + + if (ls->free_vg) { + /* In future we may need to free ls->actions here */ + free_ls_resources(ls); + free(ls); + free_count++; + } + } else { + need_free++; + } + } + } + + if (list_empty(&lockspaces)) { + if (!gl_type_static) { + gl_use_dlm = 0; + gl_use_sanlock = 0; + } + } + pthread_mutex_unlock(&lockspaces_mutex); + + if (stop_count || free_count || need_stop || need_free) { + log_debug("for_each_lockspace do_stop %d do_free %d " + "stop_count %d free_count %d need_stop %d need_free %d", + do_stop, do_free, stop_count, free_count, need_stop, need_free); + } + + return need_stop + need_free; +} + +/* + * This is only called when the daemon is exiting so the sleep/retry + * loop doesn't have any adverse impact. + */ + +static void for_each_lockspace_retry(int do_stop, int do_free, int do_force) +{ + int count; + + while (1) { + count = for_each_lockspace(do_stop, do_free, do_force); + if (!count) + break; + + log_debug("for_each_lockspace_retry remaining %d", count); + sleep(1); + } +} + +static int work_init_vg(struct action *act) +{ + struct lockspace *ls; + char ls_name[MAX_NAME+1]; + int rv = 0; + + memset(ls_name, 0, sizeof(ls_name)); + + vg_ls_name(act->vg_name, ls_name); + + /* + * The max dlm ls name is 64 and the max sanlock ls name is 48. So, + * after the "lvm_" prefix, only the first 60/44 characters of the VG + * name are used for the lockspace name. This will cause a collision + * in the lock manager if two different VG names have the first 60/44 + * chars in common. At the time of vgcreate (here), check if any other + * VG's are known that would collide. If the collision is not detected + * at vgcreate time, it will be detected at start time and add_lockspace + * will fail for the second of the two matching ls names. + */ + pthread_mutex_lock(&lockspaces_mutex); + list_for_each_entry(ls, &lockspaces, list) { + if ((ls->lm_type == LD_LM_SANLOCK) && !strncmp(ls->name, ls_name, 48)) { + rv = -EEXIST; + break; + } + if ((ls->lm_type == LD_LM_DLM) && !strcmp(ls->name, ls_name)) { + rv = -EEXIST; + break; + } + } + pthread_mutex_unlock(&lockspaces_mutex); + + if (rv == -EEXIST) { + log_error("Existing lockspace name %s matches new %s VG names %s %s", + ls->name, ls_name, ls->vg_name, act->vg_name); + return rv; + } + + if (act->lm_type == LD_LM_SANLOCK) + rv = lm_init_vg_sanlock(ls_name, act->vg_name, act->flags, act->vg_args); + else if (act->lm_type == LD_LM_DLM) + rv = lm_init_vg_dlm(ls_name, act->vg_name, act->flags, act->vg_args); + else + rv = -EINVAL; + + return rv; +} + +static int work_rename_vg(struct action *act) +{ + char ls_name[MAX_NAME+1]; + int rv = 0; + + memset(ls_name, 0, sizeof(ls_name)); + + vg_ls_name(act->vg_name, ls_name); + + if (act->lm_type == LD_LM_SANLOCK) + rv = lm_rename_vg_sanlock(ls_name, act->vg_name, act->flags, act->vg_args); + else if (act->lm_type == LD_LM_DLM) + return 0; + else + rv = -EINVAL; + + return rv; +} + +static void work_test_gl(void) +{ + struct lockspace *ls; + int is_enabled = 0; + + pthread_mutex_lock(&lockspaces_mutex); + list_for_each_entry(ls, &lockspaces, list) { + if (ls->lm_type != LD_LM_SANLOCK) + continue; + + pthread_mutex_lock(&ls->mutex); + if (ls->create_done && !ls->thread_stop) { + is_enabled = lm_gl_is_enabled(ls); + if (is_enabled) { + log_debug("S %s worker found gl_is_enabled", ls->name); + strncpy(gl_lsname_sanlock, ls->name, MAX_NAME); + } + } + pthread_mutex_unlock(&ls->mutex); + + if (is_enabled) + break; + } + + if (!is_enabled) + log_debug("worker found no gl_is_enabled"); + pthread_mutex_unlock(&lockspaces_mutex); +} + +static int work_init_lv(struct action *act) +{ + struct lockspace *ls; + char ls_name[MAX_NAME+1]; + char vg_args[MAX_ARGS+1]; + char lv_args[MAX_ARGS+1]; + uint64_t free_offset = 0; + int lm_type = 0; + int rv = 0; + + memset(ls_name, 0, sizeof(ls_name)); + memset(vg_args, 0, sizeof(vg_args)); + memset(lv_args, 0, sizeof(lv_args)); + + vg_ls_name(act->vg_name, ls_name); + + pthread_mutex_lock(&lockspaces_mutex); + ls = find_lockspace_name(ls_name); + if (ls) { + lm_type = ls->lm_type; + memcpy(vg_args, ls->vg_args, MAX_ARGS); + free_offset = ls->free_lock_offset; + ls->free_lock_offset = 0; + } + pthread_mutex_unlock(&lockspaces_mutex); + + if (!ls) { + lm_type = act->lm_type; + memcpy(vg_args, act->vg_args, MAX_ARGS); + } + + if (act->lm_type != lm_type) { + log_error("init_lv ls_name %s wrong lm_type %d %d", + ls_name, act->lm_type, lm_type); + return -EINVAL; + } + + if (lm_type == LD_LM_SANLOCK) { + rv = lm_init_lv_sanlock(ls_name, act->vg_name, act->lv_uuid, + vg_args, lv_args, free_offset); + + memcpy(act->lv_args, lv_args, MAX_ARGS); + return rv; + + } else if (act->lm_type == LD_LM_DLM) { + return 0; + } else { + log_error("init_lv ls_name %s bad lm_type %d", ls_name, act->lm_type); + return -EINVAL; + } +} + +/* + * When an action is queued for the worker_thread, it is processed right away. + * After processing, some actions need to be retried again in a short while. + * These actions are put on the delayed_list, and the worker_thread will + * process these delayed actions again in SHORT_DELAY_PERIOD. + */ + +#define SHORT_DELAY_PERIOD 2 +#define LONG_DELAY_PERIOD 60 + +static void *worker_thread_main(void *arg_in) +{ + struct list_head delayed_list; + struct timespec ts; + struct action *act, *safe; + uint64_t last_delayed_time = 0; + int delay_sec = LONG_DELAY_PERIOD; + int rv; + + INIT_LIST_HEAD(&delayed_list); + + while (1) { + pthread_mutex_lock(&worker_mutex); + if (clock_gettime(CLOCK_REALTIME, &ts)) { + log_error("clock_gettime failed."); + ts.tv_sec = ts.tv_nsec = 0; + } + ts.tv_sec += delay_sec; + rv = 0; + act = NULL; + + while (list_empty(&worker_list) && !worker_stop && !worker_wake && !rv) { + rv = pthread_cond_timedwait(&worker_cond, &worker_mutex, &ts); + } + worker_wake = 0; + + if (worker_stop) { + pthread_mutex_unlock(&worker_mutex); + goto out; + } + + if (!list_empty(&worker_list)) { + act = list_first_entry(&worker_list, struct action, list); + list_del(&act->list); + } + pthread_mutex_unlock(&worker_mutex); + + /* + * Do new work actions before processing delayed work actions. + */ + + if (!act) + goto delayed_work; + + if (act->op == LD_OP_RUNNING_LM) { + int run_sanlock = lm_is_running_sanlock(); + int run_dlm = lm_is_running_dlm(); + + if (daemon_test) { + run_sanlock = gl_use_sanlock; + run_dlm = gl_use_dlm; + } + + if (run_sanlock && run_dlm) + act->result = -EXFULL; + else if (!run_sanlock && !run_dlm) + act->result = -ENOLCK; + else if (run_sanlock) + act->result = LD_LM_SANLOCK; + else if (run_dlm) + act->result = LD_LM_DLM; + add_client_result(act); + + } else if ((act->op == LD_OP_LOCK) && (act->flags & LD_AF_SEARCH_LS)) { + /* + * worker_thread used as a helper to search existing + * sanlock vgs for an enabled gl. + */ + log_debug("work search for gl"); + work_test_gl(); + + /* try again to find a gl lockspace for this act */ + rv = add_lock_action(act); + if (rv < 0) { + act->result = rv; + add_client_result(act); + } + + } else if ((act->op == LD_OP_INIT) && (act->rt == LD_RT_VG)) { + log_debug("work init_vg %s", act->vg_name); + act->result = work_init_vg(act); + add_client_result(act); + + } else if ((act->op == LD_OP_INIT) && (act->rt == LD_RT_LV)) { + log_debug("work init_lv %s/%s uuid %s", act->vg_name, act->lv_name, act->lv_uuid); + act->result = work_init_lv(act); + add_client_result(act); + + } else if ((act->op == LD_OP_RENAME_FINAL) && (act->rt == LD_RT_VG)) { + log_debug("work rename_vg %s", act->vg_name); + act->result = work_rename_vg(act); + add_client_result(act); + + } else if (act->op == LD_OP_START_WAIT) { + act->result = count_lockspace_starting(act->client_id); + if (!act->result) + add_client_result(act); + else + list_add(&act->list, &delayed_list); + + } else if (act->op == LD_OP_STOP_ALL) { + act->result = for_each_lockspace(DO_STOP, DO_FREE, (act->flags & LD_AF_FORCE) ? DO_FORCE : NO_FORCE); + if (!act->result || !(act->flags & LD_AF_WAIT)) + add_client_result(act); + else + list_add(&act->list, &delayed_list); + + } else { + log_error("work unknown op %d", act->op); + act->result = -EINVAL; + add_client_result(act); + } + + delayed_work: + /* + * We may want to track retry times per action so that + * we can delay different actions by different amounts. + */ + + if (monotime() - last_delayed_time < SHORT_DELAY_PERIOD) { + delay_sec = 1; + continue; + } + last_delayed_time = monotime(); + + list_for_each_entry_safe(act, safe, &delayed_list, list) { + if (act->op == LD_OP_START_WAIT) { + log_debug("work delayed start_wait for client %u", act->client_id); + act->result = count_lockspace_starting(act->client_id); + if (!act->result) { + list_del(&act->list); + add_client_result(act); + } + + } else if (act->op == LD_OP_STOP_ALL) { + log_debug("work delayed stop_all"); + act->result = for_each_lockspace(DO_STOP, DO_FREE, (act->flags & LD_AF_FORCE) ? DO_FORCE : NO_FORCE); + if (!act->result) { + list_del(&act->list); + act->result = 0; + add_client_result(act); + } + } + } + + /* + * This is not explicitly queued work, and not delayed work, + * but lockspace thread cleanup that's needed when a + * lockspace has been stopped/removed or failed to start. + */ + + for_each_lockspace(NO_STOP, DO_FREE, NO_FORCE); + + if (list_empty(&delayed_list)) + delay_sec = LONG_DELAY_PERIOD; + else + delay_sec = 1; + } +out: + list_for_each_entry_safe(act, safe, &delayed_list, list) { + list_del(&act->list); + free_action(act); + } + + pthread_mutex_lock(&worker_mutex); + list_for_each_entry_safe(act, safe, &worker_list, list) { + list_del(&act->list); + free_action(act); + } + pthread_mutex_unlock(&worker_mutex); + return NULL; +} + +static int setup_worker_thread(void) +{ + int rv; + + INIT_LIST_HEAD(&worker_list); + + pthread_mutex_init(&worker_mutex, NULL); + pthread_cond_init(&worker_cond, NULL); + + rv = pthread_create(&worker_thread, NULL, worker_thread_main, NULL); + if (rv) + return -1; + return 0; +} + +static void close_worker_thread(void) +{ + pthread_mutex_lock(&worker_mutex); + worker_stop = 1; + pthread_cond_signal(&worker_cond); + pthread_mutex_unlock(&worker_mutex); + pthread_join(worker_thread, NULL); +} + +/* client_mutex is locked */ +static struct client *find_client_work(void) +{ + struct client *cl; + + list_for_each_entry(cl, &client_list, list) { + if (cl->recv || cl->dead) + return cl; + } + return NULL; +} + +/* client_mutex is locked */ +static struct client *find_client_id(uint32_t id) +{ + struct client *cl; + + list_for_each_entry(cl, &client_list, list) { + if (cl->id == id) + return cl; + } + return NULL; +} + +/* client_mutex is locked */ +static struct client *find_client_pi(int pi) +{ + struct client *cl; + + list_for_each_entry(cl, &client_list, list) { + if (cl->pi == pi) + return cl; + } + return NULL; +} + +/* + * wake up poll() because we have added an fd + * back into pollfd and poll() needs to be restarted + * to recognize it. + */ +static void restart_poll(void) +{ + int rv; + rv = write(restart_fds[1], "w", 1); + if (!rv || rv < 0) + log_debug("restart_poll write %d", errno); +} + +/* poll will take requests from client again, cl->mutex must be held */ +static void client_resume(struct client *cl) +{ + if (cl->dead) + return; + + if (!cl->poll_ignore || cl->fd == -1 || cl->pi == -1) { + /* shouldn't happen */ + log_error("client_resume %u bad state ig %d fd %d pi %d", + cl->id, cl->poll_ignore, cl->fd, cl->pi); + return; + } + + pthread_mutex_lock(&pollfd_mutex); + if (pollfd[cl->pi].fd != POLL_FD_IGNORE) { + log_error("client_resume %u pi %d fd %d not IGNORE", + cl->id, cl->pi, cl->fd); + } + pollfd[cl->pi].fd = cl->fd; + pollfd[cl->pi].events = POLLIN; + pthread_mutex_unlock(&pollfd_mutex); + + restart_poll(); +} + +/* called from client_thread, cl->mutex is held */ +static int client_send_result(struct client *cl, struct action *act) +{ + response res; + char result_flags[128]; + int dump_len = 0; + int dump_fd = -1; + int rv = 0; + + if (cl->dead) { + log_debug("send cl %u skip dead", cl->id); + return -1; + } + + memset(result_flags, 0, sizeof(result_flags)); + + buffer_init(&res.buffer); + + /* + * EUNATCH is returned when the global lock existed, + * but had been disabled when we tried to lock it, + * so we removed it, and no longer have a gl to lock. + */ + + if (act->result == -EUNATCH) + act->result = -ENOLS; + + /* + * init_vg with dlm|sanlock returns vg_args + * init_lv with sanlock returns lv_args + */ + + if (act->result == -ENOLS) { + /* + * The lockspace could not be found, in which case + * the caller may want to know if any lockspaces exist + * or if lockspaces exist, but not one with the global lock. + * Given this detail, it may be able to procede without + * the lock. + */ + pthread_mutex_lock(&lockspaces_mutex); + if (list_empty(&lockspaces)) + strcat(result_flags, "NO_LOCKSPACES,"); + pthread_mutex_unlock(&lockspaces_mutex); + + if (gl_use_sanlock) { + if (!gl_lsname_sanlock[0]) + strcat(result_flags, "NO_GL_LS,"); + } else if (gl_use_dlm) { + if (!gl_lsname_dlm[0]) + strcat(result_flags, "NO_GL_LS,"); + } else { + strcat(result_flags, "NO_GL_LS,"); + } + } + + if (act->flags & LD_AF_DUP_GL_LS) + strcat(result_flags, "DUP_GL_LS,"); + + if ((act->flags & LD_AF_WARN_GL_REMOVED) || gl_vg_removed) + strcat(result_flags, "WARN_GL_REMOVED,"); + + if (act->op == LD_OP_INIT) { + /* + * init is a special case where lock args need + * to be passed back to the client. + */ + const char *vg_args = "none"; + const char *lv_args = "none"; + + if (act->vg_args[0]) + vg_args = act->vg_args; + + if (act->lv_args[0]) + lv_args = act->lv_args; + + log_debug("send %s[%d] cl %u %s %s rv %d vg_args %s lv_args %s", + cl->name[0] ? cl->name : "client", cl->pid, cl->id, + op_str(act->op), rt_str(act->rt), + act->result, vg_args ? vg_args : "", lv_args ? lv_args : ""); + + res = daemon_reply_simple("OK", + "op = " FMTd64, (int64_t)act->op, + "op_result = " FMTd64, (int64_t) act->result, + "lm_result = " FMTd64, (int64_t) act->lm_rv, + "vg_lock_args = %s", vg_args, + "lv_lock_args = %s", lv_args, + "result_flags = %s", result_flags[0] ? result_flags : "none", + NULL); + + } else if (act->op == LD_OP_DUMP_LOG || act->op == LD_OP_DUMP_INFO) { + /* + * lvmlockctl creates the unix socket then asks us to write to it. + * FIXME: move processing this to a new dedicated query thread to + * avoid having a large data dump interfere with normal operation + * of the client thread? + */ + + dump_fd = setup_dump_socket(); + if (dump_fd < 0) + act->result = dump_fd; + else if (act->op == LD_OP_DUMP_LOG) + act->result = dump_log(&dump_len); + else if (act->op == LD_OP_DUMP_INFO) + act->result = dump_info(&dump_len); + else + act->result = -EINVAL; + + log_debug("send %s[%d] cl %u dump result %d dump_len %d", + cl->name[0] ? cl->name : "client", cl->pid, cl->id, + act->result, dump_len); + + res = daemon_reply_simple("OK", + "result = " FMTd64, (int64_t) act->result, + "dump_len = " FMTd64, (int64_t) dump_len, + NULL); + } else { + /* + * A normal reply. + */ + + log_debug("send %s[%d] cl %u %s %s rv %d %s %s", + cl->name[0] ? cl->name : "client", cl->pid, cl->id, + op_str(act->op), rt_str(act->rt), + act->result, (act->result == -ENOLS) ? "ENOLS" : "", result_flags); + + res = daemon_reply_simple("OK", + "op = " FMTd64, (int64_t) act->op, + "lock_type = %s", lm_str(act->lm_type), + "op_result = " FMTd64, (int64_t) act->result, + "lm_result = " FMTd64, (int64_t) act->lm_rv, + "result_flags = %s", result_flags[0] ? result_flags : "none", + NULL); + } + + if (!buffer_write(cl->fd, &res.buffer)) { + rv = -errno; + if (rv >= 0) + rv = -1; + log_debug("send cl %u fd %d error %d", cl->id, cl->fd, rv); + } + + buffer_destroy(&res.buffer); + + client_resume(cl); + + if (dump_fd >= 0) { + /* To avoid deadlock, send data here after the reply. */ + send_dump_buf(dump_fd, dump_len); + close(dump_fd); + } + + return rv; +} + +/* called from client_thread */ +static void client_purge(struct client *cl) +{ + struct lockspace *ls; + struct action *act; + + /* + * If the client made no lock requests, there can be + * no locks to release for it. + */ + if (!cl->lock_ops) + return; + + pthread_mutex_lock(&lockspaces_mutex); + list_for_each_entry(ls, &lockspaces, list) { + if (!(act = alloc_action())) + continue; + + act->op = LD_OP_CLOSE; + act->client_id = cl->id; + + pthread_mutex_lock(&ls->mutex); + if (!ls->thread_stop) { + list_add_tail(&act->list, &ls->actions); + ls->thread_work = 1; + pthread_cond_signal(&ls->cond); + } else { + free_action(act); + } + pthread_mutex_unlock(&ls->mutex); + } + pthread_mutex_unlock(&lockspaces_mutex); +} + +static int add_lock_action(struct action *act) +{ + struct lockspace *ls = NULL; + char ls_name[MAX_NAME+1]; + + memset(ls_name, 0, sizeof(ls_name)); + + /* + * Determine which lockspace this action is for, and set ls_name. + */ + + if (act->rt == LD_RT_GL) { + /* Global lock is requested */ + if (gl_use_sanlock && (act->op == LD_OP_ENABLE || act->op == LD_OP_DISABLE)) { + vg_ls_name(act->vg_name, ls_name); + } else { + if (!gl_use_dlm && !gl_use_sanlock) { + if (lm_is_running_dlm()) + gl_use_dlm = 1; + else if (lm_is_running_sanlock()) + gl_use_sanlock = 1; + } + gl_ls_name(ls_name); + } + } else { + /* VG lock is requested */ + vg_ls_name(act->vg_name, ls_name); + } + + retry: + pthread_mutex_lock(&lockspaces_mutex); + if (ls_name[0]) + ls = find_lockspace_name(ls_name); + pthread_mutex_unlock(&lockspaces_mutex); + if (!ls) { + if (act->op == LD_OP_UPDATE && act->rt == LD_RT_VG) { + log_debug("lockspace \"%s\" not found ignored for vg update", ls_name); + return -ENOLS; + + } else if (act->flags & LD_AF_SEARCH_LS) { + /* + * Fail if we've already tried searching for the lockspace. + */ + log_debug("lockspace \"%s\" not found after search", ls_name); + return -ENOLS; + + } else if (act->op == LD_OP_LOCK && act->rt == LD_RT_GL && gl_use_sanlock) { + /* + * The sanlock global lock may have been enabled in an existing VG, + * so search existing VGs for an enabled global lock. + */ + log_debug("lockspace \"%s\" not found for sanlock gl, searching...", ls_name); + act->flags |= LD_AF_SEARCH_LS; + add_work_action(act); + return 0; + + } else if (act->op == LD_OP_LOCK && act->rt == LD_RT_GL && act->mode != LD_LK_UN && gl_use_dlm) { + /* + * Automatically start the dlm global lockspace when + * a command tries to acquire the global lock. + */ + log_debug("lockspace \"%s\" not found for dlm gl, adding...", ls_name); + act->flags |= LD_AF_SEARCH_LS; + act->flags |= LD_AF_WAIT_STARTING; + add_dlm_global_lockspace(NULL); + goto retry; + + } else if (act->op == LD_OP_LOCK && act->mode == LD_LK_UN) { + log_debug("lockspace \"%s\" not found for unlock ignored", ls_name); + return -ENOLS; + + } else { + log_debug("lockspace \"%s\" not found", ls_name); + return -ENOLS; + } + } + + if (act->lm_type == LD_LM_NONE) { + /* return to the command the type we are using */ + act->lm_type = ls->lm_type; + } else if (act->lm_type != ls->lm_type) { + /* should not happen */ + log_error("S %s add_lock_action bad lm_type %d ls %d", + ls_name, act->lm_type, ls->lm_type); + pthread_mutex_unlock(&lockspaces_mutex); + return -EINVAL; + } + + pthread_mutex_lock(&ls->mutex); + if (ls->thread_stop) { + pthread_mutex_unlock(&ls->mutex); + pthread_mutex_unlock(&lockspaces_mutex); + log_error("lockspace is stopping %s", ls_name); + return -ESTALE; + } + + if (!ls->create_fail && !ls->create_done && !(act->flags & LD_AF_WAIT_STARTING)) { + pthread_mutex_unlock(&ls->mutex); + pthread_mutex_unlock(&lockspaces_mutex); + log_debug("lockspace is starting %s", ls_name); + return -ESTARTING; + } + + list_add_tail(&act->list, &ls->actions); + ls->thread_work = 1; + pthread_cond_signal(&ls->cond); + pthread_mutex_unlock(&ls->mutex); + pthread_mutex_unlock(&lockspaces_mutex); + + /* lockspace_thread_main / res_process take it from here */ + + return 0; +} + +static int str_to_op_rt(const char *req_name, int *op, int *rt) +{ + if (!req_name) + goto out; + + if (!strcmp(req_name, "hello")) { + *op = LD_OP_HELLO; + *rt = 0; + return 0; + } + if (!strcmp(req_name, "quit")) { + *op = LD_OP_QUIT; + *rt = 0; + return 0; + } + if (!strcmp(req_name, "info")) { + *op = LD_OP_DUMP_INFO; + *rt = 0; + return 0; + } + if (!strcmp(req_name, "dump")) { + *op = LD_OP_DUMP_LOG; + *rt = 0; + return 0; + } + if (!strcmp(req_name, "init_vg")) { + *op = LD_OP_INIT; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "init_lv")) { + *op = LD_OP_INIT; + *rt = LD_RT_LV; + return 0; + } + if (!strcmp(req_name, "free_vg")) { + *op = LD_OP_FREE; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "busy_vg")) { + *op = LD_OP_BUSY; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "free_lv")) { + *op = LD_OP_FREE; + *rt = LD_RT_LV; + return 0; + } + if (!strcmp(req_name, "start_vg")) { + *op = LD_OP_START; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "stop_vg")) { + *op = LD_OP_STOP; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "start_wait")) { + *op = LD_OP_START_WAIT; + *rt = 0; + return 0; + } + if (!strcmp(req_name, "stop_all")) { + *op = LD_OP_STOP_ALL; + *rt = 0; + return 0; + } + if (!strcmp(req_name, "lock_gl")) { + *op = LD_OP_LOCK; + *rt = LD_RT_GL; + return 0; + } + if (!strcmp(req_name, "lock_vg")) { + *op = LD_OP_LOCK; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "lock_lv")) { + *op = LD_OP_LOCK; + *rt = LD_RT_LV; + return 0; + } + if (!strcmp(req_name, "vg_update")) { + *op = LD_OP_UPDATE; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "enable_gl")) { + *op = LD_OP_ENABLE; + *rt = LD_RT_GL; + return 0; + } + if (!strcmp(req_name, "disable_gl")) { + *op = LD_OP_DISABLE; + *rt = LD_RT_GL; + return 0; + } + if (!strcmp(req_name, "rename_vg_before")) { + *op = LD_OP_RENAME_BEFORE; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "rename_vg_final")) { + *op = LD_OP_RENAME_FINAL; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "running_lm")) { + *op = LD_OP_RUNNING_LM; + *rt = 0; + return 0; + } + if (!strcmp(req_name, "find_free_lock")) { + *op = LD_OP_FIND_FREE_LOCK; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "kill_vg")) { + *op = LD_OP_KILL_VG; + *rt = LD_RT_VG; + return 0; + } + if (!strcmp(req_name, "drop_vg")) { + *op = LD_OP_DROP_VG; + *rt = LD_RT_VG; + return 0; + } +out: + return -1; +} + +static int str_to_mode(const char *str) +{ + if (!str) + goto out; + if (!strcmp(str, "un")) + return LD_LK_UN; + if (!strcmp(str, "nl")) + return LD_LK_NL; + if (!strcmp(str, "sh")) + return LD_LK_SH; + if (!strcmp(str, "ex")) + return LD_LK_EX; +out: + return LD_LK_IV; +} + +static int str_to_lm(const char *str) +{ + if (!str || !strcmp(str, "none")) + return LD_LM_NONE; + if (!strcmp(str, "sanlock")) + return LD_LM_SANLOCK; + if (!strcmp(str, "dlm")) + return LD_LM_DLM; + return -2; +} + +static uint32_t str_to_opts(const char *str) +{ + uint32_t flags = 0; + + if (!str) + goto out; + if (strstr(str, "persistent")) + flags |= LD_AF_PERSISTENT; + if (strstr(str, "unlock_cancel")) + flags |= LD_AF_UNLOCK_CANCEL; + if (strstr(str, "next_version")) + flags |= LD_AF_NEXT_VERSION; + if (strstr(str, "wait")) + flags |= LD_AF_WAIT; + if (strstr(str, "force")) + flags |= LD_AF_FORCE; + if (strstr(str, "ex_disable")) + flags |= LD_AF_EX_DISABLE; + if (strstr(str, "enable")) + flags |= LD_AF_ENABLE; + if (strstr(str, "disable")) + flags |= LD_AF_DISABLE; +out: + return flags; +} + +/* + * dump info + * client_list: each client struct + * lockspaces: each lockspace struct + * lockspace actions: each action struct + * lockspace resources: each resource struct + * lockspace resource actions: each action struct + * lockspace resource locks: each lock struct + */ + +static int setup_dump_socket(void) +{ + int s; + + s = socket(AF_LOCAL, SOCK_DGRAM, 0); + if (s < 0) + return s; + + memset(&dump_addr, 0, sizeof(dump_addr)); + dump_addr.sun_family = AF_LOCAL; + strcpy(&dump_addr.sun_path[1], DUMP_SOCKET_NAME); + dump_addrlen = sizeof(sa_family_t) + strlen(dump_addr.sun_path+1) + 1; + + return s; +} + +#define MAX_SEND_LEN 65536 +#define RESEND_DELAY_US 1000 +#define RESEND_DELAY_US_MAX 500000 + +static void send_dump_buf(int fd, int dump_len) +{ + int pos = 0; + int ret; + int send_len; + int delay = 0; + + if (!dump_len) + return; +repeat: + if (dump_len - pos < MAX_SEND_LEN) + send_len = dump_len - pos; + else + send_len = MAX_SEND_LEN; + + ret = sendto(fd, dump_buf + pos, send_len, MSG_NOSIGNAL | MSG_DONTWAIT, + (struct sockaddr *)&dump_addr, dump_addrlen); + if (ret < 0) { + if ((errno == EAGAIN || errno == EINTR) && (delay < RESEND_DELAY_US_MAX)) { + usleep(RESEND_DELAY_US); + delay += RESEND_DELAY_US; + goto repeat; + } + log_error("send_dump_buf delay %d errno %d", delay, errno); + return; + } + + pos += ret; + + if (pos < dump_len) + goto repeat; + + log_debug("send_dump_buf delay %d total %d", delay, pos); +} + +static int print_structs(const char *prefix, int pos, int len) +{ + return snprintf(dump_buf + pos, len - pos, + "info=%s " + "unused_action_count=%d " + "unused_client_count=%d " + "unused_resource_count=%d " + "unused_lock_count=%d\n", + prefix, + unused_action_count, + unused_client_count, + unused_resource_count, + unused_lock_count); +} + +static int print_client(struct client *cl, const char *prefix, int pos, int len) +{ + return snprintf(dump_buf + pos, len - pos, + "info=%s " + "pid=%d " + "fd=%d " + "pi=%d " + "id=%u " + "name=%s\n", + prefix, + cl->pid, + cl->fd, + cl->pi, + cl->id, + cl->name[0] ? cl->name : "."); +} + +static int print_lockspace(struct lockspace *ls, const char *prefix, int pos, int len) +{ + return snprintf(dump_buf + pos, len - pos, + "info=%s " + "ls_name=%s " + "vg_name=%s " + "vg_uuid=%s " + "vg_sysid=%s " + "vg_args=%s " + "lm_type=%s " + "host_id=%llu " + "create_fail=%d " + "create_done=%d " + "thread_work=%d " + "thread_stop=%d " + "thread_done=%d " + "kill_vg=%d " + "drop_vg=%d " + "sanlock_gl_enabled=%d\n", + prefix, + ls->name, + ls->vg_name, + ls->vg_uuid, + ls->vg_sysid[0] ? ls->vg_sysid : ".", + ls->vg_args, + lm_str(ls->lm_type), + (unsigned long long)ls->host_id, + ls->create_fail ? 1 : 0, + ls->create_done ? 1 : 0, + ls->thread_work ? 1 : 0, + ls->thread_stop ? 1 : 0, + ls->thread_done ? 1 : 0, + ls->kill_vg, + ls->drop_vg, + ls->sanlock_gl_enabled ? 1 : 0); +} + +static int print_action(struct action *act, const char *prefix, int pos, int len) +{ + return snprintf(dump_buf + pos, len - pos, + "info=%s " + "client_id=%u " + "flags=0x%x " + "version=%u " + "op=%s " + "rt=%s " + "mode=%s " + "lm_type=%s " + "result=%d " + "lm_rv=%d\n", + prefix, + act->client_id, + act->flags, + act->version, + op_str(act->op), + rt_str(act->rt), + mode_str(act->mode), + lm_str(act->lm_type), + act->result, + act->lm_rv); +} + +static int print_resource(struct resource *r, const char *prefix, int pos, int len) +{ + return snprintf(dump_buf + pos, len - pos, + "info=%s " + "name=%s " + "type=%s " + "mode=%s " + "sh_count=%d " + "version=%u\n", + prefix, + r->name, + rt_str(r->type), + mode_str(r->mode), + r->sh_count, + r->version); +} + +static int print_lock(struct lock *lk, const char *prefix, int pos, int len) +{ + return snprintf(dump_buf + pos, len - pos, + "info=%s " + "mode=%s " + "version=%u " + "flags=0x%x " + "client_id=%u\n", + prefix, + mode_str(lk->mode), + lk->version, + lk->flags, + lk->client_id); +} + +static int dump_info(int *dump_len) +{ + struct client *cl; + struct lockspace *ls; + struct resource *r; + struct lock *lk; + struct action *act; + int len, pos, ret; + int rv = 0; + + memset(dump_buf, 0, sizeof(dump_buf)); + len = sizeof(dump_buf); + pos = 0; + + /* + * memory + */ + + pthread_mutex_lock(&unused_struct_mutex); + ret = print_structs("structs", pos, len); + if (ret >= len - pos) { + pthread_mutex_unlock(&unused_struct_mutex); + return -ENOSPC; + } + pos += ret; + pthread_mutex_unlock(&unused_struct_mutex); + + /* + * clients + */ + + pthread_mutex_lock(&client_mutex); + list_for_each_entry(cl, &client_list, list) { + ret = print_client(cl, "client", pos, len); + if (ret >= len - pos) { + rv = -ENOSPC; + break; + } + pos += ret; + } + pthread_mutex_unlock(&client_mutex); + + if (rv < 0) + return rv; + + /* + * lockspaces with their action/resource/lock info + */ + + pthread_mutex_lock(&lockspaces_mutex); + list_for_each_entry(ls, &lockspaces, list) { + + ret = print_lockspace(ls, "ls", pos, len); + if (ret >= len - pos) { + rv = -ENOSPC; + goto out; + } + pos += ret; + + list_for_each_entry(act, &ls->actions, list) { + ret = print_action(act, "ls_action", pos, len); + if (ret >= len - pos) { + rv = -ENOSPC; + goto out; + } + pos += ret; + } + + list_for_each_entry(r, &ls->resources, list) { + ret = print_resource(r, "r", pos, len); + if (ret >= len - pos) { + rv = -ENOSPC; + goto out; + } + pos += ret; + + list_for_each_entry(lk, &r->locks, list) { + ret = print_lock(lk, "lk", pos, len); + if (ret >= len - pos) { + rv = -ENOSPC; + goto out; + } + pos += ret; + } + + list_for_each_entry(act, &r->actions, list) { + ret = print_action(act, "r_action", pos, len); + if (ret >= len - pos) { + rv = -ENOSPC; + goto out; + } + pos += ret; + } + } + } +out: + pthread_mutex_unlock(&lockspaces_mutex); + + *dump_len = pos; + + return rv; +} + +/* called from client_thread, cl->mutex is held */ +static void client_recv_action(struct client *cl) +{ + request req; + response res; + struct action *act; + const char *cl_name; + const char *vg_name; + const char *vg_uuid; + const char *vg_sysid; + const char *str; + int64_t val; + uint32_t opts = 0; + int result = 0; + int cl_pid; + int op, rt, lm, mode; + int rv; + + buffer_init(&req.buffer); + + rv = buffer_read(cl->fd, &req.buffer); + if (!rv) { + if (errno == ECONNRESET) { + log_debug("client recv %u ECONNRESET", cl->id); + cl->dead = 1; + } else { + log_error("client recv %u buffer_read error %d", cl->id, errno); + } + buffer_destroy(&req.buffer); + client_resume(cl); + return; + } + + req.cft = dm_config_from_string(req.buffer.mem); + if (!req.cft) { + log_error("client recv %u config_from_string error", cl->id); + buffer_destroy(&req.buffer); + client_resume(cl); + return; + } + + str = daemon_request_str(req, "request", NULL); + rv = str_to_op_rt(str, &op, &rt); + if (rv < 0) { + log_error("client recv %u bad request name \"%s\"", cl->id, str ? str : ""); + dm_config_destroy(req.cft); + buffer_destroy(&req.buffer); + client_resume(cl); + return; + } + + if (op == LD_OP_HELLO || op == LD_OP_QUIT) { + + /* + * FIXME: add the client command name to the hello messages + * so it can be saved in cl->name here. + */ + + result = 0; + + if (op == LD_OP_QUIT) { + log_debug("op quit"); + pthread_mutex_lock(&lockspaces_mutex); + if (list_empty(&lockspaces)) + daemon_quit = 1; + else + result = -EBUSY; + pthread_mutex_unlock(&lockspaces_mutex); + } + + buffer_init(&res.buffer); + + res = daemon_reply_simple("OK", + "result = " FMTd64, (int64_t) result, + "protocol = %s", lvmlockd_protocol, + "version = " FMTd64, (int64_t) lvmlockd_protocol_version, + NULL); + buffer_write(cl->fd, &res.buffer); + buffer_destroy(&res.buffer); + dm_config_destroy(req.cft); + buffer_destroy(&req.buffer); + client_resume(cl); + return; + } + + cl_name = daemon_request_str(req, "cmd", NULL); + cl_pid = daemon_request_int(req, "pid", 0); + vg_name = daemon_request_str(req, "vg_name", NULL); + vg_uuid = daemon_request_str(req, "vg_uuid", NULL); + vg_sysid = daemon_request_str(req, "vg_sysid", NULL); + str = daemon_request_str(req, "mode", NULL); + mode = str_to_mode(str); + str = daemon_request_str(req, "opts", NULL); + opts = str_to_opts(str); + str = daemon_request_str(req, "vg_lock_type", NULL); + lm = str_to_lm(str); + + if (cl_pid && cl_pid != cl->pid) + log_error("client recv bad message pid %d client %d", cl_pid, cl->pid); + + /* FIXME: do this in hello message instead */ + if (!cl->name[0] && cl_name) + strncpy(cl->name, cl_name, MAX_NAME); + + if (!gl_use_dlm && !gl_use_sanlock && (lm > 0)) { + if (lm == LD_LM_DLM && lm_support_dlm()) + gl_use_dlm = 1; + else if (lm == LD_LM_SANLOCK && lm_support_sanlock()) + gl_use_sanlock = 1; + + log_debug("set gl_use_%s", lm_str(lm)); + } + + if (!(act = alloc_action())) { + log_error("No memory for action"); + dm_config_destroy(req.cft); + buffer_destroy(&req.buffer); + client_resume(cl); + return; + } + + act->client_id = cl->id; + act->op = op; + act->rt = rt; + act->mode = mode; + act->flags = opts; + act->lm_type = lm; + + if (vg_name && strcmp(vg_name, "none")) + strncpy(act->vg_name, vg_name, MAX_NAME); + + if (vg_uuid && strcmp(vg_uuid, "none")) + strncpy(act->vg_uuid, vg_uuid, 64); + + if (vg_sysid && strcmp(vg_sysid, "none")) + strncpy(act->vg_sysid, vg_sysid, MAX_NAME); + + str = daemon_request_str(req, "lv_name", NULL); + if (str && strcmp(str, "none")) + strncpy(act->lv_name, str, MAX_NAME); + + str = daemon_request_str(req, "lv_uuid", NULL); + if (str && strcmp(str, "none")) + strncpy(act->lv_uuid, str, MAX_NAME); + + val = daemon_request_int(req, "version", 0); + if (val) + act->version = (uint32_t)val; + + str = daemon_request_str(req, "vg_lock_args", NULL); + if (str && strcmp(str, "none")) + strncpy(act->vg_args, str, MAX_ARGS); + + str = daemon_request_str(req, "lv_lock_args", NULL); + if (str && strcmp(str, "none")) + strncpy(act->lv_args, str, MAX_ARGS); + + /* start_vg will include lvmlocal.conf local/host_id here */ + val = daemon_request_int(req, "host_id", 0); + if (val) + act->host_id = val; + + act->max_retries = daemon_request_int(req, "max_retries", DEFAULT_MAX_RETRIES); + + dm_config_destroy(req.cft); + buffer_destroy(&req.buffer); + + log_debug("recv %s[%d] cl %u %s %s \"%s\" mode %s flags %x", + cl->name[0] ? cl->name : "client", cl->pid, cl->id, + op_str(act->op), rt_str(act->rt), act->vg_name, mode_str(act->mode), opts); + + if (lm == LD_LM_DLM && !lm_support_dlm()) { + log_debug("dlm not supported"); + rv = -EPROTONOSUPPORT; + goto out; + } + + if (lm == LD_LM_SANLOCK && !lm_support_sanlock()) { + log_debug("sanlock not supported"); + rv = -EPROTONOSUPPORT; + goto out; + } + + if (act->op == LD_OP_LOCK && act->mode != LD_LK_UN) + cl->lock_ops = 1; + + switch (act->op) { + case LD_OP_START: + rv = add_lockspace(act); + break; + case LD_OP_STOP: + rv = rem_lockspace(act); + break; + case LD_OP_DUMP_LOG: + case LD_OP_DUMP_INFO: + /* The client thread reply will copy and send the dump. */ + add_client_result(act); + rv = 0; + break; + case LD_OP_INIT: + case LD_OP_START_WAIT: + case LD_OP_STOP_ALL: + case LD_OP_RENAME_FINAL: + case LD_OP_RUNNING_LM: + add_work_action(act); + rv = 0; + break; + case LD_OP_LOCK: + case LD_OP_UPDATE: + case LD_OP_ENABLE: + case LD_OP_DISABLE: + case LD_OP_FREE: + case LD_OP_RENAME_BEFORE: + case LD_OP_FIND_FREE_LOCK: + case LD_OP_KILL_VG: + case LD_OP_DROP_VG: + case LD_OP_BUSY: + rv = add_lock_action(act); + break; + default: + rv = -EINVAL; + }; + +out: + if (rv < 0) { + act->result = rv; + add_client_result(act); + } +} + +static void *client_thread_main(void *arg_in) +{ + struct client *cl; + struct action *act; + struct action *act_un; + int rv; + + while (1) { + pthread_mutex_lock(&client_mutex); + while (!client_work && list_empty(&client_results)) { + if (client_stop) { + pthread_mutex_unlock(&client_mutex); + goto out; + } + pthread_cond_wait(&client_cond, &client_mutex); + } + + /* + * Send outgoing results back to clients + */ + + if (!list_empty(&client_results)) { + act = list_first_entry(&client_results, struct action, list); + list_del(&act->list); + cl = find_client_id(act->client_id); + pthread_mutex_unlock(&client_mutex); + + if (cl) { + pthread_mutex_lock(&cl->mutex); + rv = client_send_result(cl, act); + pthread_mutex_unlock(&cl->mutex); + } else { + log_debug("no client %u for result", act->client_id); + rv = -1; + } + + /* + * The client failed after we acquired an LV lock for + * it, but before getting this reply saying it's done. + * So the lv will not be active and we should release + * the lv lock it requested. + */ + if ((rv < 0) && (act->flags & LD_AF_LV_LOCK)) { + log_debug("auto unlock lv for failed client %u", act->client_id); + if ((act_un = alloc_action())) { + memcpy(act_un, act, sizeof(struct action)); + act_un->mode = LD_LK_UN; + act_un->flags |= LD_AF_LV_UNLOCK; + act_un->flags &= ~LD_AF_LV_LOCK; + add_lock_action(act_un); + } + } + + free_action(act); + continue; + } + + /* + * Queue incoming actions for lockspace threads + */ + + if (client_work) { + cl = find_client_work(); + if (!cl) + client_work = 0; + pthread_mutex_unlock(&client_mutex); + + if (!cl) + continue; + + pthread_mutex_lock(&cl->mutex); + + if (cl->recv) { + cl->recv = 0; + client_recv_action(cl); + } + + if (cl->dead) { + /* + log_debug("client rem %d pi %d fd %d ig %d", + cl->id, cl->pi, cl->fd, cl->poll_ignore); + */ + + /* + * If cl->dead was set in main_loop, then the + * fd has already been closed and the pollfd + * entry is already unused. + * main_loop set dead=1, ignore=0, pi=-1, fd=-1 + * + * if cl->dead was not set in main_loop, but + * set in client_recv_action, then the main_loop + * should be ignoring this client fd. + * main_loop set ignore=1 + */ + + if (cl->poll_ignore) { + log_debug("client close %d pi %d fd %d", + cl->id, cl->pi, cl->fd); + /* assert cl->pi != -1 */ + /* assert pollfd[pi].fd == FD_IGNORE */ + if (close(cl->fd)) + log_error("client close %d pi %d fd %d failed", + cl->id, cl->pi, cl->fd); + rem_pollfd(cl->pi); + cl->pi = -1; + cl->fd = -1; + cl->poll_ignore = 0; + } else { + /* main thread should have closed */ + if (cl->pi != -1 || cl->fd != -1) { + log_error("client %d bad state pi %d fd %d", + cl->id, cl->pi, cl->fd); + } + } + pthread_mutex_unlock(&cl->mutex); + + pthread_mutex_lock(&client_mutex); + list_del(&cl->list); + pthread_mutex_unlock(&client_mutex); + + client_purge(cl); + + free_client(cl); + } else { + pthread_mutex_unlock(&cl->mutex); + } + } + pthread_mutex_unlock(&client_mutex); + } +out: + return NULL; +} + +static int setup_client_thread(void) +{ + int rv; + + INIT_LIST_HEAD(&client_list); + INIT_LIST_HEAD(&client_results); + + pthread_mutex_init(&client_mutex, NULL); + pthread_cond_init(&client_cond, NULL); + + rv = pthread_create(&client_thread, NULL, client_thread_main, NULL); + if (rv) + return -1; + return 0; +} + +static void close_client_thread(void) +{ + pthread_mutex_lock(&client_mutex); + client_stop = 1; + pthread_cond_signal(&client_cond); + pthread_mutex_unlock(&client_mutex); + pthread_join(client_thread, NULL); +} + +/* + * Get a list of all VGs with a lockd type (sanlock|dlm) from lvmetad. + * We'll match this list against a list of existing lockspaces that are + * found in the lock manager. + * + * For each of these VGs, also create a struct resource on ls->resources to + * represent each LV in the VG that uses a lock. For each of these LVs + * that are active, we'll attempt to adopt a lock. + */ + +static int get_lockd_vgs(struct list_head *vg_lockd) +{ + struct list_head update_vgs; + daemon_reply reply; + struct dm_config_node *cn; + struct dm_config_node *metadata; + struct dm_config_node *md_cn; + struct dm_config_node *lv_cn; + struct lockspace *ls, *safe; + struct resource *r; + const char *vg_name; + const char *vg_uuid; + const char *lv_uuid; + const char *lock_type; + const char *lock_args; + char find_str_path[PATH_MAX]; + int rv = 0; + + INIT_LIST_HEAD(&update_vgs); + + reply = send_lvmetad("vg_list", "token = %s", "skip", NULL); + + if (reply.error || strcmp(daemon_reply_str(reply, "response", ""), "OK")) { + log_error("vg_list from lvmetad failed %d", reply.error); + rv = -EINVAL; + goto destroy; + } + + if (!(cn = dm_config_find_node(reply.cft->root, "volume_groups"))) { + log_error("get_lockd_vgs no vgs"); + rv = -EINVAL; + goto destroy; + } + + /* create an update_vgs list of all vg uuids */ + + for (cn = cn->child; cn; cn = cn->sib) { + vg_uuid = cn->key; + + if (!(ls = alloc_lockspace())) { + rv = -ENOMEM; + break; + } + + strncpy(ls->vg_uuid, vg_uuid, 64); + list_add_tail(&ls->list, &update_vgs); + log_debug("get_lockd_vgs %s", vg_uuid); + } + destroy: + daemon_reply_destroy(reply); + + if (rv < 0) + goto out; + + /* get vg_name and lock_type for each vg uuid entry in update_vgs */ + + list_for_each_entry(ls, &update_vgs, list) { + reply = send_lvmetad("vg_lookup", + "token = %s", "skip", + "uuid = %s", ls->vg_uuid, + NULL); + + if (reply.error || strcmp(daemon_reply_str(reply, "response", ""), "OK")) { + log_error("vg_lookup from lvmetad failed %d", reply.error); + rv = -EINVAL; + goto next; + } + + vg_name = daemon_reply_str(reply, "name", NULL); + if (!vg_name) { + log_error("get_lockd_vgs %s no name", ls->vg_uuid); + rv = -EINVAL; + goto next; + } + + strncpy(ls->vg_name, vg_name, MAX_NAME); + + metadata = dm_config_find_node(reply.cft->root, "metadata"); + if (!metadata) { + log_error("get_lockd_vgs %s name %s no metadata", + ls->vg_uuid, ls->vg_name); + rv = -EINVAL; + goto next; + } + + lock_type = dm_config_find_str(metadata, "metadata/lock_type", NULL); + ls->lm_type = str_to_lm(lock_type); + + if ((ls->lm_type != LD_LM_SANLOCK) && (ls->lm_type != LD_LM_DLM)) { + log_debug("get_lockd_vgs %s not lockd type", ls->vg_name); + continue; + } + + lock_args = dm_config_find_str(metadata, "metadata/lock_args", NULL); + if (lock_args) + strncpy(ls->vg_args, lock_args, MAX_ARGS); + + log_debug("get_lockd_vgs %s lock_type %s lock_args %s", + ls->vg_name, lock_type, lock_args ?: "none"); + + /* + * Make a record (struct resource) of each lv that uses a lock. + * For any lv that uses a lock, we'll check if the lv is active + * and if so try to adopt a lock for it. + */ + + for (md_cn = metadata->child; md_cn; md_cn = md_cn->sib) { + if (strcmp(md_cn->key, "logical_volumes")) + continue; + + for (lv_cn = md_cn->child; lv_cn; lv_cn = lv_cn->sib) { + snprintf(find_str_path, PATH_MAX, "%s/lock_type", lv_cn->key); + lock_type = dm_config_find_str(lv_cn, find_str_path, NULL); + + if (!lock_type) + continue; + + snprintf(find_str_path, PATH_MAX, "%s/lock_args", lv_cn->key); + lock_args = dm_config_find_str(lv_cn, find_str_path, NULL); + + snprintf(find_str_path, PATH_MAX, "%s/id", lv_cn->key); + lv_uuid = dm_config_find_str(lv_cn, find_str_path, NULL); + + if (!lv_uuid) { + log_error("get_lock_vgs no lv id for name %s", lv_cn->key); + continue; + } + + if (!(r = alloc_resource())) { + rv = -ENOMEM; + goto next; + } + + r->use_vb = 0; + r->type = LD_RT_LV; + strncpy(r->name, lv_uuid, MAX_NAME); + if (lock_args) + strncpy(r->lv_args, lock_args, MAX_ARGS); + list_add_tail(&r->list, &ls->resources); + log_debug("get_lockd_vgs %s lv %s %s (name %s)", + ls->vg_name, r->name, lock_args ? lock_args : "", lv_cn->key); + } + } + next: + daemon_reply_destroy(reply); + + if (rv < 0) + break; + } +out: + /* Return lockd VG's on the vg_lockd list. */ + + list_for_each_entry_safe(ls, safe, &update_vgs, list) { + list_del(&ls->list); + + if ((ls->lm_type == LD_LM_SANLOCK) || (ls->lm_type == LD_LM_DLM)) + list_add_tail(&ls->list, vg_lockd); + else + free(ls); + } + + return rv; +} + +static char _dm_uuid[64]; + +static char *get_dm_uuid(char *dm_name) +{ + struct dm_info info; + struct dm_task *dmt; + const char *uuid; + + if (!(dmt = dm_task_create(DM_DEVICE_INFO))) + goto fail_out; + + if (!dm_task_set_name(dmt, dm_name)) + goto fail; + + if (!dm_task_run(dmt)) + goto fail; + + if (!dm_task_get_info(dmt, &info)) + goto fail; + + if (!info.exists) + goto fail; + + uuid = dm_task_get_uuid(dmt); + if (!uuid) { + log_error("Failed to get uuid for device %s", dm_name); + goto fail; + } + + if (strncmp(uuid, "LVM", 3)) { + log_debug("dm device %s is not from LVM", dm_name); + goto fail; + } + + memset(_dm_uuid, 0, sizeof(_dm_uuid)); + strncpy(_dm_uuid, uuid, sizeof(_dm_uuid)-1); + dm_task_destroy(dmt); + return _dm_uuid; + +fail: + dm_task_destroy(dmt); +fail_out: + return NULL; +} + +/* + * dm reports the LV uuid as: + * LVM-ydpRIdDWBDX25upmj2k0D4deat6oxH8er03T0f4xM8rPIV8XqIhwv3h8Y7xRWjMr + * + * the lock name for the LV is: + * r03T0f-4xM8-rPIV-8XqI-hwv3-h8Y7-xRWjMr + * + * This function formats both as: + * r03T0f4xM8rPIV8XqIhwv3h8Y7xRWjMr + * + * and returns 1 if they match. + */ + +static int match_dm_uuid(char *dm_uuid, char *lv_lock_uuid) +{ + char buf1[64]; + char buf2[64]; + int i, j; + + memset(buf1, 0, sizeof(buf1)); + memset(buf2, 0, sizeof(buf2)); + + for (i = 0, j = 0; i < strlen(lv_lock_uuid); i++) { + if (lv_lock_uuid[i] == '-') + continue; + buf1[j] = lv_lock_uuid[i]; + j++; + } + + for (i = 36, j = 0; i < 69; i++) { + buf2[j] = dm_uuid[i]; + j++; + } + + if (!strcmp(buf1, buf2)) + return 1; + return 0; +} + +/* + * All LVs with a lock_type are on ls->resources. + * Remove any that are not active. The remaining + * will have locks adopted. + */ + +static int remove_inactive_lvs(struct list_head *vg_lockd) +{ + struct lockspace *ls; + struct resource *r, *rsafe; + struct dm_names *names; + struct dm_task *dmt; + char *dm_uuid; + char *vgname, *lvname, *layer; + char namebuf[MAX_NAME+1]; + unsigned next = 0; + int rv = 0; + + if (!(dmt = dm_task_create(DM_DEVICE_LIST))) + return -1; + + if (!dm_task_run(dmt)) { + log_error("Failed to get dm devices"); + rv = -1; + goto ret; + } + + if (!(names = dm_task_get_names(dmt))) { + log_error("Failed to get dm names"); + rv = -1; + goto ret; + } + + if (!names->dev) { + log_debug("dm names none found"); + goto out; + } + + /* + * For each dm name, compare it to each lv in each lockd vg. + */ + + do { + names = (struct dm_names *)((char *) names + next); + + dm_uuid = get_dm_uuid(names->name); + if (!dm_uuid) + goto next_dmname; + + vgname = NULL; + lvname = NULL; + layer = NULL; + + memset(namebuf, 0, sizeof(namebuf)); + strncpy(namebuf, names->name, MAX_NAME); + vgname = namebuf; + + if (!dm_split_lvm_name(NULL, namebuf, &vgname, &lvname, &layer)) { + log_error("failed to split dm name %s", namebuf); + goto next_dmname; + } + + log_debug("adopt remove_inactive dm name %s dm uuid %s vgname %s lvname %s", + names->name, dm_uuid, vgname, lvname); + + if (!vgname || !lvname) { + log_debug("dm name %s invalid split vg %s lv %s layer %s", + names->name, vgname ? vgname : "", lvname ? lvname : "", layer ? layer : ""); + goto next_dmname; + } + + list_for_each_entry(ls, vg_lockd, list) { + if (strcmp(vgname, ls->vg_name)) + continue; + + if (!strcmp(lvname, "lvmlock")) + continue; + + list_for_each_entry(r, &ls->resources, list) { + if (!match_dm_uuid(dm_uuid, r->name)) + continue; + + /* Found an active LV in a lockd VG. */ + log_debug("dm device %s adopt in vg %s lv %s", + names->name, ls->vg_name, r->name); + r->adopt = 1; + goto next_dmname; + } + } +next_dmname: + next = names->next; + } while (next); + +out: + /* Remove any struct resources that do not need locks adopted. */ + list_for_each_entry(ls, vg_lockd, list) { + list_for_each_entry_safe(r, rsafe, &ls->resources, list) { + if (r->adopt) { + r->adopt = 0; + } else { + log_debug("lockd vg %s remove inactive lv %s", ls->vg_name, r->name); + list_del(&r->list); + free_resource(r); + } + } + } +ret: + dm_task_destroy(dmt); + return rv; +} + +static void adopt_locks(void) +{ + struct list_head ls_found; + struct list_head vg_lockd; + struct list_head to_unlock; + struct lockspace *ls, *lsafe; + struct lockspace *ls1, *l1safe; + struct lockspace *ls2, *l2safe; + struct resource *r, *rsafe; + struct action *act, *asafe; + int count_start = 0, count_start_done = 0, count_start_fail = 0; + int count_adopt = 0, count_adopt_done = 0, count_adopt_fail = 0; + int found, rv; + + INIT_LIST_HEAD(&adopt_results); + + INIT_LIST_HEAD(&ls_found); + INIT_LIST_HEAD(&vg_lockd); + INIT_LIST_HEAD(&to_unlock); + + /* + * Get list of lockspaces from lock managers. + * Get list of VGs from lvmetad with a lockd type. + * Get list of active lockd type LVs from /dev. + * + * ECONNREFUSED means the lock manager is not running. + * This is expected for at least one of them. + */ + + if (lm_support_dlm()) { + rv = lm_get_lockspaces_dlm(&ls_found); + if ((rv < 0) && (rv != -ECONNREFUSED)) + goto fail; + } + + if (lm_support_sanlock()) { + rv = lm_get_lockspaces_sanlock(&ls_found); + if ((rv < 0) && (rv != -ECONNREFUSED)) + goto fail; + } + + if (list_empty(&ls_found)) { + log_debug("No lockspaces found to adopt"); + return; + } + + /* + * Adds a struct lockspace to vg_lockd for each lockd VG. + * Adds a struct resource to ls->resources for each LV. + */ + rv = get_lockd_vgs(&vg_lockd); + if (rv < 0) { + log_error("adopt_locks get_lockd_vgs failed"); + goto fail; + } + + /* + * For each resource on each lockspace, check if the + * corresponding LV is active. If so, leave the + * resource struct, if not free the resource struct. + * The remain entries need to have locks adopted. + */ + rv = remove_inactive_lvs(&vg_lockd); + if (rv < 0) { + log_error("adopt_locks remove_inactive_lvs failed"); + goto fail; + } + + list_for_each_entry(ls, &ls_found, list) { + if (ls->lm_type == LD_LM_DLM) + gl_use_dlm = 1; + + log_debug("adopt %s lockspace %s vg %s", + lm_str(ls->lm_type), ls->name, ls->vg_name); + } + + if (!gl_use_dlm) + gl_use_sanlock = 1; + + list_for_each_entry(ls, &vg_lockd, list) { + log_debug("adopt lvmetad vg %s lock_type %s lock_args %s", + ls->vg_name, lm_str(ls->lm_type), ls->vg_args); + + list_for_each_entry(r, &ls->resources, list) + log_debug("adopt lv %s %s", ls->vg_name, r->name); + } + + /* + * Compare and merge the list of lockspaces in ls_found + * and the list of lockd VGs in vg_lockd. + * + * An ls from ls_found may not have had any active lvs when + * previous lvmlockd died, but the ls should still be joined, + * and checked for GL/VG locks. + * + * An ls from vg_lockd with active lvs should be in ls_found. + * If it's not then we might want to join the ls and acquire locks + * for the active lvs (as opposed to adopting orphans for them.) + * The orphan lock in the ls should have prevented the ls in + * the lock manager from going away. + * + * If an ls in vg_lockd has no active lvs and does not have + * a matching entry in ls_found, then skip it. + * + * An ls in ls_found should always have a matching ls in + * vg_lockd. If it doesn't, then maybe the vg has been + * removed even though the lockspace for the vg is still + * in the lock manager. Just leave the ls in the lm + * alone, and skip the ls_found entry. + */ + + list_for_each_entry_safe(ls1, l1safe, &ls_found, list) { + + /* The dlm global lockspace is special and doesn't match a VG. */ + if (!strcmp(ls1->name, gl_lsname_dlm)) { + list_del(&ls1->list); + free(ls1); + continue; + } + + found = 0; + + list_for_each_entry_safe(ls2, l2safe, &vg_lockd, list) { + if (strcmp(ls1->vg_name, ls2->vg_name)) + continue; + + /* + * LS in both ls_found and vg_lockd. + */ + log_debug("ls %s matches vg %s", ls1->name, ls2->vg_name); + memcpy(ls1->vg_uuid, ls2->vg_uuid, 64); + memcpy(ls1->vg_args, ls2->vg_args, MAX_ARGS); + list_for_each_entry_safe(r, rsafe, &ls2->resources, list) { + list_del(&r->list); + list_add(&r->list, &ls1->resources); + } + list_del(&ls2->list); + free(ls2); + found = 1; + break; + } + + /* + * LS in ls_found, not in vg_lockd. + * An lvm lockspace found in the lock manager has no + * corresponding VG in lvmetad. This shouldn't usually + * happen, but it's possible the VG could have been removed + * while the orphaned lockspace from it was still around. + * Report an error and leave the ls in the lm alone. + */ + if (!found) { + log_error("No VG %s found for lockspace %s %s", + ls1->vg_name, ls1->name, lm_str(ls1->lm_type)); + list_del(&ls1->list); + free(ls1); + } + } + + /* + * LS in vg_lockd, not in ls_found. + * lockd vgs from lvmetad that do not have an existing lockspace. + * This wouldn't be unusual; we just skip the vg. + * But, if the vg has active lvs, then it should have had locks + * and a lockspace. Should we attempt to join the lockspace and + * acquire (not adopt) locks for these LVs? + */ + + list_for_each_entry_safe(ls, lsafe, &vg_lockd, list) { + if (!list_empty(&ls->resources)) { + /* We should have found a lockspace. */ + /* add this ls and acquire locks for ls->resources? */ + log_error("No lockspace %s %s found for VG %s with active LVs", + ls->name, lm_str(ls->lm_type), ls->vg_name); + } else { + /* The VG wasn't started in the previous lvmlockd. */ + log_debug("No ls found for vg %s", ls->vg_name); + } + + list_del(&ls->list); + free(ls); + } + + /* + * Create and queue start actions to add lockspaces. + */ + + if (gl_use_dlm) { + if (!(act = alloc_action())) + goto fail; + log_debug("adopt add dlm global lockspace"); + act->op = LD_OP_START; + act->flags = (LD_AF_ADOPT | LD_AF_WAIT); + act->rt = LD_RT_GL; + act->lm_type = LD_LM_DLM; + act->client_id = INTERNAL_CLIENT_ID; + add_dlm_global_lockspace(act); + count_start++; + } + + list_for_each_entry_safe(ls, lsafe, &ls_found, list) { + if (!(act = alloc_action())) + goto fail; + act->op = LD_OP_START; + act->flags = (LD_AF_ADOPT | LD_AF_WAIT); + act->rt = LD_RT_VG; + act->lm_type = ls->lm_type; + act->client_id = INTERNAL_CLIENT_ID; + strncpy(act->vg_name, ls->vg_name, MAX_NAME); + memcpy(act->vg_uuid, ls->vg_uuid, 64); + memcpy(act->vg_args, ls->vg_args, MAX_ARGS); + act->host_id = ls->host_id; + + /* set act->version from lvmetad data? */ + + log_debug("adopt add %s vg lockspace %s", lm_str(act->lm_type), act->vg_name); + + rv = add_lockspace_thread(ls->name, act->vg_name, act->vg_uuid, + act->lm_type, act->vg_args, act); + if (rv < 0) { + log_error("Failed to create lockspace thread for VG %s", ls->vg_name); + list_del(&ls->list); + free(ls); + free_action(act); + count_start_fail++; + continue; + } + + /* + * When the lockspace_thread is done with the start act, + * it will see the act ADOPT flag and move the act onto + * the adopt_results list for us to collect below. + */ + count_start++; + } + + log_debug("adopt starting %d lockspaces", count_start); + + /* + * Wait for all start/rejoin actions to complete. Each start action + * queued above will appear on the adopt_results list when finished. + */ + + while (count_start_done < count_start) { + sleep(1); + act = NULL; + + pthread_mutex_lock(&client_mutex); + if (!list_empty(&adopt_results)) { + act = list_first_entry(&adopt_results, struct action, list); + list_del(&act->list); + } + pthread_mutex_unlock(&client_mutex); + + if (!act) + continue; + + if (act->result < 0) { + log_error("adopt add lockspace failed vg %s %d", act->vg_name, act->result); + count_start_fail++; + } + + free_action(act); + count_start_done++; + } + + log_debug("adopt started %d lockspaces done %d fail %d", + count_start, count_start_done, count_start_fail); + + /* + * Create lock-adopt actions for active LVs (ls->resources), + * and GL/VG locks (we don't know if these locks were held + * and orphaned by the last lvmlockd, so try to adopt them + * to see.) + * + * A proper struct lockspace now exists on the lockspaces list + * for each ls in ls_found. Lock ops for one of those + * lockspaces can be done as OP_LOCK actions queued using + * add_lock_action(); + * + * Start by attempting to adopt the lock in the most likely + * mode it was left in (ex for lvs, sh for vg/gl). If + * the mode is wrong, the lm will return an error and we + * try again with the other mode. + */ + + list_for_each_entry(ls, &ls_found, list) { + + /* + * Adopt orphan LV locks. + */ + + list_for_each_entry(r, &ls->resources, list) { + if (!(act = alloc_action())) + goto fail; + act->op = LD_OP_LOCK; + act->rt = LD_RT_LV; + act->mode = LD_LK_EX; + act->flags = (LD_AF_ADOPT | LD_AF_PERSISTENT); + act->client_id = INTERNAL_CLIENT_ID; + act->lm_type = ls->lm_type; + strncpy(act->vg_name, ls->vg_name, MAX_NAME); + strncpy(act->lv_uuid, r->name, MAX_NAME); + strncpy(act->lv_args, r->lv_args, MAX_ARGS); + + log_debug("adopt lock for lv %s %s", act->vg_name, act->lv_uuid); + + rv = add_lock_action(act); + if (rv < 0) { + log_error("adopt add_lock_action lv %s %s error %d", act->vg_name, act->lv_uuid, rv); + count_adopt_fail++; + free_action(act); + } else { + count_adopt++; + } + } + + /* + * Adopt orphan VG lock. + */ + + if (!(act = alloc_action())) + goto fail; + act->op = LD_OP_LOCK; + act->rt = LD_RT_VG; + act->mode = LD_LK_SH; + act->flags = LD_AF_ADOPT; + act->client_id = INTERNAL_CLIENT_ID; + act->lm_type = ls->lm_type; + strncpy(act->vg_name, ls->vg_name, MAX_NAME); + + log_debug("adopt lock for vg %s", act->vg_name); + + rv = add_lock_action(act); + if (rv < 0) { + log_error("adopt add_lock_action vg %s error %d", act->vg_name, rv); + count_adopt_fail++; + free_action(act); + } else { + count_adopt++; + } + } + + /* + * Adopt orphan GL lock. + */ + + if (!(act = alloc_action())) + goto fail; + act->op = LD_OP_LOCK; + act->rt = LD_RT_GL; + act->mode = LD_LK_SH; + act->flags = LD_AF_ADOPT; + act->client_id = INTERNAL_CLIENT_ID; + act->lm_type = (gl_use_sanlock ? LD_LM_SANLOCK : LD_LM_DLM); + + log_debug("adopt lock for gl"); + + rv = add_lock_action(act); + if (rv < 0) { + log_error("adopt add_lock_action gl %s error %d", act->vg_name, rv); + count_adopt_fail++; + free_action(act); + } else { + count_adopt++; + } + + /* + * Wait for lock-adopt actions to complete. The completed + * actions are passed back here via the adopt_results list. + */ + + while (count_adopt_done < count_adopt) { + sleep(1); + act = NULL; + + pthread_mutex_lock(&client_mutex); + if (!list_empty(&adopt_results)) { + act = list_first_entry(&adopt_results, struct action, list); + list_del(&act->list); + } + pthread_mutex_unlock(&client_mutex); + + if (!act) + continue; + + /* + * lock adopt results + */ + + if (act->result == -EUCLEAN) { + /* + * Adopt failed because the orphan has a different mode + * than initially requested. Repeat the lock-adopt operation + * with the other mode. N.B. this logic depends on first + * trying sh then ex for GL/VG locks, and ex then sh for + * LV locks. + */ + + if ((act->rt != LD_RT_LV) && (act->mode == LD_LK_SH)) { + /* GL/VG locks: attempt to adopt ex after sh failed. */ + act->mode = LD_LK_EX; + rv = add_lock_action(act); + + } else if ((act->rt == LD_RT_LV) && (act->mode == LD_LK_EX)) { + /* LV locks: attempt to adopt sh after ex failed. */ + act->mode = LD_LK_SH; + rv = add_lock_action(act); + + } else { + log_error("Failed to adopt %s lock in vg %s error %d", + rt_str(act->rt), act->vg_name, act->result); + count_adopt_fail++; + count_adopt_done++; + free_action(act); + rv = 0; + } + + if (rv < 0) { + log_error("adopt add_lock_action again %s", act->vg_name); + count_adopt_fail++; + count_adopt_done++; + free_action(act); + } + + } else if (act->result == -ENOENT) { + /* + * No orphan lock exists. This is common for GL/VG locks + * because they may not have been held when lvmlockd exited. + * It's also expected for LV types that do not use a lock. + */ + + if (act->rt == LD_RT_LV) { + /* Unexpected, we should have found an orphan. */ + log_error("Failed to adopt LV lock for %s %s error %d", + act->vg_name, act->lv_uuid, act->result); + count_adopt_fail++; + } else { + /* Normal, no GL/VG lock was orphaned. */ + log_debug("Did not adopt %s lock in vg %s error %d", + rt_str(act->rt), act->vg_name, act->result); + } + + count_adopt_done++; + free_action(act); + + } else if (act->result < 0) { + /* + * Some unexpected error. + */ + + log_error("adopt lock rt %s vg %s lv %s error %d", + rt_str(act->rt), act->vg_name, act->lv_uuid, act->result); + count_adopt_fail++; + count_adopt_done++; + free_action(act); + + } else { + /* + * Adopt success. + */ + + if (act->rt == LD_RT_LV) { + log_debug("adopt success lv %s %s %s", act->vg_name, act->lv_uuid, mode_str(act->mode)); + free_action(act); + } else if (act->rt == LD_RT_VG) { + log_debug("adopt success vg %s %s", act->vg_name, mode_str(act->mode)); + list_add_tail(&act->list, &to_unlock); + } else if (act->rt == LD_RT_GL) { + log_debug("adopt success gl %s %s", act->vg_name, mode_str(act->mode)); + list_add_tail(&act->list, &to_unlock); + } + count_adopt_done++; + } + } + + /* + * Release adopted GL/VG locks. + * The to_unlock actions were the ones used to lock-adopt the GL/VG locks; + * now use them to do the unlocks. These actions will again be placed + * on adopt_results for us to collect because they have the ADOPT flag set. + */ + + count_adopt = 0; + count_adopt_done = 0; + + list_for_each_entry_safe(act, asafe, &to_unlock, list) { + list_del(&act->list); + + if (act->mode == LD_LK_EX) { + /* + * FIXME: we probably want to check somehow that + * there's no lvm command still running that's + * using this ex lock and changing things. + */ + log_warn("adopt releasing ex %s lock %s", + rt_str(act->rt), act->vg_name); + } + + act->mode = LD_LK_UN; + + log_debug("adopt unlock for %s %s", rt_str(act->rt), act->vg_name); + + rv = add_lock_action(act); + if (rv < 0) { + log_error("adopt unlock add_lock_action error %d", rv); + free_action(act); + } else { + count_adopt++; + } + } + + /* Wait for the unlocks to complete. */ + + while (count_adopt_done < count_adopt) { + sleep(1); + act = NULL; + + pthread_mutex_lock(&client_mutex); + if (!list_empty(&adopt_results)) { + act = list_first_entry(&adopt_results, struct action, list); + list_del(&act->list); + } + pthread_mutex_unlock(&client_mutex); + + if (!act) + continue; + + if (act->result < 0) + log_error("adopt unlock error %d", act->result); + + count_adopt_done++; + free_action(act); + } + + + /* FIXME: purge any remaining orphan locks in each rejoined ls? */ + + if (count_start_fail || count_adopt_fail) + goto fail; + + log_debug("adopt_locks done"); + return; + +fail: + log_error("adopt_locks failed, reset host"); +} + +static int get_peer_pid(int fd) +{ + struct ucred cred; + unsigned int len = sizeof(cred); + + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) + return -1; + + return cred.pid; +} + +static void process_listener(int poll_fd) +{ + struct client *cl; + int fd, pi; + + /* assert poll_fd == listen_fd */ + + fd = accept(listen_fd, NULL, NULL); + if (fd < 0) + return; + + if (!(cl = alloc_client())) { + if (!close(fd)) + log_error("failed to close lockd poll fd"); + return; + } + + pi = add_pollfd(fd); + if (pi < 0) { + log_error("process_listener add_pollfd error %d", pi); + free_client(cl); + return; + } + + cl->pi = pi; + cl->fd = fd; + cl->pid = get_peer_pid(fd); + + pthread_mutex_init(&cl->mutex, NULL); + + pthread_mutex_lock(&client_mutex); + client_ids++; + + if (client_ids == INTERNAL_CLIENT_ID) + client_ids++; + if (!client_ids) + client_ids++; + + cl->id = client_ids; + list_add_tail(&cl->list, &client_list); + pthread_mutex_unlock(&client_mutex); + + log_debug("new cl %u pi %d fd %d", cl->id, cl->pi, cl->fd); +} + +/* + * main loop polls on pipe[0] so that a thread can + * restart the poll by writing to pipe[1]. + */ +static int setup_restart(void) +{ + if (pipe(restart_fds)) { + log_error("setup_restart pipe error %d", errno); + return -1; + } + + restart_pi = add_pollfd(restart_fds[0]); + if (restart_pi < 0) + return restart_pi; + + return 0; +} + +/* + * thread wrote 'w' to restart_fds[1] to restart poll() + * after adding an fd back into pollfd. + */ +static void process_restart(int fd) +{ + char wake[1]; + int rv; + + /* assert fd == restart_fds[0] */ + + rv = read(restart_fds[0], wake, 1); + if (!rv || rv < 0) + log_debug("process_restart error %d", errno); +} + +static void sigterm_handler(int sig __attribute__((unused))) +{ + daemon_quit = 1; +} + +static int main_loop(daemon_state *ds_arg) +{ + struct client *cl; + int i, rv, is_recv, is_dead; + + signal(SIGTERM, &sigterm_handler); + + rv = setup_structs(); + if (rv < 0) { + log_error("Can't allocate memory"); + return rv; + } + + strcpy(gl_lsname_dlm, S_NAME_GL_DLM); + + INIT_LIST_HEAD(&lockspaces); + pthread_mutex_init(&lockspaces_mutex, NULL); + pthread_mutex_init(&pollfd_mutex, NULL); + pthread_mutex_init(&log_mutex, NULL); + + openlog("lvmlockd", LOG_CONS | LOG_PID, LOG_DAEMON); + log_warn("lvmlockd started"); + + listen_fd = ds_arg->socket_fd; + listen_pi = add_pollfd(listen_fd); + + setup_client_thread(); + setup_worker_thread(); + setup_restart(); + + pthread_mutex_init(&lvmetad_mutex, NULL); + lvmetad_handle = lvmetad_open(NULL); + if (lvmetad_handle.error || lvmetad_handle.socket_fd < 0) + log_error("lvmetad_open error %d", lvmetad_handle.error); + else + lvmetad_connected = 1; + + /* + * Attempt to rejoin lockspaces and adopt locks from a previous + * instance of lvmlockd that left behind lockspaces/locks. + */ + if (adopt_opt) + adopt_locks(); + + while (1) { + rv = poll(pollfd, pollfd_maxi + 1, -1); + if ((rv == -1 && errno == EINTR) || daemon_quit) { + if (daemon_quit) { + int count; + /* first sigterm would trigger stops, and + second sigterm may finish the joins. */ + count = for_each_lockspace(DO_STOP, DO_FREE, NO_FORCE); + if (!count) + break; + log_debug("ignore shutdown for %d lockspaces", count); + daemon_quit = 0; + } + continue; + } + if (rv < 0) { + log_error("poll errno %d", errno); + break; + } + + for (i = 0; i <= pollfd_maxi; i++) { + if (pollfd[i].fd < 0) + continue; + + is_recv = 0; + is_dead = 0; + + if (pollfd[i].revents & POLLIN) + is_recv = 1; + if (pollfd[i].revents & (POLLERR | POLLHUP | POLLNVAL)) + is_dead = 1; + + if (!is_recv && !is_dead) + continue; + + if (i == listen_pi) { + process_listener(pollfd[i].fd); + continue; + } + + if (i == restart_pi) { + process_restart(pollfd[i].fd); + continue; + } + + /* + log_debug("poll pi %d fd %d revents %x", + i, pollfd[i].fd, pollfd[i].revents); + */ + + pthread_mutex_lock(&client_mutex); + cl = find_client_pi(i); + if (cl) { + pthread_mutex_lock(&cl->mutex); + + if (cl->recv) { + /* should not happen */ + log_error("main client %u already recv", cl->id); + + } else if (cl->dead) { + /* should not happen */ + log_error("main client %u already dead", cl->id); + + } else if (is_dead) { + log_debug("close %s[%d] cl %u fd %d", + cl->name[0] ? cl->name : "client", + cl->pid, cl->id, cl->fd); + cl->dead = 1; + cl->pi = -1; + cl->fd = -1; + cl->poll_ignore = 0; + if (close(pollfd[i].fd)) + log_error("close fd %d failed", pollfd[i].fd); + pollfd[i].fd = POLL_FD_UNUSED; + pollfd[i].events = 0; + pollfd[i].revents = 0; + + } else if (is_recv) { + cl->recv = 1; + cl->poll_ignore = 1; + pollfd[i].fd = POLL_FD_IGNORE; + pollfd[i].events = 0; + pollfd[i].revents = 0; + } + + pthread_mutex_unlock(&cl->mutex); + + client_work = 1; + pthread_cond_signal(&client_cond); + + /* client_thread will pick up and work on any + client with cl->recv or cl->dead set */ + + } else { + /* don't think this can happen */ + log_error("no client for index %d fd %d", + i, pollfd[i].fd); + if (close(pollfd[i].fd)) + log_error("close fd %d failed", pollfd[i].fd); + pollfd[i].fd = POLL_FD_UNUSED; + pollfd[i].events = 0; + pollfd[i].revents = 0; + } + pthread_mutex_unlock(&client_mutex); + + /* After set_dead, should we scan pollfd for + last unused slot and reduce pollfd_maxi? */ + } + } + + for_each_lockspace_retry(DO_STOP, DO_FREE, DO_FORCE); + close_worker_thread(); + close_client_thread(); + closelog(); + daemon_close(lvmetad_handle); + return 1; /* libdaemon uses 1 for success */ +} + +static void usage(char *prog, FILE *file) +{ + fprintf(file, "Usage:\n"); + fprintf(file, "%s [options]\n\n", prog); + fprintf(file, " --help | -h\n"); + fprintf(file, " Show this help information.\n"); + fprintf(file, " --version | -V\n"); + fprintf(file, " Show version of lvmlockd.\n"); + fprintf(file, " --test | -T\n"); + fprintf(file, " Test mode, do not call lock manager.\n"); + fprintf(file, " --foreground | -f\n"); + fprintf(file, " Don't fork.\n"); + fprintf(file, " --daemon-debug | -D\n"); + fprintf(file, " Don't fork and print debugging to stdout.\n"); + fprintf(file, " --pid-file | -p <path>\n"); + fprintf(file, " Set path to the pid file. [%s]\n", LVMLOCKD_PIDFILE); + fprintf(file, " --socket-path | -s <path>\n"); + fprintf(file, " Set path to the socket to listen on. [%s]\n", LVMLOCKD_SOCKET); + fprintf(file, " --syslog-priority | -S err|warning|debug\n"); + fprintf(file, " Write log messages from this level up to syslog. [%s]\n", _syslog_num_to_name(LOG_SYSLOG_PRIO)); + fprintf(file, " --gl-type | -g <str>\n"); + fprintf(file, " Set global lock type to be dlm|sanlock.\n"); + fprintf(file, " --host-id | -i <num>\n"); + fprintf(file, " Set the local sanlock host id.\n"); + fprintf(file, " --host-id-file | -F <path>\n"); + fprintf(file, " A file containing the local sanlock host_id.\n"); + fprintf(file, " --sanlock-timeout | -o <seconds>\n"); + fprintf(file, " Set the sanlock lockspace I/O timeout.\n"); + fprintf(file, " --adopt | -A 0|1\n"); + fprintf(file, " Adopt locks from a previous instance of lvmlockd.\n"); +} + +int main(int argc, char *argv[]) +{ + daemon_state ds = { + .daemon_main = main_loop, + .daemon_init = NULL, + .daemon_fini = NULL, + .pidfile = getenv("LVM_LVMLOCKD_PIDFILE"), + .socket_path = getenv("LVM_LVMLOCKD_SOCKET"), + .protocol = lvmlockd_protocol, + .protocol_version = lvmlockd_protocol_version, + .name = "lvmlockd", + }; + + static struct option long_options[] = { + {"help", no_argument, 0, 'h' }, + {"version", no_argument, 0, 'V' }, + {"test", no_argument, 0, 'T' }, + {"foreground", no_argument, 0, 'f' }, + {"daemon-debug", no_argument, 0, 'D' }, + {"pid-file", required_argument, 0, 'p' }, + {"socket-path", required_argument, 0, 's' }, + {"gl-type", required_argument, 0, 'g' }, + {"host-id", required_argument, 0, 'i' }, + {"host-id-file", required_argument, 0, 'F' }, + {"adopt", required_argument, 0, 'A' }, + {"syslog-priority", required_argument, 0, 'S' }, + {"sanlock-timeout", required_argument, 0, 'o' }, + {0, 0, 0, 0 } + }; + + while (1) { + int c; + int lm; + int option_index = 0; + + c = getopt_long(argc, argv, "hVTfDp:s:l:g:S:I:A:o:", + long_options, &option_index); + if (c == -1) + break; + + switch (c) { + case '0': + break; + case 'h': + usage(argv[0], stdout); + exit(EXIT_SUCCESS); + case 'V': + printf("lvmlockd version: " LVM_VERSION "\n"); + exit(EXIT_SUCCESS); + case 'T': + daemon_test = 1; + break; + case 'f': + ds.foreground = 1; + break; + case 'D': + ds.foreground = 1; + daemon_debug = 1; + break; + case 'p': + ds.pidfile = strdup(optarg); + break; + case 's': + ds.socket_path = strdup(optarg); + break; + case 'g': + lm = str_to_lm(optarg); + if (lm == LD_LM_DLM && lm_support_dlm()) + gl_use_dlm = 1; + else if (lm == LD_LM_SANLOCK && lm_support_sanlock()) + gl_use_sanlock = 1; + else { + fprintf(stderr, "invalid gl-type option\n"); + exit(EXIT_FAILURE); + } + break; + case 'i': + daemon_host_id = atoi(optarg); + break; + case 'F': + daemon_host_id_file = strdup(optarg); + break; + case 'o': + sanlock_io_timeout = atoi(optarg); + break; + case 'A': + adopt_opt = atoi(optarg); + break; + case 'S': + syslog_priority = _syslog_name_to_num(optarg); + break; + case '?': + default: + usage(argv[0], stdout); + exit(EXIT_FAILURE); + } + } + + if (!ds.pidfile) + ds.pidfile = LVMLOCKD_PIDFILE; + + if (!ds.socket_path) + ds.socket_path = LVMLOCKD_SOCKET; + + /* runs daemon_main/main_loop */ + daemon_start(ds); + + return 0; +}
diff --git a/daemons/lvmlockd/lvmlockd-dlm.c b/daemons/lvmlockd/lvmlockd-dlm.c new file mode 100644 index 0000000..280cf2b --- /dev/null +++ b/daemons/lvmlockd/lvmlockd-dlm.c
@@ -0,0 +1,777 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ + +#define _XOPEN_SOURCE 500 /* pthread */ +#define _ISOC99_SOURCE + +#include "tool.h" + +#include "daemon-server.h" +#include "xlate.h" + +#include "lvmlockd-internal.h" +#include "lvmlockd-client.h" + +/* + * Using synchronous _wait dlm apis so do not define _REENTRANT and + * link with non-threaded version of library, libdlm_lt. + */ +#include "libdlm.h" + +#include <stddef.h> +#include <poll.h> +#include <errno.h> +#include <endian.h> +#include <fcntl.h> +#include <byteswap.h> +#include <syslog.h> +#include <dirent.h> + +struct lm_dlm { + dlm_lshandle_t *dh; +}; + +struct rd_dlm { + struct dlm_lksb lksb; + struct val_blk *vb; +}; + +int lm_data_size_dlm(void) +{ + return sizeof(struct rd_dlm); +} + +/* + * lock_args format + * + * vg_lock_args format for dlm is + * vg_version_string:undefined:cluster_name + * + * lv_lock_args are not used for dlm + * + * version_string is MAJOR.MINOR.PATCH + * undefined may contain ":" + */ + +#define VG_LOCK_ARGS_MAJOR 1 +#define VG_LOCK_ARGS_MINOR 0 +#define VG_LOCK_ARGS_PATCH 0 + +static int dlm_has_lvb_bug; + +static int cluster_name_from_args(char *vg_args, char *clustername) +{ + return last_string_from_args(vg_args, clustername); +} + +static int check_args_version(char *vg_args) +{ + unsigned int major = 0; + int rv; + + rv = version_from_args(vg_args, &major, NULL, NULL); + if (rv < 0) { + log_error("check_args_version %s error %d", vg_args, rv); + return rv; + } + + if (major > VG_LOCK_ARGS_MAJOR) { + log_error("check_args_version %s major %d %d", vg_args, major, VG_LOCK_ARGS_MAJOR); + return -1; + } + + return 0; +} + +/* This will be set after dlm_controld is started. */ +#define DLM_CLUSTER_NAME_PATH "/sys/kernel/config/dlm/cluster/cluster_name" + +static int read_cluster_name(char *clustername) +{ + static const char close_error_msg[] = "read_cluster_name: close_error %d"; + char *n; + int fd; + int rv; + + if (daemon_test) { + sprintf(clustername, "%s", "test"); + return 0; + } + + fd = open(DLM_CLUSTER_NAME_PATH, O_RDONLY); + if (fd < 0) { + log_debug("read_cluster_name: open error %d, check dlm_controld", fd); + return fd; + } + + rv = read(fd, clustername, MAX_ARGS); + if (rv < 0) { + log_error("read_cluster_name: cluster name read error %d, check dlm_controld", fd); + if (close(fd)) + log_error(close_error_msg, fd); + return rv; + } + + n = strstr(clustername, "\n"); + if (n) + *n = '\0'; + if (close(fd)) + log_error(close_error_msg, fd); + return 0; +} + +int lm_init_vg_dlm(char *ls_name, char *vg_name, uint32_t flags, char *vg_args) +{ + char clustername[MAX_ARGS+1]; + char lock_args_version[MAX_ARGS+1]; + int rv; + + memset(clustername, 0, sizeof(clustername)); + memset(lock_args_version, 0, sizeof(lock_args_version)); + + snprintf(lock_args_version, MAX_ARGS, "%u.%u.%u", + VG_LOCK_ARGS_MAJOR, VG_LOCK_ARGS_MINOR, VG_LOCK_ARGS_PATCH); + + rv = read_cluster_name(clustername); + if (rv < 0) + return -EMANAGER; + + if (strlen(clustername) + strlen(lock_args_version) + 2 > MAX_ARGS) { + log_error("init_vg_dlm args too long"); + return -EARGS; + } + + snprintf(vg_args, MAX_ARGS, "%s:%s", lock_args_version, clustername); + rv = 0; + + log_debug("init_vg_dlm done %s vg_args %s", ls_name, vg_args); + return rv; +} + +int lm_prepare_lockspace_dlm(struct lockspace *ls) +{ + char sys_clustername[MAX_ARGS+1]; + char arg_clustername[MAX_ARGS+1]; + uint32_t major = 0, minor = 0, patch = 0; + struct lm_dlm *lmd; + int rv; + + if (daemon_test) + goto skip_args; + + memset(sys_clustername, 0, sizeof(sys_clustername)); + memset(arg_clustername, 0, sizeof(arg_clustername)); + + rv = read_cluster_name(sys_clustername); + if (rv < 0) + return -EMANAGER; + + rv = dlm_kernel_version(&major, &minor, &patch); + if (rv < 0) { + log_error("prepare_lockspace_dlm kernel_version not detected %d", rv); + dlm_has_lvb_bug = 1; + } + + if ((major == 6) && (minor == 0) && (patch == 1)) { + log_debug("dlm kernel version %u.%u.%u has lvb bug", major, minor, patch); + dlm_has_lvb_bug = 1; + } + + if (!ls->vg_args[0]) { + /* global lockspace has no vg args */ + goto skip_args; + } + + rv = check_args_version(ls->vg_args); + if (rv < 0) + return -EARGS; + + rv = cluster_name_from_args(ls->vg_args, arg_clustername); + if (rv < 0) { + log_error("prepare_lockspace_dlm %s no cluster name from args %s", ls->name, ls->vg_args); + return -EARGS; + } + + if (strcmp(sys_clustername, arg_clustername)) { + log_error("prepare_lockspace_dlm %s mismatching cluster names sys %s arg %s", + ls->name, sys_clustername, arg_clustername); + return -EARGS; + } + + skip_args: + lmd = malloc(sizeof(struct lm_dlm)); + if (!lmd) + return -ENOMEM; + + ls->lm_data = lmd; + return 0; +} + +int lm_add_lockspace_dlm(struct lockspace *ls, int adopt) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + + if (daemon_test) + return 0; + + if (adopt) + lmd->dh = dlm_open_lockspace(ls->name); + else + lmd->dh = dlm_new_lockspace(ls->name, 0600, DLM_LSFL_NEWEXCL); + + if (!lmd->dh) { + log_error("add_lockspace_dlm %s adopt %d error", ls->name, adopt); + free(lmd); + ls->lm_data = NULL; + return -1; + } + + return 0; +} + +int lm_rem_lockspace_dlm(struct lockspace *ls, int free_vg) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + int rv; + + if (daemon_test) + goto out; + + /* + * If free_vg is set, it means we are doing vgremove, and we may want + * to tell any other nodes to leave the lockspace. This is not really + * necessary since there should be no harm in having an unused + * lockspace sitting around. A new "notification lock" would need to + * be added with a callback to signal this. + */ + + rv = dlm_release_lockspace(ls->name, lmd->dh, 1); + if (rv < 0) { + log_error("rem_lockspace_dlm error %d", rv); + return rv; + } + out: + free(lmd); + ls->lm_data = NULL; + return 0; +} + +static int lm_add_resource_dlm(struct lockspace *ls, struct resource *r, int with_lock_nl) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + struct rd_dlm *rdd = (struct rd_dlm *)r->lm_data; + uint32_t flags = 0; + char *buf; + int rv; + + if (r->type == LD_RT_GL || r->type == LD_RT_VG) { + buf = malloc(sizeof(struct val_blk) + DLM_LVB_LEN); + if (!buf) + return -ENOMEM; + memset(buf, 0, sizeof(struct val_blk) + DLM_LVB_LEN); + + rdd->vb = (struct val_blk *)buf; + rdd->lksb.sb_lvbptr = buf + sizeof(struct val_blk); + + flags |= LKF_VALBLK; + } + + if (!with_lock_nl) + goto out; + + /* because this is a new NL lock request */ + flags |= LKF_EXPEDITE; + + if (daemon_test) + goto out; + + rv = dlm_ls_lock_wait(lmd->dh, LKM_NLMODE, &rdd->lksb, flags, + r->name, strlen(r->name), + 0, NULL, NULL, NULL); + if (rv < 0) { + log_error("S %s R %s add_resource_dlm lock error %d", ls->name, r->name, rv); + return rv; + } + out: + return 0; +} + +int lm_rem_resource_dlm(struct lockspace *ls, struct resource *r) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + struct rd_dlm *rdd = (struct rd_dlm *)r->lm_data; + struct dlm_lksb *lksb; + int rv = 0; + + if (daemon_test) + goto out; + + lksb = &rdd->lksb; + + if (!lksb->sb_lkid) + goto out; + + rv = dlm_ls_unlock_wait(lmd->dh, lksb->sb_lkid, 0, lksb); + if (rv < 0) { + log_error("S %s R %s rem_resource_dlm unlock error %d", ls->name, r->name, rv); + } + out: + if (rdd->vb) + free(rdd->vb); + + memset(rdd, 0, sizeof(struct rd_dlm)); + r->lm_init = 0; + return rv; +} + +static int to_dlm_mode(int ld_mode) +{ + switch (ld_mode) { + case LD_LK_EX: + return LKM_EXMODE; + case LD_LK_SH: + return LKM_PRMODE; + }; + return -1; +} + +static int lm_adopt_dlm(struct lockspace *ls, struct resource *r, int ld_mode, + struct val_blk *vb_out) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + struct rd_dlm *rdd = (struct rd_dlm *)r->lm_data; + struct dlm_lksb *lksb; + uint32_t flags = 0; + int mode; + int rv; + + memset(vb_out, 0, sizeof(struct val_blk)); + + if (!r->lm_init) { + rv = lm_add_resource_dlm(ls, r, 0); + if (rv < 0) + return rv; + r->lm_init = 1; + } + + lksb = &rdd->lksb; + + flags |= LKF_PERSISTENT; + flags |= LKF_ORPHAN; + + if (rdd->vb) + flags |= LKF_VALBLK; + + mode = to_dlm_mode(ld_mode); + if (mode < 0) { + log_error("adopt_dlm invalid mode %d", ld_mode); + rv = -EINVAL; + goto fail; + } + + log_debug("S %s R %s adopt_dlm", ls->name, r->name); + + if (daemon_test) + return 0; + + /* + * dlm returns 0 for success, -EAGAIN if an orphan is + * found with another mode, and -ENOENT if no orphan. + * + * cast/bast/param are (void *)1 because the kernel + * returns errors if some are null. + */ + + rv = dlm_ls_lockx(lmd->dh, mode, lksb, flags, + r->name, strlen(r->name), 0, + (void *)1, (void *)1, (void *)1, + NULL, NULL); + + if (rv == -1 && errno == -EAGAIN) { + log_debug("S %s R %s adopt_dlm adopt mode %d try other mode", + ls->name, r->name, ld_mode); + rv = -EUCLEAN; + goto fail; + } + if (rv < 0) { + log_debug("S %s R %s adopt_dlm mode %d flags %x error %d errno %d", + ls->name, r->name, mode, flags, rv, errno); + goto fail; + } + + /* + * FIXME: For GL/VG locks we probably want to read the lvb, + * especially if adopting an ex lock, because when we + * release this adopted ex lock we may want to write new + * lvb values based on the current lvb values (at lease + * in the GL case where we increment the current values.) + * + * It should be possible to read the lvb by requesting + * this lock in the same mode it's already in. + */ + + return rv; + + fail: + lm_rem_resource_dlm(ls, r); + return rv; +} + +/* + * Use PERSISTENT so that if lvmlockd exits while holding locks, + * the locks will remain orphaned in the dlm, still protecting what + * they were acquired to protect. + */ + +int lm_lock_dlm(struct lockspace *ls, struct resource *r, int ld_mode, + struct val_blk *vb_out, int adopt) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + struct rd_dlm *rdd = (struct rd_dlm *)r->lm_data; + struct dlm_lksb *lksb; + struct val_blk vb; + uint32_t flags = 0; + int mode; + int rv; + + if (adopt) { + /* When adopting, we don't follow the normal method + of acquiring a NL lock then converting it to the + desired mode. */ + return lm_adopt_dlm(ls, r, ld_mode, vb_out); + } + + if (!r->lm_init) { + rv = lm_add_resource_dlm(ls, r, 1); + if (rv < 0) + return rv; + r->lm_init = 1; + } + + lksb = &rdd->lksb; + + flags |= LKF_CONVERT; + flags |= LKF_NOQUEUE; + flags |= LKF_PERSISTENT; + + if (rdd->vb) + flags |= LKF_VALBLK; + + mode = to_dlm_mode(ld_mode); + if (mode < 0) { + log_error("lock_dlm invalid mode %d", ld_mode); + return -EINVAL; + } + + log_debug("S %s R %s lock_dlm", ls->name, r->name); + + if (daemon_test) { + if (rdd->vb) { + vb_out->version = le16_to_cpu(rdd->vb->version); + vb_out->flags = le16_to_cpu(rdd->vb->flags); + vb_out->r_version = le32_to_cpu(rdd->vb->r_version); + } + return 0; + } + + /* + * The dlm lvb bug means that converting NL->EX will not return + * the latest lvb, so we have to convert NL->PR->EX to reread it. + */ + if (dlm_has_lvb_bug && (ld_mode == LD_LK_EX)) { + rv = dlm_ls_lock_wait(lmd->dh, LKM_PRMODE, lksb, flags, + r->name, strlen(r->name), + 0, NULL, NULL, NULL); + if (rv == -1) { + log_debug("S %s R %s lock_dlm acquire mode PR for %d rv %d", + ls->name, r->name, mode, rv); + goto lockrv; + } + + /* Fall through to request EX. */ + } + + rv = dlm_ls_lock_wait(lmd->dh, mode, lksb, flags, + r->name, strlen(r->name), + 0, NULL, NULL, NULL); +lockrv: + if (rv == -1 && errno == EAGAIN) { + log_debug("S %s R %s lock_dlm acquire mode %d rv EAGAIN", ls->name, r->name, mode); + return -EAGAIN; + } + if (rv < 0) { + log_error("S %s R %s lock_dlm acquire error %d errno %d", ls->name, r->name, rv, errno); + return rv; + } + + if (rdd->vb) { + if (lksb->sb_flags & DLM_SBF_VALNOTVALID) { + log_debug("S %s R %s lock_dlm VALNOTVALID", ls->name, r->name); + memset(rdd->vb, 0, sizeof(struct val_blk)); + memset(vb_out, 0, sizeof(struct val_blk)); + goto out; + } + + /* + * 'vb' contains disk endian values, not host endian. + * It is copied directly to rdd->vb which is also kept + * in disk endian form. + * vb_out is returned to the caller in host endian form. + */ + memcpy(&vb, lksb->sb_lvbptr, sizeof(struct val_blk)); + memcpy(rdd->vb, &vb, sizeof(vb)); + + vb_out->version = le16_to_cpu(vb.version); + vb_out->flags = le16_to_cpu(vb.flags); + vb_out->r_version = le32_to_cpu(vb.r_version); + } +out: + return 0; +} + +int lm_convert_dlm(struct lockspace *ls, struct resource *r, + int ld_mode, uint32_t r_version) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + struct rd_dlm *rdd = (struct rd_dlm *)r->lm_data; + struct dlm_lksb *lksb = &rdd->lksb; + uint32_t mode; + uint32_t flags = 0; + int rv; + + log_debug("S %s R %s convert_dlm", ls->name, r->name); + + flags |= LKF_CONVERT; + flags |= LKF_NOQUEUE; + flags |= LKF_PERSISTENT; + + if (rdd->vb && r_version && (r->mode == LD_LK_EX)) { + if (!rdd->vb->version) { + /* first time vb has been written */ + rdd->vb->version = cpu_to_le16(VAL_BLK_VERSION); + } + rdd->vb->r_version = cpu_to_le32(r_version); + memcpy(lksb->sb_lvbptr, rdd->vb, sizeof(struct val_blk)); + + log_debug("S %s R %s convert_dlm set r_version %u", + ls->name, r->name, r_version); + + flags |= LKF_VALBLK; + } + + mode = to_dlm_mode(ld_mode); + + if (daemon_test) + return 0; + + rv = dlm_ls_lock_wait(lmd->dh, mode, lksb, flags, + r->name, strlen(r->name), + 0, NULL, NULL, NULL); + if (rv == -1 && errno == EAGAIN) { + /* FIXME: When does this happen? Should something different be done? */ + log_error("S %s R %s convert_dlm mode %d rv EAGAIN", ls->name, r->name, mode); + return -EAGAIN; + } + if (rv < 0) { + log_error("S %s R %s convert_dlm error %d", ls->name, r->name, rv); + } + return rv; +} + +int lm_unlock_dlm(struct lockspace *ls, struct resource *r, + uint32_t r_version, uint32_t lmu_flags) +{ + struct lm_dlm *lmd = (struct lm_dlm *)ls->lm_data; + struct rd_dlm *rdd = (struct rd_dlm *)r->lm_data; + struct dlm_lksb *lksb = &rdd->lksb; + struct val_blk vb_prev; + struct val_blk vb_next; + uint32_t flags = 0; + int new_vb = 0; + int rv; + + /* + * Do not set PERSISTENT, because we don't need an orphan + * NL lock to protect anything. + */ + + flags |= LKF_CONVERT; + + if (rdd->vb && (r->mode == LD_LK_EX)) { + + /* vb_prev and vb_next are in disk endian form */ + memcpy(&vb_prev, rdd->vb, sizeof(struct val_blk)); + memcpy(&vb_next, rdd->vb, sizeof(struct val_blk)); + + if (!vb_prev.version) { + vb_next.version = cpu_to_le16(VAL_BLK_VERSION); + new_vb = 1; + } + + if ((lmu_flags & LMUF_FREE_VG) && (r->type == LD_RT_VG)) { + vb_next.flags = cpu_to_le16(VBF_REMOVED); + new_vb = 1; + } + + if (r_version) { + vb_next.r_version = cpu_to_le32(r_version); + new_vb = 1; + } + + if (new_vb) { + memcpy(rdd->vb, &vb_next, sizeof(struct val_blk)); + memcpy(lksb->sb_lvbptr, &vb_next, sizeof(struct val_blk)); + + log_debug("S %s R %s unlock_dlm vb old %x %x %u new %x %x %u", + ls->name, r->name, + le16_to_cpu(vb_prev.version), + le16_to_cpu(vb_prev.flags), + le32_to_cpu(vb_prev.r_version), + le16_to_cpu(vb_next.version), + le16_to_cpu(vb_next.flags), + le32_to_cpu(vb_next.r_version)); + } else { + log_debug("S %s R %s unlock_dlm vb unchanged", ls->name, r->name); + } + + flags |= LKF_VALBLK; + } else { + log_debug("S %s R %s unlock_dlm", ls->name, r->name); + } + + if (daemon_test) + return 0; + + rv = dlm_ls_lock_wait(lmd->dh, LKM_NLMODE, lksb, flags, + r->name, strlen(r->name), + 0, NULL, NULL, NULL); + if (rv < 0) { + log_error("S %s R %s unlock_dlm error %d", ls->name, r->name, rv); + } + + return rv; +} + +/* + * This list could be read from dlm_controld via libdlmcontrol, + * but it's simpler to get it from sysfs. + */ + +#define DLM_LOCKSPACES_PATH "/sys/kernel/config/dlm/cluster/spaces" + +/* + * FIXME: this should be implemented differently. + * It's not nice to use an aspect of the dlm clustering + * implementation, which could change. It would be + * better to do something like use a special lock in the + * lockspace that was held PR by all nodes, and then an + * EX request on it could check if it's started (and + * possibly also notify others to stop it automatically). + * Or, possibly an enhancement to libdlm that would give + * info about lockspace members. + * + * (We could let the VG be removed while others still + * have the lockspace running, which largely works, but + * introduces problems if another VG with the same name is + * recreated while others still have the lockspace running + * for the previous VG. We'd also want a way to clean up + * the stale lockspaces on the others eventually.) + */ + +int lm_hosts_dlm(struct lockspace *ls, int notify) +{ + static const char closedir_err_msg[] = "lm_hosts_dlm: closedir failed"; + char ls_nodes_path[PATH_MAX]; + struct dirent *de; + DIR *ls_dir; + int count = 0; + + if (daemon_test) + return 0; + + memset(ls_nodes_path, 0, sizeof(ls_nodes_path)); + snprintf(ls_nodes_path, PATH_MAX-1, "%s/%s/nodes", + DLM_LOCKSPACES_PATH, ls->name); + + if (!(ls_dir = opendir(ls_nodes_path))) + return -ECONNREFUSED; + + while ((de = readdir(ls_dir))) { + if (de->d_name[0] == '.') + continue; + count++; + } + + if (closedir(ls_dir)) + log_error(closedir_err_msg); + + if (!count) { + log_error("lm_hosts_dlm found no nodes in %s", ls_nodes_path); + return 0; + } + + /* + * Assume that a count of one node represents ourself, + * and any value over one represents other nodes. + */ + + return count - 1; +} + +int lm_get_lockspaces_dlm(struct list_head *ls_rejoin) +{ + static const char closedir_err_msg[] = "lm_get_lockspace_dlm: closedir failed"; + struct lockspace *ls; + struct dirent *de; + DIR *ls_dir; + + if (!(ls_dir = opendir(DLM_LOCKSPACES_PATH))) + return -ECONNREFUSED; + + while ((de = readdir(ls_dir))) { + if (de->d_name[0] == '.') + continue; + + if (strncmp(de->d_name, LVM_LS_PREFIX, strlen(LVM_LS_PREFIX))) + continue; + + if (!(ls = alloc_lockspace())) { + if (closedir(ls_dir)) + log_error(closedir_err_msg); + return -ENOMEM; + } + + ls->lm_type = LD_LM_DLM; + strncpy(ls->name, de->d_name, MAX_NAME); + strncpy(ls->vg_name, ls->name + strlen(LVM_LS_PREFIX), MAX_NAME); + list_add_tail(&ls->list, ls_rejoin); + } + + if (closedir(ls_dir)) + log_error(closedir_err_msg); + return 0; +} + +int lm_is_running_dlm(void) +{ + char sys_clustername[MAX_ARGS+1]; + int rv; + + if (daemon_test) + return gl_use_dlm; + + memset(sys_clustername, 0, sizeof(sys_clustername)); + + rv = read_cluster_name(sys_clustername); + if (rv < 0) + return 0; + return 1; +} +
diff --git a/daemons/lvmlockd/lvmlockd-internal.h b/daemons/lvmlockd/lvmlockd-internal.h new file mode 100644 index 0000000..a2280b8 --- /dev/null +++ b/daemons/lvmlockd/lvmlockd-internal.h
@@ -0,0 +1,605 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ + +#ifndef _LVM_LVMLOCKD_INTERNAL_H +#define _LVM_LVMLOCKD_INTERNAL_H + +#define MAX_NAME 64 +#define MAX_ARGS 64 + +#define R_NAME_GL_DISABLED "_GLLK_disabled" +#define R_NAME_GL "GLLK" +#define R_NAME_VG "VGLK" +#define S_NAME_GL_DLM "lvm_global" +#define LVM_LS_PREFIX "lvm_" /* ls name is prefix + vg_name */ +/* global lockspace name for sanlock is a vg name */ + +/* lock manager types */ +enum { + LD_LM_NONE = 0, + LD_LM_UNUSED = 1, /* place holder so values match lib/locking/lvmlockd.h */ + LD_LM_DLM = 2, + LD_LM_SANLOCK = 3, +}; + +/* operation types */ +enum { + LD_OP_HELLO = 1, + LD_OP_QUIT, + LD_OP_INIT, + LD_OP_FREE, + LD_OP_START, + LD_OP_STOP, + LD_OP_LOCK, + LD_OP_UPDATE, + LD_OP_CLOSE, + LD_OP_ENABLE, + LD_OP_DISABLE, + LD_OP_START_WAIT, + LD_OP_STOP_ALL, + LD_OP_DUMP_INFO, + LD_OP_DUMP_LOG, + LD_OP_RENAME_BEFORE, + LD_OP_RENAME_FINAL, + LD_OP_RUNNING_LM, + LD_OP_FIND_FREE_LOCK, + LD_OP_KILL_VG, + LD_OP_DROP_VG, + LD_OP_BUSY, +}; + +/* resource types */ +enum { + LD_RT_GL = 1, + LD_RT_VG, + LD_RT_LV, +}; + +/* lock modes, more restrictive must be larger value */ +enum { + LD_LK_IV = -1, + LD_LK_UN = 0, + LD_LK_NL = 1, + LD_LK_SH = 2, + LD_LK_EX = 3, +}; + +struct list_head { + struct list_head *next, *prev; +}; + +struct client { + struct list_head list; + pthread_mutex_t mutex; + int pid; + int fd; + int pi; + uint32_t id; + unsigned int recv : 1; + unsigned int dead : 1; + unsigned int poll_ignore : 1; + unsigned int lock_ops : 1; + char name[MAX_NAME+1]; +}; + +#define LD_AF_PERSISTENT 0x00000001 +#define LD_AF_NO_CLIENT 0x00000002 +#define LD_AF_UNLOCK_CANCEL 0x00000004 +#define LD_AF_NEXT_VERSION 0x00000008 +#define LD_AF_WAIT 0x00000010 +#define LD_AF_FORCE 0x00000020 +#define LD_AF_EX_DISABLE 0x00000040 +#define LD_AF_ENABLE 0x00000080 +#define LD_AF_DISABLE 0x00000100 +#define LD_AF_SEARCH_LS 0x00000200 +#define LD_AF_WAIT_STARTING 0x00001000 +#define LD_AF_DUP_GL_LS 0x00002000 +#define LD_AF_ADOPT 0x00010000 +#define LD_AF_WARN_GL_REMOVED 0x00020000 +#define LD_AF_LV_LOCK 0x00040000 +#define LD_AF_LV_UNLOCK 0x00080000 + +/* + * Number of times to repeat a lock request after + * a lock conflict (-EAGAIN) if unspecified in the + * request. + */ +#define DEFAULT_MAX_RETRIES 4 + +struct action { + struct list_head list; + uint32_t client_id; + uint32_t flags; /* LD_AF_ */ + uint32_t version; + uint64_t host_id; + int8_t op; /* operation type LD_OP_ */ + int8_t rt; /* resource type LD_RT_ */ + int8_t mode; /* lock mode LD_LK_ */ + int8_t lm_type; /* lock manager: LM_DLM, LM_SANLOCK */ + int retries; + int max_retries; + int result; + int lm_rv; /* return value from lm_ function */ + char vg_uuid[64]; + char vg_name[MAX_NAME+1]; + char lv_name[MAX_NAME+1]; + char lv_uuid[MAX_NAME+1]; + char vg_args[MAX_ARGS+1]; + char lv_args[MAX_ARGS+1]; + char vg_sysid[MAX_NAME+1]; +}; + +struct resource { + struct list_head list; /* lockspace.resources */ + char name[MAX_NAME+1]; /* vg name or lv name */ + int8_t type; /* resource type LD_RT_ */ + int8_t mode; + unsigned int sh_count; /* number of sh locks on locks list */ + uint32_t version; + uint32_t last_client_id; /* last client_id to lock or unlock resource */ + unsigned int lm_init : 1; /* lm_data is initialized */ + unsigned int adopt : 1; /* temp flag in remove_inactive_lvs */ + unsigned int version_zero_valid : 1; + unsigned int use_vb : 1; + struct list_head locks; + struct list_head actions; + char lv_args[MAX_ARGS+1]; + char lm_data[0]; /* lock manager specific data */ +}; + +#define LD_LF_PERSISTENT 0x00000001 + +struct lock { + struct list_head list; /* resource.locks */ + int8_t mode; /* lock mode LD_LK_ */ + uint32_t version; + uint32_t flags; /* LD_LF_ */ + uint32_t client_id; /* may be 0 for persistent or internal locks */ +}; + +struct lockspace { + struct list_head list; /* lockspaces */ + char name[MAX_NAME+1]; + char vg_name[MAX_NAME+1]; + char vg_uuid[64]; + char vg_args[MAX_ARGS+1]; /* lock manager specific args */ + char vg_sysid[MAX_NAME+1]; + int8_t lm_type; /* lock manager: LM_DLM, LM_SANLOCK */ + void *lm_data; + uint64_t host_id; + uint64_t free_lock_offset; /* start search for free lock here */ + + uint32_t start_client_id; /* client_id that started the lockspace */ + pthread_t thread; /* makes synchronous lock requests */ + pthread_cond_t cond; + pthread_mutex_t mutex; + unsigned int create_fail : 1; + unsigned int create_done : 1; + unsigned int thread_work : 1; + unsigned int thread_stop : 1; + unsigned int thread_done : 1; + unsigned int sanlock_gl_enabled: 1; + unsigned int sanlock_gl_dup: 1; + unsigned int free_vg: 1; + unsigned int kill_vg: 1; + unsigned int drop_vg: 1; + + struct list_head actions; /* new client actions */ + struct list_head resources; /* resource/lock state for gl/vg/lv */ +}; + +/* val_blk version */ +#define VAL_BLK_VERSION 0x0101 + +/* val_blk flags */ +#define VBF_REMOVED 0x0001 + +struct val_blk { + uint16_t version; + uint16_t flags; + uint32_t r_version; +}; + +/* lm_unlock flags */ +#define LMUF_FREE_VG 0x00000001 + +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list; + list->prev = list; +} + +static inline void __list_add(struct list_head *new, + struct list_head *prev, + struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +static inline void __list_del(struct list_head *prev, struct list_head *next) +{ + next->prev = prev; + prev->next = next; +} + +static inline void list_add(struct list_head *new, struct list_head *head) +{ + __list_add(new, head, head->next); +} + +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + __list_add(new, head->prev, head); +} + +static inline void list_del(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); +} + +static inline int list_empty(const struct list_head *head) +{ + return head->next == head; +} + +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +#define list_first_entry(ptr, type, member) \ + list_entry((ptr)->next, type, member) + +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + + +/* to improve readability */ +#define WAIT 1 +#define NO_WAIT 0 +#define FORCE 1 +#define NO_FORCE 0 + +/* + * global variables + */ + +#ifndef EXTERN +#define EXTERN extern +#define INIT(X) +#else +#undef EXTERN +#define EXTERN +#define INIT(X) =X +#endif + +/* + * gl_type_static and gl_use_ are set by command line or config file + * to specify whether the global lock comes from dlm or sanlock. + * Without a static setting, lvmlockd will figure out where the + * global lock should be (but it could get mixed up in cases where + * both sanlock and dlm vgs exist.) + * + * gl_use_dlm means that the gl should come from lockspace gl_lsname_dlm + * gl_use_sanlock means that the gl should come from lockspace gl_lsname_sanlock + * + * gl_use_dlm has precedence over gl_use_sanlock, so if a node sees both + * dlm and sanlock vgs, it will use the dlm gl. + * + * gl_use_ is set when the first evidence of that lm_type is seen + * in any command. + * + * gl_lsname_sanlock is set when the first vg is seen in which an + * enabled gl is exists, or when init_vg creates a vg with gl enabled, + * or when enable_gl is used. + * + * gl_lsname_sanlock is cleared when free_vg deletes a vg with gl enabled + * or when disable_gl matches. + */ + +EXTERN int gl_type_static; +EXTERN int gl_use_dlm; +EXTERN int gl_use_sanlock; +EXTERN int gl_vg_removed; +EXTERN char gl_lsname_dlm[MAX_NAME+1]; +EXTERN char gl_lsname_sanlock[MAX_NAME+1]; +EXTERN int global_dlm_lockspace_exists; + +EXTERN int daemon_test; /* run as much as possible without a live lock manager */ +EXTERN int daemon_debug; +EXTERN int daemon_host_id; +EXTERN const char *daemon_host_id_file; +EXTERN int sanlock_io_timeout; + +/* + * This flag is set to 1 if we see multiple vgs with the global + * lock enabled. While this is set, we return a special flag + * with the vg lock result indicating to the lvm command that + * there is a duplicate gl in the vg which should be resolved. + * While this is set, find_lockspace_name has the side job of + * counting the number of lockspaces with enabled gl's so that + * this can be set back to zero when the duplicates are disabled. + */ +EXTERN int sanlock_gl_dup; + +void log_level(int level, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +#define log_debug(fmt, args...) log_level(LOG_DEBUG, fmt, ##args) +#define log_error(fmt, args...) log_level(LOG_ERR, fmt, ##args) +#define log_warn(fmt, args...) log_level(LOG_WARNING, fmt, ##args) + +struct lockspace *alloc_lockspace(void); +int lockspaces_empty(void); +int last_string_from_args(char *args_in, char *last); +int version_from_args(char *args, unsigned int *major, unsigned int *minor, unsigned int *patch); + +static inline const char *mode_str(int x) +{ + switch (x) { + case LD_LK_IV: + return "iv"; + case LD_LK_UN: + return "un"; + case LD_LK_NL: + return "nl"; + case LD_LK_SH: + return "sh"; + case LD_LK_EX: + return "ex"; + default: + return "."; + }; +} + +#ifdef LOCKDDLM_SUPPORT + +int lm_init_vg_dlm(char *ls_name, char *vg_name, uint32_t flags, char *vg_args); +int lm_prepare_lockspace_dlm(struct lockspace *ls); +int lm_add_lockspace_dlm(struct lockspace *ls, int adopt); +int lm_rem_lockspace_dlm(struct lockspace *ls, int free_vg); +int lm_lock_dlm(struct lockspace *ls, struct resource *r, int ld_mode, + struct val_blk *vb_out, int adopt); +int lm_convert_dlm(struct lockspace *ls, struct resource *r, + int ld_mode, uint32_t r_version); +int lm_unlock_dlm(struct lockspace *ls, struct resource *r, + uint32_t r_version, uint32_t lmu_flags); +int lm_rem_resource_dlm(struct lockspace *ls, struct resource *r); +int lm_get_lockspaces_dlm(struct list_head *ls_rejoin); +int lm_data_size_dlm(void); +int lm_is_running_dlm(void); +int lm_hosts_dlm(struct lockspace *ls, int notify); + +static inline int lm_support_dlm(void) +{ + return 1; +} + +#else + +static inline int lm_init_vg_dlm(char *ls_name, char *vg_name, uint32_t flags, char *vg_args) +{ + return -1; +} + +static inline int lm_prepare_lockspace_dlm(struct lockspace *ls) +{ + return -1; +} + +static inline int lm_add_lockspace_dlm(struct lockspace *ls, int adopt) +{ + return -1; +} + +static inline int lm_rem_lockspace_dlm(struct lockspace *ls, int free_vg) +{ + return -1; +} + +static inline int lm_lock_dlm(struct lockspace *ls, struct resource *r, int ld_mode, + struct val_blk *vb_out, int adopt) +{ + return -1; +} + +static inline int lm_convert_dlm(struct lockspace *ls, struct resource *r, + int ld_mode, uint32_t r_version) +{ + return -1; +} + +static inline int lm_unlock_dlm(struct lockspace *ls, struct resource *r, + uint32_t r_version, uint32_t lmu_flags) +{ + return -1; +} + +static inline int lm_rem_resource_dlm(struct lockspace *ls, struct resource *r) +{ + return -1; +} + +static inline int lm_get_lockspaces_dlm(struct list_head *ls_rejoin) +{ + return -1; +} + +static inline int lm_data_size_dlm(void) +{ + return -1; +} + +static inline int lm_is_running_dlm(void) +{ + return 0; +} + +static inline int lm_support_dlm(void) +{ + return 0; +} + +static inline int lm_hosts_dlm(struct lockspace *ls, int notify) +{ + return 0; +} + +#endif /* dlm support */ + +#ifdef LOCKDSANLOCK_SUPPORT + +int lm_init_vg_sanlock(char *ls_name, char *vg_name, uint32_t flags, char *vg_args); +int lm_init_lv_sanlock(char *ls_name, char *vg_name, char *lv_name, char *vg_args, char *lv_args, uint64_t free_offset); +int lm_free_lv_sanlock(struct lockspace *ls, struct resource *r); +int lm_rename_vg_sanlock(char *ls_name, char *vg_name, uint32_t flags, char *vg_args); +int lm_prepare_lockspace_sanlock(struct lockspace *ls); +int lm_add_lockspace_sanlock(struct lockspace *ls, int adopt); +int lm_rem_lockspace_sanlock(struct lockspace *ls, int free_vg); +int lm_lock_sanlock(struct lockspace *ls, struct resource *r, int ld_mode, + struct val_blk *vb_out, int *retry, int adopt); +int lm_convert_sanlock(struct lockspace *ls, struct resource *r, + int ld_mode, uint32_t r_version); +int lm_unlock_sanlock(struct lockspace *ls, struct resource *r, + uint32_t r_version, uint32_t lmu_flags); +int lm_able_gl_sanlock(struct lockspace *ls, int enable); +int lm_ex_disable_gl_sanlock(struct lockspace *ls); +int lm_hosts_sanlock(struct lockspace *ls, int notify); +int lm_rem_resource_sanlock(struct lockspace *ls, struct resource *r); +int lm_gl_is_enabled(struct lockspace *ls); +int lm_get_lockspaces_sanlock(struct list_head *ls_rejoin); +int lm_data_size_sanlock(void); +int lm_is_running_sanlock(void); +int lm_find_free_lock_sanlock(struct lockspace *ls, uint64_t *free_offset); + +static inline int lm_support_sanlock(void) +{ + return 1; +} + +#else + +static inline int lm_init_vg_sanlock(char *ls_name, char *vg_name, uint32_t flags, char *vg_args) +{ + return -1; +} + +static inline int lm_init_lv_sanlock(char *ls_name, char *vg_name, char *lv_name, char *vg_args, char *lv_args, uint64_t free_offset) +{ + return -1; +} + +static inline int lm_free_lv_sanlock(struct lockspace *ls, struct resource *r) +{ + return -1; +} + +static inline int lm_rename_vg_sanlock(char *ls_name, char *vg_name, uint32_t flags, char *vg_args) +{ + return -1; +} + +static inline int lm_prepare_lockspace_sanlock(struct lockspace *ls) +{ + return -1; +} + +static inline int lm_add_lockspace_sanlock(struct lockspace *ls, int adopt) +{ + return -1; +} + +static inline int lm_rem_lockspace_sanlock(struct lockspace *ls, int free_vg) +{ + return -1; +} + +static inline int lm_lock_sanlock(struct lockspace *ls, struct resource *r, int ld_mode, + struct val_blk *vb_out, int *retry, int adopt) +{ + return -1; +} + +static inline int lm_convert_sanlock(struct lockspace *ls, struct resource *r, + int ld_mode, uint32_t r_version) +{ + return -1; +} + +static inline int lm_unlock_sanlock(struct lockspace *ls, struct resource *r, + uint32_t r_version, uint32_t lmu_flags) +{ + return -1; +} + +static inline int lm_able_gl_sanlock(struct lockspace *ls, int enable) +{ + return -1; +} + +static inline int lm_ex_disable_gl_sanlock(struct lockspace *ls) +{ + return -1; +} + +static inline int lm_hosts_sanlock(struct lockspace *ls, int notify) +{ + return -1; +} + +static inline int lm_rem_resource_sanlock(struct lockspace *ls, struct resource *r) +{ + return -1; +} + +static inline int lm_gl_is_enabled(struct lockspace *ls) +{ + return -1; +} + +static inline int lm_get_lockspaces_sanlock(struct list_head *ls_rejoin) +{ + return -1; +} + +static inline int lm_data_size_sanlock(void) +{ + return -1; +} + +static inline int lm_is_running_sanlock(void) +{ + return 0; +} + +static inline int lm_find_free_lock_sanlock(struct lockspace *ls, uint64_t *free_offset) +{ + return -1; +} + +static inline int lm_support_sanlock(void) +{ + return 0; +} + +#endif /* sanlock support */ + +#endif /* _LVM_LVMLOCKD_INTERNAL_H */
diff --git a/daemons/lvmlockd/lvmlockd-sanlock.c b/daemons/lvmlockd/lvmlockd-sanlock.c new file mode 100644 index 0000000..e344cb1 --- /dev/null +++ b/daemons/lvmlockd/lvmlockd-sanlock.c
@@ -0,0 +1,1863 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + */ + +#define _XOPEN_SOURCE 500 /* pthread */ +#define _ISOC99_SOURCE + +#include "tool.h" + +#include "daemon-server.h" +#include "xlate.h" + +#include "lvmlockd-internal.h" +#include "lvmlockd-client.h" + +#include "sanlock.h" +#include "sanlock_rv.h" +#include "sanlock_admin.h" +#include "sanlock_resource.h" + +#include <stddef.h> +#include <poll.h> +#include <errno.h> +#include <syslog.h> + +/* +------------------------------------------------------------------------------- +For each VG, lvmlockd creates a sanlock lockspace that holds the leases for +that VG. There's a lease for the VG lock, and there's a lease for each active +LV. sanlock maintains (reads/writes) these leases, which exist on storage. +That storage is a hidden LV within the VG: /dev/vg/lvmlock. lvmlockd gives the +path of this internal LV to sanlock, which then reads/writes the leases on it. + +# lvs -a cc -o+uuid + LV VG Attr LSize LV UUID + lv1 cc -wi-a----- 2.00g 7xoDtu-yvNM-iwQx-C94t-BbYs-UzBl-o8hAIa + lv2 cc -wi-a----- 100.00g exxNPX-wZdO-uCNy-yiGa-aJGT-JKVl-arfcYT + [lvmlock] cc -wi-ao---- 256.00m iLpDel-hR0T-hJ3u-rnVo-PcDh-mcjt-sF9egM + +# sanlock status +s lvm_cc:1:/dev/mapper/cc-lvmlock:0 +r lvm_cc:exxNPX-wZdO-uCNy-yiGa-aJGT-JKVl-arfcYT:/dev/mapper/cc-lvmlock:71303168:13 p 26099 +r lvm_cc:7xoDtu-yvNM-iwQx-C94t-BbYs-UzBl-o8hAIa:/dev/mapper/cc-lvmlock:70254592:3 p 26099 + +This shows that sanlock is maintaining leases on /dev/mapper/cc-lvmlock. + +sanlock acquires a lockspace lease when the lockspace is joined, i.e. when the +VG is started by 'vgchange --lock-start cc'. This lockspace lease exists at +/dev/mapper/cc-lvmlock offset 0, and sanlock regularly writes to it to maintain +ownership of it. Joining the lockspace (by acquiring the lockspace lease in +it) then allows standard resource leases to be acquired in the lockspace for +whatever the application wants. lvmlockd uses resource leases for the VG lock +and LV locks. + +sanlock acquires a resource lease for each actual lock that lvm commands use. +Above, there are two LV locks that are held because the two LVs are active. +These are on /dev/mapper/cc-lvmlock at offsets 71303168 and 70254592. sanlock +does not write to these resource leases except when acquiring and releasing +them (e.g. lvchange -ay/-an). The renewal of the lockspace lease maintains +ownership of all the resource leases in the lockspace. + +If the host loses access to the disk that the sanlock lv lives on, then sanlock +can no longer renew its lockspace lease. The lockspace lease will eventually +expire, at which point the host will lose ownership of it, and of all resource +leases it holds in the lockspace. Eventually, other hosts will be able to +acquire those leases. sanlock ensures that another host will not be able to +acquire one of the expired leases until the current host has quit using it. + +It is important that the host "quit using" the leases it is holding if the +sanlock storage is lost and they begin expiring. If the host cannot quit using +the leases and release them within a limited time, then sanlock will use the +local watchdog to forcibly reset the host before any other host can acquire +them. This is severe, but preferable to possibly corrupting the data protected +by the lease. It ensures that two nodes will not be using the same lease at +once. For LV leases, that means that another host will not be able to activate +the LV while another host still has it active. + +sanlock notifies the application that it cannot renew the lockspace lease. The +application needs to quit using all leases in the lockspace and release them as +quickly as possible. In the initial version, lvmlockd ignored this +notification, so sanlock would eventually reach the point where it would use +the local watchdog to reset the host. However, it's better to attempt a +response. If that response succeeds, the host can avoid being reset. If the +response fails, then sanlock will eventually reset the host as the last resort. +sanlock gives the application about 40 seconds to complete its response and +release its leases before resetting the host. + +An application can specify the path and args of a program that sanlock should +run to notify it if the lockspace lease cannot be renewed. This program should +carry out the application's response to the expiring leases: attempt to quit +using the leases and then release them. lvmlockd gives this command to sanlock +for each VG when that VG is started: 'lvmlockctl --kill vg_name' + +If sanlock loses access to lease storage in that VG, it runs lvmlockctl --kill, +which: + +1. Uses syslog to explain what is happening. + +2. Notifies lvmlockd that the VG is being killed, so lvmlockd can + immediatley return an error for this condition if any new lock + requests are made. (This step would not be strictly necessary.) + +3. Attempts to quit using the VG. This is not yet implemented, but + will eventually use blkdeactivate on the VG (or a more forceful + equivalent.) + +4. If step 3 was successful at terminating all use of the VG, then + lvmlockd is told to release all the leases for the VG. If this + is all done without about 40 seconds, the host can avoid being + reset. + +Until steps 3 and 4 are fully implemented, manual steps can be substituted. +This is primarily for testing since the problem needs to be noticed and +responded to in a very short time. The manual alternative to step 3 is to kill +any processes using file systems on LV's in the VG, unmount all file systems on +the LVs, and deactivate all the LVs. Once this is done, the manual alternative +to step 4 is to run 'lvmlockctl --drop vg_name', which tells lvmlockd to +release all the leases for the VG. +------------------------------------------------------------------------------- +*/ + + +/* + * Each lockspace thread has its own sanlock daemon connection. + * If they shared one, sanlock acquire/release calls would be + * serialized. Some aspects of sanlock expect a single connection + * from each pid: signals due to a sanlock_request, and + * acquire/release/convert/inquire. The later can probably be + * addressed with a flag to indicate that the pid field should be + * interpretted as 'ci' (which the caller would need to figure + * out somehow.) + */ + +struct lm_sanlock { + struct sanlk_lockspace ss; + int align_size; + int sock; /* sanlock daemon connection */ +}; + +struct rd_sanlock { + union { + struct sanlk_resource rs; + char buf[sizeof(struct sanlk_resource) + sizeof(struct sanlk_disk)]; + }; + struct val_blk *vb; +}; + +struct sanlk_resourced { + union { + struct sanlk_resource rs; + char buf[sizeof(struct sanlk_resource) + sizeof(struct sanlk_disk)]; + }; +}; + +int lm_data_size_sanlock(void) +{ + return sizeof(struct rd_sanlock); +} + +/* + * lock_args format + * + * vg_lock_args format for sanlock is + * vg_version_string:undefined:lock_lv_name + * + * lv_lock_args format for sanlock is + * lv_version_string:undefined:offset + * + * version_string is MAJOR.MINOR.PATCH + * undefined may contain ":" + * + * If a new version of the lock_args string cannot be + * handled by an old version of lvmlockd, then the + * new lock_args string should contain a larger major number. + */ + +#define VG_LOCK_ARGS_MAJOR 1 +#define VG_LOCK_ARGS_MINOR 0 +#define VG_LOCK_ARGS_PATCH 0 + +#define LV_LOCK_ARGS_MAJOR 1 +#define LV_LOCK_ARGS_MINOR 0 +#define LV_LOCK_ARGS_PATCH 0 + +/* + * offset 0 is lockspace + * offset align_size * 1 is unused + * offset align_size * 2 is unused + * ... + * offset align_size * 64 is unused + * offset align_size * 65 is gl lock + * offset align_size * 66 is vg lock + * offset align_size * 67 is first lv lock + * offset align_size * 68 is second lv lock + * ... + */ + +#define LS_BEGIN 0 +#define GL_LOCK_BEGIN UINT64_C(65) +#define VG_LOCK_BEGIN UINT64_C(66) +#define LV_LOCK_BEGIN UINT64_C(67) + +static uint64_t daemon_test_lv_count; + +static int lock_lv_name_from_args(char *vg_args, char *lock_lv_name) +{ + return last_string_from_args(vg_args, lock_lv_name); +} + +static int lock_lv_offset_from_args(char *lv_args, uint64_t *lock_lv_offset) +{ + char offset_str[MAX_ARGS+1]; + int rv; + + memset(offset_str, 0, sizeof(offset_str)); + + rv = last_string_from_args(lv_args, offset_str); + if (rv < 0) + return rv; + + *lock_lv_offset = strtoull(offset_str, NULL, 10); + return 0; +} + +static int check_args_version(char *args, unsigned int our_major) +{ + unsigned int major = 0; + int rv; + + rv = version_from_args(args, &major, NULL, NULL); + if (rv < 0) { + log_error("check_args_version %s error %d", args, rv); + return rv; + } + + if (major > our_major) { + log_error("check_args_version %s major %u %u", args, major, our_major); + return -1; + } + + return 0; +} + +#define MAX_LINE 64 + +static int read_host_id_file(void) +{ + FILE *file; + char line[MAX_LINE]; + char key_str[MAX_LINE]; + char val_str[MAX_LINE]; + char *key, *val, *sep; + int host_id = 0; + + file = fopen(daemon_host_id_file, "r"); + if (!file) + goto out; + + while (fgets(line, MAX_LINE, file)) { + if (line[0] == '#' || line[0] == '\n') + continue; + + key = line; + sep = strstr(line, "="); + val = sep + 1; + + if (!sep || !val) + continue; + + *sep = '\0'; + memset(key_str, 0, sizeof(key_str)); + memset(val_str, 0, sizeof(val_str)); + (void) sscanf(key, "%s", key_str); + (void) sscanf(val, "%s", val_str); + + if (!strcmp(key_str, "host_id")) { + host_id = atoi(val_str); + break; + } + } + if (fclose(file)) + log_error("failed to close host id file %s", daemon_host_id_file); +out: + log_debug("host_id %d from %s", host_id, daemon_host_id_file); + return host_id; +} + +/* + * vgcreate + * + * For init_vg, vgcreate passes the internal lv name as vg_args. + * This constructs the full/proper vg_args format, containing the + * version and lv name, and returns the real lock_args in vg_args. + */ + +int lm_init_vg_sanlock(char *ls_name, char *vg_name, uint32_t flags, char *vg_args) +{ + struct sanlk_lockspace ss; + struct sanlk_resourced rd; + struct sanlk_disk disk; + char lock_lv_name[MAX_ARGS+1]; + char lock_args_version[MAX_ARGS+1]; + const char *gl_name = NULL; + uint32_t daemon_version; + uint32_t daemon_proto; + uint64_t offset; + int align_size; + int i, rv; + + memset(&ss, 0, sizeof(ss)); + memset(&rd, 0, sizeof(rd)); + memset(&disk, 0, sizeof(disk)); + memset(lock_lv_name, 0, sizeof(lock_lv_name)); + memset(lock_args_version, 0, sizeof(lock_args_version)); + + if (!vg_args || !vg_args[0] || !strcmp(vg_args, "none")) { + log_error("S %s init_vg_san vg_args missing", ls_name); + return -EARGS; + } + + snprintf(lock_args_version, MAX_ARGS, "%u.%u.%u", + VG_LOCK_ARGS_MAJOR, VG_LOCK_ARGS_MINOR, VG_LOCK_ARGS_PATCH); + + /* see comment above about input vg_args being only lock_lv_name */ + snprintf(lock_lv_name, MAX_ARGS, "%s", vg_args); + + if (strlen(lock_lv_name) + strlen(lock_args_version) + 2 > MAX_ARGS) + return -EARGS; + + snprintf(disk.path, SANLK_PATH_LEN-1, "/dev/mapper/%s-%s", vg_name, lock_lv_name); + + log_debug("S %s init_vg_san path %s", ls_name, disk.path); + + if (daemon_test) { + if (!gl_lsname_sanlock[0]) + strncpy(gl_lsname_sanlock, ls_name, MAX_NAME); + snprintf(vg_args, MAX_ARGS, "%s:%s", lock_args_version, lock_lv_name); + return 0; + } + + rv = sanlock_version(0, &daemon_version, &daemon_proto); + if (rv < 0) { + log_error("S %s init_vg_san failed to connect to sanlock daemon", ls_name); + return -EMANAGER; + } + + log_debug("sanlock daemon version %08x proto %08x", + daemon_version, daemon_proto); + + align_size = sanlock_align(&disk); + if (align_size <= 0) { + log_error("S %s init_vg_san bad disk align size %d %s", + ls_name, align_size, disk.path); + return -EARGS; + } + + strncpy(ss.name, ls_name, SANLK_NAME_LEN); + memcpy(ss.host_id_disk.path, disk.path, SANLK_PATH_LEN); + ss.host_id_disk.offset = LS_BEGIN * align_size; + + rv = sanlock_write_lockspace(&ss, 0, 0, sanlock_io_timeout); + if (rv < 0) { + log_error("S %s init_vg_san write_lockspace error %d %s", + ls_name, rv, ss.host_id_disk.path); + return rv; + } + + /* + * We want to create the global lock in the first sanlock vg. + * If other sanlock vgs exist, then one of them must contain + * the gl. If gl_lsname_sanlock is not set, then perhaps + * the sanlock vg with the gl has been removed or has not yet + * been seen. (Would vgcreate get this far in that case?) + * If dlm vgs exist, then we choose to use the dlm gl and + * not a sanlock gl. + */ + + if (flags & LD_AF_ENABLE) + gl_name = R_NAME_GL; + else if (flags & LD_AF_DISABLE) + gl_name = R_NAME_GL_DISABLED; + else if (!gl_use_sanlock || gl_lsname_sanlock[0] || !lockspaces_empty()) + gl_name = R_NAME_GL_DISABLED; + else + gl_name = R_NAME_GL; + + memcpy(rd.rs.lockspace_name, ss.name, SANLK_NAME_LEN); + strncpy(rd.rs.name, gl_name, SANLK_NAME_LEN); + memcpy(rd.rs.disks[0].path, disk.path, SANLK_PATH_LEN); + rd.rs.disks[0].offset = align_size * GL_LOCK_BEGIN; + rd.rs.num_disks = 1; + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (rv < 0) { + log_error("S %s init_vg_san write_resource gl error %d %s", + ls_name, rv, rd.rs.disks[0].path); + return rv; + } + + memcpy(rd.rs.lockspace_name, ss.name, SANLK_NAME_LEN); + strncpy(rd.rs.name, R_NAME_VG, SANLK_NAME_LEN); + memcpy(rd.rs.disks[0].path, disk.path, SANLK_PATH_LEN); + rd.rs.disks[0].offset = align_size * VG_LOCK_BEGIN; + rd.rs.num_disks = 1; + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (rv < 0) { + log_error("S %s init_vg_san write_resource vg error %d %s", + ls_name, rv, rd.rs.disks[0].path); + return rv; + } + + if (!strcmp(gl_name, R_NAME_GL)) + strncpy(gl_lsname_sanlock, ls_name, MAX_NAME); + + snprintf(vg_args, MAX_ARGS, "%s:%s", lock_args_version, lock_lv_name); + + log_debug("S %s init_vg_san done vg_args %s", ls_name, vg_args); + + /* + * Go through all lv resource slots and initialize them with the + * correct lockspace name but a special resource name that indicates + * it is unused. + */ + + memset(&rd, 0, sizeof(rd)); + rd.rs.num_disks = 1; + memcpy(rd.rs.disks[0].path, disk.path, SANLK_PATH_LEN); + strncpy(rd.rs.lockspace_name, ls_name, SANLK_NAME_LEN); + strcpy(rd.rs.name, "#unused"); + + offset = align_size * LV_LOCK_BEGIN; + + log_debug("S %s init_vg_san clearing lv lease areas", ls_name); + + for (i = 0; ; i++) { + rd.rs.disks[0].offset = offset; + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (rv == -EMSGSIZE || rv == -ENOSPC) { + /* This indicates the end of the device is reached. */ + rv = -EMSGSIZE; + break; + } + + if (rv) { + log_error("clear lv resource area %llu error %d", + (unsigned long long)offset, rv); + break; + } + offset += align_size; + } + + return 0; +} + +/* + * lvcreate + * + * The offset at which the lv lease is written is passed + * all the way back to the lvcreate command so that it + * can be saved in the lv's lock_args in the vg metadata. + */ + +int lm_init_lv_sanlock(char *ls_name, char *vg_name, char *lv_name, + char *vg_args, char *lv_args, uint64_t free_offset) +{ + struct sanlk_resourced rd; + char lock_lv_name[MAX_ARGS+1]; + char lock_args_version[MAX_ARGS+1]; + uint64_t offset; + int align_size; + int rv; + + memset(&rd, 0, sizeof(rd)); + memset(lock_lv_name, 0, sizeof(lock_lv_name)); + memset(lock_args_version, 0, sizeof(lock_args_version)); + + rv = lock_lv_name_from_args(vg_args, lock_lv_name); + if (rv < 0) { + log_error("S %s init_lv_san lock_lv_name_from_args error %d %s", + ls_name, rv, vg_args); + return rv; + } + + snprintf(lock_args_version, MAX_ARGS, "%u.%u.%u", + LV_LOCK_ARGS_MAJOR, LV_LOCK_ARGS_MINOR, LV_LOCK_ARGS_PATCH); + + if (daemon_test) { + align_size = 1048576; + snprintf(lv_args, MAX_ARGS, "%s:%llu", + lock_args_version, + (unsigned long long)((align_size * LV_LOCK_BEGIN) + (align_size * daemon_test_lv_count))); + daemon_test_lv_count++; + return 0; + } + + strncpy(rd.rs.lockspace_name, ls_name, SANLK_NAME_LEN); + rd.rs.num_disks = 1; + snprintf(rd.rs.disks[0].path, SANLK_PATH_LEN-1, "/dev/mapper/%s-%s", vg_name, lock_lv_name); + + align_size = sanlock_align(&rd.rs.disks[0]); + if (align_size <= 0) { + log_error("S %s init_lv_san align error %d", ls_name, align_size); + return -EINVAL; + } + + if (free_offset) + offset = free_offset; + else + offset = align_size * LV_LOCK_BEGIN; + rd.rs.disks[0].offset = offset; + + while (1) { + rd.rs.disks[0].offset = offset; + + memset(rd.rs.name, 0, SANLK_NAME_LEN); + + rv = sanlock_read_resource(&rd.rs, 0); + if (rv == -EMSGSIZE || rv == -ENOSPC) { + /* This indicates the end of the device is reached. */ + log_debug("S %s init_lv_san read limit offset %llu", + ls_name, (unsigned long long)offset); + rv = -EMSGSIZE; + return rv; + } + + if (rv && rv != SANLK_LEADER_MAGIC) { + log_error("S %s init_lv_san read error %d offset %llu", + ls_name, rv, (unsigned long long)offset); + break; + } + + if (!strncmp(rd.rs.name, lv_name, SANLK_NAME_LEN)) { + log_error("S %s init_lv_san resource name %s already exists at %llu", + ls_name, lv_name, (unsigned long long)offset); + return -EEXIST; + } + + /* + * If we read newly extended space, it will not be initialized + * with an "#unused" resource, but will return SANLK_LEADER_MAGIC + * indicating an uninitialized paxos structure on disk. + */ + if ((rv == SANLK_LEADER_MAGIC) || !strcmp(rd.rs.name, "#unused")) { + log_debug("S %s init_lv_san %s found unused area at %llu", + ls_name, lv_name, (unsigned long long)offset); + + strncpy(rd.rs.name, lv_name, SANLK_NAME_LEN); + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (!rv) { + snprintf(lv_args, MAX_ARGS, "%s:%llu", + lock_args_version, (unsigned long long)offset); + } else { + log_error("S %s init_lv_san write error %d offset %llu", + ls_name, rv, (unsigned long long)rv); + } + break; + } + + offset += align_size; + } + + return rv; +} + +/* + * Read the lockspace and each resource, replace the lockspace name, + * and write it back. + */ + +int lm_rename_vg_sanlock(char *ls_name, char *vg_name, uint32_t flags, char *vg_args) +{ + struct sanlk_lockspace ss; + struct sanlk_resourced rd; + struct sanlk_disk disk; + char lock_lv_name[MAX_ARGS+1]; + uint64_t offset; + uint32_t io_timeout; + int align_size; + int i, rv; + + memset(&disk, 0, sizeof(disk)); + memset(lock_lv_name, 0, sizeof(lock_lv_name)); + + if (!vg_args || !vg_args[0] || !strcmp(vg_args, "none")) { + log_error("S %s rename_vg_san vg_args missing", ls_name); + return -EINVAL; + } + + rv = lock_lv_name_from_args(vg_args, lock_lv_name); + if (rv < 0) { + log_error("S %s init_lv_san lock_lv_name_from_args error %d %s", + ls_name, rv, vg_args); + return rv; + } + + snprintf(disk.path, SANLK_PATH_LEN-1, "/dev/mapper/%s-%s", vg_name, lock_lv_name); + + log_debug("S %s rename_vg_san path %s", ls_name, disk.path); + + if (daemon_test) + return 0; + + /* FIXME: device is not always ready for us here */ + sleep(1); + + align_size = sanlock_align(&disk); + if (align_size <= 0) { + log_error("S %s rename_vg_san bad align size %d %s", + ls_name, align_size, disk.path); + return -EINVAL; + } + + /* + * Lockspace + */ + + memset(&ss, 0, sizeof(ss)); + memcpy(ss.host_id_disk.path, disk.path, SANLK_PATH_LEN); + ss.host_id_disk.offset = LS_BEGIN * align_size; + + rv = sanlock_read_lockspace(&ss, 0, &io_timeout); + if (rv < 0) { + log_error("S %s rename_vg_san read_lockspace error %d %s", + ls_name, rv, ss.host_id_disk.path); + return rv; + } + + strncpy(ss.name, ls_name, SANLK_NAME_LEN); + + rv = sanlock_write_lockspace(&ss, 0, 0, sanlock_io_timeout); + if (rv < 0) { + log_error("S %s rename_vg_san write_lockspace error %d %s", + ls_name, rv, ss.host_id_disk.path); + return rv; + } + + /* + * GL resource + */ + + memset(&rd, 0, sizeof(rd)); + memcpy(rd.rs.disks[0].path, disk.path, SANLK_PATH_LEN); + rd.rs.disks[0].offset = align_size * GL_LOCK_BEGIN; + rd.rs.num_disks = 1; + + rv = sanlock_read_resource(&rd.rs, 0); + if (rv < 0) { + log_error("S %s rename_vg_san read_resource gl error %d %s", + ls_name, rv, rd.rs.disks[0].path); + return rv; + } + + strncpy(rd.rs.lockspace_name, ss.name, SANLK_NAME_LEN); + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (rv < 0) { + log_error("S %s rename_vg_san write_resource gl error %d %s", + ls_name, rv, rd.rs.disks[0].path); + return rv; + } + + /* + * VG resource + */ + + memset(&rd, 0, sizeof(rd)); + memcpy(rd.rs.disks[0].path, disk.path, SANLK_PATH_LEN); + rd.rs.disks[0].offset = align_size * VG_LOCK_BEGIN; + rd.rs.num_disks = 1; + + rv = sanlock_read_resource(&rd.rs, 0); + if (rv < 0) { + log_error("S %s rename_vg_san write_resource vg error %d %s", + ls_name, rv, rd.rs.disks[0].path); + return rv; + } + + strncpy(rd.rs.lockspace_name, ss.name, SANLK_NAME_LEN); + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (rv < 0) { + log_error("S %s rename_vg_san write_resource vg error %d %s", + ls_name, rv, rd.rs.disks[0].path); + return rv; + } + + /* + * LV resources + */ + + offset = align_size * LV_LOCK_BEGIN; + + for (i = 0; ; i++) { + memset(&rd, 0, sizeof(rd)); + memcpy(rd.rs.disks[0].path, disk.path, SANLK_PATH_LEN); + rd.rs.disks[0].offset = offset; + rd.rs.num_disks = 1; + + rv = sanlock_read_resource(&rd.rs, 0); + if (rv == -EMSGSIZE || rv == -ENOSPC) { + /* This indicates the end of the device is reached. */ + rv = -EMSGSIZE; + break; + } + + if (rv < 0) { + log_error("S %s rename_vg_san read_resource resource area %llu error %d", + ls_name, (unsigned long long)offset, rv); + break; + } + + strncpy(rd.rs.lockspace_name, ss.name, SANLK_NAME_LEN); + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (rv) { + log_error("S %s rename_vg_san write_resource resource area %llu error %d", + ls_name, (unsigned long long)offset, rv); + break; + } + offset += align_size; + } + + return 0; +} + +/* lvremove */ +int lm_free_lv_sanlock(struct lockspace *ls, struct resource *r) +{ + struct rd_sanlock *rds = (struct rd_sanlock *)r->lm_data; + struct sanlk_resource *rs = &rds->rs; + int rv; + + log_debug("S %s R %s free_lv_san", ls->name, r->name); + + if (daemon_test) + return 0; + + strcpy(rs->name, "#unused"); + + rv = sanlock_write_resource(rs, 0, 0, 0); + if (rv < 0) { + log_error("S %s R %s free_lv_san write error %d", + ls->name, r->name, rv); + } + + return rv; +} + +int lm_ex_disable_gl_sanlock(struct lockspace *ls) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct sanlk_resourced rd1; + struct sanlk_resourced rd2; + struct sanlk_resource *rs1; + struct sanlk_resource *rs2; + struct sanlk_resource **rs_args; + int rv; + + if (daemon_test) + return 0; + + rs_args = malloc(2 * sizeof(struct sanlk_resource *)); + if (!rs_args) + return -ENOMEM; + + rs1 = &rd1.rs; + rs2 = &rd2.rs; + + memset(&rd1, 0, sizeof(rd1)); + memset(&rd2, 0, sizeof(rd2)); + + strncpy(rd1.rs.lockspace_name, ls->name, SANLK_NAME_LEN); + strncpy(rd1.rs.name, R_NAME_GL, SANLK_NAME_LEN); + + strncpy(rd2.rs.lockspace_name, ls->name, SANLK_NAME_LEN); + strncpy(rd2.rs.name, R_NAME_GL_DISABLED, SANLK_NAME_LEN); + + rd1.rs.num_disks = 1; + strncpy(rd1.rs.disks[0].path, lms->ss.host_id_disk.path, SANLK_PATH_LEN-1); + rd1.rs.disks[0].offset = lms->align_size * GL_LOCK_BEGIN; + + rv = sanlock_acquire(lms->sock, -1, 0, 1, &rs1, NULL); + if (rv < 0) { + log_error("S %s ex_disable_gl_san acquire error %d", + ls->name, rv); + goto out; + } + + rs_args[0] = rs1; + rs_args[1] = rs2; + + rv = sanlock_release(lms->sock, -1, SANLK_REL_RENAME, 2, rs_args); + if (rv < 0) { + log_error("S %s ex_disable_gl_san release_rename error %d", + ls->name, rv); + } + +out: + free(rs_args); + return rv; +} + +/* + * enable/disable exist because each vg contains a global lock, + * but we only want to use the gl from one of them. The first + * sanlock vg created, has its gl enabled, and subsequent + * sanlock vgs have their gl disabled. If the vg containing the + * gl is removed, the gl from another sanlock vg needs to be + * enabled. Or, if gl in multiple vgs are somehow enabled, we + * want to be able to disable one of them. + * + * Disable works by naming/renaming the gl resource to have a + * name that is different from the predefined name. + * When a host attempts to acquire the gl with its standard + * predefined name, it will fail because the resource's name + * on disk doesn't match. + */ + +int lm_able_gl_sanlock(struct lockspace *ls, int enable) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct sanlk_resourced rd; + const char *gl_name; + int rv; + + if (enable) + gl_name = R_NAME_GL; + else + gl_name = R_NAME_GL_DISABLED; + + if (daemon_test) + goto out; + + memset(&rd, 0, sizeof(rd)); + + strncpy(rd.rs.lockspace_name, ls->name, SANLK_NAME_LEN); + strncpy(rd.rs.name, gl_name, SANLK_NAME_LEN); + + rd.rs.num_disks = 1; + strncpy(rd.rs.disks[0].path, lms->ss.host_id_disk.path, SANLK_PATH_LEN-1); + rd.rs.disks[0].offset = lms->align_size * GL_LOCK_BEGIN; + + rv = sanlock_write_resource(&rd.rs, 0, 0, 0); + if (rv < 0) { + log_error("S %s able_gl %d write_resource gl error %d %s", + ls->name, enable, rv, rd.rs.disks[0].path); + return rv; + } +out: + log_debug("S %s able_gl %s", ls->name, gl_name); + + ls->sanlock_gl_enabled = enable; + + if (enable) + strncpy(gl_lsname_sanlock, ls->name, MAX_NAME); + + if (!enable && !strcmp(gl_lsname_sanlock, ls->name)) + memset(gl_lsname_sanlock, 0, sizeof(gl_lsname_sanlock)); + + return 0; +} + +static int gl_is_enabled(struct lockspace *ls, struct lm_sanlock *lms) +{ + char strname[SANLK_NAME_LEN + 1]; + struct sanlk_resourced rd; + uint64_t offset; + int rv; + + if (daemon_test) + return 1; + + memset(&rd, 0, sizeof(rd)); + + strncpy(rd.rs.lockspace_name, ls->name, SANLK_NAME_LEN); + + /* leave rs.name empty, it is what we're checking */ + + rd.rs.num_disks = 1; + strncpy(rd.rs.disks[0].path, lms->ss.host_id_disk.path, SANLK_PATH_LEN-1); + + offset = lms->align_size * GL_LOCK_BEGIN; + rd.rs.disks[0].offset = offset; + + rv = sanlock_read_resource(&rd.rs, 0); + if (rv < 0) { + log_error("gl_is_enabled read_resource error %d", rv); + return rv; + } + + memset(strname, 0, sizeof(strname)); + memcpy(strname, rd.rs.name, SANLK_NAME_LEN); + + if (!strcmp(strname, R_NAME_GL_DISABLED)) { + return 0; + } + + if (!strcmp(strname, R_NAME_GL)) { + return 1; + } + + log_error("gl_is_enabled invalid gl name %s", strname); + return -1; +} + +int lm_gl_is_enabled(struct lockspace *ls) +{ + int rv; + rv = gl_is_enabled(ls, ls->lm_data); + ls->sanlock_gl_enabled = rv; + return rv; +} + +/* + * This is called at the beginning of lvcreate to + * ensure there is free space for a new LV lock. + * If not, lvcreate will extend the lvmlock lv + * before continuing with creating the new LV. + * This way, lm_init_lv_san() should find a free + * lock (unless the autoextend of lvmlock lv has + * been disabled.) + */ + +int lm_find_free_lock_sanlock(struct lockspace *ls, uint64_t *free_offset) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct sanlk_resourced rd; + uint64_t offset; + int rv; + + if (daemon_test) { + *free_offset = (1048576 * LV_LOCK_BEGIN) + (1048576 * (daemon_test_lv_count + 1)); + return 0; + } + + memset(&rd, 0, sizeof(rd)); + + strncpy(rd.rs.lockspace_name, ls->name, SANLK_NAME_LEN); + rd.rs.num_disks = 1; + strncpy(rd.rs.disks[0].path, lms->ss.host_id_disk.path, SANLK_PATH_LEN-1); + + offset = lms->align_size * LV_LOCK_BEGIN; + + while (1) { + rd.rs.disks[0].offset = offset; + + memset(rd.rs.name, 0, SANLK_NAME_LEN); + + rv = sanlock_read_resource(&rd.rs, 0); + if (rv == -EMSGSIZE || rv == -ENOSPC) { + /* This indicates the end of the device is reached. */ + log_debug("S %s find_free_lock_san read limit offset %llu", + ls->name, (unsigned long long)offset); + return -EMSGSIZE; + } + + /* + * If we read newly extended space, it will not be initialized + * with an "#unused" resource, but will return an error about + * an invalid paxos structure on disk. + */ + if (rv == SANLK_LEADER_MAGIC) { + log_debug("S %s find_free_lock_san found empty area at %llu", + ls->name, (unsigned long long)offset); + *free_offset = offset; + return 0; + } + + if (rv) { + log_error("S %s find_free_lock_san read error %d offset %llu", + ls->name, rv, (unsigned long long)offset); + break; + } + + if (!strcmp(rd.rs.name, "#unused")) { + log_debug("S %s find_free_lock_san found unused area at %llu", + ls->name, (unsigned long long)offset); + *free_offset = offset; + return 0; + } + + offset += lms->align_size; + } + + return rv; +} + +/* + * host A: start_vg/add_lockspace + * host B: vgremove + * + * The global lock cannot always be held around start_vg + * on host A because the gl is in a vg that may not be + * started yet, or may be in the vg we are starting. + * + * If B removes the vg, destroying the delta leases, + * while A is a lockspace member, it will cause A's + * sanlock delta lease renewal to fail, and lockspace + * recovery. + * + * I expect this overlap would usually cause a failure + * in the add_lockspace() on host A when it sees that + * the lockspace structures have been clobbered by B. + * Having add_lockspace() fail should be a fine result. + * + * If add_lockspace was somehow able to finish, the + * subsequent renewal would probably fail instead. + * This should also not create any major problems. + */ + +int lm_prepare_lockspace_sanlock(struct lockspace *ls) +{ + struct stat st; + struct lm_sanlock *lms = NULL; + char lock_lv_name[MAX_ARGS+1]; + char lsname[SANLK_NAME_LEN + 1]; + char disk_path[SANLK_PATH_LEN]; + char killpath[SANLK_PATH_LEN]; + char killargs[SANLK_PATH_LEN]; + int gl_found; + int ret, rv; + + memset(disk_path, 0, sizeof(disk_path)); + memset(lock_lv_name, 0, sizeof(lock_lv_name)); + + /* + * Construct the path to lvmlockctl by using the path to the lvm binary + * and appending "lockctl" to get /path/to/lvmlockctl. + */ + memset(killpath, 0, sizeof(killpath)); + snprintf(killpath, SANLK_PATH_LEN - 1, "%slockctl", LVM_PATH); + + memset(killargs, 0, sizeof(killargs)); + snprintf(killargs, SANLK_PATH_LEN - 1, "--kill %s", ls->vg_name); + + rv = check_args_version(ls->vg_args, VG_LOCK_ARGS_MAJOR); + if (rv < 0) { + ret = -EARGS; + goto fail; + } + + rv = lock_lv_name_from_args(ls->vg_args, lock_lv_name); + if (rv < 0) { + log_error("S %s prepare_lockspace_san lock_lv_name_from_args error %d %s", + ls->name, rv, ls->vg_args); + ret = -EARGS; + goto fail; + } + + snprintf(disk_path, SANLK_PATH_LEN-1, "/dev/mapper/%s-%s", + ls->vg_name, lock_lv_name); + + /* + * When a vg is started, the internal sanlock lv should be + * activated before lvmlockd is asked to add the lockspace. + * (sanlock needs to use the lv.) + * + * In the future we might be able to ask something on the system + * to activate the sanlock lv from here, and with that we might be + * able to start sanlock VGs without requiring a + * vgchange --lock-start command. + */ + + /* FIXME: device is not always ready for us here */ + sleep(1); + + rv = stat(disk_path, &st); + if (rv < 0) { + log_error("S %s prepare_lockspace_san stat error %d disk_path %s", + ls->name, errno, disk_path); + ret = -EARGS; + goto fail; + } + + if (!ls->host_id) { + if (daemon_host_id) + ls->host_id = daemon_host_id; + else if (daemon_host_id_file) + ls->host_id = read_host_id_file(); + } + + if (!ls->host_id || ls->host_id > 2000) { + log_error("S %s prepare_lockspace_san invalid host_id %llu", + ls->name, (unsigned long long)ls->host_id); + ret = -EHOSTID; + goto fail; + } + + lms = malloc(sizeof(struct lm_sanlock)); + if (!lms) { + ret = -ENOMEM; + goto fail; + } + + memset(lsname, 0, sizeof(lsname)); + strncpy(lsname, ls->name, SANLK_NAME_LEN); + + memset(lms, 0, sizeof(struct lm_sanlock)); + memcpy(lms->ss.name, lsname, SANLK_NAME_LEN); + lms->ss.host_id_disk.offset = 0; + lms->ss.host_id = ls->host_id; + strncpy(lms->ss.host_id_disk.path, disk_path, SANLK_PATH_LEN-1); + + if (daemon_test) { + if (!gl_lsname_sanlock[0]) { + strncpy(gl_lsname_sanlock, lsname, MAX_NAME); + log_debug("S %s prepare_lockspace_san use global lock", lsname); + } + goto out; + } + + lms->sock = sanlock_register(); + if (lms->sock < 0) { + log_error("S %s prepare_lockspace_san register error %d", lsname, lms->sock); + lms->sock = 0; + ret = -EMANAGER; + goto fail; + } + + log_debug("set killpath to %s %s", killpath, killargs); + + rv = sanlock_killpath(lms->sock, 0, killpath, killargs); + if (rv < 0) { + log_error("S %s killpath error %d", lsname, rv); + ret = -EMANAGER; + goto fail; + } + + rv = sanlock_restrict(lms->sock, SANLK_RESTRICT_SIGKILL); + if (rv < 0) { + log_error("S %s restrict error %d", lsname, rv); + ret = -EMANAGER; + goto fail; + } + + lms->align_size = sanlock_align(&lms->ss.host_id_disk); + if (lms->align_size <= 0) { + log_error("S %s prepare_lockspace_san align error %d", lsname, lms->align_size); + ret = -EMANAGER; + goto fail; + } + + gl_found = gl_is_enabled(ls, lms); + if (gl_found < 0) { + log_error("S %s prepare_lockspace_san gl_enabled error %d", lsname, gl_found); + ret = -EARGS; + goto fail; + } + + ls->sanlock_gl_enabled = gl_found; + + if (gl_found) { + if (gl_use_dlm) { + log_error("S %s prepare_lockspace_san gl_use_dlm is set", lsname); + } else if (gl_lsname_sanlock[0] && strcmp(gl_lsname_sanlock, lsname)) { + log_error("S %s prepare_lockspace_san multiple sanlock global locks current %s", + lsname, gl_lsname_sanlock); + } else { + strncpy(gl_lsname_sanlock, lsname, MAX_NAME); + log_debug("S %s prepare_lockspace_san use global lock %s", + lsname, gl_lsname_sanlock); + } + } + +out: + ls->lm_data = lms; + log_debug("S %s prepare_lockspace_san done", lsname); + return 0; + +fail: + if (lms && lms->sock) + close(lms->sock); + if (lms) + free(lms); + return ret; +} + +int lm_add_lockspace_sanlock(struct lockspace *ls, int adopt) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + int rv; + + if (daemon_test) { + sleep(2); + goto out; + } + + rv = sanlock_add_lockspace_timeout(&lms->ss, 0, sanlock_io_timeout); + if (rv == -EEXIST && adopt) { + /* We could alternatively just skip the sanlock call for adopt. */ + log_debug("S %s add_lockspace_san adopt found ls", ls->name); + goto out; + } + if (rv < 0) { + /* retry for some errors? */ + log_error("S %s add_lockspace_san add_lockspace error %d", ls->name, rv); + goto fail; + } + + /* + * Don't let the lockspace be cleanly released if orphan locks + * exist, because the orphan locks are still protecting resources + * that are being used on the host, e.g. active lvs. If the + * lockspace is cleanly released, another host could acquire the + * orphan leases. + */ + + rv = sanlock_set_config(ls->name, 0, SANLK_CONFIG_USED_BY_ORPHANS, NULL); + if (rv < 0) { + log_error("S %s add_lockspace_san set_config error %d", ls->name, rv); + sanlock_rem_lockspace(&lms->ss, 0); + goto fail; + } + +out: + log_debug("S %s add_lockspace_san done", ls->name); + return 0; + +fail: + if (close(lms->sock)) + log_error("failed to close sanlock daemon socket connection"); + free(lms); + ls->lm_data = NULL; + return rv; +} + +int lm_rem_lockspace_sanlock(struct lockspace *ls, int free_vg) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + int rv; + + if (daemon_test) + goto out; + + rv = sanlock_rem_lockspace(&lms->ss, 0); + if (rv < 0) { + log_error("S %s rem_lockspace_san error %d", ls->name, rv); + return rv; + } + + if (free_vg) { + /* + * Destroy sanlock lockspace (delta leases). Forces failure for any + * other host that is still using or attempts to use this lockspace. + * This shouldn't be generally necessary, but there may some races + * between nodes starting and removing a vg which this could help. + */ + strncpy(lms->ss.name, "#unused", SANLK_NAME_LEN); + + rv = sanlock_write_lockspace(&lms->ss, 0, 0, sanlock_io_timeout); + if (rv < 0) { + log_error("S %s rem_lockspace free_vg write_lockspace error %d %s", + ls->name, rv, lms->ss.host_id_disk.path); + } + } + + if (close(lms->sock)) + log_error("failed to close sanlock daemon socket connection"); +out: + free(lms); + ls->lm_data = NULL; + + /* FIXME: should we only clear gl_lsname when doing free_vg? */ + + if (!strcmp(ls->name, gl_lsname_sanlock)) + memset(gl_lsname_sanlock, 0, sizeof(gl_lsname_sanlock)); + + return 0; +} + +static int lm_add_resource_sanlock(struct lockspace *ls, struct resource *r) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct rd_sanlock *rds = (struct rd_sanlock *)r->lm_data; + + strncpy(rds->rs.lockspace_name, ls->name, SANLK_NAME_LEN); + strncpy(rds->rs.name, r->name, SANLK_NAME_LEN); + rds->rs.num_disks = 1; + memcpy(rds->rs.disks[0].path, lms->ss.host_id_disk.path, SANLK_PATH_LEN); + + if (r->type == LD_RT_GL) + rds->rs.disks[0].offset = GL_LOCK_BEGIN * lms->align_size; + else if (r->type == LD_RT_VG) + rds->rs.disks[0].offset = VG_LOCK_BEGIN * lms->align_size; + + /* LD_RT_LV offset is set in each lm_lock call from lv_args. */ + + if (r->type == LD_RT_GL || r->type == LD_RT_VG) { + rds->vb = malloc(sizeof(struct val_blk)); + if (!rds->vb) + return -ENOMEM; + memset(rds->vb, 0, sizeof(struct val_blk)); + } + + return 0; +} + +int lm_rem_resource_sanlock(struct lockspace *ls, struct resource *r) +{ + struct rd_sanlock *rds = (struct rd_sanlock *)r->lm_data; + + /* FIXME: assert r->mode == UN or unlock if it's not? */ + + if (rds->vb) + free(rds->vb); + + memset(rds, 0, sizeof(struct rd_sanlock)); + r->lm_init = 0; + return 0; +} + +int lm_lock_sanlock(struct lockspace *ls, struct resource *r, int ld_mode, + struct val_blk *vb_out, int *retry, int adopt) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct rd_sanlock *rds = (struct rd_sanlock *)r->lm_data; + struct sanlk_resource *rs; + struct sanlk_options opt; + uint64_t lock_lv_offset; + uint32_t flags = 0; + struct val_blk vb; + int added = 0; + int rv; + + if (!r->lm_init) { + rv = lm_add_resource_sanlock(ls, r); + if (rv < 0) + return rv; + r->lm_init = 1; + added = 1; + } + + rs = &rds->rs; + + /* + * While there are duplicate global locks, keep checking + * to see if any have been disabled. + */ + if (sanlock_gl_dup && ls->sanlock_gl_enabled && + (r->type == LD_RT_GL || r->type == LD_RT_VG)) + ls->sanlock_gl_enabled = gl_is_enabled(ls, ls->lm_data); + + if (r->type == LD_RT_LV) { + /* + * The lv may have been removed and recreated with a new lease + * offset, so we need to get the offset from lv_args each time + * instead of reusing the value that we last set in rds->rs. + * act->lv_args is copied to r->lv_args before every lm_lock(). + */ + + rv = check_args_version(r->lv_args, LV_LOCK_ARGS_MAJOR); + if (rv < 0) { + log_error("S %s R %s lock_san wrong lv_args version %s", + ls->name, r->name, r->lv_args); + return rv; + } + + rv = lock_lv_offset_from_args(r->lv_args, &lock_lv_offset); + if (rv < 0) { + log_error("S %s R %s lock_san lv_offset_from_args error %d %s", + ls->name, r->name, rv, r->lv_args); + return rv; + } + + if (!added && (rds->rs.disks[0].offset != lock_lv_offset)) { + log_debug("S %s R %s lock_san offset old %llu new %llu", + ls->name, r->name, + (unsigned long long)rds->rs.disks[0].offset, + (unsigned long long)lock_lv_offset); + } + + rds->rs.disks[0].offset = lock_lv_offset; + } + + if (ld_mode == LD_LK_SH) { + rs->flags |= SANLK_RES_SHARED; + } else if (ld_mode == LD_LK_EX) { + rs->flags &= ~SANLK_RES_SHARED; + } else { + log_error("lock_san invalid mode %d", ld_mode); + return -EINVAL; + } + + /* + * Use PERSISTENT because if lvmlockd exits while holding + * a lock, it's not safe to simply clear/drop the lock while + * a command or lv is using it. + */ + + rs->flags |= SANLK_RES_PERSISTENT; + + log_debug("S %s R %s lock_san %s at %s:%llu", + ls->name, r->name, mode_str(ld_mode), rs->disks[0].path, + (unsigned long long)rs->disks[0].offset); + + if (daemon_test) { + if (rds->vb) { + vb_out->version = le16_to_cpu(rds->vb->version); + vb_out->flags = le16_to_cpu(rds->vb->flags); + vb_out->r_version = le32_to_cpu(rds->vb->r_version); + } + return 0; + } + + if (rds->vb) + flags |= SANLK_ACQUIRE_LVB; + if (adopt) + flags |= SANLK_ACQUIRE_ORPHAN_ONLY; + + /* + * Don't block waiting for a failed lease to expire since it causes + * sanlock_acquire to block for a long time, which would prevent this + * thread from processing other lock requests. + */ + flags |= SANLK_ACQUIRE_OWNER_NOWAIT; + + memset(&opt, 0, sizeof(opt)); + sprintf(opt.owner_name, "%s", "lvmlockd"); + + rv = sanlock_acquire(lms->sock, -1, flags, 1, &rs, &opt); + + if (rv == -EAGAIN) { + /* + * It appears that sanlock_acquire returns EAGAIN when we request + * a shared lock but the lock is held ex by another host. + * There's no point in retrying this case, just return an error. + */ + log_debug("S %s R %s lock_san acquire mode %d rv EAGAIN", ls->name, r->name, ld_mode); + *retry = 0; + return -EAGAIN; + } + + if ((rv == -EMSGSIZE) && (r->type == LD_RT_LV)) { + /* + * sanlock tried to read beyond the end of the device, + * so the offset of the lv lease is beyond the end of the + * device, which means that the lease lv was extended, and + * the lease for this lv was allocated in the new space. + * The lvm command will see this error, refresh the lvmlock + * lv, and try again. + */ + log_debug("S %s R %s lock_san acquire offset %llu rv EMSGSIZE", + ls->name, r->name, (unsigned long long)rs->disks[0].offset); + *retry = 0; + return -EMSGSIZE; + } + + if (adopt && (rv == -EUCLEAN)) { + /* + * The orphan lock exists but in a different mode than we asked + * for, so the caller should try again with the other mode. + */ + log_debug("S %s R %s lock_san adopt mode %d try other mode", + ls->name, r->name, ld_mode); + *retry = 0; + return -EUCLEAN; + } + + if (adopt && (rv == -ENOENT)) { + /* + * No orphan lock exists. + */ + log_debug("S %s R %s lock_san adopt mode %d no orphan found", + ls->name, r->name, ld_mode); + *retry = 0; + return -ENOENT; + } + + if (rv == SANLK_ACQUIRE_IDLIVE || rv == SANLK_ACQUIRE_OWNED || rv == SANLK_ACQUIRE_OTHER) { + /* + * The lock is held by another host. These failures can + * happen while multiple hosts are concurrently acquiring + * shared locks. We want to retry a couple times in this + * case because we'll probably get the sh lock. + * + * I believe these are also the errors when requesting an + * ex lock that another host holds ex. We want to report + * something like: "lock is held by another host" in this case. + * Retry is pointless here. + * + * We can't distinguish between the two cases above, + * so if requesting a sh lock, retry a couple times, + * otherwise don't. + */ + log_debug("S %s R %s lock_san acquire mode %d rv %d", ls->name, r->name, ld_mode, rv); + *retry = (ld_mode == LD_LK_SH) ? 1 : 0; + return -EAGAIN; + } + + if (rv == SANLK_ACQUIRE_OWNED_RETRY) { + /* + * The lock is held by a failed host, and will eventually + * expire. If we retry we'll eventually acquire the lock + * (or find someone else has acquired it). The EAGAIN retry + * attempts for SH locks above would not be sufficient for + * the length of expiration time. We could add a longer + * retry time here to cover the full expiration time and block + * the activation command for that long. For now just return + * the standard error indicating that another host still owns + * the lease. FIXME: return a different error number so the + * command can print an different error indicating that the + * owner of the lease is in the process of expiring? + */ + log_debug("S %s R %s lock_san acquire mode %d rv %d", ls->name, r->name, ld_mode, rv); + *retry = 0; + return -EAGAIN; + } + + if (rv < 0) { + log_error("S %s R %s lock_san acquire error %d", + ls->name, r->name, rv); + + /* if the gl has been disabled, remove and free the gl resource */ + if ((rv == SANLK_LEADER_RESOURCE) && (r->type == LD_RT_GL)) { + if (!lm_gl_is_enabled(ls)) { + log_error("S %s R %s lock_san gl has been disabled", + ls->name, r->name); + if (!strcmp(gl_lsname_sanlock, ls->name)) + memset(gl_lsname_sanlock, 0, sizeof(gl_lsname_sanlock)); + return -EUNATCH; + } + } + + if (added) + lm_rem_resource_sanlock(ls, r); + + /* sanlock gets i/o errors trying to read/write the leases. */ + if (rv == -EIO) + rv = -ELOCKIO; + + /* + * The sanlock lockspace can disappear if the lease storage fails, + * the delta lease renewals fail, the lockspace enters recovery, + * lvmlockd holds no leases in the lockspace, so sanlock can + * stop and free the lockspace. + */ + if (rv == -ENOSPC) + rv = -ELOCKIO; + + return rv; + } + + if (rds->vb) { + rv = sanlock_get_lvb(0, rs, (char *)&vb, sizeof(vb)); + if (rv < 0) { + log_error("S %s R %s lock_san get_lvb error %d", ls->name, r->name, rv); + memset(rds->vb, 0, sizeof(struct val_blk)); + memset(vb_out, 0, sizeof(struct val_blk)); + goto out; + } + + /* + * 'vb' contains disk endian values, not host endian. + * It is copied directly to rrs->vb which is also kept + * in disk endian form. + * vb_out is returned to the caller in host endian form. + */ + + memcpy(rds->vb, &vb, sizeof(vb)); + + vb_out->version = le16_to_cpu(vb.version); + vb_out->flags = le16_to_cpu(vb.flags); + vb_out->r_version = le32_to_cpu(vb.r_version); + } +out: + return rv; +} + +int lm_convert_sanlock(struct lockspace *ls, struct resource *r, + int ld_mode, uint32_t r_version) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct rd_sanlock *rds = (struct rd_sanlock *)r->lm_data; + struct sanlk_resource *rs = &rds->rs; + struct val_blk vb; + uint32_t flags = 0; + int rv; + + log_debug("S %s R %s convert_san %s to %s", + ls->name, r->name, mode_str(r->mode), mode_str(ld_mode)); + + if (daemon_test) + goto rs_flag; + + if (rds->vb && r_version && (r->mode == LD_LK_EX)) { + if (!rds->vb->version) { + /* first time vb has been written */ + rds->vb->version = cpu_to_le16(VAL_BLK_VERSION); + } + if (r_version) + rds->vb->r_version = cpu_to_le32(r_version); + memcpy(&vb, rds->vb, sizeof(vb)); + + log_debug("S %s R %s convert_san set r_version %u", + ls->name, r->name, r_version); + + rv = sanlock_set_lvb(0, rs, (char *)&vb, sizeof(vb)); + if (rv < 0) { + log_error("S %s R %s convert_san set_lvb error %d", + ls->name, r->name, rv); + } + } + + rs_flag: + if (ld_mode == LD_LK_SH) + rs->flags |= SANLK_RES_SHARED; + else + rs->flags &= ~SANLK_RES_SHARED; + + if (daemon_test) + return 0; + + rv = sanlock_convert(lms->sock, -1, flags, rs); + if (rv == -EAGAIN) { + /* FIXME: When could this happen? Should something different be done? */ + log_error("S %s R %s convert_san EAGAIN", ls->name, r->name); + return -EAGAIN; + } + if (rv < 0) { + log_error("S %s R %s convert_san convert error %d", ls->name, r->name, rv); + } + + return rv; +} + +static int release_rename(struct lockspace *ls, struct resource *r) +{ + struct rd_sanlock rd1; + struct rd_sanlock rd2; + struct sanlk_resource *res1; + struct sanlk_resource *res2; + struct sanlk_resource **res_args; + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct rd_sanlock *rds = (struct rd_sanlock *)r->lm_data; + int rv; + + log_debug("S %s R %s release rename", ls->name, r->name); + + res_args = malloc(2 * sizeof(struct sanlk_resource *)); + if (!res_args) + return -ENOMEM; + + memcpy(&rd1, rds, sizeof(struct rd_sanlock)); + memcpy(&rd2, rds, sizeof(struct rd_sanlock)); + + res1 = (struct sanlk_resource *)&rd1; + res2 = (struct sanlk_resource *)&rd2; + + strcpy(res2->name, "invalid_removed"); + + res_args[0] = res1; + res_args[1] = res2; + + rv = sanlock_release(lms->sock, -1, SANLK_REL_RENAME, 2, res_args); + if (rv < 0) { + log_error("S %s R %s unlock_san release rename error %d", ls->name, r->name, rv); + } + + free(res_args); + + return rv; +} + +/* + * rds->vb is stored in le + * + * r_version is r->version + * + * for GL locks lvmlockd just increments this value + * each time the global lock is released from ex. + * + * for VG locks it is the seqno from the vg metadata. + */ + +int lm_unlock_sanlock(struct lockspace *ls, struct resource *r, + uint32_t r_version, uint32_t lmu_flags) +{ + struct lm_sanlock *lms = (struct lm_sanlock *)ls->lm_data; + struct rd_sanlock *rds = (struct rd_sanlock *)r->lm_data; + struct sanlk_resource *rs = &rds->rs; + struct val_blk vb; + int rv; + + log_debug("S %s R %s unlock_san %s r_version %u flags %x", + ls->name, r->name, mode_str(r->mode), r_version, lmu_flags); + + if (daemon_test) { + if (rds->vb && r_version && (r->mode == LD_LK_EX)) { + if (!rds->vb->version) + rds->vb->version = cpu_to_le16(VAL_BLK_VERSION); + if (r_version) + rds->vb->r_version = cpu_to_le32(r_version); + } + return 0; + } + + if (rds->vb && r_version && (r->mode == LD_LK_EX)) { + if (!rds->vb->version) { + /* first time vb has been written */ + rds->vb->version = cpu_to_le16(VAL_BLK_VERSION); + } + if (r_version) + rds->vb->r_version = cpu_to_le32(r_version); + memcpy(&vb, rds->vb, sizeof(vb)); + + log_debug("S %s R %s unlock_san set r_version %u", + ls->name, r->name, r_version); + + rv = sanlock_set_lvb(0, rs, (char *)&vb, sizeof(vb)); + if (rv < 0) { + log_error("S %s R %s unlock_san set_lvb error %d", + ls->name, r->name, rv); + } + } + + /* + * For vgremove (FREE_VG) we unlock-rename the vg and gl locks + * so they cannot be reacquired. + */ + if ((lmu_flags & LMUF_FREE_VG) && + (r->type == LD_RT_GL || r->type == LD_RT_VG)) { + return release_rename(ls, r); + } + + rv = sanlock_release(lms->sock, -1, 0, 1, &rs); + if (rv < 0) + log_error("S %s R %s unlock_san release error %d", ls->name, r->name, rv); + + if (rv == -EIO) + rv = -ELOCKIO; + + return rv; +} + +int lm_hosts_sanlock(struct lockspace *ls, int notify) +{ + struct sanlk_host *hss = NULL; + struct sanlk_host *hs; + uint32_t state; + int hss_count = 0; + int found_self = 0; + int found_others = 0; + int i, rv; + + if (daemon_test) + return 0; + + rv = sanlock_get_hosts(ls->name, 0, &hss, &hss_count, 0); + if (rv < 0) { + log_error("S %s hosts_san get_hosts error %d", ls->name, rv); + return 0; + } + + if (!hss || !hss_count) { + log_error("S %s hosts_san zero hosts", ls->name); + return 0; + } + + hs = hss; + + for (i = 0; i < hss_count; i++) { + log_debug("S %s hosts_san host_id %llu gen %llu flags %x", + ls->name, + (unsigned long long)hs->host_id, + (unsigned long long)hs->generation, + hs->flags); + + if (hs->host_id == ls->host_id) { + found_self = 1; + hs++; + continue; + } + + state = hs->flags & SANLK_HOST_MASK; + if (state == SANLK_HOST_LIVE) + found_others++; + hs++; + } + free(hss); + + if (found_others && notify) { + /* + * We could use the sanlock event mechanism to notify lvmlockd + * on other hosts to stop this VG. lvmlockd would need to + * register for and listen for sanlock events in the main loop. + * The events are slow to propagate. We'd need to retry for a + * while before all the hosts see the event and stop the VG. + * sanlock_set_event(ls->name, &he, SANLK_SETEV_ALL_HOSTS); + * + * Wait to try this until there appears to be real value/interest + * in doing it. + */ + } + + if (!found_self) { + log_error("S %s hosts_san self not found others %d", ls->name, found_others); + return 0; + } + + return found_others; +} + +int lm_get_lockspaces_sanlock(struct list_head *ls_rejoin) +{ + struct sanlk_lockspace *ss_all = NULL; + struct sanlk_lockspace *ss; + struct lockspace *ls; + int ss_count = 0; + int i, rv; + + rv = sanlock_get_lockspaces(&ss_all, &ss_count, 0); + if (rv < 0) + return rv; + + if (!ss_all || !ss_count) + return 0; + + ss = ss_all; + + for (i = 0; i < ss_count; i++) { + + if (strncmp(ss->name, LVM_LS_PREFIX, strlen(LVM_LS_PREFIX))) + continue; + + if (!(ls = alloc_lockspace())) + return -ENOMEM; + + ls->lm_type = LD_LM_SANLOCK; + ls->host_id = ss->host_id; + strncpy(ls->name, ss->name, MAX_NAME); + strncpy(ls->vg_name, ss->name + strlen(LVM_LS_PREFIX), MAX_NAME); + list_add_tail(&ls->list, ls_rejoin); + + ss++; + } + + free(ss_all); + return 0; +} + +int lm_is_running_sanlock(void) +{ + uint32_t daemon_version; + uint32_t daemon_proto; + int rv; + + if (daemon_test) + return gl_use_sanlock; + + rv = sanlock_version(0, &daemon_version, &daemon_proto); + if (rv < 0) + return 0; + return 1; +}
diff --git a/daemons/lvmpolld/.gitignore b/daemons/lvmpolld/.gitignore new file mode 100644 index 0000000..4ffad0a --- /dev/null +++ b/daemons/lvmpolld/.gitignore
@@ -0,0 +1 @@ +lvmpolld
diff --git a/daemons/lvmpolld/Makefile.in b/daemons/lvmpolld/Makefile.in new file mode 100644 index 0000000..0bc2861 --- /dev/null +++ b/daemons/lvmpolld/Makefile.in
@@ -0,0 +1,48 @@ +# +# Copyright (C) 2014-2015 Red Hat, Inc. +# +# This file is part of LVM2. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU Lesser General Public License v.2.1. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ + +SOURCES = lvmpolld-core.c lvmpolld-data-utils.c lvmpolld-cmd-utils.c + +TARGETS = lvmpolld + +.PHONY: install_lvmpolld + +CFLOW_LIST = $(SOURCES) +CFLOW_LIST_TARGET = $(LIB_NAME).cflow +CFLOW_TARGET = lvmpolld + +include $(top_builddir)/make.tmpl + +INCLUDES += -I$(top_srcdir)/libdaemon/server +LVMLIBS = -ldaemonserver $(LVMINTERNAL_LIBS) -ldevmapper + +LIBS += $(PTHREAD_LIBS) + +LDFLAGS += -L$(top_builddir)/libdaemon/server $(DAEMON_LDFLAGS) +CLDFLAGS += -L$(top_builddir)/libdaemon/server +CFLAGS += $(DAEMON_CFLAGS) + +lvmpolld: $(OBJECTS) $(top_builddir)/libdaemon/client/libdaemonclient.a \ + $(top_builddir)/libdaemon/server/libdaemonserver.a + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJECTS) $(LVMLIBS) $(LIBS) + +install_lvmpolld: lvmpolld + $(INSTALL_PROGRAM) -D $< $(sbindir)/$(<F) + +install_lvm2: install_lvmpolld + +install: install_lvm2
diff --git a/daemons/lvmpolld/lvmpolld-cmd-utils.c b/daemons/lvmpolld/lvmpolld-cmd-utils.c new file mode 100644 index 0000000..f70fd0d --- /dev/null +++ b/daemons/lvmpolld/lvmpolld-cmd-utils.c
@@ -0,0 +1,144 @@ +/* + * Copyright (C) 2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lvmpolld-common.h" + +/* extract this info from autoconf/automake files */ +#define LVPOLL_CMD "lvpoll" + +#define MIN_ARGV_SIZE 8 + +static const char *const const polling_ops[] = { [PVMOVE] = LVMPD_REQ_PVMOVE, + [CONVERT] = LVMPD_REQ_CONVERT, + [MERGE] = LVMPD_REQ_MERGE, + [MERGE_THIN] = LVMPD_REQ_MERGE_THIN }; + +const char *polling_op(enum poll_type type) +{ + return type < POLL_TYPE_MAX ? polling_ops[type] : "<undefined>"; +} + +static int add_to_cmd_arr(const char ***cmdargv, const char *str, unsigned *ind) +{ + const char **newargv; + + if (*ind && !(*ind % MIN_ARGV_SIZE)) { + newargv = dm_realloc(*cmdargv, (*ind / MIN_ARGV_SIZE + 1) * MIN_ARGV_SIZE * sizeof(char *)); + if (!newargv) + return 0; + *cmdargv = newargv; + } + + *(*cmdargv + (*ind)++) = str; + + return 1; +} + +const char **cmdargv_ctr(const struct lvmpolld_lv *pdlv, const char *lvm_binary, unsigned abort_polling, unsigned handle_missing_pvs) +{ + unsigned i = 0; + const char **cmd_argv = dm_malloc(MIN_ARGV_SIZE * sizeof(char *)); + + if (!cmd_argv) + return NULL; + + /* path to lvm2 binary */ + if (!add_to_cmd_arr(&cmd_argv, lvm_binary, &i)) + goto err; + + /* cmd to execute */ + if (!add_to_cmd_arr(&cmd_argv, LVPOLL_CMD, &i)) + goto err; + + /* transfer internal polling interval */ + if (pdlv->sinterval && + (!add_to_cmd_arr(&cmd_argv, "--interval", &i) || + !add_to_cmd_arr(&cmd_argv, pdlv->sinterval, &i))) + goto err; + + /* pass abort param */ + if (abort_polling && + !add_to_cmd_arr(&cmd_argv, "--abort", &i)) + goto err; + + /* pass handle-missing-pvs. used by mirror polling operation */ + if (handle_missing_pvs && + !add_to_cmd_arr(&cmd_argv, "--handlemissingpvs", &i)) + goto err; + + /* one of: "convert", "pvmove", "merge", "merge_thin" */ + if (!add_to_cmd_arr(&cmd_argv, "--polloperation", &i) || + !add_to_cmd_arr(&cmd_argv, polling_ops[pdlv->type], &i)) + goto err; + + /* vg/lv name */ + if (!add_to_cmd_arr(&cmd_argv, pdlv->lvname, &i)) + goto err; + + /* disable metadata backup */ + if (!add_to_cmd_arr(&cmd_argv, "-An", &i)) + goto err; + + /* terminating NULL */ + if (!add_to_cmd_arr(&cmd_argv, NULL, &i)) + goto err; + + return cmd_argv; +err: + dm_free(cmd_argv); + return NULL; +} + +/* FIXME: in fact exclude should be va list */ +static int copy_env(const char ***cmd_envp, unsigned *i, const char *exclude) +{ + const char * const* tmp = (const char * const*) environ; + + if (!tmp) + return 0; + + while (*tmp) { + if (strncmp(*tmp, exclude, strlen(exclude)) && !add_to_cmd_arr(cmd_envp, *tmp, i)) + return 0; + tmp++; + } + + return 1; +} + +const char **cmdenvp_ctr(const struct lvmpolld_lv *pdlv) +{ + unsigned i = 0; + const char **cmd_envp = dm_malloc(MIN_ARGV_SIZE * sizeof(char *)); + + if (!cmd_envp) + return NULL; + + /* copy whole environment from lvmpolld, exclude LVM_SYSTEM_DIR if set */ + if (!copy_env(&cmd_envp, &i, "LVM_SYSTEM_DIR=")) + goto err; + + /* Add per client LVM_SYSTEM_DIR variable if set */ + if (*pdlv->lvm_system_dir_env && !add_to_cmd_arr(&cmd_envp, pdlv->lvm_system_dir_env, &i)) + goto err; + + /* terminating NULL */ + if (!add_to_cmd_arr(&cmd_envp, NULL, &i)) + goto err; + + return cmd_envp; +err: + dm_free(cmd_envp); + return NULL; +}
diff --git a/daemons/lvmpolld/lvmpolld-cmd-utils.h b/daemons/lvmpolld/lvmpolld-cmd-utils.h new file mode 100644 index 0000000..73a1783 --- /dev/null +++ b/daemons/lvmpolld/lvmpolld-cmd-utils.h
@@ -0,0 +1,25 @@ +/* + * Copyright (C) 2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _LVM_LVMPOLLD_CMD_UTILS_H +#define _LVM_LVMPOLLD_CMD_UTILS_H + +#include "lvmpolld-data-utils.h" + +const char **cmdargv_ctr(const struct lvmpolld_lv *pdlv, const char *lvm_binary, unsigned abort, unsigned handle_missing_pvs); +const char **cmdenvp_ctr(const struct lvmpolld_lv *pdlv); + +const char *polling_op(enum poll_type); + +#endif /* _LVM_LVMPOLLD_CMD_UTILS_H */
diff --git a/daemons/lvmpolld/lvmpolld-common.h b/daemons/lvmpolld/lvmpolld-common.h new file mode 100644 index 0000000..b31081a --- /dev/null +++ b/daemons/lvmpolld/lvmpolld-common.h
@@ -0,0 +1,31 @@ +/* + * Copyright (C) 2010-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * This file must be included first by every lvmpolld source file. + */ +#ifndef _LVM_LVMPOLLD_COMMON_H +#define _LVM_LVMPOLLD_COMMON_H + +#define _REENTRANT + +#include "tool.h" + +#include "lvmpolld-cmd-utils.h" +#include "lvmpolld-protocol.h" + +#include <assert.h> +#include <errno.h> + +#endif /* _LVM_LVMPOLLD_COMMON_H */
diff --git a/daemons/lvmpolld/lvmpolld-core.c b/daemons/lvmpolld/lvmpolld-core.c new file mode 100644 index 0000000..fd73272 --- /dev/null +++ b/daemons/lvmpolld/lvmpolld-core.c
@@ -0,0 +1,999 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lvmpolld-common.h" + +#include "lvm-version.h" +#include "daemon-server.h" +#include "daemon-log.h" + +#include <getopt.h> +#include <poll.h> +#include <wait.h> + +#define LVMPOLLD_SOCKET DEFAULT_RUN_DIR "/lvmpolld.socket" + +#define PD_LOG_PREFIX "LVMPOLLD" +#define LVM2_LOG_PREFIX "\tLVPOLL" + +/* predefined reason for response = "failed" case */ +#define REASON_REQ_NOT_IMPLEMENTED "request not implemented" +#define REASON_MISSING_LVID "request requires lvid set" +#define REASON_MISSING_LVNAME "request requires lvname set" +#define REASON_MISSING_VGNAME "request requires vgname set" +#define REASON_POLLING_FAILED "polling of lvm command failed" +#define REASON_ILLEGAL_ABORT_REQUEST "abort only supported with PVMOVE polling operation" +#define REASON_DIFFERENT_OPERATION_IN_PROGRESS "Different operation on LV already in progress" +#define REASON_INVALID_INTERVAL "request requires interval set" +#define REASON_ENOMEM "not enough memory" + +struct lvmpolld_state { + daemon_idle *idle; + log_state *log; + const char *log_config; + const char *lvm_binary; + + struct lvmpolld_store *id_to_pdlv_abort; + struct lvmpolld_store *id_to_pdlv_poll; +}; + +static pthread_key_t key; + +static const char *_strerror_r(int errnum, struct lvmpolld_thread_data *data) +{ +#ifdef _GNU_SOURCE + return strerror_r(errnum, data->buf, sizeof(data->buf)); /* never returns NULL */ +#elif (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) + return strerror_r(errnum, data->buf, sizeof(data->buf)) ? "" : data->buf; +#else +# warning "Can't decide proper strerror_r implementation. lvmpolld will not issue specific system error messages" + return ""; +#endif +} + +static void _usage(const char *prog, FILE *file) +{ + fprintf(file, "Usage:\n" + "%s [-V] [-h] [-f] [-l {all|wire|debug}] [-s path] [-B path] [-p path] [-t secs]\n" + "%s --dump [-s path]\n" + " -V|--version Show version info\n" + " -h|--help Show this help information\n" + " -f|--foreground Don't fork, run in the foreground\n" + " --dump Dump full lvmpolld state\n" + " -l|--log Logging message level (-l {all|wire|debug})\n" + " -p|--pidfile Set path to the pidfile\n" + " -s|--socket Set path to the communication socket\n" + " -B|--binary Path to lvm2 binary\n" + " -t|--timeout Time to wait in seconds before shutdown on idle (missing or 0 = inifinite)\n\n", prog, prog); +} + +static int _init(struct daemon_state *s) +{ + struct lvmpolld_state *ls = s->private; + ls->log = s->log; + + /* + * log warnings to stderr by default. Otherwise we would miss any lvpoll + * error messages in default configuration + */ + daemon_log_enable(ls->log, DAEMON_LOG_OUTLET_STDERR, DAEMON_LOG_WARN, 1); + + if (!daemon_log_parse(ls->log, DAEMON_LOG_OUTLET_STDERR, ls->log_config, 1)) + return 0; + + if (pthread_key_create(&key, lvmpolld_thread_data_destroy)) { + FATAL(ls, "%s: %s", PD_LOG_PREFIX, "Failed to create pthread key"); + return 0; + } + + ls->id_to_pdlv_poll = pdst_init("polling"); + ls->id_to_pdlv_abort = pdst_init("abort"); + + if (!ls->id_to_pdlv_poll || !ls->id_to_pdlv_abort) { + FATAL(ls, "%s: %s", PD_LOG_PREFIX, "Failed to allocate internal data structures"); + return 0; + } + + ls->lvm_binary = ls->lvm_binary ?: LVM_PATH; + + if (access(ls->lvm_binary, X_OK)) { + FATAL(ls, "%s: %s %s", PD_LOG_PREFIX, "Execute access rights denied on", ls->lvm_binary); + return 0; + } + + if (ls->idle) + ls->idle->is_idle = 1; + + return 1; +} + +static void _lvmpolld_stores_lock(struct lvmpolld_state *ls) +{ + pdst_lock(ls->id_to_pdlv_poll); + pdst_lock(ls->id_to_pdlv_abort); +} + +static void _lvmpolld_stores_unlock(struct lvmpolld_state *ls) +{ + pdst_unlock(ls->id_to_pdlv_abort); + pdst_unlock(ls->id_to_pdlv_poll); +} + +static void _lvmpolld_global_lock(struct lvmpolld_state *ls) +{ + _lvmpolld_stores_lock(ls); + + pdst_locked_lock_all_pdlvs(ls->id_to_pdlv_poll); + pdst_locked_lock_all_pdlvs(ls->id_to_pdlv_abort); +} + +static void _lvmpolld_global_unlock(struct lvmpolld_state *ls) +{ + pdst_locked_unlock_all_pdlvs(ls->id_to_pdlv_abort); + pdst_locked_unlock_all_pdlvs(ls->id_to_pdlv_poll); + + _lvmpolld_stores_unlock(ls); +} + +static int _fini(struct daemon_state *s) +{ + int done; + const struct timespec t = { .tv_nsec = 250000000 }; /* .25 sec */ + struct lvmpolld_state *ls = s->private; + + DEBUGLOG(s, "fini"); + + DEBUGLOG(s, "sending cancel requests"); + + _lvmpolld_global_lock(ls); + pdst_locked_send_cancel(ls->id_to_pdlv_poll); + pdst_locked_send_cancel(ls->id_to_pdlv_abort); + _lvmpolld_global_unlock(ls); + + DEBUGLOG(s, "waiting for background threads to finish"); + + while(1) { + _lvmpolld_stores_lock(ls); + done = !pdst_locked_get_active_count(ls->id_to_pdlv_poll) && + !pdst_locked_get_active_count(ls->id_to_pdlv_abort); + _lvmpolld_stores_unlock(ls); + if (done) + break; + nanosleep(&t, NULL); + } + + DEBUGLOG(s, "destroying internal data structures"); + + _lvmpolld_stores_lock(ls); + pdst_locked_destroy_all_pdlvs(ls->id_to_pdlv_poll); + pdst_locked_destroy_all_pdlvs(ls->id_to_pdlv_abort); + _lvmpolld_stores_unlock(ls); + + pdst_destroy(ls->id_to_pdlv_poll); + pdst_destroy(ls->id_to_pdlv_abort); + + pthread_key_delete(key); + + return 1; +} + +static response reply(const char *res, const char *reason) +{ + return daemon_reply_simple(res, "reason = %s", reason, NULL); +} + +static int read_single_line(struct lvmpolld_thread_data *data, int err) +{ + ssize_t r = getline(&data->line, &data->line_size, err ? data->ferr : data->fout); + + if (r > 0 && *(data->line + r - 1) == '\n') + *(data->line + r - 1) = '\0'; + + return (r > 0); +} + +static void update_idle_state(struct lvmpolld_state *ls) +{ + if (!ls->idle) + return; + + _lvmpolld_stores_lock(ls); + + ls->idle->is_idle = !pdst_locked_get_active_count(ls->id_to_pdlv_poll) && + !pdst_locked_get_active_count(ls->id_to_pdlv_abort); + + _lvmpolld_stores_unlock(ls); + + DEBUGLOG(ls, "%s: %s %s%s", PD_LOG_PREFIX, "daemon is", ls->idle->is_idle ? "" : "not ", "idle"); +} + +/* make this configurable */ +#define MAX_TIMEOUT 2 + +static int poll_for_output(struct lvmpolld_lv *pdlv, struct lvmpolld_thread_data *data) +{ + int ch_stat, r, err = 1, fds_count = 2, timeout = 0; + pid_t pid; + struct lvmpolld_cmd_stat cmd_state = { .retcode = -1, .signal = 0 }; + struct pollfd fds[] = { { .fd = data->outpipe[0], .events = POLLIN }, + { .fd = data->errpipe[0], .events = POLLIN } }; + + if (!(data->fout = fdopen(data->outpipe[0], "r")) || !(data->ferr = fdopen(data->errpipe[0], "r"))) { + ERROR(pdlv->ls, "%s: %s: (%d) %s", PD_LOG_PREFIX, "failed to open file stream", + errno, _strerror_r(errno, data)); + goto out; + } + + while (1) { + do { + r = poll(fds, 2, pdlv_get_timeout(pdlv) * 1000); + } while (r < 0 && errno == EINTR); + + DEBUGLOG(pdlv->ls, "%s: %s %d", PD_LOG_PREFIX, "poll() returned", r); + if (r < 0) { + ERROR(pdlv->ls, "%s: %s (PID %d) failed: (%d) %s", + PD_LOG_PREFIX, "poll() for LVM2 cmd", pdlv->cmd_pid, + errno, _strerror_r(errno, data)); + goto out; + } else if (!r) { + timeout++; + + WARN(pdlv->ls, "%s: %s (PID %d) %s", PD_LOG_PREFIX, + "polling for output of the lvm cmd", pdlv->cmd_pid, + "has timed out"); + + if (timeout > MAX_TIMEOUT) { + ERROR(pdlv->ls, "%s: %s (PID %d) (no output for %d seconds)", + PD_LOG_PREFIX, + "LVM2 cmd is unresponsive too long", + pdlv->cmd_pid, + timeout * pdlv_get_timeout(pdlv)); + goto out; + } + + continue; /* while(1) */ + } + + timeout = 0; + + /* handle the command's STDOUT */ + if (fds[0].revents & POLLIN) { + DEBUGLOG(pdlv->ls, "%s: %s", PD_LOG_PREFIX, "caught input data in STDOUT"); + + assert(read_single_line(data, 0)); /* may block indef. anyway */ + INFO(pdlv->ls, "%s: PID %d: %s: '%s'", LVM2_LOG_PREFIX, + pdlv->cmd_pid, "STDOUT", data->line); + } else if (fds[0].revents) { + if (fds[0].revents & POLLHUP) + DEBUGLOG(pdlv->ls, "%s: %s", PD_LOG_PREFIX, "caught POLLHUP"); + else + WARN(pdlv->ls, "%s: %s", PD_LOG_PREFIX, "poll for command's STDOUT failed"); + + fds[0].fd = -1; + fds_count--; + } + + /* handle the command's STDERR */ + if (fds[1].revents & POLLIN) { + DEBUGLOG(pdlv->ls, "%s: %s", PD_LOG_PREFIX, + "caught input data in STDERR"); + + assert(read_single_line(data, 1)); /* may block indef. anyway */ + WARN(pdlv->ls, "%s: PID %d: %s: '%s'", LVM2_LOG_PREFIX, + pdlv->cmd_pid, "STDERR", data->line); + } else if (fds[1].revents) { + if (fds[1].revents & POLLHUP) + DEBUGLOG(pdlv->ls, "%s: %s", PD_LOG_PREFIX, "caught err POLLHUP"); + else + WARN(pdlv->ls, "%s: %s", PD_LOG_PREFIX, "poll for command's STDOUT failed"); + + fds[1].fd = -1; + fds_count--; + } + + do { + /* + * fds_count == 0 means polling reached EOF + * or received error on both descriptors. + * In such case, just wait for command to finish + */ + pid = waitpid(pdlv->cmd_pid, &ch_stat, fds_count ? WNOHANG : 0); + } while (pid < 0 && errno == EINTR); + + if (pid) { + if (pid < 0) { + ERROR(pdlv->ls, "%s: %s (PID %d) failed: (%d) %s", + PD_LOG_PREFIX, "waitpid() for lvm2 cmd", + pdlv->cmd_pid, errno, + _strerror_r(errno, data)); + goto out; + } + DEBUGLOG(pdlv->ls, "%s: %s", PD_LOG_PREFIX, "child exited"); + break; + } + } /* while(1) */ + + DEBUGLOG(pdlv->ls, "%s: %s", PD_LOG_PREFIX, "about to collect remaining lines"); + if (fds[0].fd >= 0) + while (read_single_line(data, 0)) { + assert(r > 0); + INFO(pdlv->ls, "%s: PID %d: %s: %s", LVM2_LOG_PREFIX, pdlv->cmd_pid, "STDOUT", data->line); + } + if (fds[1].fd >= 0) + while (read_single_line(data, 1)) { + assert(r > 0); + WARN(pdlv->ls, "%s: PID %d: %s: %s", LVM2_LOG_PREFIX, pdlv->cmd_pid, "STDERR", data->line); + } + + if (WIFEXITED(ch_stat)) { + cmd_state.retcode = WEXITSTATUS(ch_stat); + if (cmd_state.retcode) + ERROR(pdlv->ls, "%s: %s (PID %d) %s (retcode: %d)", PD_LOG_PREFIX, + "lvm2 cmd", pdlv->cmd_pid, "failed", cmd_state.retcode); + else + INFO(pdlv->ls, "%s: %s (PID %d) %s", PD_LOG_PREFIX, + "lvm2 cmd", pdlv->cmd_pid, "finished successfully"); + } else if (WIFSIGNALED(ch_stat)) { + ERROR(pdlv->ls, "%s: %s (PID %d) %s (%d)", PD_LOG_PREFIX, + "lvm2 cmd", pdlv->cmd_pid, "got terminated by signal", + WTERMSIG(ch_stat)); + cmd_state.signal = WTERMSIG(ch_stat); + } + + err = 0; +out: + if (!err) + pdlv_set_cmd_state(pdlv, &cmd_state); + + return err; +} + +static void debug_print(struct lvmpolld_state *ls, const char * const* ptr) +{ + const char * const* tmp = ptr; + + if (!tmp) + return; + + while (*tmp) { + DEBUGLOG(ls, "%s: %s", PD_LOG_PREFIX, *tmp); + tmp++; + } +} + +static void *fork_and_poll(void *args) +{ + int outfd, errfd, state; + struct lvmpolld_thread_data *data; + pid_t r; + + int error = 1; + struct lvmpolld_lv *pdlv = (struct lvmpolld_lv *) args; + struct lvmpolld_state *ls = pdlv->ls; + + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &state); + data = lvmpolld_thread_data_constructor(pdlv); + pthread_setspecific(key, data); + pthread_setcancelstate(state, &state); + + if (!data) { + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "Failed to initialize per-thread data"); + goto err; + } + + DEBUGLOG(ls, "%s: %s", PD_LOG_PREFIX, "cmd line arguments:"); + debug_print(ls, pdlv->cmdargv); + DEBUGLOG(ls, "%s: %s", PD_LOG_PREFIX, "---end---"); + + DEBUGLOG(ls, "%s: %s", PD_LOG_PREFIX, "cmd environment variables:"); + debug_print(ls, pdlv->cmdenvp); + DEBUGLOG(ls, "%s: %s", PD_LOG_PREFIX, "---end---"); + + outfd = data->outpipe[1]; + errfd = data->errpipe[1]; + + r = fork(); + if (!r) { + /* child */ + /* !!! Do not touch any posix thread primitives !!! */ + + if ((dup2(outfd, STDOUT_FILENO ) != STDOUT_FILENO) || + (dup2(errfd, STDERR_FILENO ) != STDERR_FILENO)) + _exit(LVMPD_RET_DUP_FAILED); + + execve(*(pdlv->cmdargv), (char *const *)pdlv->cmdargv, (char *const *)pdlv->cmdenvp); + + _exit(LVMPD_RET_EXC_FAILED); + } else { + /* parent */ + if (r == -1) { + ERROR(ls, "%s: %s: (%d) %s", PD_LOG_PREFIX, "fork failed", + errno, _strerror_r(errno, data)); + goto err; + } + + INFO(ls, "%s: LVM2 cmd \"%s\" (PID: %d)", PD_LOG_PREFIX, *(pdlv->cmdargv), r); + + pdlv->cmd_pid = r; + + /* failure to close write end of any pipe will result in broken polling */ + if (close(data->outpipe[1])) { + ERROR(ls, "%s: %s: (%d) %s", PD_LOG_PREFIX, "failed to close write end of pipe", + errno, _strerror_r(errno, data)); + goto err; + } + data->outpipe[1] = -1; + + if (close(data->errpipe[1])) { + ERROR(ls, "%s: %s: (%d) %s", PD_LOG_PREFIX, "failed to close write end of err pipe", + errno, _strerror_r(errno, data)); + goto err; + } + data->errpipe[1] = -1; + + error = poll_for_output(pdlv, data); + DEBUGLOG(ls, "%s: %s", PD_LOG_PREFIX, "polling for lvpoll output has finished"); + } + +err: + r = 0; + + pdst_lock(pdlv->pdst); + + if (error) { + /* last reader is responsible for pdlv cleanup */ + r = pdlv->cmd_pid; + pdlv_set_error(pdlv, 1); + } + + pdlv_set_polling_finished(pdlv, 1); + if (data) + data->pdlv = NULL; + + pdst_locked_dec(pdlv->pdst); + + pdst_unlock(pdlv->pdst); + + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &state); + lvmpolld_thread_data_destroy(data); + pthread_setspecific(key, NULL); + pthread_setcancelstate(state, &state); + + update_idle_state(ls); + + /* + * This is unfortunate case where we + * know nothing about state of lvm cmd and + * (eventually) ongoing progress. + * + * harvest zombies + */ + if (r) + while(waitpid(r, NULL, 0) < 0 && errno == EINTR); + + return NULL; +} + +static response progress_info(client_handle h, struct lvmpolld_state *ls, request req) +{ + char *id; + struct lvmpolld_lv *pdlv; + struct lvmpolld_store *pdst; + struct lvmpolld_lv_state st; + response r; + const char *lvid = daemon_request_str(req, LVMPD_PARM_LVID, NULL); + const char *sysdir = daemon_request_str(req, LVMPD_PARM_SYSDIR, NULL); + unsigned abort_polling = daemon_request_int(req, LVMPD_PARM_ABORT, 0); + + if (!lvid) + return reply(LVMPD_RESP_FAILED, REASON_MISSING_LVID); + + id = construct_id(sysdir, lvid); + if (!id) { + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "progress_info request failed to construct ID."); + return reply(LVMPD_RESP_FAILED, REASON_ENOMEM); + } + + DEBUGLOG(ls, "%s: %s: %s", PD_LOG_PREFIX, "ID", id); + + pdst = abort_polling ? ls->id_to_pdlv_abort : ls->id_to_pdlv_poll; + + pdst_lock(pdst); + + pdlv = pdst_locked_lookup(pdst, id); + if (pdlv) { + /* + * with store lock held, I'm the only reader accessing the pdlv + */ + st = pdlv_get_status(pdlv); + + if (st.error || st.polling_finished) { + INFO(ls, "%s: %s %s", PD_LOG_PREFIX, + "Polling finished. Removing related data structure for LV", + lvid); + pdst_locked_remove(pdst, id); + pdlv_destroy(pdlv); + } + } + /* pdlv must not be dereferenced from now on */ + + pdst_unlock(pdst); + + dm_free(id); + + if (pdlv) { + if (st.error) + return reply(LVMPD_RESP_FAILED, REASON_POLLING_FAILED); + + if (st.polling_finished) + r = daemon_reply_simple(LVMPD_RESP_FINISHED, + "reason = %s", st.cmd_state.signal ? LVMPD_REAS_SIGNAL : LVMPD_REAS_RETCODE, + LVMPD_PARM_VALUE " = " FMTd64, (int64_t)(st.cmd_state.signal ?: st.cmd_state.retcode), + NULL); + else + r = daemon_reply_simple(LVMPD_RESP_IN_PROGRESS, NULL); + } + else + r = daemon_reply_simple(LVMPD_RESP_NOT_FOUND, NULL); + + return r; +} + +static struct lvmpolld_lv *construct_pdlv(request req, struct lvmpolld_state *ls, + struct lvmpolld_store *pdst, + const char *interval, const char *id, + const char *vgname, const char *lvname, + const char *sysdir, enum poll_type type, + unsigned abort_polling, unsigned uinterval) +{ + const char **cmdargv, **cmdenvp; + struct lvmpolld_lv *pdlv; + unsigned handle_missing_pvs = daemon_request_int(req, LVMPD_PARM_HANDLE_MISSING_PVS, 0); + + pdlv = pdlv_create(ls, id, vgname, lvname, sysdir, type, + interval, uinterval, pdst); + + if (!pdlv) { + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "failed to create internal LV data structure."); + return NULL; + } + + cmdargv = cmdargv_ctr(pdlv, pdlv->ls->lvm_binary, abort_polling, handle_missing_pvs); + if (!cmdargv) { + pdlv_destroy(pdlv); + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "failed to construct cmd arguments for lvpoll command"); + return NULL; + } + + pdlv->cmdargv = cmdargv; + + cmdenvp = cmdenvp_ctr(pdlv); + if (!cmdenvp) { + pdlv_destroy(pdlv); + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "failed to construct cmd environment for lvpoll command"); + return NULL; + } + + pdlv->cmdenvp = cmdenvp; + + return pdlv; +} + +static int spawn_detached_thread(struct lvmpolld_lv *pdlv) +{ + int r; + pthread_attr_t attr; + + if (pthread_attr_init(&attr) != 0) + return 0; + + if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) + return 0; + + r = pthread_create(&pdlv->tid, &attr, fork_and_poll, (void *)pdlv); + + if (pthread_attr_destroy(&attr) != 0) + return 0; + + return !r; +} + +static response poll_init(client_handle h, struct lvmpolld_state *ls, request req, enum poll_type type) +{ + char *id; + struct lvmpolld_lv *pdlv; + struct lvmpolld_store *pdst; + unsigned uinterval; + + const char *interval = daemon_request_str(req, LVMPD_PARM_INTERVAL, NULL); + const char *lvid = daemon_request_str(req, LVMPD_PARM_LVID, NULL); + const char *lvname = daemon_request_str(req, LVMPD_PARM_LVNAME, NULL); + const char *vgname = daemon_request_str(req, LVMPD_PARM_VGNAME, NULL); + const char *sysdir = daemon_request_str(req, LVMPD_PARM_SYSDIR, NULL); + unsigned abort_polling = daemon_request_int(req, LVMPD_PARM_ABORT, 0); + + assert(type < POLL_TYPE_MAX); + + if (abort_polling && type != PVMOVE) + return reply(LVMPD_RESP_EINVAL, REASON_ILLEGAL_ABORT_REQUEST); + + if (!interval || strpbrk(interval, "-") || sscanf(interval, "%u", &uinterval) != 1) + return reply(LVMPD_RESP_EINVAL, REASON_INVALID_INTERVAL); + + if (!lvname) + return reply(LVMPD_RESP_FAILED, REASON_MISSING_LVNAME); + + if (!lvid) + return reply(LVMPD_RESP_FAILED, REASON_MISSING_LVID); + + if (!vgname) + return reply(LVMPD_RESP_FAILED, REASON_MISSING_VGNAME); + + id = construct_id(sysdir, lvid); + if (!id) { + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "poll_init request failed to construct ID."); + return reply(LVMPD_RESP_FAILED, REASON_ENOMEM); + } + + DEBUGLOG(ls, "%s: %s=%s", PD_LOG_PREFIX, "ID", id); + + pdst = abort_polling ? ls->id_to_pdlv_abort : ls->id_to_pdlv_poll; + + pdst_lock(pdst); + + pdlv = pdst_locked_lookup(pdst, id); + if (pdlv && pdlv_get_polling_finished(pdlv)) { + WARN(ls, "%s: %s %s", PD_LOG_PREFIX, "Force removal of uncollected info for LV", + lvid); + /* + * lvmpolld has to remove uncollected results in this case. + * otherwise it would have to refuse request for new polling + * lv with same id. + */ + pdst_locked_remove(pdst, id); + pdlv_destroy(pdlv); + pdlv = NULL; + } + + if (pdlv) { + if (!pdlv_is_type(pdlv, type)) { + pdst_unlock(pdst); + ERROR(ls, "%s: %s '%s': expected: %s, requested: %s", + PD_LOG_PREFIX, "poll operation type mismatch on LV identified by", + id, + polling_op(pdlv_get_type(pdlv)), polling_op(type)); + dm_free(id); + return reply(LVMPD_RESP_EINVAL, + REASON_DIFFERENT_OPERATION_IN_PROGRESS); + } + pdlv->init_rq_count++; /* safe. protected by store lock */ + } else { + pdlv = construct_pdlv(req, ls, pdst, interval, id, vgname, + lvname, sysdir, type, abort_polling, 2 * uinterval); + if (!pdlv) { + pdst_unlock(pdst); + dm_free(id); + return reply(LVMPD_RESP_FAILED, REASON_ENOMEM); + } + if (!pdst_locked_insert(pdst, id, pdlv)) { + pdlv_destroy(pdlv); + pdst_unlock(pdst); + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "couldn't store internal LV data structure"); + dm_free(id); + return reply(LVMPD_RESP_FAILED, REASON_ENOMEM); + } + if (!spawn_detached_thread(pdlv)) { + ERROR(ls, "%s: %s", PD_LOG_PREFIX, "failed to spawn detached monitoring thread"); + pdst_locked_remove(pdst, id); + pdlv_destroy(pdlv); + pdst_unlock(pdst); + dm_free(id); + return reply(LVMPD_RESP_FAILED, REASON_ENOMEM); + } + + pdst_locked_inc(pdst); + if (ls->idle) + ls->idle->is_idle = 0; + } + + pdst_unlock(pdst); + + dm_free(id); + + return daemon_reply_simple(LVMPD_RESP_OK, NULL); +} + +static response dump_state(client_handle h, struct lvmpolld_state *ls, request r) +{ + response res = { 0 }; + struct buffer *b = &res.buffer; + + buffer_init(b); + + _lvmpolld_global_lock(ls); + + buffer_append(b, "# Registered polling operations\n\n"); + buffer_append(b, "poll {\n"); + pdst_locked_dump(ls->id_to_pdlv_poll, b); + buffer_append(b, "}\n\n"); + + buffer_append(b, "# Registered abort operations\n\n"); + buffer_append(b, "abort {\n"); + pdst_locked_dump(ls->id_to_pdlv_abort, b); + buffer_append(b, "}"); + + _lvmpolld_global_unlock(ls); + + return res; +} + +static response _handler(struct daemon_state s, client_handle h, request r) +{ + struct lvmpolld_state *ls = s.private; + const char *rq = daemon_request_str(r, "request", "NONE"); + + if (!strcmp(rq, LVMPD_REQ_PVMOVE)) + return poll_init(h, ls, r, PVMOVE); + else if (!strcmp(rq, LVMPD_REQ_CONVERT)) + return poll_init(h, ls, r, CONVERT); + else if (!strcmp(rq, LVMPD_REQ_MERGE)) + return poll_init(h, ls, r, MERGE); + else if (!strcmp(rq, LVMPD_REQ_MERGE_THIN)) + return poll_init(h, ls, r, MERGE_THIN); + else if (!strcmp(rq, LVMPD_REQ_PROGRESS)) + return progress_info(h, ls, r); + else if (!strcmp(rq, LVMPD_REQ_DUMP)) + return dump_state(h, ls, r); + else + return reply(LVMPD_RESP_EINVAL, REASON_REQ_NOT_IMPLEMENTED); +} + +static int process_timeout_arg(const char *str, unsigned *max_timeouts) +{ + char *endptr; + unsigned long l; + + errno = 0; + l = strtoul(str, &endptr, 10); + if (errno || *endptr || l >= UINT_MAX) + return 0; + + *max_timeouts = (unsigned) l; + + return 1; +} + +/* Client functionality */ +typedef int (*action_fn_t) (void *args); + +struct log_line_baton { + const char *prefix; +}; + +daemon_handle _lvmpolld = { .error = 0 }; + +static daemon_handle _lvmpolld_open(const char *socket) +{ + daemon_info lvmpolld_info = { + .path = "lvmpolld", + .socket = socket ?: DEFAULT_RUN_DIR "/lvmpolld.socket", + .protocol = LVMPOLLD_PROTOCOL, + .protocol_version = LVMPOLLD_PROTOCOL_VERSION + }; + + return daemon_open(lvmpolld_info); +} + +static void _log_line(const char *line, void *baton) { + struct log_line_baton *b = baton; + fprintf(stdout, "%s%s\n", b->prefix, line); +} + +static int printout_raw_response(const char *prefix, const char *msg) +{ + struct log_line_baton b = { .prefix = prefix }; + char *buf; + char *pos; + + buf = dm_strdup(msg); + pos = buf; + + if (!buf) + return 0; + + while (pos) { + char *next = strchr(pos, '\n'); + if (next) + *next = 0; + _log_line(pos, &b); + pos = next ? next + 1 : 0; + } + dm_free(buf); + + return 1; +} + +/* place all action implementations below */ + +static int action_dump(void *args __attribute__((unused))) +{ + daemon_request req; + daemon_reply repl; + int r = 0; + + req = daemon_request_make(LVMPD_REQ_DUMP); + if (!req.cft) { + fprintf(stderr, "Failed to create lvmpolld " LVMPD_REQ_DUMP " request.\n"); + goto out_req; + } + + repl = daemon_send(_lvmpolld, req); + if (repl.error) { + fprintf(stderr, "Failed to send a request or receive response.\n"); + goto out_rep; + } + + /* + * This is dumb copy & paste from libdaemon log routines. + */ + if (!printout_raw_response(" ", repl.buffer.mem)) { + fprintf(stderr, "Failed to print out the response.\n"); + goto out_rep; + } + + r = 1; + +out_rep: + daemon_reply_destroy(repl); +out_req: + daemon_request_destroy(req); + + return r; +} + +enum action_index { + ACTION_DUMP = 0, + ACTION_MAX /* keep at the end */ +}; + +static const action_fn_t actions[ACTION_MAX] = { [ACTION_DUMP] = action_dump }; + +static int _make_action(enum action_index idx, void *args) +{ + return idx < ACTION_MAX ? actions[idx](args) : 0; +} + +static int _lvmpolld_client(const char *socket, unsigned action) +{ + int r; + + _lvmpolld = _lvmpolld_open(socket); + + if (_lvmpolld.error || _lvmpolld.socket_fd < 0) { + fprintf(stderr, "Failed to establish connection with lvmpolld.\n"); + return 0; + } + + r = _make_action(action, NULL); + + daemon_close(_lvmpolld); + + return r ? EXIT_SUCCESS : EXIT_FAILURE; +} + +static int action_idx = ACTION_MAX; +static struct option long_options[] = { + /* Have actions always at the beginning of the array. */ + {"dump", no_argument, &action_idx, ACTION_DUMP }, /* or an option_index ? */ + + /* other options */ + {"binary", required_argument, 0, 'B' }, + {"foreground", no_argument, 0, 'f' }, + {"help", no_argument, 0, 'h' }, + {"log", required_argument, 0, 'l' }, + {"pidfile", required_argument, 0, 'p' }, + {"socket", required_argument, 0, 's' }, + {"timeout", required_argument, 0, 't' }, + {"version", no_argument, 0, 'V' }, + {0, 0, 0, 0 } +}; + +int main(int argc, char *argv[]) +{ + int opt; + int option_index = 0; + int client = 0, server = 0; + unsigned action = ACTION_MAX; + struct timeval timeout; + daemon_idle di = { .ptimeout = &timeout }; + struct lvmpolld_state ls = { .log_config = "" }; + daemon_state s = { + .daemon_fini = _fini, + .daemon_init = _init, + .handler = _handler, + .name = "lvmpolld", + .pidfile = getenv("LVM_LVMPOLLD_PIDFILE") ?: LVMPOLLD_PIDFILE, + .private = &ls, + .protocol = LVMPOLLD_PROTOCOL, + .protocol_version = LVMPOLLD_PROTOCOL_VERSION, + .socket_path = getenv("LVM_LVMPOLLD_SOCKET") ?: LVMPOLLD_SOCKET, + }; + + while ((opt = getopt_long(argc, argv, "fhVl:p:s:B:t:", long_options, &option_index)) != -1) { + switch (opt) { + case 0 : + if (action < ACTION_MAX) { + fprintf(stderr, "Can't perform more actions. Action already requested: %s\n", + long_options[action].name); + _usage(argv[0], stderr); + exit(EXIT_FAILURE); + } + action = action_idx; + client = 1; + break; + case '?': + _usage(argv[0], stderr); + exit(EXIT_FAILURE); + case 'B': /* --binary */ + ls.lvm_binary = optarg; + server = 1; + break; + case 'V': /* --version */ + printf("lvmpolld version: " LVM_VERSION "\n"); + exit(EXIT_SUCCESS); + case 'f': /* --foreground */ + s.foreground = 1; + server = 1; + break; + case 'h': /* --help */ + _usage(argv[0], stdout); + exit(EXIT_SUCCESS); + case 'l': /* --log */ + ls.log_config = optarg; + server = 1; + break; + case 'p': /* --pidfile */ + s.pidfile = optarg; + server = 1; + break; + case 's': /* --socket */ + s.socket_path = optarg; + break; + case 't': /* --timeout in seconds */ + if (!process_timeout_arg(optarg, &di.max_timeouts)) { + fprintf(stderr, "Invalid value of timeout parameter.\n"); + exit(EXIT_FAILURE); + } + /* 0 equals to wait indefinitely */ + if (di.max_timeouts) + s.idle = ls.idle = &di; + server = 1; + break; + } + } + + if (client && server) { + fprintf(stderr, "Invalid combination of client and server parameters.\n\n"); + _usage(argv[0], stdout); + exit(EXIT_FAILURE); + } + + if (client) + return _lvmpolld_client(s.socket_path, action); + + /* Server */ + daemon_start(s); + + return EXIT_SUCCESS; +}
diff --git a/daemons/lvmpolld/lvmpolld-data-utils.c b/daemons/lvmpolld/lvmpolld-data-utils.c new file mode 100644 index 0000000..99883f8 --- /dev/null +++ b/daemons/lvmpolld/lvmpolld-data-utils.c
@@ -0,0 +1,391 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lvmpolld-common.h" + +#include "config-util.h" + +#include <fcntl.h> +#include <signal.h> + +static char *_construct_full_lvname(const char *vgname, const char *lvname) +{ + char *name; + size_t l; + + l = strlen(vgname) + strlen(lvname) + 2; /* vg/lv and \0 */ + name = (char *) dm_malloc(l * sizeof(char)); + if (!name) + return NULL; + + if (dm_snprintf(name, l, "%s/%s", vgname, lvname) < 0) { + dm_free(name); + name = NULL; + } + + return name; +} + +static char *_construct_lvm_system_dir_env(const char *sysdir) +{ + /* + * Store either "LVM_SYSTEM_DIR=/path/to..." + * - or - + * just single char to store NULL byte + */ + size_t l = sysdir ? strlen(sysdir) + 16 : 1; + char *env = (char *) dm_malloc(l * sizeof(char)); + + if (!env) + return NULL; + + *env = '\0'; + + if (sysdir && dm_snprintf(env, l, "LVM_SYSTEM_DIR=%s", sysdir) < 0) { + dm_free(env); + env = NULL; + } + + return env; +} + +static const char *_get_lvid(const char *lvmpolld_id, const char *sysdir) +{ + return lvmpolld_id ? (lvmpolld_id + (sysdir ? strlen(sysdir) : 0)) : NULL; +} + +char *construct_id(const char *sysdir, const char *uuid) +{ + char *id; + int r; + size_t l; + + l = strlen(uuid) + (sysdir ? strlen(sysdir) : 0) + 1; + id = (char *) dm_malloc(l * sizeof(char)); + if (!id) + return NULL; + + r = sysdir ? dm_snprintf(id, l, "%s%s", sysdir, uuid) : + dm_snprintf(id, l, "%s", uuid); + + if (r < 0) { + dm_free(id); + id = NULL; + } + + return id; +} + +struct lvmpolld_lv *pdlv_create(struct lvmpolld_state *ls, const char *id, + const char *vgname, const char *lvname, + const char *sysdir, enum poll_type type, + const char *sinterval, unsigned pdtimeout, + struct lvmpolld_store *pdst) +{ + char *lvmpolld_id = dm_strdup(id), /* copy */ + *full_lvname = _construct_full_lvname(vgname, lvname), /* copy */ + *lvm_system_dir_env = _construct_lvm_system_dir_env(sysdir); /* copy */ + + struct lvmpolld_lv tmp = { + .ls = ls, + .type = type, + .lvmpolld_id = lvmpolld_id, + .lvid = _get_lvid(lvmpolld_id, sysdir), + .lvname = full_lvname, + .lvm_system_dir_env = lvm_system_dir_env, + .sinterval = dm_strdup(sinterval), /* copy */ + .pdtimeout = pdtimeout < MIN_POLLING_TIMEOUT ? MIN_POLLING_TIMEOUT : pdtimeout, + .cmd_state = { .retcode = -1, .signal = 0 }, + .pdst = pdst, + .init_rq_count = 1 + }, *pdlv = (struct lvmpolld_lv *) dm_malloc(sizeof(struct lvmpolld_lv)); + + if (!pdlv || !tmp.lvid || !tmp.lvname || !tmp.lvm_system_dir_env || !tmp.sinterval) + goto err; + + memcpy(pdlv, &tmp, sizeof(*pdlv)); + + if (pthread_mutex_init(&pdlv->lock, NULL)) + goto err; + + return pdlv; + +err: + dm_free((void *)full_lvname); + dm_free((void *)lvmpolld_id); + dm_free((void *)lvm_system_dir_env); + dm_free((void *)tmp.sinterval); + dm_free((void *)pdlv); + + return NULL; +} + +void pdlv_destroy(struct lvmpolld_lv *pdlv) +{ + dm_free((void *)pdlv->lvmpolld_id); + dm_free((void *)pdlv->lvname); + dm_free((void *)pdlv->sinterval); + dm_free((void *)pdlv->lvm_system_dir_env); + dm_free((void *)pdlv->cmdargv); + dm_free((void *)pdlv->cmdenvp); + + pthread_mutex_destroy(&pdlv->lock); + + dm_free((void *)pdlv); +} + +unsigned pdlv_get_polling_finished(struct lvmpolld_lv *pdlv) +{ + unsigned ret; + + pdlv_lock(pdlv); + ret = pdlv->polling_finished; + pdlv_unlock(pdlv); + + return ret; +} + +struct lvmpolld_lv_state pdlv_get_status(struct lvmpolld_lv *pdlv) +{ + struct lvmpolld_lv_state r; + + pdlv_lock(pdlv); + r.error = pdlv_locked_error(pdlv); + r.polling_finished = pdlv_locked_polling_finished(pdlv); + r.cmd_state = pdlv_locked_cmd_state(pdlv); + pdlv_unlock(pdlv); + + return r; +} + +void pdlv_set_cmd_state(struct lvmpolld_lv *pdlv, const struct lvmpolld_cmd_stat *cmd_state) +{ + pdlv_lock(pdlv); + pdlv->cmd_state = *cmd_state; + pdlv_unlock(pdlv); +} + +void pdlv_set_error(struct lvmpolld_lv *pdlv, unsigned error) +{ + pdlv_lock(pdlv); + pdlv->error = error; + pdlv_unlock(pdlv); +} + +void pdlv_set_polling_finished(struct lvmpolld_lv *pdlv, unsigned finished) +{ + pdlv_lock(pdlv); + pdlv->polling_finished = finished; + pdlv_unlock(pdlv); +} + +struct lvmpolld_store *pdst_init(const char *name) +{ + struct lvmpolld_store *pdst = (struct lvmpolld_store *) dm_malloc(sizeof(struct lvmpolld_store)); + if (!pdst) + return NULL; + + pdst->store = dm_hash_create(32); + if (!pdst->store) + goto err_hash; + if (pthread_mutex_init(&pdst->lock, NULL)) + goto err_mutex; + + pdst->name = name; + pdst->active_polling_count = 0; + + return pdst; + +err_mutex: + dm_hash_destroy(pdst->store); +err_hash: + dm_free(pdst); + return NULL; +} + +void pdst_destroy(struct lvmpolld_store *pdst) +{ + if (!pdst) + return; + + dm_hash_destroy(pdst->store); + pthread_mutex_destroy(&pdst->lock); + dm_free(pdst); +} + +void pdst_locked_lock_all_pdlvs(const struct lvmpolld_store *pdst) +{ + struct dm_hash_node *n; + + dm_hash_iterate(n, pdst->store) + pdlv_lock(dm_hash_get_data(pdst->store, n)); +} + +void pdst_locked_unlock_all_pdlvs(const struct lvmpolld_store *pdst) +{ + struct dm_hash_node *n; + + dm_hash_iterate(n, pdst->store) + pdlv_unlock(dm_hash_get_data(pdst->store, n)); +} + +static void _pdlv_locked_dump(struct buffer *buff, const struct lvmpolld_lv *pdlv) +{ + char tmp[1024]; + const struct lvmpolld_cmd_stat *cmd_state = &pdlv->cmd_state; + + /* pdlv-section { */ + if (dm_snprintf(tmp, sizeof(tmp), "\t%s {\n", pdlv->lvmpolld_id) > 0) + buffer_append(buff, tmp); + + if (dm_snprintf(tmp, sizeof(tmp), "\t\tlvid=\"%s\"\n", pdlv->lvid) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\ttype=\"%s\"\n", polling_op(pdlv->type)) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\tlvname=\"%s\"\n", pdlv->lvname) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\tlvmpolld_internal_timeout=%d\n", pdlv->pdtimeout) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\tlvm_command_interval=\"%s\"\n", pdlv->sinterval ?: "<undefined>") > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\tLVM_SYSTEM_DIR=\"%s\"\n", + (*pdlv->lvm_system_dir_env ? (pdlv->lvm_system_dir_env + strlen("LVM_SYSTEM_DIR=")) : "<undefined>")) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\tlvm_command_pid=%d\n", pdlv->cmd_pid) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\tpolling_finished=%d\n", pdlv->polling_finished) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\terror_occured=%d\n", pdlv->error) > 0) + buffer_append(buff, tmp); + if (dm_snprintf(tmp, sizeof(tmp), "\t\tinit_requests_count=%d\n", pdlv->init_rq_count) > 0) + buffer_append(buff, tmp); + + /* lvm_commmand-section { */ + buffer_append(buff, "\t\tlvm_command {\n"); + if (cmd_state->retcode == -1 && !cmd_state->signal) + buffer_append(buff, "\t\t\tstate=\"" LVMPD_RESP_IN_PROGRESS "\"\n"); + else { + buffer_append(buff, "\t\t\tstate=\"" LVMPD_RESP_FINISHED "\"\n"); + if (dm_snprintf(tmp, sizeof(tmp), "\t\t\treason=\"%s\"\n\t\t\tvalue=%d\n", + (cmd_state->signal ? LVMPD_REAS_SIGNAL : LVMPD_REAS_RETCODE), + (cmd_state->signal ?: cmd_state->retcode)) > 0) + buffer_append(buff, tmp); + } + buffer_append(buff, "\t\t}\n"); + /* } lvm_commmand-section */ + + buffer_append(buff, "\t}\n"); + /* } pdlv-section */ +} + +void pdst_locked_dump(const struct lvmpolld_store *pdst, struct buffer *buff) +{ + struct dm_hash_node *n; + + dm_hash_iterate(n, pdst->store) + _pdlv_locked_dump(buff, dm_hash_get_data(pdst->store, n)); +} + +void pdst_locked_send_cancel(const struct lvmpolld_store *pdst) +{ + struct lvmpolld_lv *pdlv; + struct dm_hash_node *n; + + dm_hash_iterate(n, pdst->store) { + pdlv = dm_hash_get_data(pdst->store, n); + if (!pdlv_locked_polling_finished(pdlv)) + pthread_cancel(pdlv->tid); + } +} + +void pdst_locked_destroy_all_pdlvs(const struct lvmpolld_store *pdst) +{ + struct dm_hash_node *n; + + dm_hash_iterate(n, pdst->store) + pdlv_destroy(dm_hash_get_data(pdst->store, n)); +} + +struct lvmpolld_thread_data *lvmpolld_thread_data_constructor(struct lvmpolld_lv *pdlv) +{ + struct lvmpolld_thread_data *data = (struct lvmpolld_thread_data *) dm_malloc(sizeof(struct lvmpolld_thread_data)); + if (!data) + return NULL; + + data->pdlv = NULL; + data->line = NULL; + data->line_size = 0; + data->fout = data->ferr = NULL; + data->outpipe[0] = data->outpipe[1] = data->errpipe[0] = data->errpipe[1] = -1; + + if (pipe(data->outpipe) || pipe(data->errpipe)) { + lvmpolld_thread_data_destroy(data); + return NULL; + } + + if (fcntl(data->outpipe[0], F_SETFD, FD_CLOEXEC) || + fcntl(data->outpipe[1], F_SETFD, FD_CLOEXEC) || + fcntl(data->errpipe[0], F_SETFD, FD_CLOEXEC) || + fcntl(data->errpipe[1], F_SETFD, FD_CLOEXEC)) { + lvmpolld_thread_data_destroy(data); + return NULL; + } + + data->pdlv = pdlv; + + return data; +} + +void lvmpolld_thread_data_destroy(void *thread_private) +{ + struct lvmpolld_thread_data *data = (struct lvmpolld_thread_data *) thread_private; + if (!data) + return; + + if (data->pdlv) { + pdst_lock(data->pdlv->pdst); + /* + * FIXME: skip this step if lvmpolld is activated + * by systemd. + */ + if (!pdlv_get_polling_finished(data->pdlv)) + kill(data->pdlv->cmd_pid, SIGTERM); + pdlv_set_polling_finished(data->pdlv, 1); + pdst_locked_dec(data->pdlv->pdst); + pdst_unlock(data->pdlv->pdst); + } + + /* may get reallocated in getline(). dm_free must not be used */ + free(data->line); + + if (data->fout && !fclose(data->fout)) + data->outpipe[0] = -1; + + if (data->ferr && !fclose(data->ferr)) + data->errpipe[0] = -1; + + if (data->outpipe[0] >= 0) + (void) close(data->outpipe[0]); + + if (data->outpipe[1] >= 0) + (void) close(data->outpipe[1]); + + if (data->errpipe[0] >= 0) + (void) close(data->errpipe[0]); + + if (data->errpipe[1] >= 0) + (void) close(data->errpipe[1]); + + dm_free(data); +}
diff --git a/daemons/lvmpolld/lvmpolld-data-utils.h b/daemons/lvmpolld/lvmpolld-data-utils.h new file mode 100644 index 0000000..5bb5c86 --- /dev/null +++ b/daemons/lvmpolld/lvmpolld-data-utils.h
@@ -0,0 +1,215 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _LVM_LVMPOLLD_DATA_UTILS_H +#define _LVM_LVMPOLLD_DATA_UTILS_H + +#include <pthread.h> + +struct buffer; +struct lvmpolld_state; + +enum poll_type { + PVMOVE = 0, + CONVERT, + MERGE, + MERGE_THIN, + POLL_TYPE_MAX +}; + +struct lvmpolld_cmd_stat { + int retcode; + int signal; +}; + +struct lvmpolld_store { + pthread_mutex_t lock; + void *store; + const char *name; + unsigned active_polling_count; +}; + +struct lvmpolld_lv { + /* + * accessing following vars doesn't + * require struct lvmpolld_lv lock + */ + struct lvmpolld_state *const ls; + const enum poll_type type; + const char *const lvid; + const char *const lvmpolld_id; + const char *const lvname; /* full vg/lv name */ + const unsigned pdtimeout; /* in seconds */ + const char *const sinterval; + const char *const lvm_system_dir_env; + struct lvmpolld_store *const pdst; + const char *const *cmdargv; + const char *const *cmdenvp; + + /* only used by write */ + pid_t cmd_pid; + pthread_t tid; + + pthread_mutex_t lock; + + /* block of shared variables protected by lock */ + struct lvmpolld_cmd_stat cmd_state; + unsigned init_rq_count; /* for debuging purposes only */ + unsigned polling_finished:1; /* no more updates */ + unsigned error:1; /* unrecoverable error occured in lvmpolld */ +}; + +typedef void (*lvmpolld_parse_output_fn_t) (struct lvmpolld_lv *pdlv, const char *line); + +/* TODO: replace with configuration option */ +#define MIN_POLLING_TIMEOUT 60 + +struct lvmpolld_lv_state { + unsigned error:1; + unsigned polling_finished:1; + struct lvmpolld_cmd_stat cmd_state; +}; + +struct lvmpolld_thread_data { + char *line; + size_t line_size; + int outpipe[2]; + int errpipe[2]; + FILE *fout; + FILE *ferr; + char buf[1024]; + struct lvmpolld_lv *pdlv; +}; + +char *construct_id(const char *sysdir, const char *lvid); + +/* LVMPOLLD_LV_T section */ + +/* only call with appropriate struct lvmpolld_store lock held */ +struct lvmpolld_lv *pdlv_create(struct lvmpolld_state *ls, const char *id, + const char *vgname, const char *lvname, + const char *sysdir, enum poll_type type, + const char *sinterval, unsigned pdtimeout, + struct lvmpolld_store *pdst); + +/* only call with appropriate struct lvmpolld_store lock held */ +void pdlv_destroy(struct lvmpolld_lv *pdlv); + +static inline void pdlv_lock(struct lvmpolld_lv *pdlv) +{ + pthread_mutex_lock(&pdlv->lock); +} + +static inline void pdlv_unlock(struct lvmpolld_lv *pdlv) +{ + pthread_mutex_unlock(&pdlv->lock); +} + +/* + * no struct lvmpolld_lv lock required section + */ +static inline int pdlv_is_type(const struct lvmpolld_lv *pdlv, enum poll_type type) +{ + return pdlv->type == type; +} + +static inline unsigned pdlv_get_timeout(const struct lvmpolld_lv *pdlv) +{ + return pdlv->pdtimeout; +} + +static inline enum poll_type pdlv_get_type(const struct lvmpolld_lv *pdlv) +{ + return pdlv->type; +} + +unsigned pdlv_get_polling_finished(struct lvmpolld_lv *pdlv); +struct lvmpolld_lv_state pdlv_get_status(struct lvmpolld_lv *pdlv); +void pdlv_set_cmd_state(struct lvmpolld_lv *pdlv, const struct lvmpolld_cmd_stat *cmd_state); +void pdlv_set_error(struct lvmpolld_lv *pdlv, unsigned error); +void pdlv_set_polling_finished(struct lvmpolld_lv *pdlv, unsigned finished); + +/* + * struct lvmpolld_lv lock required section + */ +static inline struct lvmpolld_cmd_stat pdlv_locked_cmd_state(const struct lvmpolld_lv *pdlv) +{ + return pdlv->cmd_state; +} + +static inline int pdlv_locked_polling_finished(const struct lvmpolld_lv *pdlv) +{ + return pdlv->polling_finished; +} + +static inline unsigned pdlv_locked_error(const struct lvmpolld_lv *pdlv) +{ + return pdlv->error; +} + +/* struct lvmpolld_store manipulation routines */ + +struct lvmpolld_store *pdst_init(const char *name); +void pdst_destroy(struct lvmpolld_store *pdst); + +void pdst_locked_dump(const struct lvmpolld_store *pdst, struct buffer *buff); +void pdst_locked_lock_all_pdlvs(const struct lvmpolld_store *pdst); +void pdst_locked_unlock_all_pdlvs(const struct lvmpolld_store *pdst); +void pdst_locked_destroy_all_pdlvs(const struct lvmpolld_store *pdst); +void pdst_locked_send_cancel(const struct lvmpolld_store *pdst); + +static inline void pdst_lock(struct lvmpolld_store *pdst) +{ + pthread_mutex_lock(&pdst->lock); +} + +static inline void pdst_unlock(struct lvmpolld_store *pdst) +{ + pthread_mutex_unlock(&pdst->lock); +} + +static inline void pdst_locked_inc(struct lvmpolld_store *pdst) +{ + pdst->active_polling_count++; +} + +static inline void pdst_locked_dec(struct lvmpolld_store *pdst) +{ + pdst->active_polling_count--; +} + +static inline unsigned pdst_locked_get_active_count(const struct lvmpolld_store *pdst) +{ + return pdst->active_polling_count; +} + +static inline int pdst_locked_insert(struct lvmpolld_store *pdst, const char *key, struct lvmpolld_lv *pdlv) +{ + return dm_hash_insert(pdst->store, key, pdlv); +} + +static inline struct lvmpolld_lv *pdst_locked_lookup(struct lvmpolld_store *pdst, const char *key) +{ + return dm_hash_lookup(pdst->store, key); +} + +static inline void pdst_locked_remove(struct lvmpolld_store *pdst, const char *key) +{ + dm_hash_remove(pdst->store, key); +} + +struct lvmpolld_thread_data *lvmpolld_thread_data_constructor(struct lvmpolld_lv *pdlv); +void lvmpolld_thread_data_destroy(void *thread_private); + +#endif /* _LVM_LVMPOLLD_DATA_UTILS_H */
diff --git a/daemons/lvmpolld/lvmpolld-protocol.h b/daemons/lvmpolld/lvmpolld-protocol.h new file mode 100644 index 0000000..4e6ae9e --- /dev/null +++ b/daemons/lvmpolld/lvmpolld-protocol.h
@@ -0,0 +1,52 @@ +/* + * Copyright (C) 2015 Red Hat, Inc. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _LVM_LVMPOLLD_PROTOCOL_H +#define _LVM_LVMPOLLD_PROTOCOL_H + +#include "polling_ops.h" + +#define LVMPOLLD_PROTOCOL "lvmpolld" +#define LVMPOLLD_PROTOCOL_VERSION 1 + +#define LVMPD_REQ_CONVERT CONVERT_POLL +#define LVMPD_REQ_DUMP "dump" +#define LVMPD_REQ_MERGE MERGE_POLL +#define LVMPD_REQ_MERGE_THIN MERGE_THIN_POLL +#define LVMPD_REQ_PROGRESS "progress_info" +#define LVMPD_REQ_PVMOVE PVMOVE_POLL + +#define LVMPD_PARM_ABORT "abort" +#define LVMPD_PARM_HANDLE_MISSING_PVS "handle_missing_pvs" +#define LVMPD_PARM_INTERVAL "interval" +#define LVMPD_PARM_LVID "lvid" +#define LVMPD_PARM_LVNAME "lvname" +#define LVMPD_PARM_SYSDIR "sysdir" +#define LVMPD_PARM_VALUE "value" /* either retcode or signal value */ +#define LVMPD_PARM_VGNAME "vgname" + +#define LVMPD_RESP_FAILED "failed" +#define LVMPD_RESP_FINISHED "finished" +#define LVMPD_RESP_IN_PROGRESS "in_progress" +#define LVMPD_RESP_EINVAL "invalid" +#define LVMPD_RESP_NOT_FOUND "not_found" +#define LVMPD_RESP_OK "OK" + +#define LVMPD_REAS_RETCODE "retcode" /* lvm cmd ret code */ +#define LVMPD_REAS_SIGNAL "signal" /* lvm cmd terminating singal */ + +#define LVMPD_RET_DUP_FAILED 100 +#define LVMPD_RET_EXC_FAILED 101 + +#endif /* _LVM_LVMPOLLD_PROTOCOL_H */
diff --git a/daemons/lvmpolld/polling_ops.h b/daemons/lvmpolld/polling_ops.h new file mode 100644 index 0000000..449d034 --- /dev/null +++ b/daemons/lvmpolld/polling_ops.h
@@ -0,0 +1,25 @@ +/* + * Copyright (C) 2014-2015 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _LVM_TOOL_POLLING_OPS_H +#define _LVM_TOOL_POLLING_OPS_H + +/* this file is also part of lvmpolld protocol */ + +#define PVMOVE_POLL "pvmove" +#define CONVERT_POLL "convert" +#define MERGE_POLL "merge" +#define MERGE_THIN_POLL "merge_thin" + +#endif /* _LVM_TOOL_POLLING_OPS_H */
diff --git a/doc/.gitignore b/doc/.gitignore new file mode 100644 index 0000000..ae5a993 --- /dev/null +++ b/doc/.gitignore
@@ -0,0 +1 @@ +example.conf
diff --git a/doc/caching_foreign_vgs.txt b/doc/caching_foreign_vgs.txt new file mode 100644 index 0000000..12ffeca --- /dev/null +++ b/doc/caching_foreign_vgs.txt
@@ -0,0 +1,86 @@ +Q: Why should lvmetad cache foreign VGs? +A: It's the most useful behavior in the "steady state". + +How to arrive at that conclusion. +Four code configurations to consider, each in two different circumstances. + +configurations: + +1. lvm not using lvmetad +2. lvm using lvmetad and lvmlockd +3. lvm using lvmetad, and lvmetad does not cache foreign VGs + (Not currently implemented.) +4. lvm using lvmetad, and lvmetad caches foreign VGs + +circumstances: + +A. steady state: PVs are not added or removed to/from foreign VGs +B. transient state: PVs are added or removed to/from foreign VGs + +combinations: + +1.A. A PV is correctly shown in the foreign VG. +1.B. A PV is correctly shown in the foreign VG. + +The most accurate representation, at the cost of always scanning disks. + + +2.A. A PV is correctly shown in the foreign VG. +2.B. A PV is correctly shown in the foreign VG. + +The most accurate representation, at the cost of using lvmlockd. + + +3.A. A PV in a foreign VG is shown as unused. +3.B. A PV in a foreign VG is shown as unused. + +If lvmetad ignores foreign VGs and does not cache them, the PVs in the +foreign VGs appear to be unused. This largely defeats the purpose of +system_id, which is meant to treat VGs/PVs as foreign instead of free +(albeit imperfectly, see below.) + + +4.A. A PV is correctly shown in the foreign VG. +4.B. A PV is not correctly shown in the foreign VG. + +This avoids the cost of always scanning disks, and avoids the cost of +using lvmlockd. The steady state 4.A. is an improvement over the steady +state 3.A. When the steady state is the common case, this is a big +advantage. When the steady state is *not* the common case, the foreign VG +concept is not as useful (if shared devices are this dynamic, lvmlockd +should be considered.) + +The limitations related to the transient state 4.B. are explained in +lvmsystemid(7), along with how to handle it. The specific inaccuracies +possible in 4.B. are: + +. PV is shown as belonging to a foreign VG, but is actually unused. +. PV is shown as unused, but actually belongs to a foreign VG. + +To resolve the inaccuracies in the transient state (4.B.), and return the +system to an accurate steady state (4.A.), the disks need to be scanned, +which updates lvmetad. The scanning/updating is a manual step, i.e. +running 'pvscan --cache', which by definition scans disks and updates +lvmetad. + +-- + +The --foreign command line option for report/display commands +(vgs/lvs/pvs/vgdisplay/lvdisplay/pvdisplay) is not directly related to +whether or not lvmetad caches foreign VGs. + +By default, foreign VGs are silently ignored and not printed by these +commands. However, when the --foreign option is used, these commands do +produce output about foreign VGs. + +(When --foreign is not used, and the command specifically requests a +foreign VG by name, an error is produced about not accessing foreign VGs, +and the foreign VG is not displayed.) + +The decision to report/display foreign VGs or not is independent of +whether lvmetad is caching those VGs. When lvmetad is caching the foreign +VG, a report/display command run with --foreign will scan disks to read +the foreign VG and give the most up to date version of it (the copy of the +foreign VG in lvmetad may be out of date due to changes to the VG by the +foreign host.) +
diff --git a/doc/example_cmdlib.c b/doc/example_cmdlib.c new file mode 100644 index 0000000..66e3532 --- /dev/null +++ b/doc/example_cmdlib.c
@@ -0,0 +1,49 @@ +/* + * Copyright (C) 2004 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License v.2. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "lvm2cmd.h" +#include <stdio.h> + +/* All output gets passed to this function line-by-line */ +void test_log_fn(int level, const char *file, int line, + int dm_errno, const char *format) +{ + /* Extract and process output here rather than printing it */ + + if (level != 4) + return; + + printf("%s\n", format); + return; +} + +int main(int argc, char **argv) +{ + void *handle; + int r; + + lvm2_log_fn(test_log_fn); + + handle = lvm2_init(); + + lvm2_log_level(handle, 1); + r = lvm2_run(handle, "vgs --noheadings vg1"); + + /* More commands here */ + + lvm2_exit(handle); + + return r; +} +
diff --git a/doc/kernel/cache-policies.txt b/doc/kernel/cache-policies.txt new file mode 100644 index 0000000..d3ca8af --- /dev/null +++ b/doc/kernel/cache-policies.txt
@@ -0,0 +1,121 @@ +Guidance for writing policies +============================= + +Try to keep transactionality out of it. The core is careful to +avoid asking about anything that is migrating. This is a pain, but +makes it easier to write the policies. + +Mappings are loaded into the policy at construction time. + +Every bio that is mapped by the target is referred to the policy. +The policy can return a simple HIT or MISS or issue a migration. + +Currently there's no way for the policy to issue background work, +e.g. to start writing back dirty blocks that are going to be evicted +soon. + +Because we map bios, rather than requests it's easy for the policy +to get fooled by many small bios. For this reason the core target +issues periodic ticks to the policy. It's suggested that the policy +doesn't update states (eg, hit counts) for a block more than once +for each tick. The core ticks by watching bios complete, and so +trying to see when the io scheduler has let the ios run. + + +Overview of supplied cache replacement policies +=============================================== + +multiqueue (mq) +--------------- + +This policy is now an alias for smq (see below). + +The following tunables are accepted, but have no effect: + + 'sequential_threshold <#nr_sequential_ios>' + 'random_threshold <#nr_random_ios>' + 'read_promote_adjustment <value>' + 'write_promote_adjustment <value>' + 'discard_promote_adjustment <value>' + +Stochastic multiqueue (smq) +--------------------------- + +This policy is the default. + +The stochastic multi-queue (smq) policy addresses some of the problems +with the multiqueue (mq) policy. + +The smq policy (vs mq) offers the promise of less memory utilization, +improved performance and increased adaptability in the face of changing +workloads. smq also does not have any cumbersome tuning knobs. + +Users may switch from "mq" to "smq" simply by appropriately reloading a +DM table that is using the cache target. Doing so will cause all of the +mq policy's hints to be dropped. Also, performance of the cache may +degrade slightly until smq recalculates the origin device's hotspots +that should be cached. + +Memory usage: +The mq policy used a lot of memory; 88 bytes per cache block on a 64 +bit machine. + +smq uses 28bit indexes to implement it's data structures rather than +pointers. It avoids storing an explicit hit count for each block. It +has a 'hotspot' queue, rather than a pre-cache, which uses a quarter of +the entries (each hotspot block covers a larger area than a single +cache block). + +All this means smq uses ~25bytes per cache block. Still a lot of +memory, but a substantial improvement nontheless. + +Level balancing: +mq placed entries in different levels of the multiqueue structures +based on their hit count (~ln(hit count)). This meant the bottom +levels generally had the most entries, and the top ones had very +few. Having unbalanced levels like this reduced the efficacy of the +multiqueue. + +smq does not maintain a hit count, instead it swaps hit entries with +the least recently used entry from the level above. The overall +ordering being a side effect of this stochastic process. With this +scheme we can decide how many entries occupy each multiqueue level, +resulting in better promotion/demotion decisions. + +Adaptability: +The mq policy maintained a hit count for each cache block. For a +different block to get promoted to the cache it's hit count has to +exceed the lowest currently in the cache. This meant it could take a +long time for the cache to adapt between varying IO patterns. + +smq doesn't maintain hit counts, so a lot of this problem just goes +away. In addition it tracks performance of the hotspot queue, which +is used to decide which blocks to promote. If the hotspot queue is +performing badly then it starts moving entries more quickly between +levels. This lets it adapt to new IO patterns very quickly. + +Performance: +Testing smq shows substantially better performance than mq. + +cleaner +------- + +The cleaner writes back all dirty blocks in a cache to decommission it. + +Examples +======== + +The syntax for a table is: + cache <metadata dev> <cache dev> <origin dev> <block size> + <#feature_args> [<feature arg>]* + <policy> <#policy_args> [<policy arg>]* + +The syntax to send a message using the dmsetup command is: + dmsetup message <mapped device> 0 sequential_threshold 1024 + dmsetup message <mapped device> 0 random_threshold 8 + +Using dmsetup: + dmsetup create blah --table "0 268435456 cache /dev/sdb /dev/sdc \ + /dev/sdd 512 0 mq 4 sequential_threshold 1024 random_threshold 8" + creates a 128GB large mapped device named 'blah' with the + sequential threshold set to 1024 and the random_threshold set to 8.
diff --git a/doc/kernel/cache.txt b/doc/kernel/cache.txt new file mode 100644 index 0000000..785eab8 --- /dev/null +++ b/doc/kernel/cache.txt
@@ -0,0 +1,309 @@ +Introduction +============ + +dm-cache is a device mapper target written by Joe Thornber, Heinz +Mauelshagen, and Mike Snitzer. + +It aims to improve performance of a block device (eg, a spindle) by +dynamically migrating some of its data to a faster, smaller device +(eg, an SSD). + +This device-mapper solution allows us to insert this caching at +different levels of the dm stack, for instance above the data device for +a thin-provisioning pool. Caching solutions that are integrated more +closely with the virtual memory system should give better performance. + +The target reuses the metadata library used in the thin-provisioning +library. + +The decision as to what data to migrate and when is left to a plug-in +policy module. Several of these have been written as we experiment, +and we hope other people will contribute others for specific io +scenarios (eg. a vm image server). + +Glossary +======== + + Migration - Movement of the primary copy of a logical block from one + device to the other. + Promotion - Migration from slow device to fast device. + Demotion - Migration from fast device to slow device. + +The origin device always contains a copy of the logical block, which +may be out of date or kept in sync with the copy on the cache device +(depending on policy). + +Design +====== + +Sub-devices +----------- + +The target is constructed by passing three devices to it (along with +other parameters detailed later): + +1. An origin device - the big, slow one. + +2. A cache device - the small, fast one. + +3. A small metadata device - records which blocks are in the cache, + which are dirty, and extra hints for use by the policy object. + This information could be put on the cache device, but having it + separate allows the volume manager to configure it differently, + e.g. as a mirror for extra robustness. This metadata device may only + be used by a single cache device. + +Fixed block size +---------------- + +The origin is divided up into blocks of a fixed size. This block size +is configurable when you first create the cache. Typically we've been +using block sizes of 256KB - 1024KB. The block size must be between 64 +(32KB) and 2097152 (1GB) and a multiple of 64 (32KB). + +Having a fixed block size simplifies the target a lot. But it is +something of a compromise. For instance, a small part of a block may be +getting hit a lot, yet the whole block will be promoted to the cache. +So large block sizes are bad because they waste cache space. And small +block sizes are bad because they increase the amount of metadata (both +in core and on disk). + +Cache operating modes +--------------------- + +The cache has three operating modes: writeback, writethrough and +passthrough. + +If writeback, the default, is selected then a write to a block that is +cached will go only to the cache and the block will be marked dirty in +the metadata. + +If writethrough is selected then a write to a cached block will not +complete until it has hit both the origin and cache devices. Clean +blocks should remain clean. + +If passthrough is selected, useful when the cache contents are not known +to be coherent with the origin device, then all reads are served from +the origin device (all reads miss the cache) and all writes are +forwarded to the origin device; additionally, write hits cause cache +block invalidates. To enable passthrough mode the cache must be clean. +Passthrough mode allows a cache device to be activated without having to +worry about coherency. Coherency that exists is maintained, although +the cache will gradually cool as writes take place. If the coherency of +the cache can later be verified, or established through use of the +"invalidate_cblocks" message, the cache device can be transitioned to +writethrough or writeback mode while still warm. Otherwise, the cache +contents can be discarded prior to transitioning to the desired +operating mode. + +A simple cleaner policy is provided, which will clean (write back) all +dirty blocks in a cache. Useful for decommissioning a cache or when +shrinking a cache. Shrinking the cache's fast device requires all cache +blocks, in the area of the cache being removed, to be clean. If the +area being removed from the cache still contains dirty blocks the resize +will fail. Care must be taken to never reduce the volume used for the +cache's fast device until the cache is clean. This is of particular +importance if writeback mode is used. Writethrough and passthrough +modes already maintain a clean cache. Future support to partially clean +the cache, above a specified threshold, will allow for keeping the cache +warm and in writeback mode during resize. + +Migration throttling +-------------------- + +Migrating data between the origin and cache device uses bandwidth. +The user can set a throttle to prevent more than a certain amount of +migration occurring at any one time. Currently we're not taking any +account of normal io traffic going to the devices. More work needs +doing here to avoid migrating during those peak io moments. + +For the time being, a message "migration_threshold <#sectors>" +can be used to set the maximum number of sectors being migrated, +the default being 204800 sectors (or 100MB). + +Updating on-disk metadata +------------------------- + +On-disk metadata is committed every time a FLUSH or FUA bio is written. +If no such requests are made then commits will occur every second. This +means the cache behaves like a physical disk that has a volatile write +cache. If power is lost you may lose some recent writes. The metadata +should always be consistent in spite of any crash. + +The 'dirty' state for a cache block changes far too frequently for us +to keep updating it on the fly. So we treat it as a hint. In normal +operation it will be written when the dm device is suspended. If the +system crashes all cache blocks will be assumed dirty when restarted. + +Per-block policy hints +---------------------- + +Policy plug-ins can store a chunk of data per cache block. It's up to +the policy how big this chunk is, but it should be kept small. Like the +dirty flags this data is lost if there's a crash so a safe fallback +value should always be possible. + +For instance, the 'mq' policy, which is currently the default policy, +uses this facility to store the hit count of the cache blocks. If +there's a crash this information will be lost, which means the cache +may be less efficient until those hit counts are regenerated. + +Policy hints affect performance, not correctness. + +Policy messaging +---------------- + +Policies will have different tunables, specific to each one, so we +need a generic way of getting and setting these. Device-mapper +messages are used. Refer to cache-policies.txt. + +Discard bitset resolution +------------------------- + +We can avoid copying data during migration if we know the block has +been discarded. A prime example of this is when mkfs discards the +whole block device. We store a bitset tracking the discard state of +blocks. However, we allow this bitset to have a different block size +from the cache blocks. This is because we need to track the discard +state for all of the origin device (compare with the dirty bitset +which is just for the smaller cache device). + +Target interface +================ + +Constructor +----------- + + cache <metadata dev> <cache dev> <origin dev> <block size> + <#feature args> [<feature arg>]* + <policy> <#policy args> [policy args]* + + metadata dev : fast device holding the persistent metadata + cache dev : fast device holding cached data blocks + origin dev : slow device holding original data blocks + block size : cache unit size in sectors + + #feature args : number of feature arguments passed + feature args : writethrough or passthrough (The default is writeback.) + + policy : the replacement policy to use + #policy args : an even number of arguments corresponding to + key/value pairs passed to the policy + policy args : key/value pairs passed to the policy + E.g. 'sequential_threshold 1024' + See cache-policies.txt for details. + +Optional feature arguments are: + writethrough : write through caching that prohibits cache block + content from being different from origin block content. + Without this argument, the default behaviour is to write + back cache block contents later for performance reasons, + so they may differ from the corresponding origin blocks. + + passthrough : a degraded mode useful for various cache coherency + situations (e.g., rolling back snapshots of + underlying storage). Reads and writes always go to + the origin. If a write goes to a cached origin + block, then the cache block is invalidated. + To enable passthrough mode the cache must be clean. + +A policy called 'default' is always registered. This is an alias for +the policy we currently think is giving best all round performance. + +As the default policy could vary between kernels, if you are relying on +the characteristics of a specific policy, always request it by name. + +Status +------ + +<metadata block size> <#used metadata blocks>/<#total metadata blocks> +<cache block size> <#used cache blocks>/<#total cache blocks> +<#read hits> <#read misses> <#write hits> <#write misses> +<#demotions> <#promotions> <#dirty> <#features> <features>* +<#core args> <core args>* <policy name> <#policy args> <policy args>* +<cache metadata mode> + +metadata block size : Fixed block size for each metadata block in + sectors +#used metadata blocks : Number of metadata blocks used +#total metadata blocks : Total number of metadata blocks +cache block size : Configurable block size for the cache device + in sectors +#used cache blocks : Number of blocks resident in the cache +#total cache blocks : Total number of cache blocks +#read hits : Number of times a READ bio has been mapped + to the cache +#read misses : Number of times a READ bio has been mapped + to the origin +#write hits : Number of times a WRITE bio has been mapped + to the cache +#write misses : Number of times a WRITE bio has been + mapped to the origin +#demotions : Number of times a block has been removed + from the cache +#promotions : Number of times a block has been moved to + the cache +#dirty : Number of blocks in the cache that differ + from the origin +#feature args : Number of feature args to follow +feature args : 'writethrough' (optional) +#core args : Number of core arguments (must be even) +core args : Key/value pairs for tuning the core + e.g. migration_threshold +policy name : Name of the policy +#policy args : Number of policy arguments to follow (must be even) +policy args : Key/value pairs e.g. sequential_threshold +cache metadata mode : ro if read-only, rw if read-write + In serious cases where even a read-only mode is deemed unsafe + no further I/O will be permitted and the status will just + contain the string 'Fail'. The userspace recovery tools + should then be used. +needs_check : 'needs_check' if set, '-' if not set + A metadata operation has failed, resulting in the needs_check + flag being set in the metadata's superblock. The metadata + device must be deactivated and checked/repaired before the + cache can be made fully operational again. '-' indicates + needs_check is not set. + +Messages +-------- + +Policies will have different tunables, specific to each one, so we +need a generic way of getting and setting these. Device-mapper +messages are used. (A sysfs interface would also be possible.) + +The message format is: + + <key> <value> + +E.g. + dmsetup message my_cache 0 sequential_threshold 1024 + + +Invalidation is removing an entry from the cache without writing it +back. Cache blocks can be invalidated via the invalidate_cblocks +message, which takes an arbitrary number of cblock ranges. Each cblock +range's end value is "one past the end", meaning 5-10 expresses a range +of values from 5 to 9. Each cblock must be expressed as a decimal +value, in the future a variant message that takes cblock ranges +expressed in hexidecimal may be needed to better support efficient +invalidation of larger caches. The cache must be in passthrough mode +when invalidate_cblocks is used. + + invalidate_cblocks [<cblock>|<cblock begin>-<cblock end>]* + +E.g. + dmsetup message my_cache 0 invalidate_cblocks 2345 3456-4567 5678-6789 + +Examples +======== + +The test suite can be found here: + +https://github.com/jthornber/device-mapper-test-suite + +dmsetup create my_cache --table '0 41943040 cache /dev/mapper/metadata \ + /dev/mapper/ssd /dev/mapper/origin 512 1 writeback default 0' +dmsetup create my_cache --table '0 41943040 cache /dev/mapper/metadata \ + /dev/mapper/ssd /dev/mapper/origin 1024 1 writeback \ + mq 4 sequential_threshold 1024 random_threshold 8'
diff --git a/doc/kernel/crypt.txt b/doc/kernel/crypt.txt new file mode 100644 index 0000000..692171f --- /dev/null +++ b/doc/kernel/crypt.txt
@@ -0,0 +1,96 @@ +dm-crypt +========= + +Device-Mapper's "crypt" target provides transparent encryption of block devices +using the kernel crypto API. + +For a more detailed description of supported parameters see: +https://gitlab.com/cryptsetup/cryptsetup/wikis/DMCrypt + +Parameters: <cipher> <key> <iv_offset> <device path> \ + <offset> [<#opt_params> <opt_params>] + +<cipher> + Encryption cipher and an optional IV generation mode. + (In format cipher[:keycount]-chainmode-ivmode[:ivopts]). + Examples: + des + aes-cbc-essiv:sha256 + twofish-ecb + + /proc/crypto contains supported crypto modes + +<key> + Key used for encryption. It is encoded as a hexadecimal number. + You can only use key sizes that are valid for the selected cipher + in combination with the selected iv mode. + Note that for some iv modes the key string can contain additional + keys (for example IV seed) so the key contains more parts concatenated + into a single string. + +<keycount> + Multi-key compatibility mode. You can define <keycount> keys and + then sectors are encrypted according to their offsets (sector 0 uses key0; + sector 1 uses key1 etc.). <keycount> must be a power of two. + +<iv_offset> + The IV offset is a sector count that is added to the sector number + before creating the IV. + +<device path> + This is the device that is going to be used as backend and contains the + encrypted data. You can specify it as a path like /dev/xxx or a device + number <major>:<minor>. + +<offset> + Starting sector within the device where the encrypted data begins. + +<#opt_params> + Number of optional parameters. If there are no optional parameters, + the optional paramaters section can be skipped or #opt_params can be zero. + Otherwise #opt_params is the number of following arguments. + + Example of optional parameters section: + 3 allow_discards same_cpu_crypt submit_from_crypt_cpus + +allow_discards + Block discard requests (a.k.a. TRIM) are passed through the crypt device. + The default is to ignore discard requests. + + WARNING: Assess the specific security risks carefully before enabling this + option. For example, allowing discards on encrypted devices may lead to + the leak of information about the ciphertext device (filesystem type, + used space etc.) if the discarded blocks can be located easily on the + device later. + +same_cpu_crypt + Perform encryption using the same cpu that IO was submitted on. + The default is to use an unbound workqueue so that encryption work + is automatically balanced between available CPUs. + +submit_from_crypt_cpus + Disable offloading writes to a separate thread after encryption. + There are some situations where offloading write bios from the + encryption threads to a single thread degrades performance + significantly. The default is to offload write bios to the same + thread because it benefits CFQ to have writes submitted using the + same context. + +Example scripts +=============== +LUKS (Linux Unified Key Setup) is now the preferred way to set up disk +encryption with dm-crypt using the 'cryptsetup' utility, see +https://gitlab.com/cryptsetup/cryptsetup + +[[ +#!/bin/sh +# Create a crypt device using dmsetup +dmsetup create crypt1 --table "0 `blockdev --getsize $1` crypt aes-cbc-essiv:sha256 babebabebabebabebabebabebabebabe 0 $1 0" +]] + +[[ +#!/bin/sh +# Create a crypt device using cryptsetup and LUKS header with default cipher +cryptsetup luksFormat $1 +cryptsetup luksOpen $1 crypt1 +]]
diff --git a/doc/kernel/delay.txt b/doc/kernel/delay.txt new file mode 100644 index 0000000..a07b592 --- /dev/null +++ b/doc/kernel/delay.txt
@@ -0,0 +1,27 @@ +dm-delay +======== + +Device-Mapper's "delay" target delays reads and/or writes +and maps them to different devices. + +Parameters: + <device> <offset> <delay> [<write_device> <write_offset> <write_delay>] + +With separate write parameters, the first set is only used for reads. +Offsets are specified in sectors. +Delays are specified in milliseconds. + +Example scripts +=============== +[[ +#!/bin/sh +# Create device delaying rw operation for 500ms +echo "0 `blockdev --getsize $1` delay $1 0 500" | dmsetup create delayed +]] + +[[ +#!/bin/sh +# Create device delaying only write operation for 500ms and +# splitting reads and writes to different devices $1 $2 +echo "0 `blockdev --getsize $1` delay $1 0 0 $2 0 500" | dmsetup create delayed +]]
diff --git a/doc/kernel/era.txt b/doc/kernel/era.txt new file mode 100644 index 0000000..3c6d01b --- /dev/null +++ b/doc/kernel/era.txt
@@ -0,0 +1,108 @@ +Introduction +============ + +dm-era is a target that behaves similar to the linear target. In +addition it keeps track of which blocks were written within a user +defined period of time called an 'era'. Each era target instance +maintains the current era as a monotonically increasing 32-bit +counter. + +Use cases include tracking changed blocks for backup software, and +partially invalidating the contents of a cache to restore cache +coherency after rolling back a vendor snapshot. + +Constructor +=========== + + era <metadata dev> <origin dev> <block size> + + metadata dev : fast device holding the persistent metadata + origin dev : device holding data blocks that may change + block size : block size of origin data device, granularity that is + tracked by the target + +Messages +======== + +None of the dm messages take any arguments. + +checkpoint +---------- + +Possibly move to a new era. You shouldn't assume the era has +incremented. After sending this message, you should check the +current era via the status line. + +take_metadata_snap +------------------ + +Create a clone of the metadata, to allow a userland process to read it. + +drop_metadata_snap +------------------ + +Drop the metadata snapshot. + +Status +====== + +<metadata block size> <#used metadata blocks>/<#total metadata blocks> +<current era> <held metadata root | '-'> + +metadata block size : Fixed block size for each metadata block in + sectors +#used metadata blocks : Number of metadata blocks used +#total metadata blocks : Total number of metadata blocks +current era : The current era +held metadata root : The location, in blocks, of the metadata root + that has been 'held' for userspace read + access. '-' indicates there is no held root + +Detailed use case +================= + +The scenario of invalidating a cache when rolling back a vendor +snapshot was the primary use case when developing this target: + +Taking a vendor snapshot +------------------------ + +- Send a checkpoint message to the era target +- Make a note of the current era in its status line +- Take vendor snapshot (the era and snapshot should be forever + associated now). + +Rolling back to an vendor snapshot +---------------------------------- + +- Cache enters passthrough mode (see: dm-cache's docs in cache.txt) +- Rollback vendor storage +- Take metadata snapshot +- Ascertain which blocks have been written since the snapshot was taken + by checking each block's era +- Invalidate those blocks in the caching software +- Cache returns to writeback/writethrough mode + +Memory usage +============ + +The target uses a bitset to record writes in the current era. It also +has a spare bitset ready for switching over to a new era. Other than +that it uses a few 4k blocks for updating metadata. + + (4 * nr_blocks) bytes + buffers + +Resilience +========== + +Metadata is updated on disk before a write to a previously unwritten +block is performed. As such dm-era should not be effected by a hard +crash such as power failure. + +Userland tools +============== + +Userland tools are found in the increasingly poorly named +thin-provisioning-tools project: + + https://github.com/jthornber/thin-provisioning-tools
diff --git a/doc/kernel/flakey.txt b/doc/kernel/flakey.txt new file mode 100644 index 0000000..6ff5c23 --- /dev/null +++ b/doc/kernel/flakey.txt
@@ -0,0 +1,53 @@ +dm-flakey +========= + +This target is the same as the linear target except that it exhibits +unreliable behaviour periodically. It's been found useful in simulating +failing devices for testing purposes. + +Starting from the time the table is loaded, the device is available for +<up interval> seconds, then exhibits unreliable behaviour for <down +interval> seconds, and then this cycle repeats. + +Also, consider using this in combination with the dm-delay target too, +which can delay reads and writes and/or send them to different +underlying devices. + +Table parameters +---------------- + <dev path> <offset> <up interval> <down interval> \ + [<num_features> [<feature arguments>]] + +Mandatory parameters: + <dev path>: Full pathname to the underlying block-device, or a + "major:minor" device-number. + <offset>: Starting sector within the device. + <up interval>: Number of seconds device is available. + <down interval>: Number of seconds device returns errors. + +Optional feature parameters: + If no feature parameters are present, during the periods of + unreliability, all I/O returns errors. + + drop_writes: + All write I/O is silently ignored. + Read I/O is handled correctly. + + corrupt_bio_byte <Nth_byte> <direction> <value> <flags>: + During <down interval>, replace <Nth_byte> of the data of + each matching bio with <value>. + + <Nth_byte>: The offset of the byte to replace. + Counting starts at 1, to replace the first byte. + <direction>: Either 'r' to corrupt reads or 'w' to corrupt writes. + 'w' is incompatible with drop_writes. + <value>: The value (from 0-255) to write. + <flags>: Perform the replacement only if bio->bi_rw has all the + selected flags set. + +Examples: + corrupt_bio_byte 32 r 1 0 + - replaces the 32nd byte of READ bios with the value 1 + + corrupt_bio_byte 224 w 0 32 + - replaces the 224th byte of REQ_META (=32) bios with the value 0
diff --git a/doc/kernel/io.txt b/doc/kernel/io.txt new file mode 100644 index 0000000..3b5d9a5 --- /dev/null +++ b/doc/kernel/io.txt
@@ -0,0 +1,75 @@ +dm-io +===== + +Dm-io provides synchronous and asynchronous I/O services. There are three +types of I/O services available, and each type has a sync and an async +version. + +The user must set up an io_region structure to describe the desired location +of the I/O. Each io_region indicates a block-device along with the starting +sector and size of the region. + + struct io_region { + struct block_device *bdev; + sector_t sector; + sector_t count; + }; + +Dm-io can read from one io_region or write to one or more io_regions. Writes +to multiple regions are specified by an array of io_region structures. + +The first I/O service type takes a list of memory pages as the data buffer for +the I/O, along with an offset into the first page. + + struct page_list { + struct page_list *next; + struct page *page; + }; + + int dm_io_sync(unsigned int num_regions, struct io_region *where, int rw, + struct page_list *pl, unsigned int offset, + unsigned long *error_bits); + int dm_io_async(unsigned int num_regions, struct io_region *where, int rw, + struct page_list *pl, unsigned int offset, + io_notify_fn fn, void *context); + +The second I/O service type takes an array of bio vectors as the data buffer +for the I/O. This service can be handy if the caller has a pre-assembled bio, +but wants to direct different portions of the bio to different devices. + + int dm_io_sync_bvec(unsigned int num_regions, struct io_region *where, + int rw, struct bio_vec *bvec, + unsigned long *error_bits); + int dm_io_async_bvec(unsigned int num_regions, struct io_region *where, + int rw, struct bio_vec *bvec, + io_notify_fn fn, void *context); + +The third I/O service type takes a pointer to a vmalloc'd memory buffer as the +data buffer for the I/O. This service can be handy if the caller needs to do +I/O to a large region but doesn't want to allocate a large number of individual +memory pages. + + int dm_io_sync_vm(unsigned int num_regions, struct io_region *where, int rw, + void *data, unsigned long *error_bits); + int dm_io_async_vm(unsigned int num_regions, struct io_region *where, int rw, + void *data, io_notify_fn fn, void *context); + +Callers of the asynchronous I/O services must include the name of a completion +callback routine and a pointer to some context data for the I/O. + + typedef void (*io_notify_fn)(unsigned long error, void *context); + +The "error" parameter in this callback, as well as the "*error" parameter in +all of the synchronous versions, is a bitset (instead of a simple error value). +In the case of an write-I/O to multiple regions, this bitset allows dm-io to +indicate success or failure on each individual region. + +Before using any of the dm-io services, the user should call dm_io_get() +and specify the number of pages they expect to perform I/O on concurrently. +Dm-io will attempt to resize its mempool to make sure enough pages are +always available in order to avoid unnecessary waiting while performing I/O. + +When the user is finished using the dm-io services, they should call +dm_io_put() and specify the same number of pages that were given on the +dm_io_get() call. +
diff --git a/doc/kernel/kcopyd.txt b/doc/kernel/kcopyd.txt new file mode 100644 index 0000000..820382c --- /dev/null +++ b/doc/kernel/kcopyd.txt
@@ -0,0 +1,47 @@ +kcopyd +====== + +Kcopyd provides the ability to copy a range of sectors from one block-device +to one or more other block-devices, with an asynchronous completion +notification. It is used by dm-snapshot and dm-mirror. + +Users of kcopyd must first create a client and indicate how many memory pages +to set aside for their copy jobs. This is done with a call to +kcopyd_client_create(). + + int kcopyd_client_create(unsigned int num_pages, + struct kcopyd_client **result); + +To start a copy job, the user must set up io_region structures to describe +the source and destinations of the copy. Each io_region indicates a +block-device along with the starting sector and size of the region. The source +of the copy is given as one io_region structure, and the destinations of the +copy are given as an array of io_region structures. + + struct io_region { + struct block_device *bdev; + sector_t sector; + sector_t count; + }; + +To start the copy, the user calls kcopyd_copy(), passing in the client +pointer, pointers to the source and destination io_regions, the name of a +completion callback routine, and a pointer to some context data for the copy. + + int kcopyd_copy(struct kcopyd_client *kc, struct io_region *from, + unsigned int num_dests, struct io_region *dests, + unsigned int flags, kcopyd_notify_fn fn, void *context); + + typedef void (*kcopyd_notify_fn)(int read_err, unsigned int write_err, + void *context); + +When the copy completes, kcopyd will call the user's completion routine, +passing back the user's context pointer. It will also indicate if a read or +write error occurred during the copy. + +When a user is done with all their copy jobs, they should call +kcopyd_client_destroy() to delete the kcopyd client, which will release the +associated memory pages. + + void kcopyd_client_destroy(struct kcopyd_client *kc); +
diff --git a/doc/kernel/linear.txt b/doc/kernel/linear.txt new file mode 100644 index 0000000..d5307d3 --- /dev/null +++ b/doc/kernel/linear.txt
@@ -0,0 +1,61 @@ +dm-linear +========= + +Device-Mapper's "linear" target maps a linear range of the Device-Mapper +device onto a linear range of another device. This is the basic building +block of logical volume managers. + +Parameters: <dev path> <offset> + <dev path>: Full pathname to the underlying block-device, or a + "major:minor" device-number. + <offset>: Starting sector within the device. + + +Example scripts +=============== +[[ +#!/bin/sh +# Create an identity mapping for a device +echo "0 `blockdev --getsize $1` linear $1 0" | dmsetup create identity +]] + + +[[ +#!/bin/sh +# Join 2 devices together +size1=`blockdev --getsize $1` +size2=`blockdev --getsize $2` +echo "0 $size1 linear $1 0 +$size1 $size2 linear $2 0" | dmsetup create joined +]] + + +[[ +#!/usr/bin/perl -w +# Split a device into 4M chunks and then join them together in reverse order. + +my $name = "reverse"; +my $extent_size = 4 * 1024 * 2; +my $dev = $ARGV[0]; +my $table = ""; +my $count = 0; + +if (!defined($dev)) { + die("Please specify a device.\n"); +} + +my $dev_size = `blockdev --getsize $dev`; +my $extents = int($dev_size / $extent_size) - + (($dev_size % $extent_size) ? 1 : 0); + +while ($extents > 0) { + my $this_start = $count * $extent_size; + $extents--; + $count++; + my $this_offset = $extents * $extent_size; + + $table .= "$this_start $extent_size linear $dev $this_offset\n"; +} + +`echo \"$table\" | dmsetup create $name`; +]]
diff --git a/doc/kernel/log-writes.txt b/doc/kernel/log-writes.txt new file mode 100644 index 0000000..c10f30c --- /dev/null +++ b/doc/kernel/log-writes.txt
@@ -0,0 +1,140 @@ +dm-log-writes +============= + +This target takes 2 devices, one to pass all IO to normally, and one to log all +of the write operations to. This is intended for file system developers wishing +to verify the integrity of metadata or data as the file system is written to. +There is a log_write_entry written for every WRITE request and the target is +able to take arbitrary data from userspace to insert into the log. The data +that is in the WRITE requests is copied into the log to make the replay happen +exactly as it happened originally. + +Log Ordering +============ + +We log things in order of completion once we are sure the write is no longer in +cache. This means that normal WRITE requests are not actually logged until the +next REQ_FLUSH request. This is to make it easier for userspace to replay the +log in a way that correlates to what is on disk and not what is in cache, to +make it easier to detect improper waiting/flushing. + +This works by attaching all WRITE requests to a list once the write completes. +Once we see a REQ_FLUSH request we splice this list onto the request and once +the FLUSH request completes we log all of the WRITEs and then the FLUSH. Only +completed WRITEs, at the time the REQ_FLUSH is issued, are added in order to +simulate the worst case scenario with regard to power failures. Consider the +following example (W means write, C means complete): + +W1,W2,W3,C3,C2,Wflush,C1,Cflush + +The log would show the following + +W3,W2,flush,W1.... + +Again this is to simulate what is actually on disk, this allows us to detect +cases where a power failure at a particular point in time would create an +inconsistent file system. + +Any REQ_FUA requests bypass this flushing mechanism and are logged as soon as +they complete as those requests will obviously bypass the device cache. + +Any REQ_DISCARD requests are treated like WRITE requests. Otherwise we would +have all the DISCARD requests, and then the WRITE requests and then the FLUSH +request. Consider the following example: + +WRITE block 1, DISCARD block 1, FLUSH + +If we logged DISCARD when it completed, the replay would look like this + +DISCARD 1, WRITE 1, FLUSH + +which isn't quite what happened and wouldn't be caught during the log replay. + +Target interface +================ + +i) Constructor + + log-writes <dev_path> <log_dev_path> + + dev_path : Device that all of the IO will go to normally. + log_dev_path : Device where the log entries are written to. + +ii) Status + + <#logged entries> <highest allocated sector> + + #logged entries : Number of logged entries + highest allocated sector : Highest allocated sector + +iii) Messages + + mark <description> + + You can use a dmsetup message to set an arbitrary mark in a log. + For example say you want to fsck a file system after every + write, but first you need to replay up to the mkfs to make sure + we're fsck'ing something reasonable, you would do something like + this: + + mkfs.btrfs -f /dev/mapper/log + dmsetup message log 0 mark mkfs + <run test> + + This would allow you to replay the log up to the mkfs mark and + then replay from that point on doing the fsck check in the + interval that you want. + + Every log has a mark at the end labeled "dm-log-writes-end". + +Userspace component +=================== + +There is a userspace tool that will replay the log for you in various ways. +It can be found here: https://github.com/josefbacik/log-writes + +Example usage +============= + +Say you want to test fsync on your file system. You would do something like +this: + +TABLE="0 $(blockdev --getsz /dev/sdb) log-writes /dev/sdb /dev/sdc" +dmsetup create log --table "$TABLE" +mkfs.btrfs -f /dev/mapper/log +dmsetup message log 0 mark mkfs + +mount /dev/mapper/log /mnt/btrfs-test +<some test that does fsync at the end> +dmsetup message log 0 mark fsync +md5sum /mnt/btrfs-test/foo +umount /mnt/btrfs-test + +dmsetup remove log +replay-log --log /dev/sdc --replay /dev/sdb --end-mark fsync +mount /dev/sdb /mnt/btrfs-test +md5sum /mnt/btrfs-test/foo +<verify md5sum's are correct> + +Another option is to do a complicated file system operation and verify the file +system is consistent during the entire operation. You could do this with: + +TABLE="0 $(blockdev --getsz /dev/sdb) log-writes /dev/sdb /dev/sdc" +dmsetup create log --table "$TABLE" +mkfs.btrfs -f /dev/mapper/log +dmsetup message log 0 mark mkfs + +mount /dev/mapper/log /mnt/btrfs-test +<fsstress to dirty the fs> +btrfs filesystem balance /mnt/btrfs-test +umount /mnt/btrfs-test +dmsetup remove log + +replay-log --log /dev/sdc --replay /dev/sdb --end-mark mkfs +btrfsck /dev/sdb +replay-log --log /dev/sdc --replay /dev/sdb --start-mark mkfs \ + --fsck "btrfsck /dev/sdb" --check fua + +And that will replay the log until it sees a FUA request, run the fsck command +and if the fsck passes it will replay to the next FUA, until it is completed or +the fsck command exists abnormally.
diff --git a/doc/kernel/log.txt b/doc/kernel/log.txt new file mode 100644 index 0000000..c155ac5 --- /dev/null +++ b/doc/kernel/log.txt
@@ -0,0 +1,54 @@ +Device-Mapper Logging +===================== +The device-mapper logging code is used by some of the device-mapper +RAID targets to track regions of the disk that are not consistent. +A region (or portion of the address space) of the disk may be +inconsistent because a RAID stripe is currently being operated on or +a machine died while the region was being altered. In the case of +mirrors, a region would be considered dirty/inconsistent while you +are writing to it because the writes need to be replicated for all +the legs of the mirror and may not reach the legs at the same time. +Once all writes are complete, the region is considered clean again. + +There is a generic logging interface that the device-mapper RAID +implementations use to perform logging operations (see +dm_dirty_log_type in include/linux/dm-dirty-log.h). Various different +logging implementations are available and provide different +capabilities. The list includes: + +Type Files +==== ===== +disk drivers/md/dm-log.c +core drivers/md/dm-log.c +userspace drivers/md/dm-log-userspace* include/linux/dm-log-userspace.h + +The "disk" log type +------------------- +This log implementation commits the log state to disk. This way, the +logging state survives reboots/crashes. + +The "core" log type +------------------- +This log implementation keeps the log state in memory. The log state +will not survive a reboot or crash, but there may be a small boost in +performance. This method can also be used if no storage device is +available for storing log state. + +The "userspace" log type +------------------------ +This log type simply provides a way to export the log API to userspace, +so log implementations can be done there. This is done by forwarding most +logging requests to userspace, where a daemon receives and processes the +request. + +The structure used for communication between kernel and userspace are +located in include/linux/dm-log-userspace.h. Due to the frequency, +diversity, and 2-way communication nature of the exchanges between +kernel and userspace, 'connector' is used as the interface for +communication. + +There are currently two userspace log implementations that leverage this +framework - "clustered-disk" and "clustered-core". These implementations +provide a cluster-coherent log for shared-storage. Device-mapper mirroring +can be used in a shared-storage environment when the cluster log implementations +are employed.
diff --git a/doc/kernel/persistent-data.txt b/doc/kernel/persistent-data.txt new file mode 100644 index 0000000..a333bcb --- /dev/null +++ b/doc/kernel/persistent-data.txt
@@ -0,0 +1,84 @@ +Introduction +============ + +The more-sophisticated device-mapper targets require complex metadata +that is managed in kernel. In late 2010 we were seeing that various +different targets were rolling their own data structures, for example: + +- Mikulas Patocka's multisnap implementation +- Heinz Mauelshagen's thin provisioning target +- Another btree-based caching target posted to dm-devel +- Another multi-snapshot target based on a design of Daniel Phillips + +Maintaining these data structures takes a lot of work, so if possible +we'd like to reduce the number. + +The persistent-data library is an attempt to provide a re-usable +framework for people who want to store metadata in device-mapper +targets. It's currently used by the thin-provisioning target and an +upcoming hierarchical storage target. + +Overview +======== + +The main documentation is in the header files which can all be found +under drivers/md/persistent-data. + +The block manager +----------------- + +dm-block-manager.[hc] + +This provides access to the data on disk in fixed sized-blocks. There +is a read/write locking interface to prevent concurrent accesses, and +keep data that is being used in the cache. + +Clients of persistent-data are unlikely to use this directly. + +The transaction manager +----------------------- + +dm-transaction-manager.[hc] + +This restricts access to blocks and enforces copy-on-write semantics. +The only way you can get hold of a writable block through the +transaction manager is by shadowing an existing block (ie. doing +copy-on-write) or allocating a fresh one. Shadowing is elided within +the same transaction so performance is reasonable. The commit method +ensures that all data is flushed before it writes the superblock. +On power failure your metadata will be as it was when last committed. + +The Space Maps +-------------- + +dm-space-map.h +dm-space-map-metadata.[hc] +dm-space-map-disk.[hc] + +On-disk data structures that keep track of reference counts of blocks. +Also acts as the allocator of new blocks. Currently two +implementations: a simpler one for managing blocks on a different +device (eg. thinly-provisioned data blocks); and one for managing +the metadata space. The latter is complicated by the need to store +its own data within the space it's managing. + +The data structures +------------------- + +dm-btree.[hc] +dm-btree-remove.c +dm-btree-spine.c +dm-btree-internal.h + +Currently there is only one data structure, a hierarchical btree. +There are plans to add more. For example, something with an +array-like interface would see a lot of use. + +The btree is 'hierarchical' in that you can define it to be composed +of nested btrees, and take multiple keys. For example, the +thin-provisioning target uses a btree with two levels of nesting. +The first maps a device id to a mapping tree, and that in turn maps a +virtual block to a physical block. + +Values stored in the btrees can have arbitrary size. Keys are always +64bits, although nesting allows you to use multiple keys.
diff --git a/doc/kernel/queue-length.txt b/doc/kernel/queue-length.txt new file mode 100644 index 0000000..f4db256 --- /dev/null +++ b/doc/kernel/queue-length.txt
@@ -0,0 +1,39 @@ +dm-queue-length +=============== + +dm-queue-length is a path selector module for device-mapper targets, +which selects a path with the least number of in-flight I/Os. +The path selector name is 'queue-length'. + +Table parameters for each path: [<repeat_count>] + <repeat_count>: The number of I/Os to dispatch using the selected + path before switching to the next path. + If not given, internal default is used. To check + the default value, see the activated table. + +Status for each path: <status> <fail-count> <in-flight> + <status>: 'A' if the path is active, 'F' if the path is failed. + <fail-count>: The number of path failures. + <in-flight>: The number of in-flight I/Os on the path. + + +Algorithm +========= + +dm-queue-length increments/decrements 'in-flight' when an I/O is +dispatched/completed respectively. +dm-queue-length selects a path with the minimum 'in-flight'. + + +Examples +======== +In case that 2 paths (sda and sdb) are used with repeat_count == 128. + +# echo "0 10 multipath 0 0 1 1 queue-length 0 2 1 8:0 128 8:16 128" \ + dmsetup create test +# +# dmsetup table +test: 0 10 multipath 0 0 1 1 queue-length 0 2 1 8:0 128 8:16 128 +# +# dmsetup status +test: 0 10 multipath 2 0 0 0 1 1 E 0 2 1 8:0 A 0 0 8:16 A 0 0
diff --git a/doc/kernel/raid.txt b/doc/kernel/raid.txt new file mode 100644 index 0000000..df2d636 --- /dev/null +++ b/doc/kernel/raid.txt
@@ -0,0 +1,259 @@ +dm-raid +======= + +The device-mapper RAID (dm-raid) target provides a bridge from DM to MD. +It allows the MD RAID drivers to be accessed using a device-mapper +interface. + + +Mapping Table Interface +----------------------- +The target is named "raid" and it accepts the following parameters: + + <raid_type> <#raid_params> <raid_params> \ + <#raid_devs> <metadata_dev0> <dev0> [.. <metadata_devN> <devN>] + +<raid_type>: + raid1 RAID1 mirroring + raid4 RAID4 dedicated parity disk + raid5_la RAID5 left asymmetric + - rotating parity 0 with data continuation + raid5_ra RAID5 right asymmetric + - rotating parity N with data continuation + raid5_ls RAID5 left symmetric + - rotating parity 0 with data restart + raid5_rs RAID5 right symmetric + - rotating parity N with data restart + raid6_zr RAID6 zero restart + - rotating parity zero (left-to-right) with data restart + raid6_nr RAID6 N restart + - rotating parity N (right-to-left) with data restart + raid6_nc RAID6 N continue + - rotating parity N (right-to-left) with data continuation + raid10 Various RAID10 inspired algorithms chosen by additional params + - RAID10: Striped Mirrors (aka 'Striping on top of mirrors') + - RAID1E: Integrated Adjacent Stripe Mirroring + - RAID1E: Integrated Offset Stripe Mirroring + - and other similar RAID10 variants + + Reference: Chapter 4 of + http://www.snia.org/sites/default/files/SNIA_DDF_Technical_Position_v2.0.pdf + +<#raid_params>: The number of parameters that follow. + +<raid_params> consists of + Mandatory parameters: + <chunk_size>: Chunk size in sectors. This parameter is often known as + "stripe size". It is the only mandatory parameter and + is placed first. + + followed by optional parameters (in any order): + [sync|nosync] Force or prevent RAID initialization. + + [rebuild <idx>] Rebuild drive number 'idx' (first drive is 0). + + [daemon_sleep <ms>] + Interval between runs of the bitmap daemon that + clear bits. A longer interval means less bitmap I/O but + resyncing after a failure is likely to take longer. + + [min_recovery_rate <kB/sec/disk>] Throttle RAID initialization + [max_recovery_rate <kB/sec/disk>] Throttle RAID initialization + [write_mostly <idx>] Mark drive index 'idx' write-mostly. + [max_write_behind <sectors>] See '--write-behind=' (man mdadm) + [stripe_cache <sectors>] Stripe cache size (RAID 4/5/6 only) + [region_size <sectors>] + The region_size multiplied by the number of regions is the + logical size of the array. The bitmap records the device + synchronisation state for each region. + + [raid10_copies <# copies>] + [raid10_format <near|far|offset>] + These two options are used to alter the default layout of + a RAID10 configuration. The number of copies is can be + specified, but the default is 2. There are also three + variations to how the copies are laid down - the default + is "near". Near copies are what most people think of with + respect to mirroring. If these options are left unspecified, + or 'raid10_copies 2' and/or 'raid10_format near' are given, + then the layouts for 2, 3 and 4 devices are: + 2 drives 3 drives 4 drives + -------- ---------- -------------- + A1 A1 A1 A1 A2 A1 A1 A2 A2 + A2 A2 A2 A3 A3 A3 A3 A4 A4 + A3 A3 A4 A4 A5 A5 A5 A6 A6 + A4 A4 A5 A6 A6 A7 A7 A8 A8 + .. .. .. .. .. .. .. .. .. + The 2-device layout is equivalent 2-way RAID1. The 4-device + layout is what a traditional RAID10 would look like. The + 3-device layout is what might be called a 'RAID1E - Integrated + Adjacent Stripe Mirroring'. + + If 'raid10_copies 2' and 'raid10_format far', then the layouts + for 2, 3 and 4 devices are: + 2 drives 3 drives 4 drives + -------- -------------- -------------------- + A1 A2 A1 A2 A3 A1 A2 A3 A4 + A3 A4 A4 A5 A6 A5 A6 A7 A8 + A5 A6 A7 A8 A9 A9 A10 A11 A12 + .. .. .. .. .. .. .. .. .. + A2 A1 A3 A1 A2 A2 A1 A4 A3 + A4 A3 A6 A4 A5 A6 A5 A8 A7 + A6 A5 A9 A7 A8 A10 A9 A12 A11 + .. .. .. .. .. .. .. .. .. + + If 'raid10_copies 2' and 'raid10_format offset', then the + layouts for 2, 3 and 4 devices are: + 2 drives 3 drives 4 drives + -------- ------------ ----------------- + A1 A2 A1 A2 A3 A1 A2 A3 A4 + A2 A1 A3 A1 A2 A2 A1 A4 A3 + A3 A4 A4 A5 A6 A5 A6 A7 A8 + A4 A3 A6 A4 A5 A6 A5 A8 A7 + A5 A6 A7 A8 A9 A9 A10 A11 A12 + A6 A5 A9 A7 A8 A10 A9 A12 A11 + .. .. .. .. .. .. .. .. .. + Here we see layouts closely akin to 'RAID1E - Integrated + Offset Stripe Mirroring'. + +<#raid_devs>: The number of devices composing the array. + Each device consists of two entries. The first is the device + containing the metadata (if any); the second is the one containing the + data. + + If a drive has failed or is missing at creation time, a '-' can be + given for both the metadata and data drives for a given position. + + +Example Tables +-------------- +# RAID4 - 4 data drives, 1 parity (no metadata devices) +# No metadata devices specified to hold superblock/bitmap info +# Chunk size of 1MiB +# (Lines separated for easy reading) + +0 1960893648 raid \ + raid4 1 2048 \ + 5 - 8:17 - 8:33 - 8:49 - 8:65 - 8:81 + +# RAID4 - 4 data drives, 1 parity (with metadata devices) +# Chunk size of 1MiB, force RAID initialization, +# min recovery rate at 20 kiB/sec/disk + +0 1960893648 raid \ + raid4 4 2048 sync min_recovery_rate 20 \ + 5 8:17 8:18 8:33 8:34 8:49 8:50 8:65 8:66 8:81 8:82 + + +Status Output +------------- +'dmsetup table' displays the table used to construct the mapping. +The optional parameters are always printed in the order listed +above with "sync" or "nosync" always output ahead of the other +arguments, regardless of the order used when originally loading the table. +Arguments that can be repeated are ordered by value. + + +'dmsetup status' yields information on the state and health of the array. +The output is as follows (normally a single line, but expanded here for +clarity): +1: <s> <l> raid \ +2: <raid_type> <#devices> <health_chars> \ +3: <sync_ratio> <sync_action> <mismatch_cnt> + +Line 1 is the standard output produced by device-mapper. +Line 2 & 3 are produced by the raid target and are best explained by example: + 0 1960893648 raid raid4 5 AAAAA 2/490221568 init 0 +Here we can see the RAID type is raid4, there are 5 devices - all of +which are 'A'live, and the array is 2/490221568 complete with its initial +recovery. Here is a fuller description of the individual fields: + <raid_type> Same as the <raid_type> used to create the array. + <health_chars> One char for each device, indicating: 'A' = alive and + in-sync, 'a' = alive but not in-sync, 'D' = dead/failed. + <sync_ratio> The ratio indicating how much of the array has undergone + the process described by 'sync_action'. If the + 'sync_action' is "check" or "repair", then the process + of "resync" or "recover" can be considered complete. + <sync_action> One of the following possible states: + idle - No synchronization action is being performed. + frozen - The current action has been halted. + resync - Array is undergoing its initial synchronization + or is resynchronizing after an unclean shutdown + (possibly aided by a bitmap). + recover - A device in the array is being rebuilt or + replaced. + check - A user-initiated full check of the array is + being performed. All blocks are read and + checked for consistency. The number of + discrepancies found are recorded in + <mismatch_cnt>. No changes are made to the + array by this action. + repair - The same as "check", but discrepancies are + corrected. + reshape - The array is undergoing a reshape. + <mismatch_cnt> The number of discrepancies found between mirror copies + in RAID1/10 or wrong parity values found in RAID4/5/6. + This value is valid only after a "check" of the array + is performed. A healthy array has a 'mismatch_cnt' of 0. + +Message Interface +----------------- +The dm-raid target will accept certain actions through the 'message' interface. +('man dmsetup' for more information on the message interface.) These actions +include: + "idle" - Halt the current sync action. + "frozen" - Freeze the current sync action. + "resync" - Initiate/continue a resync. + "recover"- Initiate/continue a recover process. + "check" - Initiate a check (i.e. a "scrub") of the array. + "repair" - Initiate a repair of the array. + "reshape"- Currently unsupported (-EINVAL). + + +Discard Support +--------------- +The implementation of discard support among hardware vendors varies. +When a block is discarded, some storage devices will return zeroes when +the block is read. These devices set the 'discard_zeroes_data' +attribute. Other devices will return random data. Confusingly, some +devices that advertise 'discard_zeroes_data' will not reliably return +zeroes when discarded blocks are read! Since RAID 4/5/6 uses blocks +from a number of devices to calculate parity blocks and (for performance +reasons) relies on 'discard_zeroes_data' being reliable, it is important +that the devices be consistent. Blocks may be discarded in the middle +of a RAID 4/5/6 stripe and if subsequent read results are not +consistent, the parity blocks may be calculated differently at any time; +making the parity blocks useless for redundancy. It is important to +understand how your hardware behaves with discards if you are going to +enable discards with RAID 4/5/6. + +Since the behavior of storage devices is unreliable in this respect, +even when reporting 'discard_zeroes_data', by default RAID 4/5/6 +discard support is disabled -- this ensures data integrity at the +expense of losing some performance. + +Storage devices that properly support 'discard_zeroes_data' are +increasingly whitelisted in the kernel and can thus be trusted. + +For trusted devices, the following dm-raid module parameter can be set +to safely enable discard support for RAID 4/5/6: + 'devices_handle_discards_safely' + + +Version History +--------------- +1.0.0 Initial version. Support for RAID 4/5/6 +1.1.0 Added support for RAID 1 +1.2.0 Handle creation of arrays that contain failed devices. +1.3.0 Added support for RAID 10 +1.3.1 Allow device replacement/rebuild for RAID 10 +1.3.2 Fix/improve redundancy checking for RAID10 +1.4.0 Non-functional change. Removes arg from mapping function. +1.4.1 RAID10 fix redundancy validation checks (commit 55ebbb5). +1.4.2 Add RAID10 "far" and "offset" algorithm support. +1.5.0 Add message interface to allow manipulation of the sync_action. + New status (STATUSTYPE_INFO) fields: sync_action and mismatch_cnt. +1.5.1 Add ability to restore transiently failed devices on resume. +1.5.2 'mismatch_cnt' is zero unless [last_]sync_action is "check". +1.6.0 Add discard support (and devices_handle_discard_safely module param). +1.7.0 Add support for MD RAID0 mappings.
diff --git a/doc/kernel/service-time.txt b/doc/kernel/service-time.txt new file mode 100644 index 0000000..fb1d4a0 --- /dev/null +++ b/doc/kernel/service-time.txt
@@ -0,0 +1,91 @@ +dm-service-time +=============== + +dm-service-time is a path selector module for device-mapper targets, +which selects a path with the shortest estimated service time for +the incoming I/O. + +The service time for each path is estimated by dividing the total size +of in-flight I/Os on a path with the performance value of the path. +The performance value is a relative throughput value among all paths +in a path-group, and it can be specified as a table argument. + +The path selector name is 'service-time'. + +Table parameters for each path: [<repeat_count> [<relative_throughput>]] + <repeat_count>: The number of I/Os to dispatch using the selected + path before switching to the next path. + If not given, internal default is used. To check + the default value, see the activated table. + <relative_throughput>: The relative throughput value of the path + among all paths in the path-group. + The valid range is 0-100. + If not given, minimum value '1' is used. + If '0' is given, the path isn't selected while + other paths having a positive value are available. + +Status for each path: <status> <fail-count> <in-flight-size> \ + <relative_throughput> + <status>: 'A' if the path is active, 'F' if the path is failed. + <fail-count>: The number of path failures. + <in-flight-size>: The size of in-flight I/Os on the path. + <relative_throughput>: The relative throughput value of the path + among all paths in the path-group. + + +Algorithm +========= + +dm-service-time adds the I/O size to 'in-flight-size' when the I/O is +dispatched and subtracts when completed. +Basically, dm-service-time selects a path having minimum service time +which is calculated by: + + ('in-flight-size' + 'size-of-incoming-io') / 'relative_throughput' + +However, some optimizations below are used to reduce the calculation +as much as possible. + + 1. If the paths have the same 'relative_throughput', skip + the division and just compare the 'in-flight-size'. + + 2. If the paths have the same 'in-flight-size', skip the division + and just compare the 'relative_throughput'. + + 3. If some paths have non-zero 'relative_throughput' and others + have zero 'relative_throughput', ignore those paths with zero + 'relative_throughput'. + +If such optimizations can't be applied, calculate service time, and +compare service time. +If calculated service time is equal, the path having maximum +'relative_throughput' may be better. So compare 'relative_throughput' +then. + + +Examples +======== +In case that 2 paths (sda and sdb) are used with repeat_count == 128 +and sda has an average throughput 1GB/s and sdb has 4GB/s, +'relative_throughput' value may be '1' for sda and '4' for sdb. + +# echo "0 10 multipath 0 0 1 1 service-time 0 2 2 8:0 128 1 8:16 128 4" \ + dmsetup create test +# +# dmsetup table +test: 0 10 multipath 0 0 1 1 service-time 0 2 2 8:0 128 1 8:16 128 4 +# +# dmsetup status +test: 0 10 multipath 2 0 0 0 1 1 E 0 2 2 8:0 A 0 0 1 8:16 A 0 0 4 + + +Or '2' for sda and '8' for sdb would be also true. + +# echo "0 10 multipath 0 0 1 1 service-time 0 2 2 8:0 128 2 8:16 128 8" \ + dmsetup create test +# +# dmsetup table +test: 0 10 multipath 0 0 1 1 service-time 0 2 2 8:0 128 2 8:16 128 8 +# +# dmsetup status +test: 0 10 multipath 2 0 0 0 1 1 E 0 2 2 8:0 A 0 0 2 8:16 A 0 0 8
diff --git a/doc/kernel/snapshot.txt b/doc/kernel/snapshot.txt new file mode 100644 index 0000000..ad6949b --- /dev/null +++ b/doc/kernel/snapshot.txt
@@ -0,0 +1,172 @@ +Device-mapper snapshot support +============================== + +Device-mapper allows you, without massive data copying: + +*) To create snapshots of any block device i.e. mountable, saved states of +the block device which are also writable without interfering with the +original content; +*) To create device "forks", i.e. multiple different versions of the +same data stream. +*) To merge a snapshot of a block device back into the snapshot's origin +device. + +In the first two cases, dm copies only the chunks of data that get +changed and uses a separate copy-on-write (COW) block device for +storage. + +For snapshot merge the contents of the COW storage are merged back into +the origin device. + + +There are three dm targets available: +snapshot, snapshot-origin, and snapshot-merge. + +*) snapshot-origin <origin> + +which will normally have one or more snapshots based on it. +Reads will be mapped directly to the backing device. For each write, the +original data will be saved in the <COW device> of each snapshot to keep +its visible content unchanged, at least until the <COW device> fills up. + + +*) snapshot <origin> <COW device> <persistent?> <chunksize> + +A snapshot of the <origin> block device is created. Changed chunks of +<chunksize> sectors will be stored on the <COW device>. Writes will +only go to the <COW device>. Reads will come from the <COW device> or +from <origin> for unchanged data. <COW device> will often be +smaller than the origin and if it fills up the snapshot will become +useless and be disabled, returning errors. So it is important to monitor +the amount of free space and expand the <COW device> before it fills up. + +<persistent?> is P (Persistent) or N (Not persistent - will not survive +after reboot). O (Overflow) can be added as a persistent store option +to allow userspace to advertise its support for seeing "Overflow" in the +snapshot status. So supported store types are "P", "PO" and "N". + +The difference between persistent and transient is with transient +snapshots less metadata must be saved on disk - they can be kept in +memory by the kernel. + + +* snapshot-merge <origin> <COW device> <persistent> <chunksize> + +takes the same table arguments as the snapshot target except it only +works with persistent snapshots. This target assumes the role of the +"snapshot-origin" target and must not be loaded if the "snapshot-origin" +is still present for <origin>. + +Creates a merging snapshot that takes control of the changed chunks +stored in the <COW device> of an existing snapshot, through a handover +procedure, and merges these chunks back into the <origin>. Once merging +has started (in the background) the <origin> may be opened and the merge +will continue while I/O is flowing to it. Changes to the <origin> are +deferred until the merging snapshot's corresponding chunk(s) have been +merged. Once merging has started the snapshot device, associated with +the "snapshot" target, will return -EIO when accessed. + + +How snapshot is used by LVM2 +============================ +When you create the first LVM2 snapshot of a volume, four dm devices are used: + +1) a device containing the original mapping table of the source volume; +2) a device used as the <COW device>; +3) a "snapshot" device, combining #1 and #2, which is the visible snapshot + volume; +4) the "original" volume (which uses the device number used by the original + source volume), whose table is replaced by a "snapshot-origin" mapping + from device #1. + +A fixed naming scheme is used, so with the following commands: + +lvcreate -L 1G -n base volumeGroup +lvcreate -L 100M --snapshot -n snap volumeGroup/base + +we'll have this situation (with volumes in above order): + +# dmsetup table|grep volumeGroup + +volumeGroup-base-real: 0 2097152 linear 8:19 384 +volumeGroup-snap-cow: 0 204800 linear 8:19 2097536 +volumeGroup-snap: 0 2097152 snapshot 254:11 254:12 P 16 +volumeGroup-base: 0 2097152 snapshot-origin 254:11 + +# ls -lL /dev/mapper/volumeGroup-* +brw------- 1 root root 254, 11 29 ago 18:15 /dev/mapper/volumeGroup-base-real +brw------- 1 root root 254, 12 29 ago 18:15 /dev/mapper/volumeGroup-snap-cow +brw------- 1 root root 254, 13 29 ago 18:15 /dev/mapper/volumeGroup-snap +brw------- 1 root root 254, 10 29 ago 18:14 /dev/mapper/volumeGroup-base + + +How snapshot-merge is used by LVM2 +================================== +A merging snapshot assumes the role of the "snapshot-origin" while +merging. As such the "snapshot-origin" is replaced with +"snapshot-merge". The "-real" device is not changed and the "-cow" +device is renamed to <origin name>-cow to aid LVM2's cleanup of the +merging snapshot after it completes. The "snapshot" that hands over its +COW device to the "snapshot-merge" is deactivated (unless using lvchange +--refresh); but if it is left active it will simply return I/O errors. + +A snapshot will merge into its origin with the following command: + +lvconvert --merge volumeGroup/snap + +we'll now have this situation: + +# dmsetup table|grep volumeGroup + +volumeGroup-base-real: 0 2097152 linear 8:19 384 +volumeGroup-base-cow: 0 204800 linear 8:19 2097536 +volumeGroup-base: 0 2097152 snapshot-merge 254:11 254:12 P 16 + +# ls -lL /dev/mapper/volumeGroup-* +brw------- 1 root root 254, 11 29 ago 18:15 /dev/mapper/volumeGroup-base-real +brw------- 1 root root 254, 12 29 ago 18:16 /dev/mapper/volumeGroup-base-cow +brw------- 1 root root 254, 10 29 ago 18:16 /dev/mapper/volumeGroup-base + + +How to determine when a merging is complete +=========================================== +The snapshot-merge and snapshot status lines end with: + <sectors_allocated>/<total_sectors> <metadata_sectors> + +Both <sectors_allocated> and <total_sectors> include both data and metadata. +During merging, the number of sectors allocated gets smaller and +smaller. Merging has finished when the number of sectors holding data +is zero, in other words <sectors_allocated> == <metadata_sectors>. + +Here is a practical example (using a hybrid of lvm and dmsetup commands): + +# lvs + LV VG Attr LSize Origin Snap% Move Log Copy% Convert + base volumeGroup owi-a- 4.00g + snap volumeGroup swi-a- 1.00g base 18.97 + +# dmsetup status volumeGroup-snap +0 8388608 snapshot 397896/2097152 1560 + ^^^^ metadata sectors + +# lvconvert --merge -b volumeGroup/snap + Merging of volume snap started. + +# lvs volumeGroup/snap + LV VG Attr LSize Origin Snap% Move Log Copy% Convert + base volumeGroup Owi-a- 4.00g 17.23 + +# dmsetup status volumeGroup-base +0 8388608 snapshot-merge 281688/2097152 1104 + +# dmsetup status volumeGroup-base +0 8388608 snapshot-merge 180480/2097152 712 + +# dmsetup status volumeGroup-base +0 8388608 snapshot-merge 16/2097152 16 + +Merging has finished. + +# lvs + LV VG Attr LSize Origin Snap% Move Log Copy% Convert + base volumeGroup owi-a- 4.00g
diff --git a/doc/kernel/statistics.txt b/doc/kernel/statistics.txt new file mode 100644 index 0000000..170ac02 --- /dev/null +++ b/doc/kernel/statistics.txt
@@ -0,0 +1,223 @@ +DM statistics +============= + +Device Mapper supports the collection of I/O statistics on user-defined +regions of a DM device. If no regions are defined no statistics are +collected so there isn't any performance impact. Only bio-based DM +devices are currently supported. + +Each user-defined region specifies a starting sector, length and step. +Individual statistics will be collected for each step-sized area within +the range specified. + +The I/O statistics counters for each step-sized area of a region are +in the same format as /sys/block/*/stat or /proc/diskstats (see: +Documentation/iostats.txt). But two extra counters (12 and 13) are +provided: total time spent reading and writing. When the histogram +argument is used, the 14th parameter is reported that represents the +histogram of latencies. All these counters may be accessed by sending +the @stats_print message to the appropriate DM device via dmsetup. + +The reported times are in milliseconds and the granularity depends on +the kernel ticks. When the option precise_timestamps is used, the +reported times are in nanoseconds. + +Each region has a corresponding unique identifier, which we call a +region_id, that is assigned when the region is created. The region_id +must be supplied when querying statistics about the region, deleting the +region, etc. Unique region_ids enable multiple userspace programs to +request and process statistics for the same DM device without stepping +on each other's data. + +The creation of DM statistics will allocate memory via kmalloc or +fallback to using vmalloc space. At most, 1/4 of the overall system +memory may be allocated by DM statistics. The admin can see how much +memory is used by reading +/sys/module/dm_mod/parameters/stats_current_allocated_bytes + +Messages +======== + + @stats_create <range> <step> + [<number_of_optional_arguments> <optional_arguments>...] + [<program_id> [<aux_data>]] + + Create a new region and return the region_id. + + <range> + "-" - whole device + "<start_sector>+<length>" - a range of <length> 512-byte sectors + starting with <start_sector>. + + <step> + "<area_size>" - the range is subdivided into areas each containing + <area_size> sectors. + "/<number_of_areas>" - the range is subdivided into the specified + number of areas. + + <number_of_optional_arguments> + The number of optional arguments + + <optional_arguments> + The following optional arguments are supported + precise_timestamps - use precise timer with nanosecond resolution + instead of the "jiffies" variable. When this argument is + used, the resulting times are in nanoseconds instead of + milliseconds. Precise timestamps are a little bit slower + to obtain than jiffies-based timestamps. + histogram:n1,n2,n3,n4,... - collect histogram of latencies. The + numbers n1, n2, etc are times that represent the boundaries + of the histogram. If precise_timestamps is not used, the + times are in milliseconds, otherwise they are in + nanoseconds. For each range, the kernel will report the + number of requests that completed within this range. For + example, if we use "histogram:10,20,30", the kernel will + report four numbers a:b:c:d. a is the number of requests + that took 0-10 ms to complete, b is the number of requests + that took 10-20 ms to complete, c is the number of requests + that took 20-30 ms to complete and d is the number of + requests that took more than 30 ms to complete. + + <program_id> + An optional parameter. A name that uniquely identifies + the userspace owner of the range. This groups ranges together + so that userspace programs can identify the ranges they + created and ignore those created by others. + The kernel returns this string back in the output of + @stats_list message, but it doesn't use it for anything else. + If we omit the number of optional arguments, program id must not + be a number, otherwise it would be interpreted as the number of + optional arguments. + + <aux_data> + An optional parameter. A word that provides auxiliary data + that is useful to the client program that created the range. + The kernel returns this string back in the output of + @stats_list message, but it doesn't use this value for anything. + + @stats_delete <region_id> + + Delete the region with the specified id. + + <region_id> + region_id returned from @stats_create + + @stats_clear <region_id> + + Clear all the counters except the in-flight i/o counters. + + <region_id> + region_id returned from @stats_create + + @stats_list [<program_id>] + + List all regions registered with @stats_create. + + <program_id> + An optional parameter. + If this parameter is specified, only matching regions + are returned. + If it is not specified, all regions are returned. + + Output format: + <region_id>: <start_sector>+<length> <step> <program_id> <aux_data> + precise_timestamps histogram:n1,n2,n3,... + + The strings "precise_timestamps" and "histogram" are printed only + if they were specified when creating the region. + + @stats_print <region_id> [<starting_line> <number_of_lines>] + + Print counters for each step-sized area of a region. + + <region_id> + region_id returned from @stats_create + + <starting_line> + The index of the starting line in the output. + If omitted, all lines are returned. + + <number_of_lines> + The number of lines to include in the output. + If omitted, all lines are returned. + + Output format for each step-sized area of a region: + + <start_sector>+<length> counters + + The first 11 counters have the same meaning as + /sys/block/*/stat or /proc/diskstats. + + Please refer to Documentation/iostats.txt for details. + + 1. the number of reads completed + 2. the number of reads merged + 3. the number of sectors read + 4. the number of milliseconds spent reading + 5. the number of writes completed + 6. the number of writes merged + 7. the number of sectors written + 8. the number of milliseconds spent writing + 9. the number of I/Os currently in progress + 10. the number of milliseconds spent doing I/Os + 11. the weighted number of milliseconds spent doing I/Os + + Additional counters: + 12. the total time spent reading in milliseconds + 13. the total time spent writing in milliseconds + + @stats_print_clear <region_id> [<starting_line> <number_of_lines>] + + Atomically print and then clear all the counters except the + in-flight i/o counters. Useful when the client consuming the + statistics does not want to lose any statistics (those updated + between printing and clearing). + + <region_id> + region_id returned from @stats_create + + <starting_line> + The index of the starting line in the output. + If omitted, all lines are printed and then cleared. + + <number_of_lines> + The number of lines to process. + If omitted, all lines are printed and then cleared. + + @stats_set_aux <region_id> <aux_data> + + Store auxiliary data aux_data for the specified region. + + <region_id> + region_id returned from @stats_create + + <aux_data> + The string that identifies data which is useful to the client + program that created the range. The kernel returns this + string back in the output of @stats_list message, but it + doesn't use this value for anything. + +Examples +======== + +Subdivide the DM device 'vol' into 100 pieces and start collecting +statistics on them: + + dmsetup message vol 0 @stats_create - /100 + +Set the auxiliary data string to "foo bar baz" (the escape for each +space must also be escaped, otherwise the shell will consume them): + + dmsetup message vol 0 @stats_set_aux 0 foo\\ bar\\ baz + +List the statistics: + + dmsetup message vol 0 @stats_list + +Print the statistics: + + dmsetup message vol 0 @stats_print 0 + +Delete the statistics: + + dmsetup message vol 0 @stats_delete 0
diff --git a/doc/kernel/striped.txt b/doc/kernel/striped.txt new file mode 100644 index 0000000..45f3b91 --- /dev/null +++ b/doc/kernel/striped.txt
@@ -0,0 +1,57 @@ +dm-stripe +========= + +Device-Mapper's "striped" target is used to create a striped (i.e. RAID-0) +device across one or more underlying devices. Data is written in "chunks", +with consecutive chunks rotating among the underlying devices. This can +potentially provide improved I/O throughput by utilizing several physical +devices in parallel. + +Parameters: <num devs> <chunk size> [<dev path> <offset>]+ + <num devs>: Number of underlying devices. + <chunk size>: Size of each chunk of data. Must be at least as + large as the system's PAGE_SIZE. + <dev path>: Full pathname to the underlying block-device, or a + "major:minor" device-number. + <offset>: Starting sector within the device. + +One or more underlying devices can be specified. The striped device size must +be a multiple of the chunk size multiplied by the number of underlying devices. + + +Example scripts +=============== + +[[ +#!/usr/bin/perl -w +# Create a striped device across any number of underlying devices. The device +# will be called "stripe_dev" and have a chunk-size of 128k. + +my $chunk_size = 128 * 2; +my $dev_name = "stripe_dev"; +my $num_devs = @ARGV; +my @devs = @ARGV; +my ($min_dev_size, $stripe_dev_size, $i); + +if (!$num_devs) { + die("Specify at least one device\n"); +} + +$min_dev_size = `blockdev --getsize $devs[0]`; +for ($i = 1; $i < $num_devs; $i++) { + my $this_size = `blockdev --getsize $devs[$i]`; + $min_dev_size = ($min_dev_size < $this_size) ? + $min_dev_size : $this_size; +} + +$stripe_dev_size = $min_dev_size * $num_devs; +$stripe_dev_size -= $stripe_dev_size % ($chunk_size * $num_devs); + +$table = "0 $stripe_dev_size striped $num_devs $chunk_size"; +for ($i = 0; $i < $num_devs; $i++) { + $table .= " $devs[$i] 0"; +} + +`echo $table | dmsetup create $dev_name`; +]] +
diff --git a/doc/kernel/switch.txt b/doc/kernel/switch.txt new file mode 100644 index 0000000..424835e --- /dev/null +++ b/doc/kernel/switch.txt
@@ -0,0 +1,138 @@ +dm-switch +========= + +The device-mapper switch target creates a device that supports an +arbitrary mapping of fixed-size regions of I/O across a fixed set of +paths. The path used for any specific region can be switched +dynamically by sending the target a message. + +It maps I/O to underlying block devices efficiently when there is a large +number of fixed-sized address regions but there is no simple pattern +that would allow for a compact representation of the mapping such as +dm-stripe. + +Background +---------- + +Dell EqualLogic and some other iSCSI storage arrays use a distributed +frameless architecture. In this architecture, the storage group +consists of a number of distinct storage arrays ("members") each having +independent controllers, disk storage and network adapters. When a LUN +is created it is spread across multiple members. The details of the +spreading are hidden from initiators connected to this storage system. +The storage group exposes a single target discovery portal, no matter +how many members are being used. When iSCSI sessions are created, each +session is connected to an eth port on a single member. Data to a LUN +can be sent on any iSCSI session, and if the blocks being accessed are +stored on another member the I/O will be forwarded as required. This +forwarding is invisible to the initiator. The storage layout is also +dynamic, and the blocks stored on disk may be moved from member to +member as needed to balance the load. + +This architecture simplifies the management and configuration of both +the storage group and initiators. In a multipathing configuration, it +is possible to set up multiple iSCSI sessions to use multiple network +interfaces on both the host and target to take advantage of the +increased network bandwidth. An initiator could use a simple round +robin algorithm to send I/O across all paths and let the storage array +members forward it as necessary, but there is a performance advantage to +sending data directly to the correct member. + +A device-mapper table already lets you map different regions of a +device onto different targets. However in this architecture the LUN is +spread with an address region size on the order of 10s of MBs, which +means the resulting table could have more than a million entries and +consume far too much memory. + +Using this device-mapper switch target we can now build a two-layer +device hierarchy: + + Upper Tier - Determine which array member the I/O should be sent to. + Lower Tier - Load balance amongst paths to a particular member. + +The lower tier consists of a single dm multipath device for each member. +Each of these multipath devices contains the set of paths directly to +the array member in one priority group, and leverages existing path +selectors to load balance amongst these paths. We also build a +non-preferred priority group containing paths to other array members for +failover reasons. + +The upper tier consists of a single dm-switch device. This device uses +a bitmap to look up the location of the I/O and choose the appropriate +lower tier device to route the I/O. By using a bitmap we are able to +use 4 bits for each address range in a 16 member group (which is very +large for us). This is a much denser representation than the dm table +b-tree can achieve. + +Construction Parameters +======================= + + <num_paths> <region_size> <num_optional_args> [<optional_args>...] + [<dev_path> <offset>]+ + +<num_paths> + The number of paths across which to distribute the I/O. + +<region_size> + The number of 512-byte sectors in a region. Each region can be redirected + to any of the available paths. + +<num_optional_args> + The number of optional arguments. Currently, no optional arguments + are supported and so this must be zero. + +<dev_path> + The block device that represents a specific path to the device. + +<offset> + The offset of the start of data on the specific <dev_path> (in units + of 512-byte sectors). This number is added to the sector number when + forwarding the request to the specific path. Typically it is zero. + +Messages +======== + +set_region_mappings <index>:<path_nr> [<index>]:<path_nr> [<index>]:<path_nr>... + +Modify the region table by specifying which regions are redirected to +which paths. + +<index> + The region number (region size was specified in constructor parameters). + If index is omitted, the next region (previous index + 1) is used. + Expressed in hexadecimal (WITHOUT any prefix like 0x). + +<path_nr> + The path number in the range 0 ... (<num_paths> - 1). + Expressed in hexadecimal (WITHOUT any prefix like 0x). + +R<n>,<m> + This parameter allows repetitive patterns to be loaded quickly. <n> and <m> + are hexadecimal numbers. The last <n> mappings are repeated in the next <m> + slots. + +Status +====== + +No status line is reported. + +Example +======= + +Assume that you have volumes vg1/switch0 vg1/switch1 vg1/switch2 with +the same size. + +Create a switch device with 64kB region size: + dmsetup create switch --table "0 `blockdev --getsize /dev/vg1/switch0` + switch 3 128 0 /dev/vg1/switch0 0 /dev/vg1/switch1 0 /dev/vg1/switch2 0" + +Set mappings for the first 7 entries to point to devices switch0, switch1, +switch2, switch0, switch1, switch2, switch1: + dmsetup message switch 0 set_region_mappings 0:0 :1 :2 :0 :1 :2 :1 + +Set repetitive mapping. This command: + dmsetup message switch 0 set_region_mappings 1000:1 :2 R2,10 +is equivalent to: + dmsetup message switch 0 set_region_mappings 1000:1 :2 :1 :2 :1 :2 :1 :2 \ + :1 :2 :1 :2 :1 :2 :1 :2 :1 :2 +
diff --git a/doc/kernel/thin-provisioning.txt b/doc/kernel/thin-provisioning.txt new file mode 100644 index 0000000..1699a55 --- /dev/null +++ b/doc/kernel/thin-provisioning.txt
@@ -0,0 +1,396 @@ +Introduction +============ + +This document describes a collection of device-mapper targets that +between them implement thin-provisioning and snapshots. + +The main highlight of this implementation, compared to the previous +implementation of snapshots, is that it allows many virtual devices to +be stored on the same data volume. This simplifies administration and +allows the sharing of data between volumes, thus reducing disk usage. + +Another significant feature is support for an arbitrary depth of +recursive snapshots (snapshots of snapshots of snapshots ...). The +previous implementation of snapshots did this by chaining together +lookup tables, and so performance was O(depth). This new +implementation uses a single data structure to avoid this degradation +with depth. Fragmentation may still be an issue, however, in some +scenarios. + +Metadata is stored on a separate device from data, giving the +administrator some freedom, for example to: + +- Improve metadata resilience by storing metadata on a mirrored volume + but data on a non-mirrored one. + +- Improve performance by storing the metadata on SSD. + +Status +====== + +These targets are very much still in the EXPERIMENTAL state. Please +do not yet rely on them in production. But do experiment and offer us +feedback. Different use cases will have different performance +characteristics, for example due to fragmentation of the data volume. + +If you find this software is not performing as expected please mail +dm-devel@redhat.com with details and we'll try our best to improve +things for you. + +Userspace tools for checking and repairing the metadata are under +development. + +Cookbook +======== + +This section describes some quick recipes for using thin provisioning. +They use the dmsetup program to control the device-mapper driver +directly. End users will be advised to use a higher-level volume +manager such as LVM2 once support has been added. + +Pool device +----------- + +The pool device ties together the metadata volume and the data volume. +It maps I/O linearly to the data volume and updates the metadata via +two mechanisms: + +- Function calls from the thin targets + +- Device-mapper 'messages' from userspace which control the creation of new + virtual devices amongst other things. + +Setting up a fresh pool device +------------------------------ + +Setting up a pool device requires a valid metadata device, and a +data device. If you do not have an existing metadata device you can +make one by zeroing the first 4k to indicate empty metadata. + + dd if=/dev/zero of=$metadata_dev bs=4096 count=1 + +The amount of metadata you need will vary according to how many blocks +are shared between thin devices (i.e. through snapshots). If you have +less sharing than average you'll need a larger-than-average metadata device. + +As a guide, we suggest you calculate the number of bytes to use in the +metadata device as 48 * $data_dev_size / $data_block_size but round it up +to 2MB if the answer is smaller. If you're creating large numbers of +snapshots which are recording large amounts of change, you may find you +need to increase this. + +The largest size supported is 16GB: If the device is larger, +a warning will be issued and the excess space will not be used. + +Reloading a pool table +---------------------- + +You may reload a pool's table, indeed this is how the pool is resized +if it runs out of space. (N.B. While specifying a different metadata +device when reloading is not forbidden at the moment, things will go +wrong if it does not route I/O to exactly the same on-disk location as +previously.) + +Using an existing pool device +----------------------------- + + dmsetup create pool \ + --table "0 20971520 thin-pool $metadata_dev $data_dev \ + $data_block_size $low_water_mark" + +$data_block_size gives the smallest unit of disk space that can be +allocated at a time expressed in units of 512-byte sectors. +$data_block_size must be between 128 (64KB) and 2097152 (1GB) and a +multiple of 128 (64KB). $data_block_size cannot be changed after the +thin-pool is created. People primarily interested in thin provisioning +may want to use a value such as 1024 (512KB). People doing lots of +snapshotting may want a smaller value such as 128 (64KB). If you are +not zeroing newly-allocated data, a larger $data_block_size in the +region of 256000 (128MB) is suggested. + +$low_water_mark is expressed in blocks of size $data_block_size. If +free space on the data device drops below this level then a dm event +will be triggered which a userspace daemon should catch allowing it to +extend the pool device. Only one such event will be sent. +Resuming a device with a new table itself triggers an event so the +userspace daemon can use this to detect a situation where a new table +already exceeds the threshold. + +A low water mark for the metadata device is maintained in the kernel and +will trigger a dm event if free space on the metadata device drops below +it. + +Updating on-disk metadata +------------------------- + +On-disk metadata is committed every time a FLUSH or FUA bio is written. +If no such requests are made then commits will occur every second. This +means the thin-provisioning target behaves like a physical disk that has +a volatile write cache. If power is lost you may lose some recent +writes. The metadata should always be consistent in spite of any crash. + +If data space is exhausted the pool will either error or queue IO +according to the configuration (see: error_if_no_space). If metadata +space is exhausted or a metadata operation fails: the pool will error IO +until the pool is taken offline and repair is performed to 1) fix any +potential inconsistencies and 2) clear the flag that imposes repair. +Once the pool's metadata device is repaired it may be resized, which +will allow the pool to return to normal operation. Note that if a pool +is flagged as needing repair, the pool's data and metadata devices +cannot be resized until repair is performed. It should also be noted +that when the pool's metadata space is exhausted the current metadata +transaction is aborted. Given that the pool will cache IO whose +completion may have already been acknowledged to upper IO layers +(e.g. filesystem) it is strongly suggested that consistency checks +(e.g. fsck) be performed on those layers when repair of the pool is +required. + +Thin provisioning +----------------- + +i) Creating a new thinly-provisioned volume. + + To create a new thinly- provisioned volume you must send a message to an + active pool device, /dev/mapper/pool in this example. + + dmsetup message /dev/mapper/pool 0 "create_thin 0" + + Here '0' is an identifier for the volume, a 24-bit number. It's up + to the caller to allocate and manage these identifiers. If the + identifier is already in use, the message will fail with -EEXIST. + +ii) Using a thinly-provisioned volume. + + Thinly-provisioned volumes are activated using the 'thin' target: + + dmsetup create thin --table "0 2097152 thin /dev/mapper/pool 0" + + The last parameter is the identifier for the thinp device. + +Internal snapshots +------------------ + +i) Creating an internal snapshot. + + Snapshots are created with another message to the pool. + + N.B. If the origin device that you wish to snapshot is active, you + must suspend it before creating the snapshot to avoid corruption. + This is NOT enforced at the moment, so please be careful! + + dmsetup suspend /dev/mapper/thin + dmsetup message /dev/mapper/pool 0 "create_snap 1 0" + dmsetup resume /dev/mapper/thin + + Here '1' is the identifier for the volume, a 24-bit number. '0' is the + identifier for the origin device. + +ii) Using an internal snapshot. + + Once created, the user doesn't have to worry about any connection + between the origin and the snapshot. Indeed the snapshot is no + different from any other thinly-provisioned device and can be + snapshotted itself via the same method. It's perfectly legal to + have only one of them active, and there's no ordering requirement on + activating or removing them both. (This differs from conventional + device-mapper snapshots.) + + Activate it exactly the same way as any other thinly-provisioned volume: + + dmsetup create snap --table "0 2097152 thin /dev/mapper/pool 1" + +External snapshots +------------------ + +You can use an external _read only_ device as an origin for a +thinly-provisioned volume. Any read to an unprovisioned area of the +thin device will be passed through to the origin. Writes trigger +the allocation of new blocks as usual. + +One use case for this is VM hosts that want to run guests on +thinly-provisioned volumes but have the base image on another device +(possibly shared between many VMs). + +You must not write to the origin device if you use this technique! +Of course, you may write to the thin device and take internal snapshots +of the thin volume. + +i) Creating a snapshot of an external device + + This is the same as creating a thin device. + You don't mention the origin at this stage. + + dmsetup message /dev/mapper/pool 0 "create_thin 0" + +ii) Using a snapshot of an external device. + + Append an extra parameter to the thin target specifying the origin: + + dmsetup create snap --table "0 2097152 thin /dev/mapper/pool 0 /dev/image" + + N.B. All descendants (internal snapshots) of this snapshot require the + same extra origin parameter. + +Deactivation +------------ + +All devices using a pool must be deactivated before the pool itself +can be. + + dmsetup remove thin + dmsetup remove snap + dmsetup remove pool + +Reference +========= + +'thin-pool' target +------------------ + +i) Constructor + + thin-pool <metadata dev> <data dev> <data block size (sectors)> \ + <low water mark (blocks)> [<number of feature args> [<arg>]*] + + Optional feature arguments: + + skip_block_zeroing: Skip the zeroing of newly-provisioned blocks. + + ignore_discard: Disable discard support. + + no_discard_passdown: Don't pass discards down to the underlying + data device, but just remove the mapping. + + read_only: Don't allow any changes to be made to the pool + metadata. + + error_if_no_space: Error IOs, instead of queueing, if no space. + + Data block size must be between 64KB (128 sectors) and 1GB + (2097152 sectors) inclusive. + + +ii) Status + + <transaction id> <used metadata blocks>/<total metadata blocks> + <used data blocks>/<total data blocks> <held metadata root> + [no_]discard_passdown ro|rw + + transaction id: + A 64-bit number used by userspace to help synchronise with metadata + from volume managers. + + used data blocks / total data blocks + If the number of free blocks drops below the pool's low water mark a + dm event will be sent to userspace. This event is edge-triggered and + it will occur only once after each resume so volume manager writers + should register for the event and then check the target's status. + + held metadata root: + The location, in blocks, of the metadata root that has been + 'held' for userspace read access. '-' indicates there is no + held root. + + discard_passdown|no_discard_passdown + Whether or not discards are actually being passed down to the + underlying device. When this is enabled when loading the table, + it can get disabled if the underlying device doesn't support it. + + ro|rw|out_of_data_space + If the pool encounters certain types of device failures it will + drop into a read-only metadata mode in which no changes to + the pool metadata (like allocating new blocks) are permitted. + + In serious cases where even a read-only mode is deemed unsafe + no further I/O will be permitted and the status will just + contain the string 'Fail'. The userspace recovery tools + should then be used. + + error_if_no_space|queue_if_no_space + If the pool runs out of data or metadata space, the pool will + either queue or error the IO destined to the data device. The + default is to queue the IO until more space is added or the + 'no_space_timeout' expires. The 'no_space_timeout' dm-thin-pool + module parameter can be used to change this timeout -- it + defaults to 60 seconds but may be disabled using a value of 0. + + needs_check + A metadata operation has failed, resulting in the needs_check + flag being set in the metadata's superblock. The metadata + device must be deactivated and checked/repaired before the + thin-pool can be made fully operational again. '-' indicates + needs_check is not set. + +iii) Messages + + create_thin <dev id> + + Create a new thinly-provisioned device. + <dev id> is an arbitrary unique 24-bit identifier chosen by + the caller. + + create_snap <dev id> <origin id> + + Create a new snapshot of another thinly-provisioned device. + <dev id> is an arbitrary unique 24-bit identifier chosen by + the caller. + <origin id> is the identifier of the thinly-provisioned device + of which the new device will be a snapshot. + + delete <dev id> + + Deletes a thin device. Irreversible. + + set_transaction_id <current id> <new id> + + Userland volume managers, such as LVM, need a way to + synchronise their external metadata with the internal metadata of the + pool target. The thin-pool target offers to store an + arbitrary 64-bit transaction id and return it on the target's + status line. To avoid races you must provide what you think + the current transaction id is when you change it with this + compare-and-swap message. + + reserve_metadata_snap + + Reserve a copy of the data mapping btree for use by userland. + This allows userland to inspect the mappings as they were when + this message was executed. Use the pool's status command to + get the root block associated with the metadata snapshot. + + release_metadata_snap + + Release a previously reserved copy of the data mapping btree. + +'thin' target +------------- + +i) Constructor + + thin <pool dev> <dev id> [<external origin dev>] + + pool dev: + the thin-pool device, e.g. /dev/mapper/my_pool or 253:0 + + dev id: + the internal device identifier of the device to be + activated. + + external origin dev: + an optional block device outside the pool to be treated as a + read-only snapshot origin: reads to unprovisioned areas of the + thin target will be mapped to this device. + +The pool doesn't store any size against the thin devices. If you +load a thin target that is smaller than you've been using previously, +then you'll have no access to blocks mapped beyond the end. If you +load a target that is bigger than before, then extra blocks will be +provisioned as and when needed. + +ii) Status + + <nr mapped sectors> <highest mapped sector> + + If the pool has encountered device errors and failed, the status + will just contain the string 'Fail'. The userspace recovery + tools should then be used.
diff --git a/doc/kernel/uevent.txt b/doc/kernel/uevent.txt new file mode 100644 index 0000000..07edbd8 --- /dev/null +++ b/doc/kernel/uevent.txt
@@ -0,0 +1,97 @@ +The device-mapper uevent code adds the capability to device-mapper to create +and send kobject uevents (uevents). Previously device-mapper events were only +available through the ioctl interface. The advantage of the uevents interface +is the event contains environment attributes providing increased context for +the event avoiding the need to query the state of the device-mapper device after +the event is received. + +There are two functions currently for device-mapper events. The first function +listed creates the event and the second function sends the event(s). + +void dm_path_uevent(enum dm_uevent_type event_type, struct dm_target *ti, + const char *path, unsigned nr_valid_paths) + +void dm_send_uevents(struct list_head *events, struct kobject *kobj) + + +The variables added to the uevent environment are: + +Variable Name: DM_TARGET +Uevent Action(s): KOBJ_CHANGE +Type: string +Description: +Value: Name of device-mapper target that generated the event. + +Variable Name: DM_ACTION +Uevent Action(s): KOBJ_CHANGE +Type: string +Description: +Value: Device-mapper specific action that caused the uevent action. + PATH_FAILED - A path has failed. + PATH_REINSTATED - A path has been reinstated. + +Variable Name: DM_SEQNUM +Uevent Action(s): KOBJ_CHANGE +Type: unsigned integer +Description: A sequence number for this specific device-mapper device. +Value: Valid unsigned integer range. + +Variable Name: DM_PATH +Uevent Action(s): KOBJ_CHANGE +Type: string +Description: Major and minor number of the path device pertaining to this +event. +Value: Path name in the form of "Major:Minor" + +Variable Name: DM_NR_VALID_PATHS +Uevent Action(s): KOBJ_CHANGE +Type: unsigned integer +Description: +Value: Valid unsigned integer range. + +Variable Name: DM_NAME +Uevent Action(s): KOBJ_CHANGE +Type: string +Description: Name of the device-mapper device. +Value: Name + +Variable Name: DM_UUID +Uevent Action(s): KOBJ_CHANGE +Type: string +Description: UUID of the device-mapper device. +Value: UUID. (Empty string if there isn't one.) + +An example of the uevents generated as captured by udevmonitor is shown +below. + +1.) Path failure. +UEVENT[1192521009.711215] change@/block/dm-3 +ACTION=change +DEVPATH=/block/dm-3 +SUBSYSTEM=block +DM_TARGET=multipath +DM_ACTION=PATH_FAILED +DM_SEQNUM=1 +DM_PATH=8:32 +DM_NR_VALID_PATHS=0 +DM_NAME=mpath2 +DM_UUID=mpath-35333333000002328 +MINOR=3 +MAJOR=253 +SEQNUM=1130 + +2.) Path reinstate. +UEVENT[1192521132.989927] change@/block/dm-3 +ACTION=change +DEVPATH=/block/dm-3 +SUBSYSTEM=block +DM_TARGET=multipath +DM_ACTION=PATH_REINSTATED +DM_SEQNUM=2 +DM_PATH=8:32 +DM_NR_VALID_PATHS=1 +DM_NAME=mpath2 +DM_UUID=mpath-35333333000002328 +MINOR=3 +MAJOR=253 +SEQNUM=1131
diff --git a/doc/kernel/verity.txt b/doc/kernel/verity.txt new file mode 100644 index 0000000..89fd8f9 --- /dev/null +++ b/doc/kernel/verity.txt
@@ -0,0 +1,208 @@ +dm-verity +========== + +Device-Mapper's "verity" target provides transparent integrity checking of +block devices using a cryptographic digest provided by the kernel crypto API. +This target is read-only. + +Construction Parameters +======================= + <version> <dev> <hash_dev> + <data_block_size> <hash_block_size> + <num_data_blocks> <hash_start_block> + <algorithm> <digest> <salt> + [<#opt_params> <opt_params>] + +<version> + This is the type of the on-disk hash format. + + 0 is the original format used in the Chromium OS. + The salt is appended when hashing, digests are stored continuously and + the rest of the block is padded with zeroes. + + 1 is the current format that should be used for new devices. + The salt is prepended when hashing and each digest is + padded with zeroes to the power of two. + +<dev> + This is the device containing data, the integrity of which needs to be + checked. It may be specified as a path, like /dev/sdaX, or a device number, + <major>:<minor>. + +<hash_dev> + This is the device that supplies the hash tree data. It may be + specified similarly to the device path and may be the same device. If the + same device is used, the hash_start should be outside the configured + dm-verity device. + +<data_block_size> + The block size on a data device in bytes. + Each block corresponds to one digest on the hash device. + +<hash_block_size> + The size of a hash block in bytes. + +<num_data_blocks> + The number of data blocks on the data device. Additional blocks are + inaccessible. You can place hashes to the same partition as data, in this + case hashes are placed after <num_data_blocks>. + +<hash_start_block> + This is the offset, in <hash_block_size>-blocks, from the start of hash_dev + to the root block of the hash tree. + +<algorithm> + The cryptographic hash algorithm used for this device. This should + be the name of the algorithm, like "sha1". + +<digest> + The hexadecimal encoding of the cryptographic hash of the root hash block + and the salt. This hash should be trusted as there is no other authenticity + beyond this point. + +<salt> + The hexadecimal encoding of the salt value. + +<#opt_params> + Number of optional parameters. If there are no optional parameters, + the optional paramaters section can be skipped or #opt_params can be zero. + Otherwise #opt_params is the number of following arguments. + + Example of optional parameters section: + 1 ignore_corruption + +ignore_corruption + Log corrupted blocks, but allow read operations to proceed normally. + +restart_on_corruption + Restart the system when a corrupted block is discovered. This option is + not compatible with ignore_corruption and requires user space support to + avoid restart loops. + +ignore_zero_blocks + Do not verify blocks that are expected to contain zeroes and always return + zeroes instead. This may be useful if the partition contains unused blocks + that are not guaranteed to contain zeroes. + +use_fec_from_device <fec_dev> + Use forward error correction (FEC) to recover from corruption if hash + verification fails. Use encoding data from the specified device. This + may be the same device where data and hash blocks reside, in which case + fec_start must be outside data and hash areas. + + If the encoding data covers additional metadata, it must be accessible + on the hash device after the hash blocks. + + Note: block sizes for data and hash devices must match. Also, if the + verity <dev> is encrypted the <fec_dev> should be too. + +fec_roots <num> + Number of generator roots. This equals to the number of parity bytes in + the encoding data. For example, in RS(M, N) encoding, the number of roots + is M-N. + +fec_blocks <num> + The number of encoding data blocks on the FEC device. The block size for + the FEC device is <data_block_size>. + +fec_start <offset> + This is the offset, in <data_block_size> blocks, from the start of the + FEC device to the beginning of the encoding data. + + +Theory of operation +=================== + +dm-verity is meant to be set up as part of a verified boot path. This +may be anything ranging from a boot using tboot or trustedgrub to just +booting from a known-good device (like a USB drive or CD). + +When a dm-verity device is configured, it is expected that the caller +has been authenticated in some way (cryptographic signatures, etc). +After instantiation, all hashes will be verified on-demand during +disk access. If they cannot be verified up to the root node of the +tree, the root hash, then the I/O will fail. This should detect +tampering with any data on the device and the hash data. + +Cryptographic hashes are used to assert the integrity of the device on a +per-block basis. This allows for a lightweight hash computation on first read +into the page cache. Block hashes are stored linearly, aligned to the nearest +block size. + +If forward error correction (FEC) support is enabled any recovery of +corrupted data will be verified using the cryptographic hash of the +corresponding data. This is why combining error correction with +integrity checking is essential. + +Hash Tree +--------- + +Each node in the tree is a cryptographic hash. If it is a leaf node, the hash +of some data block on disk is calculated. If it is an intermediary node, +the hash of a number of child nodes is calculated. + +Each entry in the tree is a collection of neighboring nodes that fit in one +block. The number is determined based on block_size and the size of the +selected cryptographic digest algorithm. The hashes are linearly-ordered in +this entry and any unaligned trailing space is ignored but included when +calculating the parent node. + +The tree looks something like: + +alg = sha256, num_blocks = 32768, block_size = 4096 + + [ root ] + / . . . \ + [entry_0] [entry_1] + / . . . \ . . . \ + [entry_0_0] . . . [entry_0_127] . . . . [entry_1_127] + / ... \ / . . . \ / \ + blk_0 ... blk_127 blk_16256 blk_16383 blk_32640 . . . blk_32767 + + +On-disk format +============== + +The verity kernel code does not read the verity metadata on-disk header. +It only reads the hash blocks which directly follow the header. +It is expected that a user-space tool will verify the integrity of the +verity header. + +Alternatively, the header can be omitted and the dmsetup parameters can +be passed via the kernel command-line in a rooted chain of trust where +the command-line is verified. + +Directly following the header (and with sector number padded to the next hash +block boundary) are the hash blocks which are stored a depth at a time +(starting from the root), sorted in order of increasing index. + +The full specification of kernel parameters and on-disk metadata format +is available at the cryptsetup project's wiki page + https://gitlab.com/cryptsetup/cryptsetup/wikis/DMVerity + +Status +====== +V (for Valid) is returned if every check performed so far was valid. +If any check failed, C (for Corruption) is returned. + +Example +======= +Set up a device: + # dmsetup create vroot --readonly --table \ + "0 2097152 verity 1 /dev/sda1 /dev/sda2 4096 4096 262144 1 sha256 "\ + "4392712ba01368efdf14b05c76f9e4df0d53664630b5d48632ed17a137f39076 "\ + "1234000000000000000000000000000000000000000000000000000000000000" + +A command line tool veritysetup is available to compute or verify +the hash tree or activate the kernel device. This is available from +the cryptsetup upstream repository https://gitlab.com/cryptsetup/cryptsetup/ +(as a libcryptsetup extension). + +Create hash on the device: + # veritysetup format /dev/sda1 /dev/sda2 + ... + Root hash: 4392712ba01368efdf14b05c76f9e4df0d53664630b5d48632ed17a137f39076 + +Activate the device: + # veritysetup create vroot /dev/sda1 /dev/sda2 \ + 4392712ba01368efdf14b05c76f9e4df0d53664630b5d48632ed17a137f39076
diff --git a/doc/kernel/zero.txt b/doc/kernel/zero.txt new file mode 100644 index 0000000..20fb38e --- /dev/null +++ b/doc/kernel/zero.txt
@@ -0,0 +1,37 @@ +dm-zero +======= + +Device-Mapper's "zero" target provides a block-device that always returns +zero'd data on reads and silently drops writes. This is similar behavior to +/dev/zero, but as a block-device instead of a character-device. + +Dm-zero has no target-specific parameters. + +One very interesting use of dm-zero is for creating "sparse" devices in +conjunction with dm-snapshot. A sparse device reports a device-size larger +than the amount of actual storage space available for that device. A user can +write data anywhere within the sparse device and read it back like a normal +device. Reads to previously unwritten areas will return a zero'd buffer. When +enough data has been written to fill up the actual storage space, the sparse +device is deactivated. This can be very useful for testing device and +filesystem limitations. + +To create a sparse device, start by creating a dm-zero device that's the +desired size of the sparse device. For this example, we'll assume a 10TB +sparse device. + +TEN_TERABYTES=`expr 10 \* 1024 \* 1024 \* 1024 \* 2` # 10 TB in sectors +echo "0 $TEN_TERABYTES zero" | dmsetup create zero1 + +Then create a snapshot of the zero device, using any available block-device as +the COW device. The size of the COW device will determine the amount of real +space available to the sparse device. For this example, we'll assume /dev/sdb1 +is an available 10GB partition. + +echo "0 $TEN_TERABYTES snapshot /dev/mapper/zero1 /dev/sdb1 p 128" | \ + dmsetup create sparse1 + +This will create a 10TB sparse device called /dev/mapper/sparse1 that has +10GB of actual storage space available. If more than 10GB of data is written +to this device, it will start returning I/O errors. +
diff --git a/doc/lvm2-raid.txt b/doc/lvm2-raid.txt new file mode 100644 index 0000000..a6f0915 --- /dev/null +++ b/doc/lvm2-raid.txt
@@ -0,0 +1,475 @@ +======================= += LVM RAID Design Doc = +======================= + +############################# +# Chapter 1: User-Interface # +############################# + +***************** CREATING A RAID DEVICE ****************** + +01: lvcreate --type <RAID type> \ +02: [--regionsize <size>] \ +03: [-i/--stripes <#>] [-I,--stripesize <size>] \ +04: [-m/--mirrors <#>] \ +05: [--[min|max]recoveryrate <kB/sec/disk>] \ +06: [--stripecache <size>] \ +07: [--writemostly <devices>] \ +08: [--maxwritebehind <size>] \ +09: [[no]sync] \ +10: <Other normal args, like: -L 5G -n lv vg> \ +11: [devices] + +Line 01: +I don't intend for there to be shorthand options for specifying the +segment type. The available RAID types are: + "raid0" - Stripe [NOT IMPLEMENTED] + "raid1" - should replace DM Mirroring + "raid10" - striped mirrors, [NOT IMPLEMENTED] + "raid4" - RAID4 + "raid5" - Same as "raid5_ls" (Same default as MD) + "raid5_la" - RAID5 Rotating parity 0 with data continuation + "raid5_ra" - RAID5 Rotating parity N with data continuation + "raid5_ls" - RAID5 Rotating parity 0 with data restart + "raid5_rs" - RAID5 Rotating parity N with data restart + "raid6" - Same as "raid6_zr" + "raid6_zr" - RAID6 Rotating parity 0 with data restart + "raid6_nr" - RAID6 Rotating parity N with data restart + "raid6_nc" - RAID6 Rotating parity N with data continuation +The exception to 'no shorthand options' will be where the RAID implementations +can displace traditional tagets. This is the case with 'mirror' and 'raid1'. +In this case, "mirror_segtype_default" - found under the "global" section in +lvm.conf - can be set to "mirror" or "raid1". The segment type inferred when +the '-m' option is used will be taken from this setting. The default segment +types can be overridden on the command line by using the '--type' argument. + +Line 02: +Region size is relevant for all RAID types. It defines the granularity for +which the bitmap will track the active areas of disk. The default is currently +4MiB. I see no reason to change this unless it is a problem for MD performance. +MD does impose a restriction of 2^21 regions for a given device, however. This +means two things: 1) we should never need a metadata area larger than +8kiB+sizeof(superblock)+bitmap_offset (IOW, pretty small) and 2) the region +size will have to be upwardly revised if the device is larger than 8TiB +(assuming defaults). + +Line 03/04: +The '-m/--mirrors' option is only relevant to RAID1 and will be used just like +it is today for DM mirroring. For all other RAID types, -i/--stripes and +-I/--stripesize are relevant. The former will specify the number of data +devices that will be used for striping. For example, if the user specifies +'--type raid0 -i 3', then 3 devices are needed. If the user specifies +'--type raid6 -i 3', then 5 devices are needed. The -I/--stripesize may be +confusing to MD users, as they use the term "chunksize". I think they will +adapt without issue and I don't wish to create a conflict with the term +"chunksize" that we use for snapshots. + +Line 05/06/07: +I'm still not clear on how to specify these options. Some are easier than +others. '--writemostly' is particularly hard because it involves specifying +which devices shall be 'write-mostly' and thus, also have 'max-write-behind' +applied to them. It has been suggested that a '--readmostly'/'--readfavored' +or similar option could be introduced as a way to specify a primary disk vs. +specifying all the non-primary disks via '--writemostly'. I like this idea, +but haven't come up with a good name yet. Thus, these will remain +unimplemented until future specification. + +Line 09/10/11: +These are familiar. + +Further creation related ideas: +Today, you can specify '--type mirror' without an '-m/--mirrors' argument +necessary. The number of devices defaults to two (and the log defaults to +'disk'). A similar thing should happen with the RAID types. All of them +should default to having two data devices unless otherwise specified. This +would mean a total number of 2 devices for RAID 0/1, 3 devices for RAID 4/5, +and 4 devices for RAID 6/10. + + +***************** CONVERTING A RAID DEVICE ****************** + +01: lvconvert [--type <RAID type>] \ +02: [-R/--regionsize <size>] \ +03: [-i/--stripes <#>] [-I,--stripesize <size>] \ +04: [-m/--mirrors <#>] \ +05: [--merge] +06: [--splitmirrors <#> [--trackchanges]] \ +07: [--replace <sub_lv|device>] \ +08: [--[min|max]recoveryrate <kB/sec/disk>] \ +09: [--stripecache <size>] \ +10: [--writemostly <devices>] \ +11: [--maxwritebehind <size>] \ +12: vg/lv +13: [devices] + +lvconvert should work exactly as it does now when dealing with mirrors - +even if(when) we switch to MD RAID1. Of course, there are no plans to +allow the presense of the metadata area to be configurable (e.g. --corelog). +It will be simple enough to detect if the LV being up/down-converted is +new or old-style mirroring. + +If we choose to use MD RAID0 as well, it will be possible to change the +number of stripes and the stripesize. It is therefore conceivable to see +something like, 'lvconvert -i +1 vg/lv'. + +Line 01: +It is possible to change the RAID type of an LV - even if that LV is already +a RAID device of a different type. For example, you could change from +RAID4 to RAID5 or RAID5 to RAID6. + +Line 02/03/04: +These are familiar options - all of which would now be available as options +for change. (However, it'd be nice if we didn't have regionsize in there. +It's simple on the kernel side, but is just an extra - often unecessary - +parameter to many functions in the LVM codebase.) + +Line 05: +This option is used to merge an LV back into a RAID1 array - provided it was +split for temporary read-only use by '--splitmirrors 1 --trackchanges'. + +Line 06: +The '--splitmirrors <#>' argument should be familiar from the "mirror" segment +type. It allows RAID1 images to be split from the array to form a new LV. +Either the original LV or the split LV - or both - could become a linear LV as +a result. If the '--trackchanges' argument is specified in addition to +'--splitmirrors', an LV will be split from the array. It will be read-only. +This operation does not change the original array - except that it uses an empty +slot to hold the position of the split LV which it expects to return in the +future (see the '--merge' argument). It tracks any changes that occur to the +array while the slot is kept in reserve. If the LV is merged back into the +array, only the changes are resync'ed to the returning image. Repeating the +'lvconvert' operation without the '--trackchanges' option will complete the +split of the LV permanently. + +Line 07: +This option allows the user to specify a sub_lv (e.g. a mirror image) or +a particular device for replacement. The device (or all the devices in +the sub_lv) will be removed and replaced with different devices from the +VG. + +Line 08/09/10/11: +It should be possible to alter these parameters of a RAID device. As with +lvcreate, however, I'm not entirely certain how to best define some of these. +We don't need all the capabilities at once though, so it isn't a pressing +issue. + +Line 12: +The LV to operate on. + +Line 13: +Devices that are to be used to satisfy the conversion request. If the +operation removes devices or splits a mirror, then the devices specified +form the list of candidates for removal. If the operation adds or replaces +devices, then the devices specified form the list of candidates for allocation. + + + +############################################### +# Chapter 2: LVM RAID internal representation # +############################################### + +The internal representation is somewhat like mirroring, but with alterations +for the different metadata components. LVM mirroring has a single log LV, +but RAID will have one for each data device. Because of this, I've added a +new 'areas' list to the 'struct lv_segment' - 'meta_areas'. There is exactly +a one-to-one relationship between 'areas' and 'meta_areas'. The 'areas' array +still holds the data sub-lv's (similar to mirroring), while the 'meta_areas' +array holds the metadata sub-lv's (akin to the mirroring log device). + +The sub_lvs will be named '%s_rimage_%d' instead of '%s_mimage_%d' as it is +for mirroring, and '%s_rmeta_%d' instead of '%s_mlog'. Thus, you can imagine +an LV named 'foo' with the following layout: +foo +[foo's lv_segment] +| +|-> foo_rimage_0 (areas[0]) +| [foo_rimage_0's lv_segment] +|-> foo_rimage_1 (areas[1]) +| [foo_rimage_1's lv_segment] +| +|-> foo_rmeta_0 (meta_areas[0]) +| [foo_rmeta_0's lv_segment] +|-> foo_rmeta_1 (meta_areas[1]) +| [foo_rmeta_1's lv_segment] + +LVM Meta-data format +==================== +The RAID format will need to be able to store parameters that are unique to +RAID and unique to specific RAID sub-devices. It will be modeled after that +of mirroring. + +Here is an example of the mirroring layout: +lv { + id = "agL1vP-1B8Z-5vnB-41cS-lhBJ-Gcvz-dh3L3H" + status = ["READ", "WRITE", "VISIBLE"] + flags = [] + segment_count = 1 + + segment1 { + start_extent = 0 + extent_count = 125 # 500 Megabytes + + type = "mirror" + mirror_count = 2 + mirror_log = "lv_mlog" + region_size = 1024 + + mirrors = [ + "lv_mimage_0", 0, + "lv_mimage_1", 0 + ] + } +} + +The real trick is dealing with the metadata devices. Mirroring has an entry, +'mirror_log', in the top-level segment. This won't work for RAID because there +is a one-to-one mapping between the data devices and the metadata devices. The +mirror devices are layed-out in sub-device/le pairs. The 'le' parameter is +redundant since it will always be zero. So for RAID, I have simple put the +metadata and data devices in pairs without the 'le' parameter. + +RAID metadata: +lv { + id = "EnpqAM-5PEg-i9wB-5amn-P116-1T8k-nS3GfD" + status = ["READ", "WRITE", "VISIBLE"] + flags = [] + segment_count = 1 + + segment1 { + start_extent = 0 + extent_count = 125 # 500 Megabytes + + type = "raid1" + device_count = 2 + region_size = 1024 + + raids = [ + "lv_rmeta_0", "lv_rimage_0", + "lv_rmeta_1", "lv_rimage_1", + ] + } +} + +The metadata also must be capable of representing the various tunables. We +already have a good example for one from mirroring, region_size. +'max_write_behind', 'stripe_cache', and '[min|max]_recovery_rate' could also +be handled in this way. However, 'write_mostly' cannot be handled in this +way, because it is a characteristic associated with the sub_lvs, not the +array as a whole. In these cases, the status field of the sub-lv's themselves +will hold these flags - the meaning being only useful in the larger context. + + +############################################## +# Chapter 3: LVM RAID implementation details # +############################################## + +New Segment Type(s) +=================== +I've created a new file 'lib/raid/raid.c' that will handle the various different +RAID types. While there will be a unique segment type for each RAID variant, +they will all share a common backend - segtype_handler functions and +segtype->flags = SEG_RAID. + +I'm also adding a new field to 'struct segment_type', parity_devs. For every +segment_type except RAID4/5/6, this will be 0. This field facilitates in +allocation and size calculations. For example, the lvcreate for RAID5 would +look something like: +~> lvcreate --type raid5 -L 30G -i 3 -n my_raid5 my_vg +or +~> lvcreate --type raid5 -n my_raid5 my_vg /dev/sd[bcdef]1 + +In the former case, the stripe count (3) and device size are computed, and +then 'segtype->parity_devs' extra devices are allocated of the same size. In +the latter case, the number of PVs is determined and 'segtype->parity_devs' is +subtracted off to determine the number of stripes. + +This should also work in the case of RAID10 and doing things in this manor +should not affect the way size is calculated via the area_multiple. + +Allocation +========== +When a RAID device is created, metadata LVs must be created along with the +data LVs that will ultimately compose the top-level RAID array. For the +foreseeable future, the metadata LVs must reside on the same device as (or +at least one of the devices that compose) the data LV. We use this property +to simplify the allocation process. Rather than allocating for the data LVs +and then asking for a small chunk of space on the same device (or the other +way around), we simply ask for the aggregate size of the data LV plus the +metadata LV. Once we have the space allocated, we divide it between the +metadata and data LVs. This also greatly simplifies the process of finding +parallel space for all the data LVs that will compose the RAID array. When +a RAID device is resized, we will not need to take the metadata LV into +account, because it will already be present. + +Apart from the metadata areas, the other unique characteristic of RAID +devices is the parity device count. The number of parity devices does nothing +to the calculation of size-per-device. The 'area_multiple' means nothing +here. The parity devices will simply be the same size as all the other devices +and will also require a metadata LV (i.e. it is treated no differently than +the other devices). + +Therefore, to allocate space for RAID devices, we need to know two things: +1) how many parity devices are required and 2) does an allocated area need to +be split out for the metadata LVs after finding the space to fill the request. +We simply add these two fields to the 'alloc_handle' data structure as, +'parity_count' and 'alloc_and_split_meta'. These two fields get set in +'_alloc_init'. The 'segtype->parity_devs' holds the number of parity +drives and can be directly copied to 'ah->parity_count' and +'alloc_and_split_meta' is set when a RAID segtype is detected and +'metadata_area_count' has been specified. With these two variables set, we +can calculate how many allocated areas we need. Also, in the routines that +find the actual space, they stop not when they have found ah->area_count but +when they have found (ah->area_count + ah->parity_count). + +Conversion +========== +RAID -> RAID, adding images +--------------------------- +When adding images to a RAID array, metadata and data components must be added +as a pair. It is best to perform as many operations as possible before writing +new LVM metadata. This allows us to error-out without having to unwind any +changes. It also makes things easier if the machine should crash during a +conversion operation. Thus, the actions performed when adding a new image are: + 1) Allocate the required number of metadata/data pairs using the method + describe above in 'Allocation' (i.e. find the metadata/data space + as one unit and split the space between them after found - this keeps + them together on the same device). + 2) Form the metadata/data LVs from the allocated space (leave them + visible) - setting required RAID_[IMAGE | META] flags as appropriate. + 3) Write the LVM metadata + 4) Activate and clear the metadata LVs. The clearing of the metadata + requires the LVM metadata be written (step 3) and is a requirement + before adding the new metadata LVs to the array. If the metadata + is not cleared, it carry residual superblock state from a previous + array the device may have been part of. + 5) Deactivate new sub-LVs and set them "hidden". + 6) expand the 'first_seg(raid_lv)->areas' and '->meta_areas' array + for inclusion of the new sub-LVs + 7) Add new sub-LVs and update 'first_seg(raid_lv)->area_count' + 8) Commit new LVM metadata +Failure during any of these steps will not affect the original RAID array. In +the worst scenario, the user may have to remove the new sub-LVs that did not +yet make it into the array. + +RAID -> RAID, removing images +----------------------------- +To remove images from a RAID, the metadata/data LV pairs must be removed +together. This is pretty straight-forward, but one place where RAID really +differs from the "mirror" segment type is how the resulting "holes" are filled. +When a device is removed from a "mirror" segment type, it is identified, moved +to the end of the 'mirrored_seg->areas' array, and then removed. This action +causes the other images to shift down and fill the position of the device which +was removed. While "raid1" could be handled in this way, the other RAID types +could not be - it would corrupt the ordering of the data on the array. Thus, +when a device is removed from a RAID array, the corresponding metadata/data +sub-LVs are removed from the 'raid_seg->meta_areas' and 'raid_seg->areas' arrays. +The slot in these 'lv_segment_area' arrays are set to 'AREA_UNASSIGNED'. RAID +is perfectly happy to construct a DM table mapping with '- -' if it comes across +area assigned in such a way. The pair of dashes is a valid way to tell the RAID +kernel target that the slot should be considered empty. So, we can remove +devices from a RAID array without affecting the correct operation of the RAID. +(It also becomes easy to replace the empty slots properly if a spare device is +available.) In the case of RAID1 device removal, the empty slot can be safely +eliminated. This is done by shifting the higher indexed devices down to fill +the slot. Even the names of the images will be renamed to properly reflect +their index in the array. Unlike the "mirror" segment type, you will never have +an image named "*_rimage_1" occupying the index position 0. + +As with adding images, removing images holds off on commiting LVM metadata +until all possible changes have been made. This reduces the likelyhood of bad +intermediate stages being left due to a failure of operation or machine crash. + +RAID1 '--splitmirrors', '--trackchanges', and '--merge' operations +------------------------------------------------------------------ +This suite of operations is only available to the "raid1" segment type. + +Splitting an image from a RAID1 array is almost identical to the removal of +an image described above. However, the metadata LV associated with the split +image is removed and the data LV is kept and promoted to a top-level device. +(i.e. It is made visible and stripped of its RAID_IMAGE status flags.) + +When the '--trackchanges' option is given along with the '--splitmirrors' +argument, the metadata LV is left as part of the original array. The data LV +is set as 'VISIBLE' and read-only (~LVM_WRITE). When the array DM table is +being created, it notices the read-only, VISIBLE nature of the sub-LV and puts +in the '- -' sentinel. Only a single image can be split from the mirror and +the name of the sub-LV cannot be changed. Unlike '--splitmirrors' on its own, +the '--name' argument must not be specified. Therefore, the name of the newly +split LV will remain the same '<lv>_rimage_<N>', where 'N' is the index of the +slot in the array for which it is associated. + +When an LV which was split from a RAID1 array with the '--trackchanges' option +is merged back into the array, its read/write status is restored and it is +set as "hidden" again. Recycling the array (suspend/resume) restores the sub-LV +to its position in the array and begins the process of sync'ing the changes that +were made since the time it was split from the array. + +RAID device replacement with '--replace' +---------------------------------------- +This option is available to all RAID segment types. + +The '--replace' option can be used to remove a particular device from a RAID +logical volume and replace it with a different one in one action (CLI command). +The device device to be removed is specified as the argument to the '--replace' +option. This option can be specified more than once in a single command, +allowing multiple devices to be replaced at the same time - provided the RAID +logical volume has the necessary redundancy to allow the action. The devices +to be used as replacements can also be specified in the command; similar to the +way allocatable devices are specified during an up-convert. + +Example> lvconvert --replace /dev/sdd1 --replace /dev/sde1 vg/lv /dev/sd[bc]1 + +RAID '--repair' +--------------- +This 'lvconvert' option is available to all RAID segment types and is described +under "RAID Fault Handling". + + +RAID Fault Handling +=================== +RAID is not like traditional LVM mirroring (i.e. the "mirror" segment type). +LVM mirroring required failed devices to be removed or the logical volume would +simply hang. RAID arrays can keep on running with failed devices. In fact, for +RAID types other than RAID1 removing a device would mean substituting an error +target or converting to a lower level RAID (e.g. RAID6 -> RAID5, or RAID4/5 to +RAID0). Therefore, rather than removing a failed device unconditionally, the +user has a couple of options to choose from. + +The automated response to a device failure is handled according to the user's +preference defined in lvm.conf:activation.raid_fault_policy. The options are: + # "warn" - Use the system log to warn the user that a device in the RAID + # logical volume has failed. It is left to the user to run + # 'lvconvert --repair' manually to remove or replace the failed + # device. As long as the number of failed devices does not + # exceed the redundancy of the logical volume (1 device for + # raid4/5, 2 for raid6, etc) the logical volume will remain + # usable. + # + # "remove" - NOT CURRENTLY IMPLEMENTED OR DOCUMENTED IN example.conf.in. + # Remove the failed device and reduce the RAID logical volume + # accordingly. If a single device dies in a 3-way mirror, + # remove it and reduce the mirror to 2-way. If a single device + # dies in a RAID 4/5 logical volume, reshape it to a striped + # volume, etc - RAID 6 -> RAID 4/5 -> RAID 0. If devices + # cannot be removed for lack of redundancy, fail. + # THIS OPTION CANNOT YET BE IMPLEMENTED BECAUSE RESHAPE IS NOT + # YET SUPPORTED IN linux/drivers/md/dm-raid.c. The superblock + # does not yet hold enough information to support reshaping. + # + # "allocate" - Attempt to use any extra physical volumes in the volume + # group as spares and replace faulty devices. + +If manual intervention is taken, either in response to the automated solution's +"warn" mode or simply because dmeventd hadn't run, then the user can call +'lvconvert --repair vg/lv' and follow the prompts. They will be prompted +whether or not to replace the device and cause a full recovery of the failed +device. + +If replacement is chosen via the manual method or "allocate" is the policy taken +by the automated response, then 'lvconvert --replace' is the mechanism used to +attempt the replacement of the failed device. + +'vgreduce --removemissing' is ineffectual at repairing RAID logical volumes. It +will remove the failed device, but the RAID logical volume will simply continue +to operate with an <unknown> sub-LV. The user should clear the failed device +with 'lvconvert --repair'.
diff --git a/doc/lvm_fault_handling.txt b/doc/lvm_fault_handling.txt new file mode 100644 index 0000000..53b447e --- /dev/null +++ b/doc/lvm_fault_handling.txt
@@ -0,0 +1,202 @@ +LVM device fault handling +========================= + +Introduction +------------ +This document is to serve as the definitive source for information +regarding the policies and procedures surrounding device failures +in LVM. It codifies LVM's responses to device failures as well as +the responsibilities of administrators. + +Device failures can be permanent or transient. A permanent failure +is one where a device becomes inaccessible and will never be +revived. A transient failure is a failure that can be recovered +from (e.g. a power failure, intermittent network outage, block +relocation, etc). The policies for handling both types of failures +is described herein. + +Users need to be aware that there are two implementations of RAID1 in LVM. +The first is defined by the "mirror" segment type. The second is defined by +the "raid1" segment type. The characteristics of each of these are defined +in lvm.conf under 'mirror_segtype_default' - the configuration setting used to +identify the default RAID1 implementation used for LVM operations. + +Available Operations During a Device Failure +-------------------------------------------- +When there is a device failure, LVM behaves somewhat differently because +only a subset of the available devices will be found for the particular +volume group. The number of operations available to the administrator +is diminished. It is not possible to create new logical volumes while +PVs cannot be accessed, for example. Operations that create, convert, or +resize logical volumes are disallowed, such as: +- lvcreate +- lvresize +- lvreduce +- lvextend +- lvconvert (unless '--repair' is used) +Operations that activate, deactivate, remove, report, or repair logical +volumes are allowed, such as: +- lvremove +- vgremove (will remove all LVs, but not the VG until consistent) +- pvs +- vgs +- lvs +- lvchange -a [yn] +- vgchange -a [yn] +Operations specific to the handling of failed devices are allowed and +are as follows: + +- 'vgreduce --removemissing <VG>': This action is designed to remove + the reference of a failed device from the LVM metadata stored on the + remaining devices. If there are (portions of) logical volumes on the + failed devices, the ability of the operation to proceed will depend + on the type of logical volumes found. If an image (i.e leg or side) + of a mirror is located on the device, that image/leg of the mirror + is eliminated along with the failed device. The result of such a + mirror reduction could be a no-longer-redundant linear device. If + a linear, stripe, or snapshot device is located on the failed device + the command will not proceed without a '--force' option. The result + of using the '--force' option is the entire removal and complete + loss of the non-redundant logical volume. If an image or metadata area + of a RAID logical volume is on the failed device, the sub-LV affected is + replace with an error target device - appearing as <unknown> in 'lvs' + output. RAID logical volumes cannot be completely repaired by vgreduce - + 'lvconvert --repair' (listed below) must be used. Once this operation is + complete on volume groups not containing RAID logical volumes, the volume + group will again have a complete and consistent view of the devices it + contains. Thus, all operations will be permitted - including creation, + conversion, and resizing operations. It is currently the preferred method + to call 'lvconvert --repair' on the individual logical volumes to repair + them followed by 'vgreduce --removemissing' to extract the physical volume's + representation in the volume group. + +- 'lvconvert --repair <VG/LV>': This action is designed specifically + to operate on individual logical volumes. If, for example, a failed + device happened to contain the images of four distinct mirrors, it would + be necessary to run 'lvconvert --repair' on each of them. The ultimate + result is to leave the faulty device in the volume group, but have no logical + volumes referencing it. (This allows for 'vgreduce --removemissing' to + removed the physical volumes cleanly.) In addition to removing mirror or + RAID images that reside on failed devices, 'lvconvert --repair' can also + replace the failed device if there are spare devices available in the + volume group. The user is prompted whether to simply remove the failed + portions of the mirror or to also allocate a replacement, if run from the + command-line. Optionally, the '--use-policies' flag can be specified which + will cause the operation not to prompt the user, but instead respect + the policies outlined in the LVM configuration file - usually, + /etc/lvm/lvm.conf. Once this operation is complete, the logical volumes + will be consistent. However, the volume group will still be inconsistent - + due to the refernced-but-missing device/PV - and operations will still be + restricted to the aformentioned actions until either the device is + restored or 'vgreduce --removemissing' is run. + +Device Revival (transient failures): +------------------------------------ +During a device failure, the above section describes what limitations +a user can expect. However, if the device returns after a period of +time, what to expect will depend on what has happened during the time +period when the device was failed. If no automated actions (described +below) or user actions were necessary or performed, then no change in +operations or logical volume layout will occur. However, if an +automated action or one of the aforementioned repair commands was +manually run, the returning device will be perceived as having stale +LVM metadata. In this case, the user can expect to see a warning +concerning inconsistent metadata. The metadata on the returning +device will be automatically replaced with the latest copy of the +LVM metadata - restoring consistency. Note, while most LVM commands +will automatically update the metadata on a restored devices, the +following possible exceptions exist: +- pvs (when it does not read/update VG metadata) + +Automated Target Response to Failures: +-------------------------------------- +The only LVM target types (i.e. "personalities") that have an automated +response to failures are the mirror and RAID logical volumes. The other target +types (linear, stripe, snapshot, etc) will simply propagate the failure. +[A snapshot becomes invalid if its underlying device fails, but the +origin will remain valid - presuming the origin device has not failed.] + +Starting with the "mirror" segment type, there are three types of errors that +a mirror can suffer - read, write, and resynchronization errors. Each is +described in depth below. + +Mirror read failures: +If a mirror is 'in-sync' (i.e. all images have been initialized and +are identical), a read failure will only produce a warning. Data is +simply pulled from one of the other images and the fault is recorded. +Sometimes - like in the case of bad block relocation - read errors can +be recovered from by the storage hardware. Therefore, it is up to the +user to decide whether to reconfigure the mirror and remove the device +that caused the error. Managing the composition of a mirror is done with +'lvconvert' and removing a device from a volume group can be done with +'vgreduce'. + +If a mirror is not 'in-sync', a read failure will produce an I/O error. +This error will propagate all the way up to the applications above the +logical volume (e.g. the file system). No automatic intervention will +take place in this case either. It is up to the user to decide what +can be done/salvaged in this senario. If the user is confident that the +images of the mirror are the same (or they are willing to simply attempt +to retreive whatever data they can), 'lvconvert' can be used to eliminate +the failed image and proceed. + +Mirror resynchronization errors: +A resynchronization error is one that occurs when trying to initialize +all mirror images to be the same. It can happen due to a failure to +read the primary image (the image considered to have the 'good' data), or +due to a failure to write the secondary images. This type of failure +only produces a warning, and it is up to the user to take action in this +case. If the error is transient, the user can simply reactivate the +mirrored logical volume to make another attempt at resynchronization. +If attempts to finish resynchronization fail, 'lvconvert' can be used to +remove the faulty device from the mirror. + +TODO... +Some sort of response to this type of error could be automated. +Since this document is the definitive source for how to handle device +failures, the process should be defined here. If the process is defined +but not implemented, it should be noted as such. One idea might be to +make a single attempt to suspend/resume the mirror in an attempt to +redo the sync operation that failed. On the other hand, if there is +a permanent failure, it may simply be best to wait for the user or the +automated response that is sure to follow from a write failure. +...TODO + +Mirror write failures: +When a write error occurs on a mirror constituent device, an attempt +to handle the failure is automatically made. This is done by calling +'lvconvert --repair --use-policies'. The policies implied by this +command are set in the LVM configuration file. They are: +- mirror_log_fault_policy: This defines what action should be taken + if the device containing the log fails. The available options are + "remove" and "allocate". Either of these options will cause the + faulty log device to be removed from the mirror. The "allocate" + policy will attempt the further action of trying to replace the + failed disk log by using space that might be available in the + volume group. If the allocation fails (or the "remove" policy + is specified), the mirror log will be maintained in memory. Should + the machine be rebooted or the logical volume deactivated, a + complete resynchronization of the mirror will be necessary upon + the follow activation - such is the nature of a mirror with a 'core' + log. The default policy for handling log failures is "allocate". + The service disruption incurred by replacing the failed log is + negligible, while the benefits of having persistent log is + pronounced. +- mirror_image_fault_policy: This defines what action should be taken + if a device containing an image fails. Again, the available options + are "remove" and "allocate". Both of these options will cause the + faulty image device to be removed - adjusting the logical volume + accordingly. For example, if one image of a 2-way mirror fails, the + mirror will be converted to a linear device. If one image of a + 3-way mirror fails, the mirror will be converted to a 2-way mirror. + The "allocate" policy takes the further action of trying to replace + the failed image using space that is available in the volume group. + Replacing a failed mirror image will incure the cost of + resynchronizing - degrading the performance of the mirror. The + default policy for handling an image failure is "remove". This + allows the mirror to still function, but gives the administrator the + choice of when to incure the extra performance costs of replacing + the failed image. + +RAID logical volume device failures are handled differently from the "mirror" +segment type. Discussion of this can be found in lvm2-raid.txt.
diff --git a/doc/lvmetad_design.txt b/doc/lvmetad_design.txt new file mode 100644 index 0000000..1961cfb --- /dev/null +++ b/doc/lvmetad_design.txt
@@ -0,0 +1,208 @@ +The design of LVMetaD +===================== + +Invocation and setup +-------------------- + +The daemon should be started automatically by the first LVM command issued on +the system, when needed. The usage of the daemon should be configurable in +lvm.conf, probably with its own section. Say + + lvmetad { + enabled = 1 # default + autostart = 1 # default + socket = "/path/to/socket" # defaults to /var/run/lvmetad or such + } + +Library integration +------------------- + +When a command needs to access metadata, it currently needs to perform a scan +of the physical devices available in the system. This is a possibly quite +expensive operation, especially if many devices are attached to the system. In +most cases, LVM needs a complete image of the system's PVs to operate +correctly, so all devices need to be read, to at least determine presence (and +content) of a PV label. Additional IO is done to obtain or write metadata +areas, but this is only marginally related and addressed by Dave's +metadata-balancing work. + +In the existing scanning code, a cache layer exists, under +lib/cache/lvmcache.[hc]. This layer is keeping a textual copy of the metadata +for a given volume group, in a format_text form, as a character string. We can +plug the lvmetad interface at this level: in lvmcache_get_vg, which is +responsible for looking up metadata in a local cache, we can, if the metadata +is not available in the local cache, query lvmetad. Under normal circumstances, +when a VG is not cached yet, this operation fails and prompts the caller to +perform a scan. Under the lvmetad enabled scenario, this would never happen and +the fall-through would only be activated when lvmetad is disabled, which would +lead to local cache being populated as usual through a locally executed scan. + +Therefore, existing stand-alone (i.e. no lvmetad) functionality of the tools +would be not compromised by adding lvmetad. With lvmetad enabled, however, +significant portions of the code would be short-circuited. + +Scanning +-------- + +Initially (at least), the lvmetad will be not allowed to read disks: it will +rely on an external program to provide the metadata. In the ideal case, this +will be triggered by udev. The role of lvmetad is then to collect and maintain +an accurate (up to the data it has received) image of the VGs available in the +system. I imagine we could extend the pvscan command (or add a new one, say +lvmetad_client, if pvscan is found to be inappropriate): + + $ pvscan --cache /dev/foo + $ pvscan --cache --remove /dev/foo + +These commands would simply read the label and the MDA (if applicable) from the +given PV and feed that data to the running lvmetad, using +lvmetad_{add,remove}_pv (see lvmetad_client.h). + +We however need to ensure a couple of things here: + +1) only LVM commands ever touch PV labels and VG metadata +2) when a device is added or removed, udev fires a rule to notify lvmetad + +While the latter is straightforward, there are issues with the first. We +*might* want to invoke the dreaded "watch" udev rule in this case, however it +ends up being implemented. Of course, we can also rely on the sysadmin to be +reasonable and not write over existing LVM metadata without first telling LVM +to let go of the respective device(s). + +Even if we simply ignore the problem, metadata write should fail in these +cases, so the admin should be unable to do substantial damage to the system. If +there were active LVs on top of the vanished PV, they are in trouble no matter +what happens there. + +Incremental scan +---------------- + +There are some new issues arising with the "udev" scan mode. Namely, the +devices of a volume group will be appearing one by one. The behaviour in this +case will be very similar to the current behaviour when devices are missing: +the volume group, until *all* its physical volumes have been discovered and +announced by udev, will be in a state with some of its devices flagged as +MISSING_PV. This means that the volume group will be, for most purposes, +read-only until it is complete and LVs residing on yet-unknown PVs won't +activate without --partial. Under usual circumstances, this is not a problem +and the current code for dealing with MISSING_PVs should be adequate. + +However, the code for reading volume groups from disks will need to be adapted, +since it currently does not work incrementally. Such support will need to track +metadata-less PVs that have been encountered so far and to provide a way to +update an existing volume group. When the first PV with metadata of a given VG +is encountered, the VG is created in lvmetad (probably in the form of "struct +volume_group") and it is assigned any previously cached metadata-less PVs it is +referencing. Any PVs that were not yet encountered will be marked as MISSING_PV +in the "struct volume_group". Upon scanning a new PV, if it belongs to any +already-known volume group, this PV is checked for consistency with the already +cached metadata (in a case of mismatch, the VG needs to be recovered or +declared conflicted), and is subsequently unmarked MISSING_PV. Care need be +taken not to unmark MISSING_PV on PVs that have this flag in their persistent +metadata, though. + +The most problematic aspect of the whole design may be orphan PVs. At any given +point, a metadata-less PV may appear orphaned, if a PV of its VG with metadata +has not been scanned yet. Eventually, we will have to decide that this PV is +really an orphan and enable its usage for creating or extending VGs. In +practice, the decision might be governed by a timeout or assumed immediately -- +the former case is a little safer, the latter is probably more transparent. I +am not very keen on using timeouts and we can probably assume that the admin +won't blindly try to re-use devices in a way that would trip up LVM in this +respect. I would be in favour of just assuming that metadata-less VGs with no +known referencing VGs are orphans -- after all, this is the same approach as we +use today. The metadata balancing support may stress this a bit more than the +usual contemporary setups do, though. + +Automatic activation +-------------------- + +It may also be prudent to provide a command that will block until a volume +group is complete, so that scripts can reliably activate/mount LVs and such. Of +course, some PVs may never appear, so a timeout is necessary. Again, this is +something not handled by current tools, but may become more important in +future. It probably does not need to be implemented right away though. + +The other aspect of the progressive VG assembly is automatic activation. The +currently only problem with that is that we would like to avoid having +activation code in lvmetad, so we would prefer to fire up an event of some sort +and let someone else handle the activation and whatnot. + +Cluster support +--------------- + +When working in a cluster, clvmd integration will be necessary: clvmd will need +to instruct lvmetad to re-read metadata as appropriate due to writes on remote +hosts. Overall, this is not hard, but the devil is in the details. I would +possibly disable lvmetad for clustered volume groups in the first phase and +only proceed when the local mode is robust and well tested. + +With lvmlockd, lvmetad state is kept up to date by flagging either an +individual VG as "invalid", or the global state as "invalid". When either +the VG or the global state are read, this invalid flag is returned along +with the data. The client command can check for this invalid state and +decide to read the information from disk rather than use the stale cached +data. After the latest data is read from disk, the command may choose to +send it to lvmetad to update the cache. lvmlockd uses version numbers +embedded in its VG and global locks to detect when cached data becomes +invalid, and it then tells lvmetad to set the related invalid flag. +dct, 2015-06-23 + +Protocol & co. +-------------- + +I expect a simple text-based protocol executed on top of an Unix Domain Socket +to be the communication interface for lvmetad. Ideally, the requests and +replies will be well-formed "config file" style strings, so we can re-use +existing parsing infrastructure. + +Since we already have two daemons, I would probably look into factoring some +common code for daemon-y things, like sockets, communication (including thread +management) and maybe logging and re-using it in all the daemons (clvmd, +dmeventd and lvmetad). This shared infrastructure should live under +daemons/common, and the existing daemons shall be gradually migrated to the +shared code. + +Future extensions +----------------- + +The above should basically cover the use of lvmetad as a cache-only +daemon. Writes could still be executed locally, and the new metadata version +can be provided to lvmetad through the socket the usual way. This is fairly +natural and in my opinion reasonable. The lvmetad acts like a cache that will +hold metadata, no more no less. + +Above this, there is a couple of things that could be worked on later, when the +above basic design is finished and implemented. + +_Metadata writing_: We may want to support writing new metadata through +lvmetad. This may or may not be a better design, but the write itself should be +more or less orthogonal to the rest of the story outlined above. + +_Locking_: Other than directing metadata writes through lvmetad, one could +conceivably also track VG/LV locking through the same. + +_Clustering_: A deeper integration of lvmetad with clvmd might be possible and +maybe desirable. Since clvmd communicates over the network with other clvmd +instances, this could be extended to metadata exchange between lvmetad's, +further cutting down scanning costs. This would combine well with the +write-through-lvmetad approach. + +Testing +------- + +Since (at least bare-bones) lvmetad has no disk interaction and is fed metadata +externally, it should be very amenable to automated testing. We need to provide +a client that can feed arbitrary, synthetic metadata to the daemon and request +the data back, providing reasonable (nearly unit-level) testing infrastructure. + +Battle plan & code layout +========================= + +- config_tree from lib/config needs to move to libdm/ +- daemon/common *client* code can go to libdm/ as well (say + libdm/libdm-daemon.{h,c} or such) +- daemon/common *server* code stays, is built in daemon/ toplevel as a static + library, say libdaemon-common.a +- daemon/lvmetad *client* code goes to lib/lvmetad +- daemon/lvmetad *server* code stays (links in daemon/libdaemon_common.a)
diff --git a/doc/lvmpolld_overview.txt b/doc/lvmpolld_overview.txt new file mode 100644 index 0000000..8c66e5e --- /dev/null +++ b/doc/lvmpolld_overview.txt
@@ -0,0 +1,81 @@ +LVM poll daemon overview +======================== + +(last updated: 2015-05-09) + +LVM poll daemon (lvmpolld) is the alternative for lvm2 classical polling +mechanisms. The motivation behind new lvmpolld was to create persistent +system service that would be more durable and transparent. It's suited +particularly for any systemd enabled distribution. + +Before lvmpolld any background polling process originating in a lvm2 command +initiated inside cgroup of a systemd service could get killed if the main +process (service) exited in such cgroup. That could lead to premature termination +of such lvm2 polling process. + +Also without lvmpolld there were no means to detect a particular polling process +suited for monitoring of specific operation is already in-progress and therefore +it's not desirable to start next one with exactly same task. lvmpolld is able to +detect such duplicate requests and not spawn such redundant process. + +lvmpolld is primarily targeted for systems with systemd as init process. For systems +without systemd there's no need to install lvmpolld because there is no issue +with observation described in second paragraph. You can still benefit from +avoiding duplicate polling process being spawned, but without systemd lvmpolld +can't easily be run on-demand (activated by a socket maintained by systemd). + +lvmpolld implement shutdown on idle and can shutdown automatically when idle +for requested time. 60 second is recommended default here. This behaviour can be +turned off if found useless. + +Data structures +--------------- + +a) Logical Volume (struct lvmpolld_lv) + +Each operation is identified by LV. Internal identifier within lvmpolld +is full LV uuid (vg_uuid+lv_uuid) prefixed with LVM_SYSTEM_DIR if set by client. + +such full identifier may look like: + + "/etc/lvm/lvm.confWFd2dU67S8Av29IcJCnYzqQirdfElnxzhCdzEh7EJrfCn9R1TIQjIj58weUZDre4" + +or without LVM_SYSTEM_DIR being set explicitly: + + "WFd2dU67S8Av29IcJCnYzqQirdfElnxzhCdzEh7EJrfCn9R1TIQjIj58weUZDre4" + + +LV carries various metadata about polling operation. The most significant are: + +VG name +LV name +polling interval (usually --interval passed to lvm2 command or default from lvm2 + configuration) +operation type (one of: pvmove, convert, merge, thin_merge) +LVM_SYSTEM_DIR (if set, this is also passed among environment variables of lvpoll + command spawned by lvmpolld) + +b) LV stores (struct lvmpolld_store) + +lvmpolld uses two stores for Logical volumes (struct lvmpolld_lv). One store for polling +operations in-progress. These operations are as of now: PV move, mirror up-conversion, +classical snapshot merge, thin snapshot merge. + +The second store is suited only for pvmove --abort operations in-progress. Both +stores are independent and identical LVs (pvmove /dev/sda3 and pvmove --abort /dev/sda3) +can be run concurently from lvmpolld point of view (on lvm2 side the consistency is +guaranteed by lvm2 locking mechanism). + +Locking order +------------- + +There are two types of locks in lvmpolld. Each store has own store lock and each LV has +own lv lock. + +Locking order is: +1) store lock +2) LV lock + +Each LV has to be inside a store. When daemon requires to take both locks it has +to take a store lock first and LV lock has to be taken afterwards (after the +appropriate store lock where the LV is being stored :))
diff --git a/doc/pvmove_outline.txt b/doc/pvmove_outline.txt new file mode 100644 index 0000000..8746b8f --- /dev/null +++ b/doc/pvmove_outline.txt
@@ -0,0 +1,52 @@ +Let's say we have an LV, made up of three segments of different PV's, +I've also added in the device major:minor as this will be useful +later: + ++-----------------------------+ +| PV1 | PV2 | PV3 | 254:3 ++----------+---------+--------+ + + +Now our hero decides to PV move PV2 to PV4: + +1. Suspend our LV (254:3), this starts queueing all io, and flushes + all pending io. Once the suspend has completed we are free to change + the mapping table. + +2. Set up *another* (254:4) device with the mapping table of our LV. + +3. Load a new mapping table into (254:3) that has identity targets for + parts that aren't moving, and a mirror target for parts that are. + +4. Unsuspend (254:3) + +So now we have: + destination of copy + +--------------------->--------------+ + | | ++-----------------------------+ + -----------+ +| Identity | mirror | Ident. | 254:3 | PV4 | ++----------+---------+--------+ +------------+ + | | | + \/ \/ \/ ++-----------------------------+ +| PV1 | PV2 | PV3 | 254:4 ++----------+---------+--------+ + +Any writes to segment2 of the LV get intercepted by the mirror target +who checks that that chunk has been copied to the new destination, if +it hasn't it queues the initial copy and defers the current io until +it has finished. Then the current io is written to *both* PV2 and the +PV4. + +5. When the copying has completed 254:3 is suspended/pending flushed. + +6. 254:4 is taken down + +7. metadata is updated on disk + +8. 254:3 has new mapping table loaded: + ++-----------------------------+ +| PV1 | PV4 | PV3 | 254:3 ++----------+---------+--------+
diff --git a/doc/tagging.txt b/doc/tagging.txt new file mode 100644 index 0000000..b66e0ec --- /dev/null +++ b/doc/tagging.txt
@@ -0,0 +1,165 @@ +Tagging aims +============ + 1) Ability to attach an unordered list of tags to LVM metadata objects. + 2) Ability to add or remove tags easily. + 3) Ability to select LVM objects for processing according to presence/absence + of specific tags. + 4) Ability to control through the config file which VGs/LVs are activated + on different machines using names or tags. + 5) Ability to overlay settings from different config files e.g. override + some settings in a global config file locally. + +Clarifications +============== + 1) Tag character set: A-Za-z0-9_+.- + Can't start with hyphen & max length is 128 (NAME_LEN). + 2) LVM object types that can be tagged: + VG, LV, LV segment + PV - tags are stored in VG metadata so disappear when PV becomes orphaned + Snapshots can't be tagged, but their origin may be. + 3) A tag can be used in place of any command line LVM object reference that + accepts (a) a list of objects; or (b) a single object as long as the + tag expands to a single object. This is not supported everywhere yet. + Duplicate arguments in a list after argument expansion may get removed + retaining the first copy of each argument. + 4) Wherever there may be ambiguity of argument type, a tag must be prefixed + by '@'; elsewhere an '@' prefix is optional. + 5) LVM1 objects cannot be tagged, as the disk format doesn't support it. + 6) Tags can be added or removed with --addtag or --deltag. + +Config file Extensions +====================== + To define host tags in config file: + + tags { + # Set a tag with the hostname + hosttags = 1 + + tag1 { } + + tag2 { + # If no exact match, tag is not set. + host_list = [ "hostname", "dbase" ] + } + } + +Activation config file example +============================== + activation { + volume_list = [ "vg1/lvol0", "@database" ] + } + + Matches against vgname, vgname/lvname or @tag set in *metadata*. + @* matches exactly against *any* tag set on the host. + The VG or LV only gets activated if a metadata tag matches. + The default if there is no match is not to activate. + If volume_list is not present and any tags are defined on the host + then it only activates if a host tag matches a metadata tag. + If volume_list is not present and no tags are defined on the host + then it does activate. + +Multiple config files +===================== + (a) lvm.conf + (b) lvm_<host_tag>.conf + + At startup, load lvm.conf. + Process tag settings. + If any host tags were defined, load lvm_tag.conf for each tag, if present. + + When searching for a specific config file entry, search order is (b) + then (a), stopping at the first match. + Within (b) use reverse order tags got set, so file for last tag set is + searched first. + New tags set in (b) *do* trigger additional config file loads. + +Usage Examples +============== + 1) Simple activation control via metadata with static config files + + lvm.conf: (Identical on every machine - global settings) + tags { + hosttags = 1 + } + + From any machine in the cluster, add db1 to the list of machines that + activate vg1/lvol2: + + lvchange --addtag @db1 vg1/lvol2 + (followed by lvchange -ay to actually activate it) + + + 2) Multiple hosts. + + Activate vg1 only on the database hosts, db1 and db2. + Activate vg2 only on the fileserver host fs1. + Activate nothing initially on the fileserver backup host fsb1, but be + prepared for it to take over from fs1. + + Option (i) - centralised admin, static configuration replicated between hosts + # Add @database tag to vg1's metadata + vgchange --addtag @database vg1 + + # Add @fileserver tag to vg2's metadata + vgchange --addtag @fileserver vg2 + + lvm.conf: (Identical on every machine) + tags { + database { + host_list = [ "db1", "db2" ] + } + fileserver { + host_list = [ "fs1" ] + } + fileserverbackup { + host_list = [ "fsb1" ] + } + } + + activation { + # Only activate if host has a tag that matches a metadata tag + volume_list = [ "@*" ] + } + + In the event of the fileserver host going down, vg2 can be brought up + on fsb1 by running *on any node* 'vgchange --addtag @fileserverbackup vg2' + followed by 'vgchange -ay vg2' + + + Option (ii) - localised admin & configuation + (i.e. each host holds *locally* which classes of volumes to activate) + # Add @database tag to vg1's metadata + vgchange --addtag @database vg1 + + # Add @fileserver tag to vg2's metadata + vgchange --addtag @fileserver vg2 + + lvm.conf: (Identical on every machine - global settings) + tags { + hosttags = 1 + } + + lvm_db1.conf: (only needs to be on db1 - could be symlink to lvm_db.conf) + activation { + volume_list = [ "@database" ] + } + + lvm_db2.conf: (only needs to be on db2 - could be symlink to lvm_db.conf) + activation { + volume_list = [ "@database" ] + } + + lvm_fs1.conf: (only needs to be on fs1 - could be symlink to lvm_fs.conf) + activation { + volume_list = [ "@fileserver" ] + } + + If fileserver goes down, to bring a spare machine fsb1 in as fileserver, + create lvm_fsb1.conf on fsb1 (or symlink to lvm_fs.conf): + + activation { + volume_list = [ "@fileserver" ] + } + + and run 'vgchange -ay vg2' or 'vgchange -ay @fileserver' +
diff --git a/doc/testing.txt b/doc/testing.txt new file mode 100644 index 0000000..214435a --- /dev/null +++ b/doc/testing.txt
@@ -0,0 +1,41 @@ +Here's how I test new LVM2 builds without interfering with the stable +LVM2 that is running the LV's on my development box. + +1) Create a set of loopback devices. + +2) Create a new directory to contain the LVM2 configuration files for + this setup. (I use /etc/lvm_loops) + +3) Write a suitable lvm.conf file, this goes in the directory you just + created. eg, my /etc/lvm_loops/lvm.conf looks like: + + log { + file="/tmp/lvm2_loop.log" + level=9 + verbose=0 + overwrite=1 + } + + devices { + scan = "/dev" + filter = ["a/loop/", "r/.*/"] + } + + + The important thing to note is the devices section which makes sure + that only the loopback devices are considered for LVM2 operations. + +4) When you want to use this test setup just set the environment + variable LVM_SYSTEM_DIR to point to your config directory + (/etc/lvm_loops in my case). + +5) It's a good idea to do a vgscan to initialise the filters: + + export LVM_SYSTEM_DIR=/etc/lvm_loops + ./lvm vgscan + + where ./lvm is the new build of LVM2 that I'm trying out. + +7) Test away. Make sure that you are explicit about which lvm + executable you want to execute (eg, ./lvm if you are in + LVM2/tools).
diff --git a/doc/udev_assembly.txt b/doc/udev_assembly.txt new file mode 100644 index 0000000..6186402 --- /dev/null +++ b/doc/udev_assembly.txt
@@ -0,0 +1,83 @@ +Automatic device assembly by udev +================================= + +We want to asynchronously assemble and activate devices as their components +become available. Eventually, the complete storage stack should be covered, +including: multipath, cryptsetup, LVM, mdadm. Each of these can be addressed +more or less separately. + +The general plan of action is to simply provide udev rules for each of the +device "type": for MD component devices, PVs, LUKS/crypto volumes and for +multipathed SCSI devices. There's no compelling reason to have a daemon do these +things: all systems that actually need to assemble multiple devices into a +single entity already either support incremental assembly or will do so shortly. + +Whenever in this document we talk about udev rules, these may include helper +programs that implement a multi-step process. In many cases, it can be expected +that the functionality can be implemented in couple lines of shell (or couple +hundred of C). + +Multipath +--------- + +For multipath, we will need to rely on SCSI IDs for now, until we have a better +scheme of things, since multipath devices can't be identified until the second +path appears, and unfortunately we need to decide whether a device is multipath +when the *first* path appears. Anyway, the multipath folks need to sort this +out, but it shouldn't bee too hard. Just bring up multipathing on anything that +appears and is set up for multipathing. + +LVM +--- + +For LVM, the crucial piece of the puzzle is lvmetad, which allows us to build up +VGs from PVs as they appear, and at the same time collect information on what is +already available. A command, pvscan --cache is expected to be used to +implement udev rules. It is relatively easy to make this command print out a +list of VGs (and possibly LVs) that have been made available by adding any +particular device to the set of visible devices. In othe words, udev says "hey, +/dev/sdb just appeared", calls pvscan --cache, which talks to lvmetad, which +says "cool, that makes vg0 complete". Pvscan takes this info and prints it out, +and the udev rule can then somehow decide whether anything needs to be done +about this "vg0". Presumably a table of devices that need to be activated +automatically is made available somewhere in /etc (probably just a simple list +of volume groups or logical volumes, given by name or UUID, globbing +possible). The udev rule can then consult this file. + +Cryptsetup +---------- + +This may be the trickiest of the lot: the obvious hurdle here is that crypto +volumes need to somehow obtain a key (passphrase, physical token or such), +meaning there is interactivity involved. On the upside, dm-crypt is a 1:1 +system: one encrypted device results in one decrypted device, so no assembly or +notification needs to be done. While interactivity is a challenge, there are at +least partial solutions around. (TODO: Milan should probably elaborate here.) + +(For LUKS devices, these can probably be detected automatically. I suppose that +non-LUKS devices can be looked up in crypttab by the rule, to decide what is the +appropriate action to take.) + +MD +-- + +Fortunately, MD (namely mdadm) already comes with a mechanism for incremental +assembly (mdadm -I or such). We can assume that this fits with the rest of stack +nicely. + + +Filesystem &c. discovery +======================== + +Considering other requirements that exist for storage systems (namely +large-scale storage deployments), it is absolutely not feasible to have the