pax_global_header00006660000000000000000000000064123275524720014523gustar00rootroot0000000000000052 comment=c6f4e0dec933e5dc97e1c8ac6005f682ce23e4f6 CMakeLists.txt000066400000000000000000000017771232755247200136430ustar00rootroot00000000000000project(thinkfan) cmake_minimum_required(VERSION 2.6) option(USE_ATASMART "Enable reading temperatures from HDDs via S.M.A.R.T") set(MAXERR 2 CACHE STRING "Fail after this many consecutive errors when in DANGEROUS mode") add_executable(thinkfan thinkfan.c config.c message.c parser.c system.c) set(CMAKE_C_FLAGS_DEBUG "-O0 -g3 -Wall -DDEBUG") if(NOT DEFINED CMAKE_C_FLAGS) set(CMAKE_C_FLAGS "-O3 -Wall") endif(NOT DEFINED CMAKE_C_FLAGS) if(MAXERR) set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DMAXERR=${MAXERR}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DMAXERR=${MAXERR}") endif(MAXERR) if(USE_ATASMART) set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DUSE_ATASMART") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUSE_ATASMART") target_link_libraries(thinkfan atasmart) endif(USE_ATASMART) install(TARGETS thinkfan DESTINATION sbin) install(FILES NEWS COPYING README examples/thinkfan.conf.complex examples/thinkfan.conf.simple DESTINATION share/doc/thinkfan) install(FILES thinkfan.1 DESTINATION share/man/man1) COPYING000066400000000000000000001045131232755247200121260ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . NEWS000066400000000000000000000070161232755247200115720ustar00rootroot00000000000000thinkfan 0.9.1 ============== This is a minor update which adds a small but useful feature: On receipt of a SIGUSR1, thinkfan will now print the current known temperatures. See the manpage for details. This is the only change in functionality over the previously released 0.9_beta2. thinkfan 0.9 ============ This took a while, and it comes with lots of changes, so brace yourself. 1) S.M.A.R.T via libatasmart ---------------------------- Thinkfan can now read temperatures directly from hard disks via libatasmart. To enable it, you need to compile with -DUSE_ATASMART. 2) cmake -------- I've switched to cmake. Don't ask me why, I think it's just more convenient. Details are in the README. 3) Multiple sensor inputs ------------------------- When using libatasmart, you obviously want to have other temperature inputs as well. Thus, thinkfan now allows temperature inputs (i.e. legacy thinkpad_acpi procfs, sysfs hwmon and atasmart) to be arbitrarily combined. In order to clean up the config syntax, the "sensor" and "fan" keywords have been deprecated in favor of other, interface-specific keywords. See README and example configs for details. 4) Various bugfixes ------------------- The depulsing hack is now only applied if the fan is actually running (thx yuszuv). Various sysfs bugs have been fixed and a rare race condition when resuming from suspend can now be worked around with DANGEROUS mode. thinkfan 0.8 ============ 1) Complex Temperature Limits ----------------------------- Thinkfan now allows you to specify temperature limits for each sensor individually. Configuring this requires more tweaking and experimentation, but's definitely worth the effort, since it allows you much more fine-grained control over your fan's behaviour. See README and the example configs for details. 2) Arbitrary Strings as Fan Levels ---------------------------------- Now you can specify arbitrary strings as fan levels. This allows you to use things like "level auto" or "level disengaged" in certain temperature ranges. The sanity checks will filter out anything that isn't a known sensible string, but as usual, you can use dangerous mode to disable them. thinkfan 0.7 ============ 1) Correction Values -------------------- Temperatures that are perfectly fine for your CPU may already be dangerous for most hard disks. For simplicity's sake, thinkfan uses only the highest temperature found in the system, but that'll most likely never be your harddisk. Thus you can now specify a correction value for any sensor. This value is added to the actual temperature and can be used to give that sensor a greater chance of being considered in the fan speed decision. I know this is quite unintuitive, but it's the least intrusive way of handling this (for now). In a later release, I might extend the config syntax to allow for sensor-specific temperature limits. So please do check out the updated README and example configs, and modify your config to save your harddisk from premature death. :-/ 2) Config Syntax ---------------- Thinkfan now has a shiny new (as in cheesy, but better than scanf) parser for the config files. It was actually already used in 0.6.5. However in this release it was changed to be much tighter on the config syntax. In all previous releases, it just skipped anything it didn't reconize. You could thus have arbitrary garbage in your config file and thinkfan would just ignore it. These times are over. Thinkfan now rejects anything that isn't a proper statement or a comment. You can get the old behaviour back by using the -D (DANGEROUS) option. README000066400000000000000000000310011232755247200117420ustar00rootroot00000000000000/************************************************************************** * thinkfan version 0.9 -- copyleft 01-2013, Victor Mataré * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . **************************************************************************/ Thinkfan is a simple, lightweight fan control program. Originally designed specifically for IBM/Lenovo Thinkpads, it now supports any kind of system via the sysfs hwmon interface (/sys/class/hwmon). It is designed to eat as little CPU power as possible. Contents of this file ===================== (0) WARNING (1) How it works (2) Install and configure (2.1) Build (2.2a) Configure hardware interface (IBM/Lenovo Thinkpads) (2.2b) Configure hardware interface (any system) (2.3) Configure fan behaviour (2.4) Test and install (3) Usage (3.1) Invocation (3.2) Temperature biasing (the -b option) (3.3) Pulsing-fan workaround (3.4) Signals (4) Contact/Bugs (0) WARNING!!!! =============== There's only very basic sanity checking on the configuration (semantic plausibility). You can set the temperature limits as insane as you like. Any change to fan behaviour that results in higher temperatures in some parts of the system will shorten your system's lifetime and/or cause weird hardware bugs that'll make you pull out your hair. No warranties whatsoever. If this program steals your car, kills your horse, smokes your dope or pees on your carpet... - too bad, you're on your own. (1) How it works ================ Thinkfan can read temperatures from /proc/acpi/ibm/thermal, from temp*_input files in /sys/class/hwmon, or directly from hard disks via S.M.A.R.T. Your fan speed is set according to predefined temperature limits that are specified in the config file. There are two modes of operation: (1.1) Simple Mode ----------------- In simple mode, thinkfan uses only the highest temperature it can find. This was the only choice in versions before 0.8. However, it's potentially dangerous for devices with a low temperature rating like hard drives. For these devices, you should specify a correction value that's added to the actual temperature. (1.2) Complex Mode ------------------ In complex mode, temperature limits are defined for each sensor individually. If *at least one* upper limit is reached we switch to the next fan level, and if *all* lower limits are reached, we switch to the previous level. This is a new feature in 0.8. It allows very fine-grained control and is the preferred way of using thinkfan. However it may require a bit of tweaking and experimentation to get a suitable config for your system. (2) How to install ================== (2.1) Build ----------- You can use ccmake to choose build options interactively: ccmake . Or set your build options from the command line. E.g. to configure a debug build with support for libatasmart: cmake -D USE_ATASMART:BOOL=ON -D CMAKE_BUILD_TYPE:STRING=Debug . Use CMAKE_BUILD_TYPE:STRING="" to get an optimized build without debug symbols. This is the default. To compile simply run: cmake --build . CMake should also provide you with a "make install" target, which defaults to a /usr/local prefix. (2.2) Configure --------------- The default config file location is /etc/thinkfan.conf. You should start with one of the supplied example configs and tweak from there. There are three possible temperature sources, which can also be combined (since 0.9). Take note of the order in which you listed your sensors, since that is the way they are matched against your temperature limits. a) /proc/acpi/ibm/ (default) Most IBM/Lenovo Thinkpads and some other Lenovo models support this. You need the thinkpad_acpi kernel driver (see 2.2a). b) /sys/class/hwmon/ This is a generic interface which is not hardware-specific. You need an hwmon-driver for your system that allows reading temperatures and controlling the fan from userspace. (see 2.2b) c) S.M.A.R.T Thinkfan uses libatasmart to read the temperature directly from hard disks. Just include a line saying atasmart /dev/sda And thinkfan will read the temperature directly from /dev/sda. (2.2a) Configure hardware interface (/proc/acpi/ibm) -------------------------------------------------------------- First, you need to load the thinkpad_acpi module with fan_control=1: # modprobe thinkpad_acpi fan_control=1 See your distribution documentation for how to load modules at bootup with custom options. Then you might want to check out which fan levels your fan controller supports by doing something like this: for i in 0 1 2 3 4 5 6 7; do echo "level $i" > /proc/acpi/ibm/fan echo "level $i..." sleep 6 cat /proc/acpi/ibm/fan | egrep "^speed" echo done echo "level auto" > /proc/acpi/ibm/fan Now you have to choose whether you want to use complex or simple temperature limits. I recommend using complex limits, since that gives you more control. Whatever you choose, you should have two lines saying tp_thermal /proc/acpi/ibm/thermal tp_fan /proc/acpi/ibm/fan in your config. /proc/acpi/ibm/thermal provides 8 or 16 temperatures, so if you use complex temperature limits, your limits need have that same length. (2.2b) Configure hardware interface (any system) ------------------------------------------------------- On all systems other than IBM/Lenovo Thinkpads, you need to provide thinkfan with the path(s) of all sysfs temperature sensor files you want to use. You may find them by doing something like this: find -L /sys/class/hwmon -maxdepth 5 -name "temp*_input" \ -print -exec cat \{\} \; 2>/dev/null Now put all file names into the config file that give you a sensible temperature reading, each one on a separate "sensor" line. Example: sensor /sys/class/hwmon/hwmon3/device/temp10_input ... Next you need to find the PWM control file of your fan: find -L /sys/class/hwmon -maxdepth 3 -name "pwm?" \ -print -exec cat \{\} \; 2>/dev/null At the moment, thinkfan can control only one fan. Support for multiple fans may be added in a later release. Put your PWM control file on a "fan" line like so: pwm_fan /sys/class/hwmon/hwmon3/device/pwm1 You'll want to try out the behaviour of your PWM controller by echo'ing some numbers from 0 to 255 to your PWM file and then checking the fan RPM in fan?_input. ATTENTION: Most hwmon drivers seem to disable userspace fan control after suspend/resume. That means you'll have to send a SIGHUP to thinkfan after resuming to make it restore userspace fan control. Check your distribution documentation to find out how you can do a "pkill -HUP thinkfan" after resuming. By default, thinkfan re-initializes the PWM control *every time* a fan speed is set. This is safe, but stupid. So if you want to do it properly, go the SIGHUP way and use the -z option (see below). (2.3) Configure fan behaviour ----------------------------- Carefully edit the fan-config tuples to your needs. Note that for the sysfs hwmon-interface, the fan level is a number from 0 to 255, while in the IBM-Interface, it's a number from 0 to 7. You also have the option of using strings like "level 0", "level auto" or "level disengaged" (WITH the quotation marks). In DANGEROUS mode, you can even use arbitrary (unknown) garbage as fan level. The temperature limits for different fan levels should overlap, so that once the fan is on, it keeps running for a while. If using simple temperature limits, you should specify a correction value for the temperature of your harddisk, because it's much more sensitive to high temperatures than your CPU. If using /proc/acpi/ibm/thermal, take a look at http://www.thinkwiki.org/wiki/Thermal_Sensors . If you're using sysfs to read temperatures, you'll have to find out about the meaning of your sensors on your own. A good starting point could be the documentation of your hwmon driver. Once you know which sensor belongs to your harddrive, you should specify a correction value for it. For a sysfs sensor, this would look like sensor /path/to/harddisk's/temp_input (15) This will add 15°C to the temperature read from your harddisk and thus keep it from heating up to the upper limit of your first fan level. In /proc/acpi/ibm/thermal, the harddisk might be at the 3rd position: sensor /proc/acpi/ibm/thermal (0, 0, 15) As this is just a quick-shot solution for the problem with overheating hard disks, I really recommend using complex temperature limits. Go take a look at thinkfan.conf.complex to learn about the syntax. (2.4) Test and install ---------------------- Run ./thinkfan -n -c PATH_TO_CONFIG and watch it do its job. Try putting some load on your system with glxgears or running some infinite loop in bash. If everything works nicely, forget about it for a while to make sure it's stable. Once you're confident that it works well for you, you may want to copy it to /usr/local/sbin or whatever you like and run it without -n. (3) USAGE ========= (3.1) Invocation ---------------- Usage: thinkfan [-hnqzD] [-b BIAS ] [-c FILE] [-s SEC] [-p[SEC]] -h This help message -s SEC Maximum seconds between temperature updates (default: 5) -b BIAS Floating point number (0 ~ 20) to control rising edge temperature biasing strength (see below). Default 5.0 -c FILE Load different configuration file (default: /etc/thinkfan.conf) -n Do not become a daemon and log to terminal instead of syslog -q Be quiet (no status info on terminal) -z Assume we don't have to worry about resuming when using the sysfs interface. Saves CPU load. -p[SEC] Use the pulsing-fan workaround (for older Thinkpads). Takes an optional floating-point argument (0 ~ 10s) as depulsing duration. Defaults to 0.5s. See (3.3). -D DANGEROUS mode: No sanity checks on config! May damage your hardware!! (3.2) Rising Temperature Exaggeration (the -b option) ----------------------------------------------------- Thinkfan takes special measures to deal with temperatures rising very suddenly (like when you turn on the computer and instantly run some CPU/GPU-intensive app). You can provide a floating point number between 0 and 20 to adjust the amount of exaggeration. If the highest known temperature jumps up 2 °C or more, the exaggeration is calculated to: exaggeration = (sleeptime * (delta_t - 1)) * (0.1 * BIAS) (BIAS is the value provided on the commandline) This value is then added to the current highest temperature and the fan speed decision is based on that. Ex: If we slept for 5 seconds during the last cycle, provided a BIAS of 10 on the commandline, and the temperature increased by 3 °C, we get a bias of: 5*2*0.1*10 = 10 °C That's pretty nervous. If you want to turn off biasing entirely, run thinkfan with -b 0. In addition to exaggerating the temperature reading, the sleep time is reduced to 2 seconds, and then slowly increased back up to the specified value. (3.3) Pulsing-fan workaround (the -p option) -------------------------------------------- Specifying this option activates the pulsing-fan workaround. It works by setting the fan controller to "disengaged" mode for a short amount of time on every cycle (check the -s option). The optional argument of the -p option is the duration for which the fan is kept in "disengaged" mode (defaults to 0.5 seconds). Note that the time spent in "disengaged" mode adds to the cycle time, so with the -p option, the default sleep time is actually 5.5 seconds. (3.4) Signals ------------- Send a SIGHUP to make thinkfan reload its config file and reinitialize fan control: kill -HUP $(. * * ******************************************************************/ #include "config.h" #include "parser.h" #include #include #include #include #include #include #include #include #include "message.h" #include "system.h" #include "thinkfan.h" static int add_sensor(struct tf_config *cfg, struct sensor *sensor); static int add_limit(struct tf_config *cfg, struct limit *limit); static int add_ibmfan(struct tf_config *cfg, char *path); static int add_pwmfan(struct tf_config *cfg, char *path); /*********************************************************************** * readconfig(char *fname) reads the config file and * returns a pointer to a struct tf_config. Returns NULL if there's any * problem with the config. **********************************************************************/ struct tf_config *readconfig(char* fname) { int err, i, j, fd, *temps_save = temps, num_temps_save = num_temps; struct tf_config *cfg_local, *cfg_save = NULL; char *s_input = NULL, *input = NULL; void *ret = NULL, *map_start; struct stat sb; line_count = 0; sensoridx = 0; num_temps = 0; prefix = "\n"; cfg_local = (struct tf_config *) malloc(sizeof(struct tf_config)); cfg_local = (struct tf_config *) memset(cfg_local, 0, sizeof(struct tf_config)); fd = open(fname, O_RDONLY); if (fd < 0) { report(LOG_ERR, LOG_ERR, "%s: %s\n", fname, strerror(errno)); goto fail; } if (fstat(fd, &sb) < 0) { report(LOG_ERR, LOG_ERR, "%s: %s\n", fname, strerror(errno)); goto fail; } map_start = (char *) mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if (map_start == MAP_FAILED) { report(LOG_ERR, LOG_ERR, "%s: %s\n", fname, strerror(errno)); goto fail; } input = (char *) map_start; while (*input != 0) { s_input = input; // mostly sanity checking and n00b catering... if ((ret = (void *) parse_sensor(&input))) { skip_blanklines(&input); *(input-sizeof(char)) = 0; if (add_sensor(cfg_local, (struct sensor *) ret)) goto fail; } else if ((ret = (void *) parse_fan(&input))) { skip_blanklines(&input); *(input-sizeof(char)) = 0; if (strcmp((char *)ret, IBM_FAN)) err = add_pwmfan(cfg_local, (char *)ret); else err = add_ibmfan(cfg_local, (char *)ret); if (err) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_FAN); if (chk_sanity) goto fail; } // guessing the fan type from the path is deprecated... prefix = "\n"; report(LOG_WARNING, LOG_NOTICE, MSG_FILE_HDR(fname, s_input)); report(LOG_WARNING, LOG_NOTICE, MSG_WRN_FAN_DEPRECATED); } else if ((ret = (void *) parse_tpfan(&input))) { skip_blanklines(&input); *(input-sizeof(char)) = 0; if (add_ibmfan(cfg_local, (char *)ret)) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_FAN); if (chk_sanity) goto fail; } } else if ((ret = (void *) parse_pwmfan(&input))) { skip_blanklines(&input); *(input-sizeof(char)) = 0; if (add_pwmfan(cfg_local, (char *)ret)) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_FAN); if (chk_sanity) goto fail; } } else if ((ret = (void *) parse_level(&input))) { skip_blanklines(&input); *(input-sizeof(char)) = 0; if ((err = add_limit(cfg_local, (struct limit *) ret))) { if (err & ERR_CONF_LOWHIGH) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_LOWHIGH); err ^= ERR_CONF_LOWHIGH; if (chk_sanity) goto fail; } if (err & ERR_CONF_LVLORDER) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_LVLORDER); err ^= ERR_CONF_LVLORDER; if (chk_sanity) goto fail; } if (err & ERR_CONF_OVERLAP) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_OVERLAP); err ^= ERR_CONF_OVERLAP; if (chk_sanity) goto fail; } if (err & ERR_CONF_LVL0) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_LVL0); err ^= ERR_CONF_LVL0; if (chk_sanity) goto fail; } if (err & ERR_CONF_LVLFORMAT) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_LVLFORMAT); err ^= ERR_CONF_LVLFORMAT; if (chk_sanity) goto fail; } if (err & ERR_CONF_LIMITLEN) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_ERR, MSG_ERR_LIMITLEN); err ^= ERR_CONF_LIMITLEN; goto fail; } } else if (err) goto fail; } else if ((ret = (void *) parse_comment(&input))) { skip_blanklines(&input); *(input-sizeof(char)) = 0; free(ret); } else if (parse_blankline(&input)) *(input-sizeof(char)) = 0; else { skip_line(&input); *(input-sizeof(char)) = 0; prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_FILE_HDR(fname, s_input)); report(LOG_ERR, LOG_WARNING, MSG_ERR_CONF_PARSE); if(chk_sanity) goto fail; } } if (cfg_local->num_limits <= 0) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_CONF_NOFAN); goto fail; } // configure fan interface if (cfg_local->fan == NULL) { prefix = "\n"; report(LOG_WARNING, LOG_NOTICE, MSG_WRN_FAN_DEFAULT); cfg_local->fan = (char *) calloc(strlen(IBM_FAN)+1, sizeof(char)); strcpy(cfg_local->fan, IBM_FAN); cfg_local->setfan = setfan_ibm; cfg_local->init_fan = init_fan_ibm; cfg_local->uninit_fan = uninit_fan_ibm; } cur_lvl = cfg_local->limits[cfg_local->num_limits - 1].level; if (depulse) cfg_local->get_temps = depulse_and_get_temps; else cfg_local->get_temps = get_temps; // Store correct level string if using /proc/acpi/ibm if (cfg_local->setfan == setfan_ibm) { for (i = 0; i < cfg_local->num_limits; i++) { if (cfg_local->limits[i].nlevel != INT_MIN) { char *conv_lvl = calloc(7 + strlen(cfg_local->limits[i].level), sizeof(char)); snprintf(conv_lvl, 7 + strlen(cfg_local->limits[i].level), "level %d", cfg_local->limits[i].nlevel); free(cfg_local->limits[i].level); cfg_local->limits[i].level = conv_lvl; } } } if (cfg_local->num_sensors == 0) { // Use the default sensor in /proc/acpi/ibm/thermal prefix = "\n"; report(LOG_WARNING, LOG_NOTICE, MSG_WRN_SENSOR_DEFAULT); struct sensor *default_sensor = (struct sensor *) malloc(sizeof(struct sensor)); memset(default_sensor->bias, 0, 16 * sizeof(int)); default_sensor->path = (char *) calloc(strlen(IBM_TEMP) + 1, sizeof(char)); strcpy(default_sensor->path, IBM_TEMP); default_sensor->get_temp = get_temp_ibm; add_sensor(cfg_local, default_sensor); } /* Bleh. This is awful. * Not sure if cheap function calls are worth this kind of crap code. * See the done: and fail: labels (urgh) */ temps = (int *) calloc(num_temps, sizeof(int)); cfg_save = config; config = cfg_local; cfg_local->get_temps(); if ((num_temps > 1 && tempidx != num_temps) || (errcnt & ERR_T_GET)) { report(LOG_ERR, LOG_ERR, MSG_ERR_T_GET); goto fail; } config = cfg_save; // configure temperature comparison method (new in 0.8) if (cfg_local->limits[0].low[1] == INT_MIN) { cfg_local->lvl_up = simple_lvl_up; cfg_local->lvl_down = simple_lvl_down; // no info in config, so count what's there an rely on that cfg_local->used_temps = found_temps; } else { if (cfg_local->limit_len < num_temps) { prefix = "\n"; report(LOG_WARNING, LOG_INFO, MSG_WRN_NUM_TEMPS( num_temps, cfg_local->limit_len)); } if (cfg_local->limit_len > num_temps) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_LONG_LIMIT); goto fail; } cfg_local->lvl_up = complex_lvl_up; cfg_local->lvl_down = complex_lvl_down; int j, tmpcount; for (j=0; j < cfg_local->num_limits; j++) { tmpcount = 0; for (i=0; i < cfg_local->limit_len; i++) if ((cfg_local->limits[j].low[i] != TEMP_UNUSED) && cfg_local->limits[j].high[i] != TEMP_UNUSED) tmpcount++; if (tmpcount > cfg_local->used_temps) cfg_local->used_temps = tmpcount; } if (found_temps < cfg_local->used_temps) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_ERR_TEMP_COUNT, cfg_local->used_temps, found_temps); if (chk_sanity) goto fail; } } // check for a sane start temperature if (cfg_local->limit_len == 1 && chk_sanity && cfg_local->limits[0].high[0] > 48) { for (i=0; i < cfg_local->num_sensors; i++) for (j=0; j < 16; j++) if (cfg_local->sensors[i] .bias[j] != 0) goto done; prefix = "\n"; report(LOG_WARNING, LOG_NOTICE, MSG_WRN_CONF_NOBIAS( cfg_local->limits[0].high[0])); } done: munmap(map_start, sb.st_size); close(fd); free(temps_save); return cfg_local; fail: free_config(cfg_local); if (temps != temps_save) free(temps); temps = temps_save; num_temps = num_temps_save; return NULL; } static int add_ibmfan(struct tf_config *cfg, char *path) { if (cfg->fan == NULL) { cfg->fan = path; cfg->setfan = setfan_ibm; cfg->init_fan = init_fan_ibm; cfg->uninit_fan = uninit_fan_ibm; return 0; } return 1; } static int add_pwmfan(struct tf_config *cfg, char *path) { if (cfg->fan == NULL) { if (resume_is_safe) cfg->setfan = setfan_sysfs; else { cfg->setfan = setfan_sysfs_safe; prefix = "\n"; report(LOG_WARNING, LOG_WARNING, MSG_WRN_SYSFS_SAFE); } cfg->fan = path; cfg->init_fan = init_fan_sysfs_once; cfg->uninit_fan = uninit_fan_sysfs; return 0; } return 1; } static int find_max(int *l) { int i, rv = INT_MIN; for (i = 0; l[i] != INT_MIN; i++) if (l[i] > rv) rv = l[i]; return rv; } static int add_sensor(struct tf_config *cfg, struct sensor *sensor) { struct tf_config *cfg_save; if (!(cfg->sensors = (struct sensor *) realloc(cfg->sensors, (cfg->num_sensors+1) * sizeof(struct sensor)))) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "Allocating memory for config: %s", strerror(errno)); free(sensor); return ERR_MALLOC; } cfg->sensors[cfg->num_sensors++] = *sensor; if (sensor->get_temp != get_temp_ibm) num_temps++; else { cfg_save = config; config = cfg; num_temps += count_temps_ibm(); config = cfg_save; if (errcnt & ERR_T_GET) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_T_GET); return ERR_T_GET; } } sensoridx++; free(sensor); return 0; } /* Yep, this is mostly sanity checking... */ static int add_limit(struct tf_config *cfg, struct limit *limit) { int rv = 0, nl, nh, i; long int tmp; char *end; // Check formatting of level string... tmp = strtol(limit->level, &end, 0); if (tmp < INT_MIN || tmp > INT_MAX) { rv |= ERR_CONF_LVLFORMAT; } else if (*end == 0 || sscanf(limit->level, "level %d", (int *)&tmp)) { limit->nlevel = (int)tmp; } else if (!strcmp(limit->level, "level disengaged") || !strcmp(limit->level, "level auto")) { limit->nlevel = INT_MIN; } else { // something broken rv |= ERR_CONF_LVLFORMAT; limit->nlevel = INT_MIN; } // Check length of limits... for (nl = 0; limit->low[nl] != INT_MIN; nl++); for (nh = 0; limit->high[nh] != INT_MIN; nh++); if (cfg->limit_len <= 0) cfg->limit_len = nl; if (nh != cfg->limit_len || nl != cfg->limit_len) { rv |= ERR_CONF_LIMITLEN; goto fail; } // Check level ordering and border values... if (cfg->num_limits <= 0) { if (find_max(limit->low) > 0) rv |= ERR_CONF_LVL0; } else { if (limit->nlevel != INT_MAX && limit->nlevel != INT_MIN && cfg->limits[cfg->num_limits-1].nlevel >= limit->nlevel) rv |= ERR_CONF_LVLORDER; if (cfg->num_limits > 1) for (i = 0; i < cfg->limit_len; i++) if (cfg->limits[cfg->num_limits-1].high[i] < limit->low[i]) rv |= ERR_CONF_OVERLAP; for (i = 0; limit->low[i] != INT_MIN; i++) { if (!(limit->low[i] == INT_MAX && limit->high[i] == INT_MAX) && limit->low[i] >= limit->high[i]) rv |= ERR_CONF_LOWHIGH; } } // ... and FINALLY do what we came for if (!(cfg->limits = (struct limit *) realloc(cfg->limits, sizeof(struct limit) * (cfg->num_limits + 1)))) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "Allocating memory for config: %s", strerror(errno)); rv |= ERR_MALLOC; goto fail; } cfg->limits[cfg->num_limits++] = *limit; goto done; fail: free(limit->level); free(limit->high); free(limit->low); done: free(limit); return rv; } void free_config(struct tf_config *cfg) { int j; if (!cfg) return; free(cfg->fan); if (cfg->num_sensors > 0) { for (j=0; j < cfg->num_sensors; j++) free(cfg->sensors[j].path); free(cfg->sensors); } for (j=0; j < cfg->num_limits; j++) { free(cfg->limits[j].level); free(cfg->limits[j].low); free(cfg->limits[j].high); } free(cfg->limits); free(cfg); } config.h000066400000000000000000000020321232755247200125020ustar00rootroot00000000000000/******************************************************************** * config.h: Declarations for config.c * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * ******************************************************************/ #ifndef CONFIG_H #define CONFIG_H #include "globaldefs.h" struct tf_config *readconfig(char *fname); void free_config(struct tf_config *cfg); #endif examples/000077500000000000000000000000001232755247200127055ustar00rootroot00000000000000examples/thinkfan.conf.complex000066400000000000000000000074011232755247200170260ustar00rootroot00000000000000###################################################################### ## thinkfan 0.9 example config file ## ================================ ## ## ATTENTION: There is only very basic sanity checking on the configuration. ## That means you can set your temperature limits as insane as you like. You ## can do anything stupid, e.g. turn off your fan when your CPU reaches 70°C. ## ## That's why this program is called thinkfan: You gotta think for yourself. ## ####################################################################### ## ## This file shows how to use sensor-specific temperature limits. ## First of all, you need to specify temperature inputs. On a Thinkpad, you can ## just use: ## tp_thermal /proc/acpi/ibm/thermal # provides us with 16 temperature inputs ## ## On other systems, you have to specify a file in /sys/class/hwmon for each ## sensor you want to use. They are numbered in their order of appearance. ## For example: # # hwmon /sys/class/hwmon5/temp2_input #1 # hwmon /sys/class/hwmon0/device/temp3_input #2 # ## If you want to read temperatures directly from the hard disk, thinkfan needs ## to be compiled with -DUSE_ATASMART. Then you can do: # # atasmart /dev/sda #3 # ... # ## You can have as many temperature inputs as you like. You should at get the ## temperature from the CPU, the GPU and the hard disk. # # ## Next we specify the fan we want to use. On a Thinkpad, this is: # tp_fan /proc/acpi/ibm/fan # ## On anything other than a Thinkpad you'll probably use some PWM control file ## in /sys/class/hwmon. Remember that fan levels range from 0 to 255 and that ## they're just a number, not including the word "level" as seen below. ## A sysfs fan would be specified like this: # # pwm_fan /sys/class/hwmon/hwmon2/device/pwm1 # ## But remember you can only have one fan. # ## Then you need to specify the temperature limits for each of the sensors. ## A dot means that the corresponding sensor should be ignored. The length of the ## UPPER and LOWER limits must be the same as the number of temperatures. In this ## example, /proc/acpi/ibm/thermal contains 16 sensors (on older thinkpads, ## there may be only 8), some of which are unused (hence the dots). ## A sysfs temperature input always contains only one sensor, so if you specify ## 5 sysfs files above, the length of your limits must be 5, too. # ## I've come up with these preliminary settings for my Thinkpad T61p. They probably ## don't make sense for anything else, so you most definitely have to work ## something out for yourself. # { "level 0" # the fan level # ^-------^ This works for /proc/acpi/ibm/thermal. # for a PWM fan in /sys/class/hwmon it would have to be just # 0 or "0". # # Sensor count: # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # ============================================== (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) # LOWER limit (54 42 42 54 42 . 42 . 42 46 54 . . . . .) # UPPER limit } { "level 1" # ^-------^ For a PWM fan you may have to use something around 30 to get the # same speed. (46 39 39 48 39 . 39 . 41 44 46 . . . . .) (58 45 45 60 45 . 45 . 45 47 56 . . . . .) } { "level 3" (52 43 43 57 43 . 43 . 43 45 51 . . . . .) (62 48 48 67 48 . 48 . 48 48 57 . . . . .) } { "level 5" (56 46 46 65 46 . 46 . 46 46 52 . . . . .) (66 49 49 69 49 . 49 . 49 49 58 . . . . .) } { "level 7" (63 47 47 67 47 . 47 . 47 47 50 . . . . .) (73 55 55 83 60 . 60 . 60 60 64 . . . . .) } { "level disengaged" # nice idea: "level auto" can also be used. # but again: only numbers for sysfs. (69 50 50 75 55 . 55 . 55 55 55 . . . . .) (99 99 99 99 99 . 99 . 99 99 99 . . . . .) } examples/thinkfan.conf.simple000066400000000000000000000034411232755247200166500ustar00rootroot00000000000000###################################################################### # thinkfan 0.7 example config file # ================================ # # ATTENTION: There is only very basic sanity checking on the configuration. # That means you can set your temperature limits as insane as you like. You # can do anything stupid, e.g. turn off your fan when your CPU reaches 70°C. # # That's why this program is called THINKfan: You gotta think for yourself. # ###################################################################### # # IBM/Lenovo Thinkpads (thinkpad_acpi, /proc/acpi/ibm) # ==================================================== # # IMPORTANT: # # To keep your HD from overheating, you have to specify a correction value for # the sensor that has the HD's temperature. You need to do this because # thinkfan uses only the highest temperature it can find in the system, and # that'll most likely never be your HD, as most HDs are already out of spec # when they reach 55 °C. # Correction values are applied from left to right in the same order as the # temperatures are read from the file. # # For example: # tp_thermal /proc/acpi/ibm/thermal (0, 0, 10) # will add a fixed value of 10 °C the 3rd value read from that file. Check out # http://www.thinkwiki.org/wiki/Thermal_Sensors to find out how much you may # want to add to certain temperatures. # Syntax: # (LEVEL, LOW, HIGH) # LEVEL is the fan level to use (0-7 with thinkpad_acpi) # LOW is the temperature at which to step down to the previous level # HIGH is the temperature at which to step up to the next level # All numbers are integers. # # I use this on my T61p: #tp_fan /proc/acpi/ibm/fan #tp_thermal /proc/acpi/ibm/thermal (0, 10, 15, 2, 10, 5, 0, 3, 0, 3) (0, 0, 55) (1, 48, 60) (2, 50, 61) (3, 52, 63) (4, 56, 65) (5, 59, 66) (7, 63, 32767) globaldefs.h000066400000000000000000000066171232755247200133540ustar00rootroot00000000000000/************************************************************************ * globaldefs.h: Stuff that's needed by all objects * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * ************************************************************************/ #ifndef GLOBALDEFS_H #define GLOBALDEFS_H #define _GNU_SOURCE #include #include #include #include #define VERSION "0.9.1" #define ERR_T_GET 1 #define ERR_FAN_INIT 1<<1 #define ERR_CONF_NOFILE 1<<2 #define ERR_CONF_LOST 1<<3 #define ERR_CONF_RELOAD 1<<4 #define ERR_PIDFILE 1<<5 #define ERR_FORK 1<<6 #define ERR_MALLOC 1<<7 #define ERR_CONF_LOWHIGH 1<<8 #define ERR_CONF_LVLORDER 1<<9 #define ERR_CONF_ORDERLOW 1<<10 #define ERR_CONF_ORDERHIGH 1<<11 #define ERR_CONF_OVERLAP 1<<12 #define ERR_CONF_LVL0 1<<13 #define ERR_FAN_SET 1<<14 #define ERR_CONF_LIMIT 1<<15 #define WRN_CONF_INTMIN_LVL 1<<16 #define ERR_CONF_LVLFORMAT 1<<17 #define ERR_CONF_LIMITLEN 1<<18 #ifndef DUMMYRUN #define PID_FILE "/var/run/thinkfan.pid" #define IBM_TEMP "/proc/acpi/ibm/thermal" #define IBM_FAN "/proc/acpi/ibm/fan" #else #define PID_FILE "/tmp/thinkfan.pid" #define IBM_TEMP "/tmp/thermal" #define IBM_FAN "/tmp/fan" #endif //DUMMYRUN #ifndef MAXERR #define MAXERR 2 #endif // Stolen from the gurus #define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) struct limit { char *level; // this is written to the fan control file. int nlevel; // A numeric interpretation of the level int *low; // int array specifying the LOWER limit, terminated by INT_MIN int *high; // dito for UPPER limit. }; struct sensor { char *path; int bias[16]; void (*get_temp)(); }; struct tf_config { struct sensor *sensors; int num_sensors; char *fan; struct limit *limits; int num_limits; int limit_len; void (*setfan)(); void (*init_fan)(); void (*uninit_fan)(); int (*lvl_up)(); int (*lvl_down)(); int (*cmp_lvl)(); void (*get_temps)(); int used_temps; // how many temperatures do we expect to find? }; struct tf_config *config; unsigned long int errcnt; int *temps, tmax, last_tmax, lvl_idx, *b_tmax, line_count; int tempidx; // global index into global temps[] array int sensoridx; // separate since one sensor may have multiple temps (ibm) int found_temps; // how may temperatures we actually found unsigned int watchdog_timeout, num_temps; char quiet, nodaemon, resume_is_safe, chk_sanity; char *config_file, *prefix, *rbuf, *cur_lvl, *oldpwm; // old contents of pwm*_enable, used for uninit_fan() float bias_level, depulse_tmp; useconds_t depulse; int triggered_tidx; #ifdef USE_ATASMART char dnd_disk; #endif #define FALSE 0 #define TRUE !FALSE #define TEMP_UNUSED INT_MAX #endif message.c000066400000000000000000000035061232755247200126630ustar00rootroot00000000000000/******************************************************************** * message.c * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * ******************************************************************/ #include "message.h" #include "globaldefs.h" #include #include #include void report(int nlevel, int dlevel, char *format, ...) { va_list ap; int level = chk_sanity ? nlevel : dlevel; va_start(ap, format); if (nodaemon && (!quiet || level > LOG_WARNING)) { fputs(prefix, stderr); vfprintf(stderr, format, ap); prefix = ""; } else { vsyslog(level, format, ap); } } void report_tstat() { char *rv = NULL, *tmp; int i, len; rv = calloc(24, sizeof(char)); strcpy(rv, "current temperatures: ("); for (i=0; likely(i < num_temps); i++) { if (unlikely(i == triggered_tidx)) len = asprintf(&tmp, "<%d>, ", temps[i]); else len = asprintf(&tmp, "%d, ", temps[i]); if (len < 1) { errcnt++; goto fail; } rv = realloc(rv, strlen(rv) + len + 1); strcat(rv, tmp); free(tmp); } rv[strlen(rv) - 2] = ')'; rv[strlen(rv) - 1] = '\0'; if (nodaemon) { puts(rv); } else { syslog(LOG_INFO, "%s", rv); } fail: free(rv); } message.h000066400000000000000000000152511232755247200126700ustar00rootroot00000000000000/******************************************************************** * message.h * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * ******************************************************************/ #ifndef MESSAGE_H #define MESSAGE_H void report(int nlevel, int dlevel, char *format, ...); void report_tstat(); #ifdef USE_ATASMART #define DND_DISK_HELP \ "\n -d Don't read S.M.A.R.T. temperature from sleeping disks" #else #define DND_DISK_HELP "" #endif #define MSG_USAGE \ "\nthinkfan " VERSION ": A minimalist fan control program\n" \ "\nUsage: thinkfan [-hnqzD [-b BIAS] [-c CONFIG] [-s SECONDS] [-p [SECONDS]]]" \ "\n -h This help message" \ "\n -s Maximum cycle time in seconds (Integer. Default: 5)" \ "\n -b Floating point number (-10 to 30) to control rising temperature" \ "\n exaggeration (see README). Default: 5.0" \ "\n -c Load different configuration file (default: /etc/thinkfan.conf)" \ "\n -n Do not become a daemon and log to terminal instead of syslog" \ "\n -q Be quiet (report only important events)" \ "\n -z Assume we don't have to worry about resuming when using the sysfs" \ "\n interface (see README!)" \ "\n -p Use the pulsing-fan workaround (for older Thinkpads). Takes an optional" \ "\n floating-point argument (0 ~ 10s) as depulsing duration. Default 0.5s." \ DND_DISK_HELP \ "\n -D DANGEROUS mode: Disable all sanity checks. May result in undefined"\ "\n behaviour!\n\n" #define MSG_FILE_HDR(file, line) "%s:%d:%s\n", file, line_count, line #define MSG_DBG_T_STAT "sleeptime=%d, tmax=%d, last_tmax=%d, biased_tmax=%d" \ " -> fan=\"%s\"\n", tmp_sleeptime, tmax, last_tmax, *b_tmax, config->limits[lvl_idx].level #define MSG_DBG_CONF_RELOAD "Received SIGHUP: reloading config...\n" #define MSG_INF_SANITY "Sanity checks are on. Exiting.\n" #define MSG_INF_INSANITY "Sanity checks are off. Continuing.\n" #define MSG_INF_CONFIG \ "Config as read from %s:\nFan level\tLow\tHigh\n", config_file #define MSG_INF_CONF_ITEM(level, low, high) " %s\t\t%d\t%d\n", level, low, high #define MSG_INF_TERM \ "Cleaning up and resetting fan control.\n" #define MSG_INF_DEPULSE(delay, time) "Disengaging the fan controller for " \ "%.3f seconds every %d seconds\n", time, delay #define MSG_WRN_SLEEPTIME_15 "WARNING: %d seconds of not realizing " \ "rising temperatures may be dangerous!\n", sleeptime #define MSG_WRN_SLEEPTIME_1 "A sleeptime of %d seconds doesn't make much " \ "sense.\n", sleeptime #define MSG_WRN_SYSFS_SAFE "WARNING: Using safe but wasteful way of settin" \ "g PWM value. Check README to know more.\n" #define MSG_WRN_SENSOR_DEFAULT "WARNING: Using default temperature inputs in" \ " " IBM_TEMP ".\n" #define MSG_WRN_FAN_DEFAULT "WARNING: Using default fan control in" \ " " IBM_FAN ".\n" #define MSG_WRN_CONF_NOBIAS(t) "WARNING: You're using simple temperature limits" \ " without correction values, and your fan will only start at %d °C. This can " \ "be dangerous for your hard drive.\n", t #define MSG_WRN_NUM_TEMPS(n, i) "WARNING: You have %d sensors but your temper" \ "ature limits only have %d entries. Excess sensors will be ignored.\n", n, i #define MSG_WRN_SENSOR_DEPRECATED "WARNING: The `sensor' keyword is deprecat" \ "ed. Please use the `hwmon' or `tp_thermal' keywords instead!\n" #define MSG_WRN_FAN_DEPRECATED "WARNING: Guessing the fan type from the path" \ " is deprecated. Please use `tp_fan' or `pwm_fan' to make things clear.\n" #define MSG_ERR_T_GET "%s: Error getting temperature.\n", __func__ #define MSG_ERR_T_GARBAGE "%s: Trailing garbage after temperature!\n" #define MSG_ERR_T_INVALID "%s: Invalid temperature: %d" #define MSG_ERR_MODOPTS \ "Module thinkpad_acpi doesn't seem to support fan_control\n" #define MSG_ERR_FANCTRL "%s: Error writing to %s: %s\n", __func__, config->fan, strerror(errno) #define MSG_ERR_FAN_INIT "%s: Error initializing fan control.\n", __func__ #define MSG_ERR_OPT_S "ERROR: option -s requires an int argument!\n" #define MSG_ERR_OPT_B "ERROR: bias must be between -10 and 30!\n" #define MSG_ERR_OPT_P "ERROR: invalid argument to option -p: %f\n", depulse_tmp #define MSG_ERR_CONF_NOFILE "Refusing to run without usable config file!\n" #define MSG_ERR_CONF_LOST "%s: Lost configuration! This is a bug. Please " \ "report this to the author.\n", __func__ #define MSG_ERR_CONF_RELOAD "Error reloading config. Keeping old one.\n" #define MSG_ERR_CONF_NOFAN "Could not find any fan speed settings in" \ " the config file. Please read AND UNDERSTAND the documentation!\n" #define MSG_ERR_CONF_LOWHIGH "Your LOWER limit is not lesser than your " \ "UPPER limit. That doesn't make sense.\n" #define MSG_ERR_CONF_OVERLAP "LOWER limit doesn't overlap with previous UPPER" \ " limit.\n" #define MSG_ERR_CONF_FAN "Thinkfan can't use more than one fan.\n" #define MSG_ERR_CONF_LVLORDER "Fan levels are not ordered correctly.\n" #define MSG_ERR_CONF_PARSE "Syntax error.\n" #define MSG_ERR_CONF_LVL0 "The LOWER limit of the first fan level cannot con" \ "tain any values greater than 0!\n" #define MSG_ERR_CONF_LVLFORMAT "Invalid fan level string. This check can" \ " be disabled by using DANGEROUS mode.\n" #define MSG_ERR_RUNNING PID_FILE " already exists. Either thinkfan is " \ "already running, or it was killed by SIGKILL. If you're sure thinkfan" \ " is not running, delete " PID_FILE " manually.\n" #define MSG_ERR_FANFILE_IBM "Error opening " IBM_FAN ". Is this a computer " \ "really Thinkpad? Is the thinkpad_acpi module loaded? Are you running thi" \ "nkfan with root privileges?\n" #define MSG_ERR_T_PARSE(str) "Error parsing temperatures: %s\n", str #define MSG_ERR_LCOUNT "The number of limits must either be 1 or equal to the" \ " number of temperatures.\n" #define MSG_ERR_LONG_LIMIT "You have configured more temperature limits " \ "than sensors. That doesn't make sense.\n" #define MSG_ERR_LIMITLEN "Inconsistent limit length.\n" #define MSG_ERR_TEMP_COUNT "Your config requires at least %d temperatures, " \ "but only %d temperatures were found.\n" #define MSG_ALERT_SENSOR "A sensor has vanished! Exiting since there's no " \ "safe way of handling this.\n" #endif parser.c000066400000000000000000000222461232755247200125350ustar00rootroot00000000000000/******************************************************************** * config_parser.c: Some cheesy recursive descent parser for the config file * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * ******************************************************************/ #include "parser.h" #include "globaldefs.h" #include "system.h" #ifdef USE_ATASMART static const char atasmart_keyword[] = "atasmart"; #endif #include #include #include #include #include #include "message.h" static const char space[] = " \t"; static const char newline[] = "\n\r\f"; static const char fan_keyword[] = "fan"; static const char sensor_keyword[] = "sensor"; static const char hwmon_keyword[] = "hwmon"; static const char tp_thermal_keyword[] = "tp_thermal"; static const char tp_fan[] = "tp_fan"; static const char pwm_fan[] = "pwm_fan"; static const char left_bracket[] = "({"; static const char right_bracket[] = ")}"; static const char separator[] = ",; "; static const char nonword[] = " \t\n\r\f,;#({})"; static const char comment[] = "#"; //static const char nonfilename[] = "\n\n{["; static const char digit[] = "0123456789"; static const char quote[] = "\""; static const char period[] = "."; /* * All these functions allocate memory only for the matching result, with the * exception of char_alt(), which never allocates memory and instead returns a * pointer to the last char that has been read from **input. * All advance the **input pointer to point to the first char that has not been * parsed. If parsing was unsuccessful, **input is reset to where it started. */ /* Match any single char out of *items. Returns a pointer to the last read char * in **input. No memory is allocated, so returned chars should be copied * before using them. */ char *char_alt(char **input, const char *items, const char invert) { if (! **input) return NULL; while (*items) if (**input == *(items++)) { if (invert) return NULL; else { if (**input == '\n') line_count++; return (*input)++; } } if (invert) { if (**input == '\n') line_count++; return (*input)++; } return NULL; } /* Match an arbitrary sequence of any chars out of *items */ char *char_cat(char **input, const char *items, const char invert) { char *ret = NULL; char *start = *input; int oldlc = line_count; while (char_alt(input, items, invert)); if (*input > start) { ret = (char*) calloc(*input - start + 2, sizeof(char)); strncpy(ret, start, *input - start); } else line_count = oldlc; return ret; } /* Match an integer expression and return it as an int */ int *parse_int(char **input) { char *end = *input; int *rv = NULL; long int l; l = strtol(*input, &end, 0); if (end > *input && l <= INT_MAX && l >= INT_MIN) { *input = end; rv = (int *) calloc(2, sizeof(int)); *rv = (int) l; rv[1] = INT_MIN; } skip_comments(input); return rv; } /* Match a single string (keyword) */ char *parse_keyword(char **input, const char *keyword) { char *start = *input; int l = strlen(keyword); char *ret = NULL; if (!strncasecmp(*input, keyword, l)) { ret = *input; *input += l; } else *input = start; return ret; } void skip_space(char **input) { char *tmp = char_cat(input, space, 0); free(tmp); } char *parse_comment(char **input) { skip_space(input); if (!char_alt(input, comment, 0)) return NULL; char *tmp = char_cat(input, newline, 1); if (tmp == NULL) { tmp = malloc(sizeof(char)); *tmp = 0; } return tmp; } void skip_comments(char **input) { char *tmp; while ((tmp = parse_comment(input))) free(tmp); } char *parse_word(char **input) { return char_cat(input, nonword, 1); } /*char *parse_newline(char **input) { char *rv; if (char_alt(input, newline, 0)) { rv = malloc(sizeof(char)); *rv = **input; return rv; } return NULL; }*/ char *parse_blankline(char **input) { skip_space(input); return char_alt(input, newline, 0); } void skip_blanklines(char **input) { while (parse_blankline(input)); } void skip_line(char **input) { char *tmp = char_cat(input, newline, 1); skip_blanklines(input); free(tmp); } void skip_skippable(char **input) { char *tmp; skip_blanklines(input); while ((tmp = parse_comment(input))) { free(tmp); skip_blanklines(input); } } /* Return the string/quotation following a keyword. */ char *parse_statement(char **input, const char *keyword) { char *start = *input; char *tmp, *ret = NULL; int oldlc = line_count; skip_space(input); if (!(tmp = parse_keyword(input, keyword))) goto done; skip_space(input); if (!(ret = parse_quotation(input, quote))) ret = parse_word(input); skip_comments(input); done: if (!ret) { line_count = oldlc; *input = start; } return ret; } char *parse_fan(char **input) { return parse_statement(input, fan_keyword); } char *parse_tpfan(char **input) { return parse_statement(input, tp_fan); } char *parse_pwmfan(char **input) { return parse_statement(input, pwm_fan); } char *skip_parse(char **input, const char *items, const char invert) { skip_space(input); return char_alt(input, items, invert); } /* Match an arbitrary-length tuple of int. Returns an array of int, * terminated by INT_MIN. */ int *parse_int_tuple(char **input) { int *rv = NULL, i = 0; int *tmp = NULL; int oldlc = line_count; if (!skip_parse(input, left_bracket, 0)) goto fail; skip_comments(input); skip_blanklines(input); do { if (!(tmp = parse_int(input))) { if (skip_parse(input, period, 0)) { tmp = malloc(sizeof(int)); *tmp = TEMP_UNUSED; } else goto fail; } rv = realloc(rv, sizeof(int) * (i+2)); rv[i++] = *tmp; free(tmp); skip_comments(input); skip_blanklines(input); skip_parse(input, separator, 0); } while(!skip_parse(input, right_bracket, 0)); rv[i] = INT_MIN; skip_comments(input); return rv; fail: line_count = oldlc; free(rv); return NULL; } struct limit *parse_level(char **input) { struct limit *rv = NULL; char *start = *input; int oldlc = line_count; if (!skip_parse(input, left_bracket, 0)) goto fail3; skip_skippable(input); rv = (struct limit *) malloc (sizeof(struct limit)); // OK, fan levels are strings now. if ( !((rv->level = char_cat(input, digit, 0)) || (rv->level = parse_quotation(input, quote))) ) goto fail3; skip_parse(input, separator, 0); skip_skippable(input); if (!(rv->low = parse_int_tuple(input)) && !(rv->low = parse_int(input))) goto fail2; skip_parse(input, separator, 0); skip_skippable(input); if(!(rv->high = parse_int_tuple(input)) && !(rv->high = parse_int(input))) goto fail1; skip_skippable(input); if (!skip_parse(input, right_bracket, 0)) goto fail; skip_skippable(input); return rv; fail: free(rv->high); fail1: free(rv->low); fail2: free(rv->level); fail3: free(rv); line_count = oldlc; *input = start; return NULL; } /* Parse a sensor statement followed by an optional bias tuple */ static struct sensor *parse_tempinput(char **input, const char *keyword) { struct sensor *rv = (struct sensor *) malloc(sizeof(struct sensor)); int *tmp, i, oldlc = line_count; char *start = *input; if (!(rv->path = parse_statement(input, keyword))) { free(rv); *input = start; line_count = oldlc; return NULL; } memset(rv->bias, 0, 16 * sizeof(int)); skip_space(input); if ((tmp = parse_int_tuple(input))) for (i = 0; (tmp[i] != INT_MIN) && i < 16; i++) { rv->bias[i] = tmp[i]; } free(tmp); skip_comments(input); return rv; } struct sensor *parse_sensor(char **input) { struct sensor *rv; char *start = *input; if ((rv = parse_tempinput(input, sensor_keyword))) { prefix = "\n"; char *line = calloc(strchr(start, '\n') - start + 1, sizeof(char)); strncpy(line, start, strchr(start, '\n') - start); report(LOG_WARNING, LOG_WARNING, MSG_FILE_HDR(config_file, line)); report(LOG_WARNING, LOG_WARNING, MSG_WRN_SENSOR_DEPRECATED); if (!strcmp(rv->path, IBM_TEMP)) rv->get_temp = get_temp_ibm; else rv->get_temp = get_temp_sysfs; free(line); } else if ((rv = parse_tempinput(input, tp_thermal_keyword))) rv->get_temp = get_temp_ibm; else if ((rv = parse_tempinput(input, hwmon_keyword))) rv->get_temp = get_temp_sysfs; #ifdef USE_ATASMART else if ((rv = parse_tempinput(input, atasmart_keyword))) rv->get_temp = get_temp_atasmart; #endif return rv; } char *parse_quotation(char **input, const char *mark) { char *ret = NULL; char *start; int oldlc = line_count; start = *input; if (!char_alt(input, mark, 0)) return NULL; ret = char_cat(input, mark, 1); if (!ret) { ret = malloc(sizeof(char)); *ret = 0; } if (!char_alt(input, mark, 0)) { free(ret); ret = NULL; line_count = oldlc; *input = start; } return ret; } parser.h000066400000000000000000000030021232755247200125270ustar00rootroot00000000000000/******************************************************************** * config_parser.h: Header for the config parser * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * ******************************************************************/ #ifndef CONFIG_PARSER_H #define CONFIG_PARSER_H struct sensor *parse_sensor(char **input); struct sensor *parse_atasmart(char **input); char *parse_fan(char **input); char *parse_tpfan(char **input); char *parse_pwmfan(char **input); struct limit *parse_level(char **input); char *parse_keyword(char **input, const char *keyword); char *parse_comment(char **input); char *parse_blankline(char **input); char *parse_quotation(char **input, const char *mark); void skip_space(char **input); void skip_comments(char **input); void skip_blanklines(char **input); void skip_line(char **input); int *parse_int(char **input); #endif rcscripts/000077500000000000000000000000001232755247200131035ustar00rootroot00000000000000rcscripts/thinkfan.default000066400000000000000000000004421232755247200162530ustar00rootroot00000000000000# Should thinkfan be started automatically on boot? # Only say "yes" when you know what you are doing, have configured # thinkfan correctly for *YOUR* machine and loaded thinkpad_acpi # with fan_control=1 (if you have a ThinkPad). START=no # Additional startup parameters DAEMON_ARGS="-q" rcscripts/thinkfan.gentoo000077500000000000000000000010441232755247200161240ustar00rootroot00000000000000#!/sbin/runscript # Copyright 1999-2008 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header: $ extra_started_commands="reload" depend() { after modules } start() { ebegin "Starting thinkfan" start-stop-daemon --start --exec /usr/sbin/thinkfan -- -q -s5 -c /etc/thinkfan.com eend $? } stop() { ebegin "Stopping thinkfan" start-stop-daemon --stop --exec /usr/sbin/thinkfan eend $? } reload() { PID=$( # Do NOT "set -e" # PATH should only include /usr/* if it runs after the mountnfs.sh script PATH=/sbin:/usr/sbin:/bin:/usr/bin DESC="fan control tool" NAME=thinkfan DAEMON=/usr/sbin/$NAME DAEMON_ARGS="-q" # This one is compiled-in, you can't change it here! PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME START=no # Exit if the package is not installed [ -x "$DAEMON" ] || exit 0 # Read configuration variable file if it is present [ -r /etc/default/$NAME ] && . /etc/default/$NAME # Check if daemon is to be started [ "$START" = "yes" ] || exit 0 # Load the VERBOSE setting and other rcS variables . /lib/init/vars.sh # Define LSB log_* functions. # Depend on lsb-base (>= 3.0-6) to ensure that this file is present. . /lib/lsb/init-functions # # Function that starts the daemon/service # do_start() { # Return # 0 if daemon has been started # 1 if daemon was already running # 2 if daemon could not be started start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ || return 1 start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \ $DAEMON_ARGS \ || return 2 # Add code here, if necessary, that waits for the process to be ready # to handle requests from services started subsequently which depend # on this one. As a last resort, sleep for some time. } # # Function that stops the daemon/service # do_stop() { # Return # 0 if daemon has been stopped # 1 if daemon was already stopped # 2 if daemon could not be stopped # other if a failure occurred start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME RETVAL="$?" [ "$RETVAL" = 2 ] && return 2 # Wait for children to finish too if this is a daemon that forks # and if the daemon is only ever run from this initscript. # If the above conditions are not satisfied then add some other code # that waits for the process to drop all resources that could be # needed by services started subsequently. A last resort is to # sleep for some time. start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON [ "$?" = 2 ] && return 2 # Many daemons don't delete their pidfiles when they exit. rm -f $PIDFILE return "$RETVAL" } # # Function that sends a SIGHUP to the daemon/service # do_reload() { # # If the daemon can reload its configuration without # restarting (for example, when it is sent a SIGHUP), # then implement that here. # start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME return 0 } case "$1" in start) [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" do_start case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; stop) [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" do_stop case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; status) status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? ;; reload|force-reload) log_daemon_msg "Reloading $DESC" "$NAME" do_reload log_end_msg $? ;; restart) log_daemon_msg "Restarting $DESC" "$NAME" do_stop case "$?" in 0|1) do_start case "$?" in 0) log_end_msg 0 ;; 1) log_end_msg 1 ;; # Old process is still running *) log_end_msg 1 ;; # Failed to start esac ;; *) # Failed to stop log_end_msg 1 ;; esac ;; *) #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 echo "Usage: $SCRIPTNAME {start|stop|restart|status|restart|force-reload}" >&2 exit 3 ;; esac : rcscripts/thinkfan.service000066400000000000000000000003601232755247200162660ustar00rootroot00000000000000[Unit] Description=simple and lightweight fan control program After=syslog.target [Service] Type=forking ExecStart=/usr/sbin/thinkfan PIDFile=/var/run/thinkfan.pid ExecReload=/bin/kill -HUP $MAINPID [Install] WantedBy=multi-user.target system.c000066400000000000000000000272441232755247200125700ustar00rootroot00000000000000/******************************************************************** * system.c: Anything that interfaces with the operating system * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * * This file contains all functions that are specific to dealing with * either /sys/class/hwmon or the /proc/acpi/ibm interface. They are * referenced in the main program via function pointers. * * I know there's a lot of code redundancy in here, but that's expected * to save us some memory access in the main loop. * ******************************************************************/ #include "globaldefs.h" #include "thinkfan.h" #include #include #include #include #include #include #include #include #include "message.h" #include "system.h" #include "parser.h" #ifdef USE_ATASMART #include #endif const char temperatures[] = "temperatures:"; #define sensor_file_ibm \ int ibm_temp; \ ssize_t r=0; \ char *input; \ input = rbuf; \ if (unlikely(((ibm_temp = open( \ config->sensors[sensoridx].path, O_RDONLY)) < 0) \ || ((r = read(ibm_temp, rbuf, 128)) < 14) \ || (close(ibm_temp) < 0))) { \ report(LOG_ERR, LOG_ERR, "%s: %s\n", \ config->sensors[sensoridx].path, strerror(errno)); \ errcnt |= ERR_T_GET; \ } \ rbuf[r] = 0; #define store_temp \ if ((int)tmp > tmax) { \ b_tmax = temps + tempidx; \ tmax = (int)tmp; \ } \ if (likely(tmp > -64)) found_temps++; \ temps[tempidx] = (int)tmp + config->sensors[sensoridx].bias[i]; \ tempidx++; int count_temps_ibm() { int *tmp; sensor_file_ibm skip_space(&input); tempidx = 0; if(likely(parse_keyword(&input, temperatures) != NULL)) for (tempidx = 0; (tmp = parse_int(&input)); tempidx++) free(tmp); return tempidx; } /******************************************************************* * get_temp_ibm reads temperatures from /proc/acpi/ibm/thermal and * returns the number of temperatures read. *******************************************************************/ void get_temp_ibm() { long int tmp; int i = 0; char *s_input; sensor_file_ibm skip_space(&input); if (likely(parse_keyword(&input, temperatures) != NULL)) { tmax = -128; while(likely(*(s_input = input) && ( (tmp = strtol(input, &input, 0)) || (input > s_input) ))) { if (unlikely(tmp < INT_MIN || tmp > INT_MAX)) errcnt |= ERR_T_GET; store_temp i++; } if (unlikely(tempidx < 2)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_T_GET); errcnt |= ERR_T_GET; } } else { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_T_PARSE(rbuf)); errcnt |= ERR_T_GET; } } /*********************************************************** * Set fan speed (IBM interface). ***********************************************************/ void setfan_ibm() { int ibm_fan, l = strlen(cur_lvl); if (unlikely((ibm_fan = open(IBM_FAN, O_RDWR, O_TRUNC)) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, IBM_FAN ": %s\n", strerror(errno)); errcnt |= ERR_FAN_SET; } else { if (unlikely(write(ibm_fan, cur_lvl, l) < l)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_FANCTRL); errcnt |= ERR_FAN_SET; } close(ibm_fan); } } /********************************************************* * Check for fan_control support in thinkpad_acpi and * activates the fan watchdog. *********************************************************/ void init_fan_ibm() { char *line = NULL; size_t count = 0; FILE *ibm_fan; int module_valid=0; if ((ibm_fan = fopen(IBM_FAN, "r+")) == NULL) { prefix = "\n"; report(LOG_ERR, LOG_ERR, IBM_FAN ": %s\n" MSG_ERR_FANFILE_IBM, strerror(errno)); errcnt |= ERR_FAN_SET; return; } while (getline(&line, &count, ibm_fan) != -1) if (!strncmp("commands:", line, 9)) module_valid = 1; if (!module_valid) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_MODOPTS); errcnt |= ERR_FAN_SET; } fprintf(ibm_fan, "watchdog %d\n", watchdog_timeout); fclose(ibm_fan); free(line); } /********************************************************* * Restore automatic fan control. *********************************************************/ void uninit_fan_ibm() { FILE *fan; if ((fan = fopen(IBM_FAN, "r+")) == NULL) { prefix = "\n"; report(LOG_ERR, LOG_ERR, IBM_FAN ": %s\n", strerror(errno)); errcnt |= ERR_FAN_SET; } else { fprintf(fan, "level auto\n"); fclose(fan); } } /**************************************************************** * Set the fan to disengaged mode for a specific duration <= 1s * to work-around the pulsating-fan problem. ****************************************************************/ void disengage() { int ibm_fan; if (unlikely((ibm_fan = open(IBM_FAN, O_RDWR)) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, IBM_FAN ": %s\n", strerror(errno)); errcnt |= ERR_FAN_SET; return; } else { if (write(ibm_fan, "level disengaged", 16) < 16) { prefix = "\n"; report(LOG_ERR, LOG_ERR, IBM_FAN ": %s\n", strerror(errno)); errcnt |= ERR_FAN_SET; } close(ibm_fan); } if (usleep(depulse)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "nanosleep(): %s\n", strerror(errno)); errcnt |= ERR_FAN_SET; } } void depulse_and_get_temps() { int nlevel = config->limits[lvl_idx].nlevel; if (nlevel != 0 && nlevel != INT_MIN && nlevel != INT_MAX) { disengage(); config->setfan(); } get_temps(); } /**************************************************************** * Read the temperature from the current sysfs sensor. ****************************************************************/ void get_temp_sysfs() { int num, fd, i = 0; long int tmp; char buf[8]; char *input = buf, *end; if (unlikely((fd = open(config->sensors[sensoridx].path, O_RDONLY)) == -1 || (num = read(fd, &buf, 7)) == -1 || close(fd) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "%s: %s\n", config->sensors[sensoridx].path, strerror(errno)); errcnt |= ERR_T_GET; return; } tmp = strtol(input, &end, 0); if (unlikely(*end != 0 && *end != '\n')) { prefix = "\n"; report(LOG_ERR, LOG_WARNING, MSG_ERR_T_GARBAGE, config->sensors[sensoridx].path); if (chk_sanity) errcnt |= ERR_T_GET; } if (unlikely(tmp < INT_MIN || tmp > INT_MAX)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_T_INVALID, config->sensors[sensoridx].path, tmp); errcnt |= ERR_T_GET; } tmp /= 1000; store_temp } /*********************************************************** * Set fan speed (sysfs interface). ***********************************************************/ void setfan_sysfs() { int fan, l = strlen(cur_lvl); if (unlikely((fan = open(config->fan, O_WRONLY)) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "%s: %s\n", config->fan, strerror(errno)); errcnt++; } else { if (unlikely(write(fan, cur_lvl, l) < l)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, MSG_ERR_FANCTRL); errcnt++; } close(fan); } } /*********************************************************** * Suspend/Resume-safe way of setting fan speed ***********************************************************/ void setfan_sysfs_safe() { init_fan_sysfs(); setfan_sysfs(); } void init_fan_sysfs_once() { preinit_fan_sysfs(); init_fan_sysfs(); } /*********************************************************** * Store old pwm_enable value to cleanly reset it when exiting ***********************************************************/ void preinit_fan_sysfs() { if (oldpwm) return; char *fan_enable = (char *) malloc((strlen(config->fan) + 8) * sizeof(char)); FILE *fan = NULL; size_t s = 0; ssize_t r = 0; strcpy(fan_enable, config->fan); strcat(fan_enable, "_enable"); if ((fan = fopen(fan_enable, "r")) == NULL) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "%s: %s\n", fan_enable, strerror(errno)); report(LOG_ERR, LOG_ERR, MSG_ERR_FAN_INIT); free(fan_enable); errcnt |= ERR_FAN_INIT; } else { if ((r = getline(&oldpwm, &s, fan)) < 2) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "%s: %s\n", fan_enable, strerror(errno)); report(LOG_ERR, LOG_ERR, MSG_ERR_FAN_INIT); errcnt |= ERR_FAN_INIT; } fclose(fan); free(fan_enable); } } /********************************************************* * Activate userspace PWM control. *********************************************************/ void init_fan_sysfs() { int fd; char *fan_enable = (char *) malloc((strlen(config->fan) + 8) * sizeof(char)); ssize_t r; strcpy(fan_enable, config->fan); strcat(fan_enable, "_enable"); if ((fd = open(fan_enable, O_WRONLY)) < 0) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "%s: %s\n", fan_enable, strerror(errno)); free(fan_enable); errcnt |= ERR_FAN_INIT; goto fail; } if ((r = write(fd, "1\n", 2)) < 2) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "%s: %s\n", fan_enable, strerror(errno)); report(LOG_ERR, LOG_ERR, MSG_ERR_FAN_INIT); errcnt |= ERR_FAN_INIT; } fail: close(fd); free(fan_enable); } /********************************************************* * Restore previous fan control mode. *********************************************************/ void uninit_fan_sysfs() { FILE *fan; char *fan_enable = (char *) malloc((strlen(config->fan) + 8) * sizeof(char)); strcpy(fan_enable, config->fan); strcat(fan_enable, "_enable"); if (oldpwm) { if ((fan = fopen(fan_enable, "r+")) == NULL) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "%s: %s\n", fan_enable, strerror(errno)); errcnt++; } else { fprintf(fan, "%s", oldpwm); fclose(fan); } free(oldpwm); free(fan_enable); oldpwm = NULL; } } #ifdef USE_ATASMART /********************************************************* * Read the temperature from the current atasmart sensor, * using 0 if the disk is in standby and dnd_disk is set. *********************************************************/ void get_temp_atasmart() { SkDisk *disk; SkBool diskSleeping = FALSE; uint64_t mKelvin; double tmp; int ret, i = 0; if (unlikely((ret = sk_disk_open(config->sensors[sensoridx].path, &disk)) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "sk_disk_open(%s): %s\n", config->sensors[sensoridx].path, strerror(errno)); errcnt |= ERR_T_GET; return; } if (unlikely(dnd_disk)) { if (unlikely((ret = sk_disk_check_sleep_mode(disk, &diskSleeping)) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "sk_disk_open(%s): %s\n", config->sensors[sensoridx].path, strerror(errno)); errcnt |= ERR_T_GET; goto end; } if (unlikely(diskSleeping)) { tmp = 0; store_temp; goto end; } } if (unlikely((ret = sk_disk_smart_read_data(disk)) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "sk_disk_smart_read_data(%s): %s\n", config->sensors[sensoridx].path, strerror(errno)); errcnt |= ERR_T_GET; goto end; } if (unlikely((ret = sk_disk_smart_get_temperature(disk, &mKelvin)) < 0)) { prefix = "\n"; report(LOG_ERR, LOG_ERR, "sk_disk_smart_get_temperature(%s): %s\n", config->sensors[sensoridx].path, strerror(errno)); errcnt |= ERR_T_GET; goto end; } tmp = mKelvin / 1000.0f; tmp -= 273.15f; if (unlikely(tmp > INT_MAX || tmp < INT_MIN)) { errcnt |= ERR_T_GET; goto end; } store_temp end: sk_disk_free(disk); return; } #endif /* USE_ATASMART */ system.h000066400000000000000000000027771232755247200126010ustar00rootroot00000000000000/******************************************************************** * system.h: Declarations and prototypes for system.c * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * * This file contains all functions that are specific to dealing with * either /sys/class/hwmon or the /proc/acpi/ibm interface. They are * referenced in the main program via function pointers. * ******************************************************************/ #ifndef SYSTEM_H #define SYSTEM_H int count_temps_ibm(); void get_temp_ibm(); void get_temp_sysfs(); #ifdef USE_ATASMART void get_temp_atasmart(); #endif void depulse_and_get_temps(); void get_temps(); void setfan_ibm(); void setfan_sysfs(); void setfan_sysfs_safe(); void init_fan_ibm(); void preinit_fan_sysfs(); void init_fan_sysfs_once(); void init_fan_sysfs(); void uninit_fan_ibm(); void uninit_fan_sysfs(); #endif thinkfan.1000066400000000000000000000121451232755247200127560ustar00rootroot00000000000000.TH THINKFAN "1" "June 2013" "thinkfan 0.9.1" "thinkfan" .SH NAME thinkfan \- A simple fan control program .SH SYNOPSIS .SY thinkfan .OP \-hnqzDd .OP \-b BIAS .OP \-c CONFIG .OP \-s SECONDS .OP \-p [DELAY] .YS .SH DESCRIPTION Thinkfan sets the fan speed according to temperature limits preconfigured in \fI/etc/thinkfan.conf\fR. It can read temperatures from three possible sources: .IP "\fI/proc/acpi/ibm/thermal\fR" Which is provided by the thinkpad_acpi kernel module, .IP "\fI/sys/class/hwmon/*/temp*_input\fR" Which may be provided by any hwmon drivers, and .IP "\fIS.M.A.R.T.\fR (since 0.9)" Which reads the temperature directly from the hard disk using libatasmart. .P Note that since 0.9 you can use any sensors of these three types at the same time. To allow that, the configuration \fBkeywords\fR have been \fBchanged\fR. The \fIsensor\fR keyword has been deprecated in favor of the new keywords \fItp_thermal\fR, \fIhwmon\fR and \fIatasmart\fR which mark the following path as a legacy thinkpad_acpi thermal file, sysfs hwmon file, or a hard disk device file, respectively. .P The fan can be \fI/proc/acpi/ibm/fan\fR or some PWM file in \fI /sys/class/hwmon\fR. Note that the \fIfan\fR config keyword is \fBdeprecated\fR as well. Instead, you should use \fItp_fan\fR for a legacy thinkpad_acpi fan file or \fIpwm_fan\fR for a sysfs PWM file. .P See the README file and the example configurations for details on these changes. .HP \fBWARNING\fR: This program does only very basic sanity checking on the configuration. That means that you can set your temperature limits as insane as you like. .P There are two general modes of operation: .SS COMPLEX MODE In complex mode, temperature limits are defined for each sensor thinkfan knows about. Setting suitable limits for each sensor in your system will probably require a bit of experimentation and good knowledge about your hardware, but it's the safest way of keeping each component within its specified temperature range. See http://www.thinkwiki.org/wiki/Thermal_Sensors for details on which sensor measures what temperature in a Thinkpad. On other systems you'll have to find out on your own. See the example configs to learn about the syntax. .SS SIMPLE MODE In simple mode, Thinkfan uses only the highest temperature found in the system. That may be dangerous, e.g. for hard disks. That's why you should provide a correction value (i.e. add 10\-15 \°C) for the sensor that has the temperature of your hard disk (or battery...). See the example config files for details about that. .SH CONFIGURATION Some example configurations are provided with the source package. For detailed explanations please read the README file. If you installed thinkfan from a distribution package, you may find them under \fI/usr/share/doc\fR or wherever your package manager puts documentation. .SH OPTIONS .TP \fB\-h\fR Show a short help message .TP \fB\-s\fR SECONDS Maximum seconds between temperature updates (default: 5) .TP \fB\-b\fR BIAS Floating point number (\-10 to 30) to control rising temperature exaggeration. If the temperature increases by more than 2 °C during one cycle, this number is used to calculate a bias, which is added to the current highest temperature seen in the system: current_tmax = current_tmax + delta_t * BIAS / 10 This means that negative numbers can be used to even out short and sudden temperature spikes like those seen on some on\-DIE sensors. Use DANGEROUS mode to remove the \-10 to +30 limit. Note that you can't have a space between \-b and a negative argument, because otherwise getopt will interpret things like \-10 as an option and fail (i.e. write "\-b\-10" instead of "\-b \-10"). Default is 15.0 .TP \fB\-c\fR FILE Load a different configuration file (default: /etc/thinkfan.conf) .TP \fB\-n\fR Do not become a daemon and log to terminal instead of syslog .TP \fB\-q\fR Be quiet (no status info on terminal) .TP \fB\-z\fR Assume we don't have to worry about resuming from standby when using the sysfs interface (see README!) .TP \fB\-p\fR [SECONDS] Use the pulsing\-fan workaround (for older Thinkpads). Takes an optional floating\-point argument (0\-10s) as depulsing duration. Default 0.5s. .TP \fB\-d\fR Do not read temperature from sleeping disks. Instead, 0 °C is used as that disk's temperature. This is needed if reading the temperature causes your disk to wake up unnecessarily. \fBNote\fR: This option is only available if thinkfan was built with \-D USE_ATASMART. .TP \fB\-D\fR DANGEROUS mode: Disable all sanity checks. May damage your hardware!! .SH SIGNALS SIGINT and SIGTERM simply interrupt operation and should cause thinkfan to terminate cleanly. .P SIGHUP makes thinkfan reload its config. If there's any problem with the new config, we keep the old one. .P SIGUSR1 causes thinkfan to dump all currently known temperatures either to syslog, or to the console (if running with the \-n option). .SH SEE ALSO git://git.code.sf.net/p/thinkfan/code .SH BUGS If you have any problems with thinkfan, please go to the help forum at sf.net: .RS .RE http://sourceforge.net/projects/thinkfan/forums/forum/905019. .P There's a bugtracker at .RS .RE http://sourceforge.net/tracker/?group_id=249873&atid=2416828. thinkfan.c000066400000000000000000000244301232755247200130400ustar00rootroot00000000000000/************************************************************************* * thinkfan version 0.9 -- copyleft 08-2013, Victor Mataré * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * * * Although it's generally considered bad style, I do make heavy use of * global variables, hoping to minimize memory access in the inner loop. * If you know better, please drop me a line. I haven't yet bothered looking * at the difference it makes in machine language. *************************************************************************/ #include "globaldefs.h" #include #include #include #include #include #include #include #include #include "thinkfan.h" #include "message.h" #include "config.h" // The system interface is part of the config now... volatile int interrupted; unsigned int sleeptime, tmp_sleeptime; #define set_fan cur_lvl = config->limits[lvl_idx].level; \ if (!quiet && nodaemon) \ report(LOG_DEBUG, LOG_DEBUG, MSG_DBG_T_STAT); \ config->setfan(); int run(); /* Return TRUE if *at least one* upper limit has been reached */ int complex_lvl_up() { int i; for (i=0; likely(i < num_temps); i++) if (unlikely(temps[i] >= config->limits[lvl_idx].high[i])) { #ifdef DEBUG triggered_tidx = i; #endif /* DEBUG */ return TRUE; } return FALSE; } /* Return TRUE if *all* lower limits have been reached */ int complex_lvl_down() { int i; for (i=0; likely(i < num_temps && temps[i] <= config->limits[lvl_idx].low[i]); i++); if (unlikely(i >= config->limit_len)) return TRUE; return FALSE; } int simple_lvl_up() { if (unlikely(*b_tmax >= config->limits[lvl_idx].high[0])) return TRUE; return FALSE; } int simple_lvl_down() { if (unlikely(*b_tmax <= config->limits[lvl_idx].low[0])) return TRUE; return FALSE; } void get_temps() { tmax = -128; tempidx = 0; sensoridx = 0; found_temps = 0; for (sensoridx = 0; likely(sensoridx < config->num_sensors); sensoridx++) { config->sensors[sensoridx].get_temp(); } if (unlikely(found_temps < config->used_temps)) { report(LOG_ALERT, LOG_ALERT, MSG_ALERT_SENSOR); errcnt |= ERR_T_GET; } } /*********************************************************** * This is the main routine which periodically checks * temperatures and adjusts the fan according to config. ***********************************************************/ int fancontrol() { float bias=0; int diff=0, i, last_errcnt = 0; int wt = watchdog_timeout; tmp_sleeptime = sleeptime; prefix = "\n"; // makes the output more readable config->init_fan(); if (errcnt) return errcnt; prefix = "\n"; // It is set to "" by the output macros // Set initial fan level... lvl_idx = config->num_limits - 1; for (i=0; i < num_temps; i++) if (temps[i] > tmax) tmax = temps[i]; /********************************************** * Main loop. This is the actual fan control. **********************************************/ while(likely(!interrupted && !errcnt)) { last_tmax = tmax; // depending on the command line, this might also call depulse() get_temps(); // If temperature increased by more than 2 °C since the // last cycle, we try to react quickly. diff = tmax - last_tmax; if (unlikely(diff >= 2)) { bias = ((float)diff * bias_level); if (tmp_sleeptime > 2) tmp_sleeptime = 2; } else { if (unlikely(diff < 0)) { tmp_sleeptime = sleeptime; bias = 0; } else if (unlikely(tmp_sleeptime < sleeptime)) tmp_sleeptime++; } *b_tmax = tmax + bias; // determine appropriate fan level and activate it if (unlikely(lvl_idx < config->num_limits - 1 && config->lvl_up())) { while (likely(lvl_idx < config->num_limits - 1 && config->lvl_up())) lvl_idx++; set_fan; } else if (unlikely(lvl_idx > 0 && config->lvl_down())) { while (likely(lvl_idx > 0 && config->lvl_down())) lvl_idx--; set_fan; tmp_sleeptime = sleeptime; } sleep(tmp_sleeptime); // state-dependant sleeptime // Write current fan level to IBM_FAN one cycle before the watchdog // timeout ends, to let it know we're alive. if (unlikely((wt -= tmp_sleeptime) <= sleeptime)) { config->setfan(); wt = watchdog_timeout; } // slowly reduce the bias if (unlikely(bias != 0)) { if (likely(bias > 0)) { if (bias < 0.5) bias = 0; else bias -= bias/2 * bias_level; } else { if (bias > -0.5) bias = 0; else bias += bias/2 * bias_level; } } if (unlikely(!chk_sanity)) { // In DANGEROUS mode, we exit only after MAXERR consecutive errors. if (unlikely(errcnt)) last_errcnt++; else last_errcnt = 0; if (likely(last_errcnt <= MAXERR)) errcnt = 0; } } return errcnt; } void sig_handler(int signum) { switch(signum) { case SIGHUP: case SIGINT: case SIGTERM: interrupted = signum; break; case SIGUSR1: report_tstat(); break; } } /*************************************************************** * Main function: * Scan for arguments, set options and initialize signal handler ***************************************************************/ int main(int argc, char **argv) { int opt, ret; char *invalid = ""; struct sigaction handler; rbuf = NULL; depulse_tmp = 0; sleeptime = 5; quiet = FALSE; chk_sanity = TRUE; bias_level = 1.5f; ret = 0; config_file = "/etc/thinkfan.conf"; nodaemon = FALSE; errcnt = 0; resume_is_safe = FALSE; prefix = "\n"; oldpwm = NULL; config = NULL; lvl_idx = 0; last_tmax = 0; tmax = 0; temps = NULL; cur_lvl = NULL; tempidx = 0; triggered_tidx = -1; char *optstring = "c:s:b:p::hnqDz" #ifdef USE_ATASMART "d"; dnd_disk = FALSE; #else ; #endif openlog("thinkfan", LOG_CONS, LOG_USER); syslog(LOG_INFO, "thinkfan " VERSION " starting..."); interrupted = 0; memset(&handler, 0, sizeof(handler)); handler.sa_handler = sig_handler; if (sigaction(SIGHUP, &handler, NULL) \ || sigaction(SIGINT, &handler, NULL) \ || sigaction(SIGTERM, &handler, NULL) \ || sigaction(SIGUSR1, &handler, NULL)) perror("sigaction"); while ((opt = getopt(argc, argv, optstring)) != -1) { switch(opt) { case 'h': fprintf(stderr, MSG_USAGE); return 0; break; #ifdef USE_ATASMART case 'd': dnd_disk = TRUE; break; #endif case 'n': nodaemon = 1; break; case 'c': config_file = optarg; break; case 'q': quiet = 1; break; case 'D': chk_sanity = 0; break; case 'z': resume_is_safe = !0; break; case 's': sleeptime = (unsigned int) strtol(optarg, &invalid, 0); if (*invalid != 0) { report(LOG_ERR, LOG_ERR, MSG_ERR_OPT_S); report(LOG_ERR, LOG_INFO, MSG_USAGE); ret = 1; goto fail; } break; case 'b': bias_level = strtof(optarg, &invalid); if (*invalid != 0) { report(LOG_ERR, LOG_ERR, MSG_ERR_OPT_B); report(LOG_ERR, LOG_INFO, MSG_USAGE); ret = 1; goto fail; } if (bias_level < -10 || bias_level > 30) { report(LOG_ERR, LOG_WARNING, MSG_ERR_OPT_B); if (chk_sanity) { report(LOG_ERR, LOG_INFO, MSG_USAGE); ret = 1; goto fail; } } bias_level /= 10; break; case 'p': if (optarg) { depulse_tmp = strtof(optarg, &invalid); if (*invalid != 0 || depulse_tmp > 10 || depulse_tmp < 0) { report(LOG_ERR, LOG_ERR, MSG_ERR_OPT_P); report(LOG_ERR, LOG_INFO, MSG_USAGE); ret = 1; goto fail; } } else depulse_tmp = 0.5f; depulse = (useconds_t) (1000*1000 * depulse_tmp); break; default: fprintf(stderr, MSG_USAGE); return 1; } } if (sleeptime > 15) { report(LOG_ERR, LOG_WARNING, MSG_WRN_SLEEPTIME_15); report(LOG_ERR, LOG_INFO, MSG_INF_SANITY); if (chk_sanity) { ret = 1; goto fail; } } else if (sleeptime < 1) { report(LOG_ERR, LOG_WARNING, MSG_WRN_SLEEPTIME_1); report(LOG_ERR, LOG_INFO, MSG_INF_SANITY); if (chk_sanity) { ret = 1; goto fail; } } watchdog_timeout = sleeptime * 6; ret = run(); fail: free_config(config); free(rbuf); free(oldpwm); free(temps); return ret; } /******************************************************************** * Outer loop. Handles signal conditions, runtime cleanup and config * reloading ********************************************************************/ int run() { int ret = 0, childpid; struct tf_config *newconfig=NULL; FILE *pidfile; rbuf = malloc(sizeof(char) * 128); prefix = "\n"; if (chk_sanity && ((pidfile = fopen(PID_FILE, "r")) != NULL)) { fclose(pidfile); report(LOG_ERR, LOG_WARNING, MSG_ERR_RUNNING); if (chk_sanity) return ERR_PIDFILE; } if ((config = readconfig(config_file)) == NULL) { report(LOG_ERR, LOG_ERR, MSG_ERR_CONF_NOFILE); return ERR_CONF_NOFILE; } config->init_fan(); get_temps(); ret |= errcnt; if (errcnt) goto cleanexit; if (depulse) report(LOG_INFO, LOG_DEBUG, MSG_INF_DEPULSE(sleeptime, depulse_tmp)); // So we try to detect most errors before forking. if (!nodaemon) { if ((childpid = fork()) != 0) { if (!quiet) fprintf(stderr, "Daemon PID: %d\n", childpid); return 0; } if (childpid < 0) { perror("fork()"); ret |= ERR_FORK; goto cleanexit; } } if ((pidfile = fopen(PID_FILE, "w+")) == NULL && chk_sanity) { report(LOG_ERR, LOG_WARNING, PID_FILE ": %s", strerror(errno)); ret |= ERR_PIDFILE; goto cleanexit; } fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); while (1) { interrupted = 0; if ((ret = fancontrol())) break; else if (interrupted == SIGHUP) { report(LOG_DEBUG, LOG_DEBUG, MSG_DBG_CONF_RELOAD); if ((newconfig = readconfig(config_file)) != NULL) { free_config(config); config = newconfig; } else report(LOG_ERR, LOG_ERR, MSG_ERR_CONF_RELOAD); } else if (SIGINT == interrupted || interrupted == SIGTERM) { report(LOG_WARNING, LOG_INFO, "\nCaught deadly signal. "); break; } } cleanexit: report(LOG_WARNING, LOG_INFO, MSG_INF_TERM); config->uninit_fan(); unlink(PID_FILE); return ret; } thinkfan.h000066400000000000000000000020561232755247200130450ustar00rootroot00000000000000/******************************************************************** * thinkfan.h: Top-level definitions. * * this file is part of thinkfan. See thinkfan.c for further information. * * thinkfan 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. * * thinkfan 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 thinkfan. If not, see . * ******************************************************************/ #ifndef THINKFAN_H #define THINKFAN_H #define _GNU_SOURCE int complex_lvl_up(); int complex_lvl_down(); int simple_lvl_up(); int simple_lvl_down(); void get_temps(); #endif