Fractoon's dedicated build - part 2

From Gentoo Linux Wiki

Jump to: navigation, search


Please format this article according to the guidelines and Wikification suggestions, then remove this notice {{Wikify}} from the article


This article is so "complete" that gentoo-wiki started complaining about it's size.

I've split it into three pages:


Contents

[edit] Firewall

[edit] Introduction

I found the documentation available regarding IPTables/IPChains incredibly over-complicated for general home usage. I did not need a full blown firewall, router or bridge and really got lost in the details, especially some of the more advanced routing options.


What I'm presenting here is a very simple 'firewall'. It uses limited state awareness and seems to work very well for my needs. I'm sure some of the more network orientated readers could pick it to bits and to be honest I'd welcome the feedback.

Gentoo's founder authored a great introductory article about using IPTables.

[edit] Preparation

IPTables forms part of the kernel and as such the preparation work involves compiling the required options into the kernel.

Linux Kernel Configuration: Here are the options I've compiled into my kernel:
Networking support  --->
   [*] Networking support
         Networking options  --->
           Select only ...
           <*> Packet socket                               (needed by dhcpcd)
           <*> Unix domain sockets                              (needed by X)
           [*] TCP/IP networking                                (no comment!)
           [ ]   IP: multicasting                    (not needed on home lan)
           [*] Network packet filtering (replaces ipchains)  --->
                 IP: Netfilter configuration  --->
                   Select only ...
                   <*> Connection tracking (required for masq/NAT)
                   < > Userspace queueing via NETLINK
                   <*> IP tables support (required for filtering/masq/NAT)
                   <*>   Connection state match support
                   <*>   Packet filtering
                   <*>     REJECT target support
                   <*>   LOG target support

This is, as far as I know, the minimal configuration that will allow state based filtering. Please see Kernel - 2.6.9 configuration for more general information

As in most things Linux based there is usually a User Space component as well. You also need to install the user space IPTables application

Code: Install the userspace tool to setup the firewall.
emerge iptables

Once this has been done we can proceed to trying out IPTables.

[edit] Firewall rules

Firewall rules can become very complicated very quickly. I have tried to keep mine very simple. In short I drop everything, then I allow incoming traffic only when I've initiated the session. In addition to this I only allow certain protocols to initiate connections. Lastly I provide some standard rejections for ping messages (attempt to fool scanners) and log any communication not catered for to my system log.

I believe that it could be possible to spoof my firewall into thinking incoming traffic has been initiated by me, but frankly, I don't have anything that valuable on the machine. What I am saying is, that if you need decent security then this may not be enough!!

I'm not making any attempt at educating anyone, apart from learning by example. Do not use this unless you've read the accompaning article as a minimum.

Here is the code:

Deny everything

Code: Drop everything by default
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

Incoming rules

Code: Allow established and related packets
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Code: Reject upd/icmp/tcp requests with 'sensible' reasons
iptables -A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable
iptables -A INPUT -p icmp -j REJECT --reject-with icmp-port-unreachable
iptables -A INPUT -p tcp -j REJECT --reject-with tcp-reset
Code: Reject any new or invalid requests just in case
iptables -A INPUT -m state --state NEW,INVALID -j DROP
Code: If got here in input rules then there is a problem. log it
iptables -A INPUT -j LOG --log-prefix "Firewall (in):"

Outgoing rules

Code: Allow ping
iptables -A OUTPUT -p udp -m state --state NEW -j ACCEPT
iptables -A OUTPUT -p icmp -m state --state NEW -j ACCEPT
Code: Allow port number 20 (ftp)
iptables -A OUTPUT -p tcp --dport ftp -m state --state NEW -j ACCEPT
Code: Allow port number 21 (ftp-data)
iptables -A OUTPUT -p tcp --dport ftp-data -m state --state NEW -j ACCEPT
Code: Allow port number 25 (smtp)
iptables -A OUTPUT -p tcp --dport smtp -m state --state NEW -j ACCEPT
Code: Allow port number 53 (domain)
iptables -A OUTPUT -p tcp --dport domain -m state --state NEW -j ACCEPT
Code: Allow port number 80 (www/http)
iptables -A OUTPUT -p tcp --dport www -m state --state NEW -j ACCEPT
Code: Allow port number 110 (pop3)
iptables -A OUTPUT -p tcp --dport pop3 -m state --state NEW -j ACCEPT
Code: Allow port number 443 (https)
iptables -A OUTPUT -p tcp --dport https -m state --state NEW -j ACCEPT
Code: Allow port number 873 (rsync) - needed to 'emerge --sync' ;-)
iptables -A OUTPUT -p tcp --dport rsync -m state --state NEW -j ACCEPT
Code: Allow established and related connections
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Code: If got here in output rules then there is a problem. log it
iptables -A OUTPUT -j LOG --log-prefix "Firewall (out):"

[edit] Start-up/Activation script

If you want to look at the table the following command is handy to know

Code: Check current IPTables config
iptables -v -L -t filter

Test the firewall operates as expected and when ready save it.

Code: Save the rules
/etc/init.d/iptables save

Ensure you backup the working copy incase you mess it up

Code: Backup the 'working' copy
cp /var/lib/iptables/rules-save /var/lib/iptables/rules.working

Check start-up script works (start, stop, start to check all is fine)

Code: Start, Stop and Re-start
/etc/init.d/iptables start
/etc/init.d/iptables stop
/etc/init.d/iptables start

Add iptables to default runlevel

Code: Add iptables to default runlevel
rc-update add iptables default

This enables IPTABLES rules, but not general ip configuration/hardening.

Code: The following bits of code have been included in my /etc/init.d/iptables scripts
Explicitly switch ECN (explicit congestion notification) off.
  echo 0 > /proc/sys/net/ipv4/tcp_ecn
If working as a router then makes sure IP forwarding is activated
  echo 0 > /proc/sys/net/ipv4/ip_forward
"Can't" remember what these two were for ... hopefully someone can help
  echo 1 > /proc/sys/net/ipv4/tcp_syncookies
  echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
Source Address Verification
  for f in /proc/sys/net/ipv4/conf/*/rp_filter; do
      echo 1 > $f
  done
Disable IP source routing and ICMP redirects
  for f in /proc/sys/net/ipv4/conf/*/accept_source_route; do
      echo 0 > $f
  done
  for f in /proc/sys/net/ipv4/conf/*/accept_redirects; do
      echo 0 > $f
  done

[edit] Syslog

Syslog-ng's configuration works on the following priciples

  • There are three components; sources, filters, and destinations that are chained together via a fourth configuration component called a log.
    • The system (and applications) are continiously generating messages that, provided you've specified the source (either local or remote) of, will be interpreted by syslog-ng.
    • The most complicated 'component' is the filter as it can be specified to operate on Facility, Priority and/or Content of the messages sourced.
    • The destination component is simply a logfile, either local or remote.
    • As already stated the log statement ties these three components together and as far as I know works inclusively, i.e. everything that matches from all the sources specified is written to all the destinations specified for the particular log rule.

If you need to know more then man syslog-ng provides all the details you could possibly want.

It is actually very simple and I think my current configuration can stand as a pretty good and 'overly' documented example:

File: /etc/syslog-ng/syslog-ng.conf
#-----------------------------------------------------------------------------
# Set the syslog-ng options (Only commenting on ones I've set)
#-----------------------------------------------------------------------------
# sync()              : The number of lines buffered before written to file
# log_fifo_size()     : The number of lines fitting to the output queue
# chain_hostnames()   : Enable or disable the chained hostname
# keep_hostname()     : Enable or disable hostname rewritting
# check_hostname()    : Enable or disable whether hostname contains vaild
#                         characters
# create_dirs()       : Enable or disable directory creation for dest files
# use_dns()           : Enable or disable dns usage
# dns_cache()         : Enable or disable dns cache
# log_msg_size()      : Max length of message in bytes
# use_fqdn()          : Add fully qualified domain name instead of short
#                         hostname
#-----------------------------------------------------------------------------
options { sync(5);
         log_fifo_size(1000);
         chain_hostnames(no);
         keep_hostname(yes);
         check_hostname(no);
         create_dirs(no);
         use_dns(no);
         dns_cache(no);
         log_msg_size(1024);
         use_fqdn(no);
};

#-----------------------------------------------------------------------------
# Define the syslog-ng message sources
#-----------------------------------------------------------------------------
# internal()              : "all" locally generated messages
# unix-stream("/dev/log") : anything written to logs?
# pipe("/proc/kmsg")      : Linux kernel messages (Don't duplicate by reading
#                           from /proc/kmsg directly or running klogd)
#-----------------------------------------------------------------------------
source src { internal();
            unix-stream("/dev/log");
            pipe("/proc/kmsg");
};

#-----------------------------------------------------------------------------
# Define the syslog-ng destination logfiles
#-----------------------------------------------------------------------------
# authpriv    : Security and authorization log
#                 file("/var/log/authpriv.log");
# syslog      : Syslog message log
#                 file("/var/log/syslog.log");
# cron        : Clock deamon log
#                 file("/var/log/cron.log");
# daemon      : System deamon log (without separate facility value?)
#                 file("/var/log/daemon.log");
# kernel      : Linux kernel log (should match dmesg?)
#                 file("/var/log/kernel.log");
# user        : Generic user-level log
#                 file("/var/log/user.log");
# debug       : All debug messages log (catchall? debugging anything?)
#                 file("/var/log/debug.log");
# messages    : All messages log (catchall? is it needed?)
#                 file("/var/log/messages.log");
# everything  : A log containing everything (catchall? is it really needed?)
#                 file("/var/log/everything.log");
# root_cons   : The "root's" console 'virtual' log
#                 usertty("root");
# console_all : Generic console 'virtual'                    (Not implemented)
#                 file("/dev/tty12");
# lpr         : Spooling logfile                             (Not implemented)
#                 file("/var/log/lpr.log");
# uucp        : UUCP log                                     (Not implemented)
#                 file("/var/log/uucp.log");
# mail        : Mail system log                              (Not implemented)
#                 file("/var/log/mail.log");
# news        : USENET log                                   (Not implemented)
#                 file("/var/log/news.log");
# xconsole    : X-server console?                            (Not implemented)
#                 pipe("/dev/xconsole");
#-----------------------------------------------------------------------------
destination authpriv { file("/var/log/authpriv.log"); };
destination syslog { file("/var/log/syslog.log"); };
destination cron { file("/var/log/cron.log"); };
destination daemon { file("/var/log/daemon.log"); };
destination kernel { file("/var/log/kernel.log"); };
destination user { file("/var/log/user.log"); };
destination debug { file("/var/log/debug.log"); };
destination messages { file("/var/log/messages.log"); };
destination everything { file("/var/log/everything.log"); };
destination root_cons { usertty("root"); };

#-----------------------------------------------------------------------------
# Define the syslog-ng filters than can apply to the incoming messages
#-----------------------------------------------------------------------------
# a. Facility - determines the type of program generating the message
#-----------------------------------------------------------------------------
# filter ff_authpriv  : Security and authorization messages
#                         { facility(auth, authpriv); };
# filter ff_syslog    : Messages generated internally
#                         { not facility(auth, authpriv)
#                           and not facility(mail); };
# filter ff_cron      : Clock deamon messages (cron & at)
#                         { facility(cron); };
# filter ff_kern      : Kernel messages
#                         { facility(kern); };
# filter ff_daemon    : System daemons messages, without separate fac. value
#                         { facility(daemon); };
# filter ff_user      : Generic user-level messages (default value, usually)
#                         { facility(user); };
# filter ff_debug     : debug-level messages
#                         { not facility(auth, authpriv, news, mail); };
# filter ff_ftp       : ftp deamon messages                  (Not implemented)
#                         { facility(ftp); };
# filter ff_mail      : mail subsystem messages              (Not implemented)
#                         { facility(mail); };
# filter ff_news      : USENET news subsystem                (Not implemented)
#                         { facility(news); };
# filter ff_uucp      : UUCP subsystem                       (Not implemented)
#                         { facility(uucp); };
# filter ff_lpr       : Spooling subsystem                   (Not implemented)
#                         { facility(lpr); };
#-----------------------------------------------------------------------------
# b. Level - determines importance of message: listed in decreasing importance
#-----------------------------------------------------------------------------
# filter fl_emergency : system is unusable
#                        { level(emerg); };
# filter fl_alert     : action must be taken immediately
#                        { level(alert); };
# filter fl_crit      : critical conditions
#                        { level(crit); };
# filter fl_err       : error conditions
#                        { level(err); };
# filter fl_warn      : warning conditions
#                        { level(warn); };
# filter fl_notice    : normal, but significant, condition
#                        { level(notice); };
# filter fl_info      : informational message
#                        { level(info); };
# filter fl_debug     : debug-level message                   (Not implemented)
#                        { level(debug); };
#-----------------------------------------------------------------------------
# c. Content - Combinations of a., b. and/or specific words etc.
#-----------------------------------------------------------------------------
# filter fc_messages  : All low priority level (excluding debugging) messages
#                       that are not security, mail or news related.
#                         { level(info..warn) and
#                           not facility(auth, authpriv, mail, news); };
#-----------------------------------------------------------------------------
filter ff_authpriv { facility(auth, authpriv); };
filter ff_cron { facility(cron); };
filter ff_kern { facility(kern); };
filter ff_daemon { facility(daemon); };
filter ff_syslog { not facility(auth, authpriv) and not facility(mail); };
filter ff_user { facility(user); };
filter ff_debug { not facility(auth, authpriv, news, mail); };

filter fl_emergency { level(emerg); };
filter fl_alert { level(alert); };
filter fl_crit { level(crit); };
filter fl_err { level(err); };
filter fl_warn { level(warn); };
filter fl_notice { level(notice); };
filter fl_info { level(info); };
filter fl_debug { level(debug); };

filter fc_messages { level(info..warn) and
                     not facility(auth, authpriv, mail, news); };

#-----------------------------------------------------------------------------
# Use the Source, Destination and Filters to actually log stuff
#-----------------------------------------------------------------------------

# Log all messages to /var/logs/everything.log
log { source(src); destination(everything); };

# Log all authentication/security to /var/logs/authpriv.log
log { source(src); filter(ff_authpriv); destination(auhtpriv); };

# Log all system to /var/logs/syslog.log
log { source(src); filter(ff_syslog); destination(syslog); };

# Log all cron events to /var/logs/cron.log
log { source(src); filter(ff_cron); destination(cron); };

# Log all deamon to /var/logs/deamon.log
log { source(src); filter(ff_syslog); destination(syslog); };

# Log all kernel to /var/logs/kernel.log
log { source(src); filter(ff_kernel); destination(kernel); };

# Log all low priority level (excluding debugging) messages that are not
# security, mail or news related to /var/logs/messages.log
log { source(src); filter(fc_messages); destination(messages); };

# Route all 'emergency' messages to root console
log { source(src); filter(fl_emergency); destination(root_cons); };

As it stands at present I'm not completely happy with the volume of data being logged and will at some stage trim this configuration down. Thought it best to capture everything at the moment though fractoon 19:28, 5 Dec 2004 (GMT)

[edit] Wireless

[edit] Introduction

There really isn't much I can add about the appaulling lack of support for drivers of the Broadcom cards. I've read that it has something to do with the cards being able to operate at 'military' frequencies and as such 'national' security prohibits them from providing drivers. This could all be a load of ol' tosh, but the long and the short of it is that ndiswrapper (free) or linuxant (not so free) routes are your only alternatives.

Needless to say I chose the 'free' route.

I had a problem compiling ndiswrapper-0.11 after applying software suspend 2 patches to my kernel so am currently running with ndiswrapper-0.10. For more details check out Power Management - Overview and howto, where I detail how to deal with this situation.

As of kernel 2.6.17 there now are experimental drivers for the BCM43xx chipset. See drivers homepage for more information.

[edit] Preparation & Information gathering

Ensure <Fn>+F2 is disabled in BIOS.

  • pressing the key combination freezes up the box!!! Could probably achieve same with some sort of keymap? (Anyone care to educate me?)
  • generates a kernel message
    • ndiswrapper (iw_set_encr:617): removing encryption key 0 failed (C0010015)

The various code listing to get the required MS Windows drivers.

Code: Install all the required utilities
emerge dhcpcd
emerge pciutils
emerge ndiswrapper
emerge wireless-tools
Code: Find the Wireless card details
lspci -n
  returns class 0280 & PCIID 14e4:4320
elinks http://pciids.sourceforge.net/iii/
  browse to 14e4:4320 to find subsystem 1028:0003
elinks http://ndiswrapper.sourceforge.net/wiki/index.php/List
  Provided good info about working combinations of ndiswrapper, kernel
& driver versions

Get a suitable windows driver Dell site has latest driver at http://ftp.us.dell.com/network/R83099.EXE driver dated 25/06/04 version 3.40.73, extracted & saved to CD}}

Code: Copy the inf and sys file to the portage directory
mount -t auto -o auto /dev/hdc /mnt/cdrom
cp /mnt/cdrom/R833099/AR/bcmwl5.* /usr/portage/

[edit] Configure/Install ndiswrapper

Code: Install the windows driver

cd /usr/portage ndiswrapper -i bcmwl5.inf

 Installing bcmwl5

ndiswrapper -l

 Installed ndis drivers:
bcmwl5 hardware present
Code: Load the ndiswrapper module and check
modprobe ndiswrapper
dmesg
 ndiswrapper version 0.10 loaded (preempt yes,smp yes)
 ACPI: PCI interrupt 0000:02:03.0[A] -> GSI 17 (level, low) -> IRQ 17
 ndiswrapper: using IRQ 17
 wlan0: ndiswrapper ethernet device xx:xx:xx:xx:xx:xx using driver bcmwl5.sys
 ndiswrapper device wlan0 supports WPA with AES/CCMP and TKIP ciphers
ndiswrapper: driver bcmwl5.sys (Broadcom,06/25/2004, 3.40.73.0) added

This matches info of the R833099.exe driver downloaded

[edit] Configure & check the wlan0 interface

Code: Check wlan0 exists
iwconfig
returns all the interface details under wlan0 ... No access point etc.
Code: Configure/check wlan0 set-up
iwconfig wlan0 essid <essidname> key restricted <keycode> commit

Replace essidname & keycode with the relevant information and if errors, then try the command without the commit

Code: Check configuration
iwconfig

should have ESSID and Encryption key set ... if not then find the

right iwconfig configuration string. man iwconfig works a treat :-)

[edit] Bring the network up

Code: Initiate ethernet over wlan0
ifconfig wlan0 up
Code: DHCP
dhcpcd wlan0
Code: Check it all worked
ifconfig
ensure inet addr, Bcast & Mask is set to sensible values

[edit] Final configurations (autoload module etc.)

We can now make the final configurations to make the changes permanent

Code: Store ndiswrapper modules setting
ndiswrapper -m
Code: Link net.wlan0 to net.lo to start-up automatically
cd /etc/init.d
ln -s net.lo net.wlan0
rc-update add net.wlan0 default
Code: Load ndiswrapper automatically
echo "ndiswrapper" >> /etc/modules.autoload.d/kernel-2.6
Code: Setup the default wireless config
cp /etc/conf.d/wireless.example /etc/conf.d/wireless

nano -w /etc/conf.d/wireless

essid_wlan0="<essid>"
mode_<essid>="Managed"
channel_<essid>="<x>"
key_<essid>="xx..xx enc restricted"
ifconfig_<essid>=( "dhcp" )
dhcpcd_<essid>="-t 5"

Making sure you replace <essid> with your essid & likewise <x> with your channel.

You should have the wireless card automatically loaded each time you boot up.

[edit] Bootsplash

Introduction

This is very much a duplicate of HOWTO Framebuffer, Bootsplash and Grubsplash, but specific to my needs.

Configure the kernelspace reqs

More details can be found at Kernel - 2.6.9 configuration

Linux Kernel Configuration: Bootsplash
Device Drivers  --->
 Block devices  --->
   <*> RAM disk support
   (4096) Default RAM disk size  (kbytes)
   [*]   Initial RAM dsik (initrd) support)

 Character devices  --->
   <*> /dev/agpgart (AGP Support)
         Uncheck all then ...
   <*>   Intel i865 chipset support
   [ ] Direct Rendering Manager (XFree86 4.1.0 > support -disable!)

 Graphics support  --->
   [*] Support for frame buffer devices
   [ ] VESA VGA graphics support                        (using radeonfb only)
   <*> ATI Radeon display support
       Console display driver support  --->
         [*] VGA text console
         [*]   Video mode selection support
         <*> Framebuffer Console Support
         [ ]   Select compiled-in fonts
       Logo configuration  --->
         deselect everything
   [*] Support for the framebuffer splash

Install/configure the userspace bits

Code: Install the required software
emerge splashutils
Code: Create the initrd to hold bootsplash
splash_geninitramfs -v -g /boot/fbsplash-emergence-1024x768 -r 1024x768 emergence
Code: Install a 'grub' skin to complete the picture

Still need to customise this for my machine, apparently there are more themes at www.bootsplash.de

[edit] UDEV

Introduction

This is still very much work in progress. The UDEV Primer is a great help when trying to understand what UDEV is all about:

Kernelspace configuration

Please check out Kernel - 2.6.9 configuration for more details

Linux Kernel Configuration: Kernel 2.6.9
General setup  --->
 [*] Support for hot-plugable devices

File systems  --->
     Pseudo filesystems  --->
       [ ] /dev file system support (OBSOLETE)

Userspace configuration

Code: Install UDEV (Done as part of install)
emerge udev
Code: Ensure hotplug is loaded
rc-update add hotplug boot
rc-update -s
Code: Using pure udev so make sure
nano -w /etc/conf.d/rc
RC_DEVICE_TARBALL="no"
RC_DEVFSD_STARTUP="no"
Code: Might need to create /dev/<equip> folders
mknod -m 660 /dev/<equip> c MajorNr MinorNr
e.g. /dev/dvdrw?

The next step is to write a decent udev rules file and I believe Writing UDEV rules should start me off on the right track

[edit] Power Management

[edit] Introduction

I believe this to be an exciting, but confusing, area of Linux development. The Linux community is taking it very serious, but as per anything Linux based it is being done in a piecemeal fashion by developers dotted all over the world with no apparent strategy. This is bourne out with the variety of tools and utilities available.

The official Gentoo Power Management Guide provides an excellent introduction and I advise strongly that you read it before thinking about implementing anything you find here. Tools such as the 'laptop-mode' scripts described later can seriously shorten your hard disk lifespan if configured incorrectly. Likewise messing around with your cooling fans etc. will affect the lifespan of your CPU.

In this article I've tried to describe how the various power management components and utilites combine to reduce power consumption on a laptop, before detailing the specific things I've implented (and still plan on implementing) to manage my laptop's power usage.

It is still early days for me regarding this topic, but implementing what I have here has definately improved my available time to use the laptop whilst running off the battery. My subjective estimate is that the available usage time is about 3 times longer than it is without anything suggested here.

[edit] General process and requirements

[edit] Power Management layers

Power management on the Inspiron 9100 is initiated via the ACPI (Advanced Configuration and Power Interface) BIOS. This 'hardware' software layer is complimented by the kernel space tools to interface with the BIOS that in turn exposes the management of the hardware and system to the userspace software tools. This looks something like this:

 -----------------------------------------------------------
[             Userspace programs e.g. acpid                 ]
 -----------------------------------------------------------
                               ^
                               |
                               v
 -----------------------------------------------------------
[         Kernelspace modules e.g. ACPI Config options      ]
 -----------------------------------------------------------
                               ^
                               |
                               v
 -----------------------------------------------------------
[                  BIOS - ACPI v2.0 aware                   ]
 -----------------------------------------------------------
                               ^
                               |
                               v
 -----------------------------------------------------------
[ Variable power usage hardware e.g. Variable CPU Frequency ]
 -----------------------------------------------------------
[edit] Hardware

The most power hungry components are the CPU, HDD & the LCD. Additional components such as the 3D Graphics accelerator, DVDRW & Wireless card can consume large amounts of power, but the biggest savings are made on the first three.

CPU

The Pentium 4 found in the Inspiron has 8 CPU states ranging from maximum power consumption at 3GHz to minimum at 375MHz.

HDD

The kernel contains 'laptop-mode' HDD (actually memory flushing) functionality. Check out usr/src/linux/Documents/laptop-mode.txt. I've heavily butchered the scripts provided, but have more or less used the default management settings suggested. Also a good idea to 'reduce' logger access to disk and to switch swap usage off

LCD

Two aspects to this one. It has been reported that lighter colours consume less power, likewise lower resolutions & colour depths. Suppose a strategy could be to use light coloured backgrounds, lower resolutions & less colour depth when running on battery. The second aspect is that the backlight can be switched off when 'suspend' or leaving the machine idle for a while. There is a radeon utility that can do this.

DVDRW

Use a large pre-fetch buffer to reduce spintime on drive?

Wireless

The power management feature appears a little flakey. Plan on only 'loading' wireless card/modules when needed, i.e. have it completely off most of the time? (Not sure if it needs to be switched to 'low-power' mode before hand?

3D graphics rendering

Not sure, don't use when in battery mode?

[edit] BIOS - ACPI

Advanced Configuration and Power Interface is already included in the kernel and a userspace daemon (using shell scripts) can be used to react to ACPI events. Read the /usr/src/linux/Documentation/acpid/* files for accurate details.

You can check which version of ACPI your BIOS supports by

Code: Check ACPI version
dmesg | grep -i acpi
should return a version, but most likely a Subsystem revision date
is the best indication of how recent your ACPI system is.

Suspend mode

I've ended up using software suspend 2 (aka swsusp2 and suspend2), but this tool is 'flakey', especially when X is involved at 'suspend' time. It requires more configuration than I've done at this stage, but everything works 'perfectly' when running in console (runlevel 3) mode. Anyone trying to figure out what is happen with 'suspend' is in for a surprise.

This area is even more confusing that normal for Linux. The version you'll find in the 'default/non-patched' kernel is the official version and although labled software suspend in the make menuconfig menu is a very different animal to swsusp2. Reading the kernel archives is interesting as the developer of swsusp2 is working (if that is the right term) with the kernel maintainer of software suspend to include it in the mainstream Linux kernel, but it doesn't look like it will happen soon.

I suggest trying the 'official' version first as it is definately the easier option to activate. Portage contains hibernation-script, that contains a hibernate script you can use to suspend to disk (in all it's various flavours), it didn't work for me.

See Software Suspend 2 for details about how to go about installing software suspend 2. You can also check out this very detailed Gentoo-Wiki article on the topic.

Getting software suspend to work with gentoo-dev-sources-2.6.9-r6 requires a portage overlaid gentoo-dev-sources ebuild. Doing so also seems to break the ndiswrapper-0.11.ebuild. ndiswrapper-0.10 works very well though.

[edit] Kernel space software

ACPI

Configuration is included in the kernel. Does need to be 'activated' by selecting (and compiling) the required components into the active kernel. Software suspend 2 contains kernel side configurations as well, so remember to inlude those if you are going to use it.

CPU Frequency scaling

Algorithms are complex, especially for SMP processors such as Pentium 4, but the options are available by default in the 2.6.9 kernel.

HDD (laptop-mode)

Managing the HHD depends on some disk writting (when to flush memory) routines that are included in the kernel by default.

All other hardware mentioned

No kernel side modules or configuration

[edit] User space software

ACPI

acpid captures & responds to ACPI events via scripts. Read /usr/src/linux/Documentation/acpid/* for details, but general process involves capturing and responding to ACPI events. This 'process' manages all the power management components apart from CPU frequency scalling.

CPU Frequency scaling

cpufreqd manages CPU freq using profiles, governors & frequency ranges via scripts runs without any triggering/interaction with acpid. It runs completely independently from the other tools it's management algorithms are a little more complex than what we program using scripts, especially when multiple CPUs are involved.

This daemon automatically adjusts the CPU frequency to optimise power management.

  • Once compiled into kernel (Can use modules?), the cpufreqd (Userspace) daemon is used to manage the CPU Frequencies and happens via to a configuration file based on policies.
  • There is a 3 layer model.
    • The CPU frequencies are adjusted by kernel core code,
    • depending on the governor implemented to
    • interpert the userspace requests (usually via policies).

There are 3 governors available in the 2.6.9 kernel; performance, powersave and userspace. The performance governor tries maximises the CPU frequency within the limits specified, the powersave minimises the CPU freq within the limites specified and the userspace one sets it to a defined number. Read the /usr/src/linux/Documentation/cpu-freq/* files for accurate details I've read reports about an on-demand governor that will set the CPU frequencies according to the load placed on the CPU rather than all the setting of profiles etc, but have no idea how near to inclusion in kernel it is.

HDD power management - Laptop mode

Laptop mode is used to minimize the time that the hard disk needs to be spun up, hence conserve battery power on laptops. Included by default in >= 2.6.6 kernels and make sure to read /usr/src/linux/Documentation/laptop-mode.txt for more details. I've used this document to create my base hdd 'management' scripts.

[edit] Portage packages used

  • hibernation-script - needed to 'activate' swsusp2
  • acpid - manage the responses to ACPI events
  • cpufreqd - manages the CPU frequency scaling
  • radeon-tool - switches the radeon backlight on/off
  • gentoo-dev-sources - 'overlaid' portage build

[edit] Installation/Configuration overview

  • Install swsusp2 to enable suspend-to-disk functionality
  • Configure & compile kernel to incorporate swsusp2, cpu freq & acpi components
  • Install and test hibernate scripts (Use swsusp2)
Files used:
/etc/hibernate/hibernate.conf - config file
/usr/sbin/hibernate - activation script
  • Install cpufreqd & implement configuration to minimise CPU frequencies when using battery
Files used:
/etc/cpufreqd - config file
/usr/sbin/cpufreqd - activation script
  • Generate laptop-mode scripts to manage HDD when using battery
Files used:
/usr/sbin/laptop-mode - activation script
  • Install acpid & write event handling script to manage battery usage. Including the usage of the radeon light switch and calling laptop-mode when required.
Files used:
/etc/acpi/events/all_events - capture all acpi events
/etc/acpi/action-all-events.sh - action all acpi events

[edit] software suspend 2

Need to create a custom gentoo-dev-sources-2.6.9-r9.ebuild. This is based on the great advice from Earthwinds in this thread. Use HOWTO Software Suspend v2 for a much more detailed account of how to go about installing and configuring Software Suspend 2

Code: Activate Portage Overlay
nano -w /etc/make.conf set PORTDIR_OVERLAY="/usr/local/portage"
Code: Create custom folder and get .ebuild
mkdir -p /usr/local/portage/sys-kernel/gentoo-dev-sources/files
cd /usr/local/portage/sys-kernel/gentoo-dev-sources
cp /usr/portage/sys-kernel/gentoo-dev-sources/gentoo-dev-sources-2.6.9-r9.ebuild .
Code: Modify the ebuild
${EDITOR} gentoo-dev-sources-2.6.9-r6.ebuild
Make the following changes:
  Add a line:
    SWSUSP="software-suspend-2.1.5-for-2.6.9"
      after the KEYWORDS... line
  Change the SRC_URI line to:
    SRC_URI="${KERNEL_URI} ${GPV_SRC} ${ARCH_URI}
    http://download.berlios.de/softwaresuspend/${SWSUSP}.tar.bz2"
  Add the function
    src_unpack() {
         kernel-2_src_unpack

         einfo "Applying ${SWSUSP} patch"
         cd ${WORKDIR}
         unpack ${SWSUSP}.tar.bz2
         cd ${WORKDIR}/linux-2.6.9-gentoo-r6
         ${WORKDIR}/${SWSUSP}/apply || die "${SWSUSP} patch failed"
    }
      before the pkg_postinst()... line 

Save the file

Code: Build digest and emerge
ebuild gentoo-dev-sources-2.6.9-r9 digest
emerge gentoo-dev-sources

ndiswrapper wouldn't compile against the kernel sources as patched here and this is how I overcame the "problem". You can find more information about wireless setup at Wireless - Installing the Broadcom BCM4306

Code: ndiswrapper v0.10
emerge =ndiswrapper-0.10

I believe it isn't the best practice so emerge specific versions of packages. The following code should mask ndiswrapper versions newer than 0.10. You can use the normal emerge ndiswrapper once this has been done

Code: Block ndiswrapper-0.11
nano /etc/portage/package.mask
add line: >=net-wireless/ndiswrapper-0.11

We can now proceed to configure the kernel!

[edit] kernel space configuration

Please see Kernel - 2.6.9 configuration for more information about kernel compilation.

ACPI specific

Linux Kernel Configuration: ACPI in Kernel
Power Management options  (ACPI, APM) --->
  ACPI (Advanced Configuration and Power Interface) support  --->
    [*] ACPI Support
    [*]   Sleep States (Experimental)
    <*>   AC Adapter
    <*>   Battery
    <*>   Button
    <*>   Fan
    <*>   Processor
    <*>     Thermal Zone
Need to evaluate if these should be loaded as modules or not. Currently
believe that they need to be in kernel to work effectively, but the modules
can be loaded when 'running off battery' detected

CPU Frequency scaling specific

Linux Kernel Configuration: CPU Freq Scaling
Power Management options  (ACPI, APM) --->
  ACPI (Advanced Configuration and Power Interface) support  --->
    CPU Frequency scaling  --->
        [*] CPU Frequency scaling
            Default CPUFreq govenor (performance)  ---> chg to userspace
              Control from userspace
        <*> 'performance' governor
        <*> 'powersave' govenor
        <*> CPU frequency table helpers (new)
        <*> Intel Pentium 4 clock modulation (new)
Need to evaluate if these should be loaded as modules or not. Currently
believe that they need to be in kernel to work effectively, but the modules
can be loaded when 'running off battery' detected

Software Suspend 2

Please see previous section about how to create the new ebuild to activate these kernel configuration options.

Linux Kernel Configuration: Software Suspend 2
Power management options (ACPI, APM)  --->
  [ ] Software Suspend (EXPERIMENTAL)
  ()  default resume device name
      Software Suspend 2  --->
        <*> Software Suspend 2
        <*> Swap writer
        <*> LFZ image compression
        <*> Text mode console support
        (/dev/hda2)   Default resume device name
        [*] Compile in debugging output
        <*> Compile checksum support
Need to evaluate if these should be loaded as modules or not. Currently
believe that they need to be in kernel to work effectively.

It saves some time to implement the hibernate-script before activating this kernel, i.e. rebooting, so proceed to that section before you reboot.

[edit] user space configuration

[edit] hibernate script

Code: Install hibernate-script
emerge hibernate-script
Code: Configure script to use swsusp2
nano /etc/hibernate/hibernate.conf
... defaults appear to work fine, need to finetune this later

The following code is optional, but I've included it for completeness.

Code: Configure grub
nano -w /boot/grub/menu.lst
  add menu entry with kernel option resume2=swap:/dev/hda2
    make the the default option
also create option with noresume2 (just in case)

Reboot to activate new kernel (Don't forget to choose it in grub!)

Code: Test if hibernate works
/usr/sbin/hibernate
This seemed to work ... shutdown & then fired-up again.
Read this to confirm
  http://softwaresuspend.berlios.de/Software-suspend-4.html

[edit] cpu frequency script

Code: Install cpufreqd
emerge cpufreqd
rc-update add cpufreqd default
read /usr/src/linux/Documentation/cpu-freq/*

There is a problem with %'s in /etc/cpufreqd.conf, must use absolute values

cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
  375000 750000 1125000 1875000 2250000 2625000 3000000
cat /sys/devices/system/cpu/cpu1/cpufreq/scaling_available_frequencies
  375000 750000 1125000 1875000 2250000 2625000 3000000
  <--------low-------->
                <----------med-------->
                                <---------high-------->
so set three profile according to these ranges

Code: Make backup of config file
cp /etc/cpufreqd.conf /etc/cpufreqd.conf.default
Code: Modify configuration
nano -w /etc/cpufreqd.conf
change minfreq=0%   to minfreq=375000
change maxfreq=33%  to maxfreq=1125000

change minfreq=33%  to minfreq=1125000
change maxfreq=66%  to maxfreq=2250000

change minfreq=66%  to minfreq=2250000
change maxfreq=100% to maxfreq=3000000
Code: Check if working
watch -n 1 'cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq'
unplug/plug in power & see it drop from 3000000 to 1125000 &
back up. This works wonderfully

[edit] laptop-mode script

Laptop mode info (found at /usr/src/linux/Documentation/laptop-mode.txt) It deals predominantly with HDD power consumption, but can be used for CDROM tuning.

The steps taken are

  • create /etc/laptop-mode/laptop-mode.conf from laptop-mode.txt
  • create /usr/sbin/laptop-mode from laptop-mode.txt
  • change provided laptop-mode.conf
    • many changes, but in general made specific to my laptop (/dev/hda)
    • changed DO_HD to DO_HD_IDLE
    • added DO_HD_APM
    • removed all linux 2.4 stuff
    • removed all xfs stuff
  • change provided laptop-mode
    • removed all linux 2.4 stuff
    • removed all xfs stuff
    • seperated DO_HD into DO_HD_IDLE & DO_HD_APM

net effect is

running /dev/hda with -S 4 in low power and -S 244 in normal mode
running /dev/hda with -B 1 in low power and -B 128 in normal mode
-S 4 = 20 secs before spin down & -S 244 = 2 hours
-B 1 = very aggressive APM, i.e. The deepest Power Saving Mode is Standby
-B 128 = medium APM, i.e. The deepest Power Saving Mode is Low Power Idle

The HDD is a Hitachi Travelstar 7K60 & runs using only 0.1 watt when sleeping, 0.25 watt when in standby, about 1.3 watt when idle & 2.5 watt when active.

ToDo: insert scripts here...

[edit] acpid script

Code: Install remainder of tools
emerge acpid
rc-update add acpid default
emerge radeontool
read Documentation/acpid/*

Configure acpid scripts to capture & deal with all events, i.e. 'control' everything except CPU, that is managed via cpufreqd

Code: Use the default events (everything)
mv /etc/acpi/events/default to /etc/acpi/events/all-events
Code: Set the event management script
nano -w /etc/acpi/events/all-events
set action to /etc/acpi/action-all-events.sh %e

The general 'strategy' used is as follows

  • Create power management & control stuff in /etc/acpi/action-all-events.sh
  • per device strategy
    • CPU dealt with by cpufreqd
    • HDD see the laptop-mode section
    • LCD not really sure, but try to limit number of colours & use white
    • LCD backlight - switch off if going to sleep also have the BIOS settings to trigger it
    • Wireless always in powersave mode
      • nano -w /etc/conf.d/wireless
      • add iwconfig_wlan0="power on"
      • I've found that unless actively using the wireless lan that this effectively switches the card off, not what is needed. See the ToDo list for id
Personal tools