Friday, December 11, 2009

Firewall made easy on Ubuntu

https://help.ubuntu.com/community/IptablesHowTo



Basic iptables howto

Iptables is a firewall, installed by default on all official Ubuntu distributions (Ubuntu, Kubuntu, Xubuntu). When you install Ubuntu, iptables is there, but it allows all traffic by default. Ubuntu 8.04 Comes with ufw - a program for managing the iptables firewall easily.
There is a wealth of information available about iptables, but much of it is fairly complex, and if you want to do a few basic things, this How To is for you.

Basic Commands

Typing
# iptables -L
lists your current rules in iptables. If you have just set up your server, you will have no rules, and you should see
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Basic Iptables Options

Here are explanations for some of the iptables options you will see in this tutorial. Don't worry about understanding everything here now, but remember to come back and look at this list as you encounter new options later on.
  • -A - Append this rule to a rule chain. Valid chains for what we're doing are INPUT, FORWARD and OUTPUT, but we mostly deal with INPUT in this tutorial, which affects only incoming traffic.
  • -L - List the current filter rules.
  • -m conntrack - Allow filter rules to match based on connection state. Permits the use of the --ctstate option.
  • --ctstate - Define the list of states for the rule to match on. Valid states are:
    • NEW - The connection has not yet been seen.
    • RELATED - The connection is new, but is related to another connection already permitted.
    • ESTABLISHED - The connection is already established.
    • INVALID - The traffic couldn't be identified for some reason.
  • -m limit - Require the rule to match only a limited number of times. Allows the use of the --limit option. Useful for limiting logging rules.
    • --limit - The maximum matching rate, given as a number followed by "/second", "/minute", "/hour", or "/day" depending on how often you want the rule to match. If this option is not used and -m limit is used, the default is "3/hour".
  • -p - The connection protocol used.
  • --dport - The destination port(s) required for this rule. A single port may be given, or a range may be given as start:end, which will match all ports from start to end, inclusive.
  • -j - Jump to the specified target. By default, iptables allows four targets:
    • ACCEPT - Accept the packet and stop processing rules in this chain.
    • REJECT - Reject the packet and notify the sender that we did so, and stop processing rules in this chain.
    • DROP - Silently ignore the packet, and stop processing rules in this chain.
    • LOG - Log the packet, and continue processing more rules in this chain. Allows the use of the --log-prefix and --log-level options.
  • --log-prefix - When logging, put this text before the log message. Use double quotes around the text to use.
  • --log-level - Log using the specified syslog level. 7 is a good choice unless you specifically need something else.
  • -i - Only match if the packet is coming in on the specified interface.
  • -I - Inserts a rule. Takes two options, the chain to insert the rule into, and the rule number it should be.
    • -I INPUT 5 would insert the rule into the INPUT chain and make it the 5th rule in the list.
  • -v - Display more information in the output. Useful for if you have rules that look similar without using -v.
  • -s --source - address[/mask] source specification
  • -d --destination - address[/mask] destination specification
  • -o --out-interface - output name[+] network interface name ([+] for wildcard)

Allowing Established Sessions

We can allow established sessions to receive traffic:
# iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  • The above rule has no spaces either side of the comma in ESTABLISHED,RELATED
If the line above doesn't work, you may be on a VPS that uses OpenVZ or doesn't have some kernel extensions installed. In that case, try this line instead:
# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Allowing Incoming Traffic on Specific Ports

You could start by blocking traffic, but you might be working over SSH, where you would need to allow SSH before blocking everything else.
To allow incoming traffic on the default SSH port (22), you could tell iptables to allow all TCP traffic on that port to come in.
# iptables -A INPUT -p tcp --dport ssh -j ACCEPT
Referring back to the list above, you can see that this tells iptables:
  • append this rule to the input chain (-A INPUT) so we look at incoming traffic
  • check to see if it is TCP (-p tcp).
  • if so, check to see if the input goes to the SSH port (--dport ssh).
  • if so, accept the input (-j ACCEPT).
Lets check the rules: (only the first few lines shown, you will see more)
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
Now, let's allow all incoming web traffic
# iptables -A INPUT -p tcp --dport 80 -j ACCEPT
Checking our rules, we have
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
We have specifically allowed tcp traffic to the ssh and web ports, but as we have not blocked anything, all traffic can still come in.

Blocking Traffic

Once a decision is made to accept a packet, no more rules affect it. As our rules allowing ssh and web traffic come first, as long as our rule to block all traffic comes after them, we can still accept the traffic we want. All we need to do is put the rule to block all traffic at the end.

# iptables -A INPUT -j DROP
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
DROP       all  --  anywhere             anywhere
Because we didn't specify an interface or a protocol, any traffic for any port on any interface is blocked, except for web and ssh.

Editing iptables

The only problem with our setup so far is that even the loopback port is blocked. We could have written the drop rule for just eth0 by specifying -i eth0, but we could also add a rule for the loopback. If we append this rule, it will come too late - after all the traffic has been dropped. We need to insert this rule before that. Since this is a lot of traffic, we'll insert it as the first rule so it's processed first.

# iptables -I INPUT 1 -i lo -j ACCEPT
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
DROP       all  --  anywhere             anywhere
The first and last lines look nearly the same, so we will list iptables in greater detail.
# iptables -L -v

Chain INPUT (policy ALLOW 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  lo     any     anywhere             anywhere
    0     0 ACCEPT     all  --  any    any     anywhere             anywhere            state RELATED,ESTABLISHED
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere            tcp dpt:ssh
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere            tcp dpt:www
    0     0 DROP       all  --  any    any     anywhere             anywhere
You can now see a lot more information. This rule is actually very important, since many programs use the loopback interface to communicate with each other. If you don't allow them to talk, you could break those programs!

Logging

In the above examples none of the traffic will be logged. If you would like to log dropped packets to syslog, this would be the quickest way:
# iptables -I INPUT 5 -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
See Tips section for more ideas on logging.

Saving iptables

If you were to reboot your machine right now, your iptables configuration would disappear. Rather than type this each time you reboot, however, you can save the configuration, and have it start up automatically. To save the configuration, you can useiptables-save and iptables-restore.

Configuration on startup

WARNING: Iptables and NetworkManager seem to have a conflict. However NetworkManager is still in Beta. If you are concerned enough about security to install a firewall you might not want to trust NetworkManager to manage it yet. Also noteNetworkManager and iptables have opposite aims. Iptables aims to keep any questionable network traffice out.NetworkManager aims to keep you connected at all times. Therefore if you want security all the time, run iptables at boot time. If you want security some of the time then NetworkManager might be the right choice.
WARNING: If you use NetworkManager (installed by default on Feisty and later) these steps will leave you unable to useNetworkManager for the interfaces you modify. Please follow the steps in the next section instead.
NOTE: It appears on Hardy, NetworkManager has an issue with properly on saving and restoring the iptable rules when using the method in the next section. Using this first method appears to work. If you find otherwise, please update this note.
Save your firewall rules to a file
# iptables-save >/etc/iptables.rules
Then modify the /etc/network/interfaces configuration file to apply the rules automatically. You will need to know the interface that you are using in order to apply the rules - if you do not know, you are probably using the interface eth0, although you should check with the following command first to see if there are any wireless cards:
$ iwconfig
If you get output similiar to the following, then you do not have any wireless cards at all and your best bet is probably eth0.

$ iwconfig

lo        no wireless extensions.

eth0      no wireless extensions.

$
When you have found out the interface you are using, please open your /etc/network/interfaces file depending on what editor you want and/or what distribution you have:
Command line:
# nano /etc/network/interfaces
For Ubuntu and Xubuntu: type ALT+F2, then in the window that pops up, type:
gksudo gedit /etc/network/interfaces
and press Enter.
For Kubuntu: type ALT+F2, then in the window that pops up, type:
kdesu kate /etc/network/interfaces
and press enter.
When in the file, search for the interface you found, and at the end of the network related lines for that interface, add the line:
pre-up iptables-restore < /etc/iptables.rules
You can also prepare a set of down rules, save them into second file /etc/iptables.downrules and apply it automatically using the above steps:
post-down iptables-restore < /etc/iptables.downrules
A fully working example using both from above:

auto eth0
iface eth0 inet dhcp
  pre-up iptables-restore < /etc/iptables.rules
  post-down iptables-restore < /etc/iptables.downrules
You may also want to keep information from byte and packet counters.

iptables-save -c > /etc/iptables.save 
The above command will in other words save the whole rule-set to a file called /etc/iptables.save with byte and packet counters still intact.
Alternatively you could add the iptables-restore and iptables-save to the if-pre-up.d and if-post-down.d directories in the /etc/network directory instead of modifying /etc/network/interface directly.
The script /etc/network/if-pre-up.d/iptaload will contain:

#!/bin/sh
iptables-restore < /etc/iptables.rules
exit 0
and/etc/network/if-post-down.d/iptasave will contain:

#!/bin/sh
if [ -f /etc/iptables.downrules ]; then
   iptables-restore < /etc/iptables.downrules
fi
iptables-save -c > /etc/iptables.save
exit 0
Then be sure to give both scripts execute permissions:
# chmod +x /etc/network/if-post-down.d/iptasave
# chmod +x /etc/network/if-pre-up.d/iptaload

Configuration on Startup for NetworkManager

NetworkManager includes the ability to run scripts when it activates or deactivates an interface. To save iptables rules on shutdown, and to restore them on startup, we are going to create such a script. To begin, press Alt+F2 and enter this command:
For Ubuntu:
$ gksudo gedit /etc/NetworkManager/dispatcher.d/01firewall
For Kubuntu:
kdesu kate /etc/NetworkManager/dispatcher.d/01firewall
Then, paste this script into your editor, save, and exit the editor.
if [ -x /usr/bin/logger ]; then
        LOGGER="/usr/bin/logger -s -p daemon.info -t FirewallHandler"
else
        LOGGER=echo
fi

case "$2" in
        pre-up)
                if [ ! -r /etc/iptables.rules ]; then
                        ${LOGGER} "No iptables rules exist to restore."
                        return
                fi
                if [ ! -x /sbin/iptables-restore ]; then
                        ${LOGGER} "No program exists to restore iptables rules."
                        return
                fi
                ${LOGGER} "Restoring iptables rules"
                /sbin/iptables-restore -c < /etc/iptables.rules
                ;;
        post-down)
                if [ ! -x /sbin/iptables-save ]; then
                        ${LOGGER} "No program exists to save iptables rules."
                        return
                fi
                ${LOGGER} "Saving iptables rules."
                /sbin/iptables-save -c > /etc/iptables.rules
                ;;
        *)
                ;;
esac
Finally, we need to make sure NetworkManager can execute this script. In a terminal window, enter this command:
# chmod +x /etc/NetworkManager/dispatcher.d/01firewall

Tips


If you manually edit iptables on a regular basis

The above steps go over how to setup your firewall rules and presume they will be relatively static (and for most people they should be). But if you do a lot of development work, you may want to have your iptables saved everytime you reboot. You could add a line like this one in /etc/network/interfaces:
pre-up iptables-restore < /etc/iptables.rules
  post-down iptables-save > /etc/iptables.rules
The line "post-down iptables-save > /etc/iptables.rules" will save the rules to be used on the next boot.

Using iptables-save/restore to test rules

If you edit your iptables beyond this tutorial, you may want to use the iptables-save and iptables-restore feature to edit and test your rules. To do this open the rules file in your favorite text editor (in this example gedit).
$ sudo iptables-save > /etc/iptables.rules
$ gksudo gedit /etc/iptables.rules
You will have a file that appears similiar to (following the example above):
# Generated by iptables-save v1.3.1 on Sun Apr 23 06:19:53 2006
*filter
:INPUT ACCEPT [368:102354]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [92952:20764374]
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
-A INPUT -j DROP
COMMIT
# Completed on Sun Apr 23 06:19:53 2006
Notice that these are iptables commands minus the iptable command. Feel free to edit this to file and save when complete. Then to test simply:
# iptables-restore < /etc/iptables.rules
After testing, if you have not added the iptables-save command above to your /etc/network/interfaces remember not to lose your changes:
# iptables-save > /etc/iptables.rules

More detailed Logging

For further detail in your syslog you may want create an additional Chain. This will be a very brief example of my /etc/iptables.rules showing how I setup my iptables to log to syslog:
# Generated by iptables-save v1.3.1 on Sun Apr 23 05:32:09 2006
*filter
:INPUT ACCEPT [273:55355]
:FORWARD ACCEPT [0:0]
:LOGNDROP - [0:0]
:OUTPUT ACCEPT [92376:20668252]
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -j LOGNDROP
-A LOGNDROP -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied TCP: " --log-level 7
-A LOGNDROP -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied UDP: " --log-level 7
-A LOGNDROP -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ICMP: " --log-level 7
-A LOGNDROP -j DROP
COMMIT
# Completed on Sun Apr 23 05:32:09 2006
Note a new CHAIN called LOGNDROP at the top of the file. Also, the standard DROP at the bottom of the INPUT chain is replaceed with LOGNDROP and add protocol descriptions so it makes sense looking at the log. Lastly we drop the traffic at the end of theLOGNDROP chain. The following gives some idea of what is happening:
  • --limit sets the number of times to log the same rule to syslog
  • --log-prefix "Denied..." adds a prefix to make finding in the syslog easier
  • --log-level 7 sets the syslog level to informational (see man syslog for more detail, but you can probably leave this)

Disabling the firewall

If you need to disable the firewall temporarily, you can flush all the rules using
# iptables -F
or create a script using text editor such as nano
# nano -w /root/fw.stop

echo "Stopping firewall and allowing everyone..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
Make sure you can execute the script
$ chmod +x /root/fw.stop
You can run the script
$ /root/fw.stop

Easy configuration via GUI

GUFW - Gufw is a graphical frontend to UFW (Uncomplicated Firewall).
A new user can use Firestarter (a gui), available in repositories (Synaptic or apt-get) to configure her/his iptable rules, without needing the command line knowledge. Please see the tutorial though... Configuration is easy, but may not be enough for the advanced user. However, it should be enough for the most home users... The (read:my) suggested outbound configuration is "restrictive", with whitelisting each connection type whenever you need it (port 80 for http, 443 for secure http -https-, 1863 for msn chat etc) from the "policy" tab within firestarter. You can also use it to see active connections from and to your computer... The firewall stays up once it is configured using the wizard. Dial-up users will have to specify it to start automatically on dial up in the wizard.
Homepage for firestarter: http://www.fs-security.com/ (again, available in repositories, no compiling required) Tutorial:http://www.fs-security.com/docs/tutorial.php

Tuesday, November 24, 2009

LJ1020 on UBuntu Karmic 9.10

HP LJ1020 driver for UBuntu Karmic (9.10):

http://hplipopensource.com/hplip-web/install_wizard/index.html

Friday, November 6, 2009

Netflix on PS3

The Netflix PS3 blue-ray CD arrived today.  The first time it ran on PS3, it gave authentication code to be put on my Netflix account from PC.  After the authentication was done, it came up with nice menu to navigate online videos available from my account's queue.  When I played some of the movies, the quality of the pictures were really beyond my expectation.  I was expecting the quality was about the same as standard TV, but what I got was almost-bluray/HDTV quality!

Bravo to both Sony & Netflix to provide with this excellent access. Now we can watch hundreds, or even thousands of movies available at Netflix on our LCD TV.

Sunday, November 1, 2009

Battery for Toyota Sienna XLE 2005

I was looking for an auto-battery replacement of my Sienna XLE 2005  at Costco.  When I asked the salesperson, he pointed me to a Costco battery for about $70 + tax (and there is no charge for returning the old one to them).  It's number 3 and the group size is 35, but when I tried to install it, it wouldn't fit as the size was smaller and the anode (positive terminal) and the cathode (negative terminal) were at the opposite side, unlike the original one,.  I went back to Costco to exchange, but unfortunately they didn' carry the one I wanted (interestingly, the reference book they had really showed  group size 35 was indeed the only group size for my car, not group size 24 as written on the original battery).

I ended up returning the battery and went to Kragen.  Luckily, they have this type, as well as the 35 (strangely, their computer initially showed group size 35 as well, but the salesperson said they carried also the group size 24).  It costed me about $80 with 84 months limited warranty (but 36 months full warranty).

Went back home in rush to install the battery, and now it works flawlessly, at least for now.

U-Verse Speed

U-Verse 6 Mbps:

http://www.speedtest.net][IMG]http://www.speedtest.net/result/609346355.png

Wednesday, October 28, 2009

PS3 is gaining market!

A few days ago there was a news telling Netflix will be available on Sony PS3.  This a good news for PS3 folks who have been inquiring Netflix when they are going to support PS3, besides XBox 360 which has been available for quite some time.

With more and more features added into PS3, not to count the price has also come down, it is now a good time to have a PS3 console as your center of home entertainment.  For a cost of $299+tax, we can get a powerful station capable of playing Bluray discs, playing games (in hi quality plus in 1080p), playing music CDs or MP3, it can also become a multimedia center to access the internet (browsing, emailing) and now to watch video streaming online.  That's all will cost us $$ more if we buy individual units.

Oh, don't forget to get that Sony Bluetooh remote control.  Nothing can be easier now!

Monday, October 12, 2009

Bresenham Algorithm

#include <stdlib.h>
#include <stdio.h>

//extern int plot(int x, int y);

int plot(int x, int y, int color)
{
    printf("plot(%d, %d, %d)\n", x, y, color);

}


void swap(int *a, int *b)
{
    int tmp;

    tmp = *a;
    *a = *b;
    *b = tmp;
    printf("swap %d with %d\n", a, b);

}



int line(int x1, int y1, int x2, int y2, int color)
{
    int steep;
    int deltax, deltay;
    int e, x, y, y_step;

    steep = (abs(y2 - y1) > (x2 - x1));

    if (steep) {
        swap(&x1, &y1);
        swap(&x2, &y2);
    }
    if (x1 > x2) {
        swap(&x1, &x2);
        swap(&y1, &y2);
    }
    deltax = x2 - x1;
    deltay = abs(y2 - y1);
    e = x1;
    y = y1;
    if (y1 < y2) {
        y_step = 1;
    } else
        y_step = -1;
    for (x = x1; x <= x2; x++) {
        if (steep)
            plot(y, x, color);
        else
            plot(x, y, color);
        e += deltay;
        if (2 * e >= deltax) {
            y += y_step;
            e -= deltax;
        }
    }
    return 0;
}


int main()
{
    int x1, x2, y1, y2, color;

    x1 = 0;
    y1 = 0;
    x2 = 50;
    y2 = 65;
    color = 1;

    line(x1, y1, x2, y2, color);
}
~
~

Sunday, September 27, 2009

Fixing choppy screen on Ubuntu Jaunty

According to a site I googled, XWindow in Ubuntu Jaunty 9.04 has some issue in accessing videocard's memory region.  My video card is NVidia GeForce 8500  GT with native driver from Nvidia.  Kernel is 2.6.30.5 (compiled from source).

I fix this by doing the following:

1) do lspci -v, find "VGA compatible controller" section.

Mine shows as:

04:00.0 VGA compatible controller: nVidia Corporation GeForce 8500 GT (rev a1) (prog-if 00 [VGA controller])
        Subsystem: ASUSTeK Computer Inc. Device 034f
        Flags: bus master, fast devsel, latency 0, IRQ 16
        Memory at fd000000 (32-bit, non-prefetchable) [size=16M]
        Memory at d0000000 (64-bit, prefetchable) [size=256M]
        Memory at fa000000 (64-bit, non-prefetchable) [size=32M]
        I/O ports at ec00 [size=128]
        [virtual] Expansion ROM at febe0000 [disabled] [size=128K]
        Capabilities: <access denied>
        Kernel driver in use: nvidia
        Kernel modules: nvidia, nvidiafb

2) Calculate the accessable memory region (in KB, not MB) by substracting non-prefetchable part  from prefetchable (pick the lower region one).  For example, as above we should compute 256M - 16M, or use Google.  For example, 256 MB = 2^18 KB and 16 MB = 2^14 KB, so (2^18) - (2^14) = 245760 KB

2) as root, edit /etc/X11/xorg.conf.  Find `Section "Device"`
3) Add `VideoRam #`, where # = the result from point 2
For example, mine should now show like below:

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    VideoRam       245760
EndSection


4) Restart XWindow
5) Test with mplayer.  Now the screen changes smoothly with no flicks.

According to some sources, this issue will be fixed in next Ubuntu Jaunty updates.

Tuesday, September 22, 2009

Unfolding a code with Full optimized flags turned on with GCC

Original code:

#include <stdio.h>
#include <math.h>


double a, b;

#define SQR(a)  ((a)*(a))

int main()
{
    double sum;

    a = 0.5;
    b = 0.5;
    sum = sqrt(SQR(sin(a)) + SQR(cos(b)));

    printf("sum = %f\n", sum);
    return 0;
}

CFLAGS is set to "-mtune=nocona -mfpmath=sse -msse3 -O3 -ffast-math"

The source code above, after compiled with GCC (e.g: gcc -S $CFLAGS test.c), gives:

    .file   "ssetest.c"
    .def    ___main;    .scl    2;  .type   32; .endef
    .section .rdata,"dr"
LC1:
    .ascii "sum = %f\12\0"
    .align 8
LC2:
    .long   0
    .long   1071644672
    .text
.globl _main
    .def    _main;  .scl    2;  .type   32; .endef
_main:
    pushl   %ebp
    movl    $16, %eax
    movl    %esp, %ebp
    subl    $24, %esp
    andl    $-16, %esp
    call    __alloca
    call    ___main
    fldl    LC2
    movl    $LC1, (%esp)
    fld     %st(0)
    fstl    _a
    fstl    _b
    fxch    %st(1)
    fsin
    fxch    %st(1)
    fcos
    fxch    %st(1)
    fstpl   -8(%ebp)
    movsd   -8(%ebp), %xmm2
    fstpl   -8(%ebp)
    movsd   -8(%ebp), %xmm0
    mulsd   %xmm2, %xmm2
    mulsd   %xmm0, %xmm0
    addsd   %xmm0, %xmm2
    sqrtsd  %xmm2, %xmm1
    movsd   %xmm1, 4(%esp)
    call    _printf
    xorl    %eax, %eax
    leave
    ret
    .comm   _a, 16   # 8
    .comm   _b, 16   # 8
    .def    _printf;    .scl    3;  .type   32; .endef

The code is so efficient.  fsin/fcos does the sine computation in CPU hardware (no emulation).  It also utilize MMX registers (xmm0, xmm1, xmm2) so memory movement is minimum.

Tuesday, September 15, 2009

Reasons Why Android Phones will win the war

Apple's iPhone is definitely now the winner in the criteria of slickness or coolness.  But one of its biggest downsides is it is tied to single provider (AT&T  in US) which charges too much ($30 for its data plan in addition to existing voice plan).

From developer's perspective (at least me), developing an application on iPhone is not that fun.  First, it uses a proprietary O/S which does much control on the device.  Secondly, Objective C used in the SDK is kind of weird to absorb from a person who's used to C/C++ or Java for beginning.  Also, the SDK only works on OS/X (sorry Linux/windows, you're forgotten!).  Another biggest downside: we cannot test our developed software on a real device, unless we pay $99 to Apple.

Meanwhile, Google Android is opensource and even based on Linux, the king of opensources.  Another thing is, it uses Java language for its application development.  The SDK supports all platforms (well, except OpenSolaris maybe?).  So far, I sense very similarities between both SDKs, though (I think because both of them follow Design Patterns paradigm?).  One biggest winning point: no fees required to test our software on a real device/handset.  This will drive a lot more programmers (especially from third word countries, where $99 is beyound their reach) to develop applications.

Why Apple should be very worried now? First, a bunch of chinese/taiwanese vendors (HTC, Huawei,etc.) are jumping into the bandwagon.  So far, HTC, Huawei, LG, Motorola, Samsung, Acer, Philips, Sony Ericsson, are in or planning to join in.  If Nokia joins the group, that'll be the scariest thing Apple will have its nightmare.

Thursday, September 10, 2009

Ooma slows down data traffic

It's been a month since I bought the Ooma VOIP system. It's been working fine, except with some issues, like the scout hang (need reset it). My configuration is to put Ooma hub right after DSL modem, so my wireless router is connected to Ooma hub. This is per suggestion in its manual.

I was curious to see how data traffic was affected. My nominal DSL speed is 6 Mbps, and when the router was connected directly to dsl modem, I could get more than 5 Mbps average. But when the router is connected behind Ooma, I could only get below 5 Mbps. It is not strange, as Ooma was acting as a NAT router too, hence added additional overhead.

The settings showed on setup.ooma.com (an alias to its internal IP address) look very similar to regular NAT router. The default internal IP address range it uses is in 172.27.35.*

Ports used:
Telephony: 50 - Running
DNS: 45 - Running
Web Server: 47 - Running
VPN: 356 - Running
Free: 37008

Next experiment I will do is to put packet sniffer on its "modem" port to figure out how it actually works.

Sunday, September 6, 2009

How much power does a Macbook draw?

To find out how much power an Apple's Macbook laptop withdraws power, I use EZ Kill-A-Watt power meter (got it from Costco for about $28). Select "Watt" mode and connect Macbook power cord to this device.

  • When the laptop is in standby mode (lid is closed) and battery is full (or at least 94% full), it withdraws 4 Watt
  • With power cord detached from laptop, the power supply withdraws 0 watt
  • During booting, the laptop withdraws max power, which is 45 watts
  • During normal mode (casual use), in average it withdraws 27-28 watts

Friday, September 4, 2009

Linux Visual Improvements

XFree86 Font Deuglification:
http://www.tutorialized.com/view/tutorial/XFree86-Font-Deuglification-Mini-HOWTO/4558

X Window System Application Performance Tuning:
http://www.rahul.net/kenton/perf.html

Saturday, August 29, 2009

It is time for Playstation 3 to prevail

Sony PS3 has been around for almost 3 years now. Recently Sony has lowered the list price by $100 and also discontinue the middle level version. With all capabilities it has, I suggest people who wants to buy either game station, multimedia center (BD player, Internet access box, etc.) pick up this box instead of Microsoft XBox360.

Some reasons I can think of:
- It has more powerful Cell processor than the old Intel Pentium used in XBox
- It comes with Blue-Ray drive
- It can run Linux
- The price is now more reasonable (recently Microsoft has also lowered XBox360)
- The now-still-beta Interactive (with 3D graphic) social networking software which can be downloaded for free. It is sooo cool! Think of a 3D Facebook :-)
- More game studios are producing games for PS3 more than ever.

Tuesday, August 18, 2009

To make USB devices work on VirtualBox on UBuntu

-Create a group called "usbfs" and add yourself to it.

-In terminal issue the following command:

sudo gedit /etc/fstab

-In this file paste the following lines, and change the group ID according to the group ID that is shown for the group "usbfs".


# 1001 is the USB group ID
none /proc/bus/usb usbfs devgid=1001,devmode=664 0 0


-Save and close file.


-In terminal, issue the following command:

VBoxManage list usbhost

-Use the output of this command to set up the filters for USB devices under VirtualBox.

Friday, June 19, 2009

The Saser is like a laser, but for sound

It was an idea born out of curiosity in the physics lab, but now a new type of ‘laser’ for generating ultra-high frequency sound waves instead of light has taken a major step towards becoming a unique and highly useful 21st century technology.

Scientists at The Univ. of Nottingham, in collaboration with colleagues in the Ukraine, have produced a new type of acoustic laser device called a Saser. It’s a sonic equivalent to the laser and produces an intense beam of uniform sound waves on a nano scale. The new device could have significant and useful applications in the worlds of computing, imaging, and even anti-terrorist security screening.

Where a “laser” (light amplification by the stimulated emission of radiation), uses packets of electromagnetic vibrations called “photons”, the “Saser” uses sound waves composed of sonic vibrations called “phonons”. In a laser, the photon beam is produced by stimulating electrons with an external power source so they release energy when they collide with other photons in a highly reflective optical cavity. This produces a coherent and controllable shining beam of laser light in which all the photons have the same frequency and rate of oscillation. From supermarket scanners to DVD players, surgery, manufacturing, and the defense industry, the application of laser technology is widespread.

The Saser mimics this technology but using sound, to produce a sonic beam of “phonons”’ which travels, not through an optical cavity like a laser, but through a tiny manmade structure called a “superlattice”. This is made out of around 50 super-thin sheets of two alternating semiconductor materials, gallium arsenide and aluminium arsenide, each layer just a few atoms thick. When stimulated by a power source (a light beam), the phonons multiply, bouncing back and forth between the layers of the lattice, until they escape out of the structure in the form of an ultra-high frequency phonon beam.

A key factor in this new science is that the Saser is the first device to emit sound waves in the terahertz frequency range…the beam of coherent acoustic waves it produces has nanometer wavelengths (billionths of a meter). Crucially the ‘superlattice’ device can be used to generate, manipulate and detect these soundwaves making the Saser capable of widespread scientific and technological applications. One example of its potential is as a sonogram, to look for defects in nanometer scale objects like micro-electric circuits. Another idea is to convert the Saser beam to THz electromagnetic waves, which may be used for medical imaging and security screening. High intensity sound waves can also change the electronic properties of nanostructures so a Saser could be used as a high-speed terahertz clock to make the computers of the future a thousand times faster.

Professor Anthony Kent from the University’s School of Physics and Astronomy, says “While our work on sasers is driven mostly by pure scientific curiosity, we feel that the technology has the potential to transform the area of acoustics, much as the laser has transformed optics in the 50 years since its invention.”

The research team at Nottingham, with help from Borys Glavin of the Lashkarev Institute of Semiconductor Physics in the Ukraine, has won the immediate accolade of the publication of their paper on the Saser experiments in this month’s Physical Review. The team has also won a grant of £636,000 from the Engineering and Physical Sciences Research Council to develop Saser technology over the next four years.

SOURCE: Univ. of Nottingham

Light sensor breakthrough could enhance digital cameras

New research by a team of Univ. of Toronto scientists could lead to substantial advancements in the performance of a variety of electronic devices including digital cameras.

Researchers created a light sensor—like a pixel in a digital camera—that benefits from a phenomenon known as multi-exciton generation (MEG). Until now, no group had collected an electrical current from a device that takes advantage of MEG.

"Digital cameras are now universal, but they suffer from a major limitation: they take poor pictures under dim light. One reason for this is that the image sensor chips inside cameras collect, at most, one electron's worth of current for every photon (particle of light) that strikes the pixel," says Ted Sargent, professor in U of T's Department of Electrical and Computer Engineering. "Instead generating multiple excitons per photon could ultimately lead to better low-light pictures."

In solar cells and digital cameras, particles of light—known as photons—are absorbed in a semiconductor, such a silicon, and generate excited electrons, known as excitons. The semiconductor chip then measures a current that flows as a result. Normally, each photon is converted into at most one exciton. This lowers the efficiency of solar cells and it limits the sensitivity of digital cameras. When a scene is dimly lit, small portable cameras like those in laptops suffer from noise and grainy images as a result of the small number excitons.

"Multi-exciton generation breaks the conventional rules that bind traditional semiconductor devices," says Sargent. "This finding shows that it's more than a fascinating concept: the tangible benefits of multiple excitons can be seen in a light sensor's measured current."

SOURCE: Univ. of Toronto

Saturday, June 6, 2009

TrendNet Wifi on Beagleboard running Angstrom Linux

By default after every boot-up, Angstrom runs wpa_supplicant daemon which tries to use WPA instead of WEP regardless of configuration in /etc/network/interfaces, hence prevent us to use WEP as wifi encryption. We need to kill this daemon by executing:

root@beagleboard:~# start-stop-daemon -K -n wpa_supplicant
root@beagleboard:~# ps -ef | /bin/grep wpa*

Then reconfigure the wlan:

iwconfig wlan0
iwconfig wlan0 key

Try to see if the USB Wifi adapter gets our AP's MAC address:

root@beagleboard:~# ps -ef | /bin/grep wpa*

Finally:

ifdown wlan0
ifup wlan0

It should get the IP (assuming our AP router is running DHCP service as well):

root@beagleboard:~# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.1.0 * 255.255.255.0 U 0 0 0 wlan0
192.168.0.0 * 255.255.255.0 U 0 0 0 usb0
default 192.168.1.1 0.0.0.0 UG 0 0 0 wlan0
default 192.168.0.200 0.0.0.0 UG 0 0 0 usb0
root@beagleboard:~#


(Note: the system used above was running Linux kernel 2.6.29:

root@beagleboard:~# uname -a
Linux beagleboard 2.6.29-omap1 #1 Wed Jun 3 18:10:47 PDT 2009 armv7l unknown

)

Monday, June 1, 2009

What is the best mobile Operating system?

Duh....smartphone environment is getting more crowded with more and more new operating systems. From Microsoft Windows Mobile, Blackberry O/S, Symbian, iPhone's OS, Google's Android and now Palm's WebOS.

Which one is the best from the following criterias?
  1. UI experiences (reponsiveness, easy to use, intuitiveness, beauty look)
  2. Features (view rotation, touch responses, supports to various wireless tech)
  3. Multi-tasking
  4. Development environment and toolkits (including rich sets of libraries)
  5. Portability
  6. Openness (open-system, open source, proprietary)
  7. Price
  8. Hardware supports
  9. Availability to developers to play (at least comes with a simulator)

Wednesday, May 13, 2009

Mathematical Advances Strengthen IT Security

European Science Foundation (05/11/09) Valleley, Sofia

A new cryptography approach based on the mathematical theory of elliptic curves is considered a leading candidate to replace the widely used RSA public key security system. Elliptic curves could enable more efficient cryptography and provide an optimum combination of security and processing efficiency.

The European Science Foundation (ESF) recently held a workshop to discuss the potential for elliptic curves and other modern techniques of mathematics in cryptography and information technology security.

"The impact of the elliptic curve method for integer factorization has played a role in introducing elliptic curves to cryptographers, albeit for attacking the underlying problem on which RSA is based (the difficulty of factoring integers)," says David Kohel, convenor of the ESF workshop, from the Institut de Mathematiques de Luminy in Marseille, France. Kohel says the advantage of elliptic curve cryptography is its immunity to the specialized attacks that have degraded the strength of RSA, meaning smaller keys can be used to provide the same levels of protection.

"In general, the cryptographer has the benefit over the cryptanalyst (the person attacking the cryptosystem) as he or she can select the key size for any desired level of security, provided everyone has the same base of knowledge of best attacks on the underlying cryptosystem," he says.

Saturday, May 9, 2009

Various Embedded Systems

Sony Clie NX80V PDA (running Palm OS)
The NX80V runs Palm OS 5.0 and has a 200 MHz XScale processor. It has 32 megs of RAM, 15.5 of which is available to the user.

AT&T HTC 8125 SmartPhone
Processor: 200 MHz TI OMAP850
Operating System: Windows Mobile 5.0
Memory: 64 MB RAM; 128 MB flash ROM (43 MB available)
In European version is Qtek 9100, AKA The HTC Wizard.
Linux port: http://linwizard.wiki.sourceforge.net/

Computer Architecture: A Quantitative Approach








































Powered by Ingram Digital

Friday, May 8, 2009

Branch Prediction Algorithm


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/******************************************************************************
Branch Prediction Simulator
(c) M. Lutfi, 2009
******************************************************************************/
#define ROW_MAJOR_ADDR(A, r, c, n) ((A) + (r)*(n) + (c))
typedef enum {
not_taken = 0,
taken
} branch_t;

typedef enum {
strongly_not_taken = 0,
weakly_not_taken,
weakly_taken,
strongly_taken
} branch_state_t;

typedef struct {
unsigned int correctPredictionCount;
branch_state_t state;
unsigned int n_iter;
} lbp_t;

enum {
BRANCH_A = 0,
BRANCH_B,
BRANCH_C,
BRANCH_D,
N_OF_BRANCHES
};

#define NBITS_OF_GBH 3 // number of bits in Global History register

lbp_t lbp_table[NBITS_OF_GBH][N_OF_BRANCHES];


unsigned char gbh=0; // global branch history register (3-bit only)
branch_t last_outcome = not_taken;


char* get_branch_state_str(branch_t b)
{
if (b == not_taken)
return "not_taken";
else
return "taken";
}

void update_gbh(void)
{
#if 0
gbh = (gbh<<1) | last_outcome;
gbh &= ((1< printf("last_outcome = %s\n", get_branch_state_str(last_outcome));
printf("gbh = %0X\n", gbh);
#endif
}

/* Local Branch Prediction FSM */
void lbp_update(lbp_t *lbp, branch_t outcome)
{
switch (lbp->state) {
case strongly_not_taken:
if (outcome == taken) {
lbp->state = weakly_not_taken;
} else {
lbp->correctPredictionCount++;
}
break;
case weakly_not_taken:
if (outcome == taken) {
lbp->state = weakly_taken;
} else {
lbp->state = strongly_not_taken;
}
break;
case weakly_taken:
if (outcome == taken) {
lbp->state = strongly_taken;
} else
lbp->state = weakly_not_taken;
break;
case strongly_taken:
if (outcome == taken) {
lbp->correctPredictionCount++;
} else {
// the outcome is NT
lbp->state = weakly_taken;
}
break;
}
lbp->n_iter++;
}


int fun(double *p, int n)
{
int r = 0;
int c = 0;
double *pA;

while (r <= n-1) {
last_outcome = not_taken;
update_gbh();
lbp_update(&lbp_table[gbh][BRANCH_A], not_taken);
while (c <= n-1) {
last_outcome = not_taken;
update_gbh();
pA = ROW_MAJOR_ADDR(p, r, c, n);
if (r < c) {
lbp_update(&lbp_table[gbh][BRANCH_C], not_taken);
*pA = 2* (*pA) + 1;
last_outcome = not_taken;
} else {
lbp_update(&lbp_table[gbh][BRANCH_C], taken);
last_outcome = taken;
}

if (r > c) {
lbp_update(&lbp_table[gbh][BRANCH_D], not_taken);
*pA = 2* (*pA) - 1;
last_outcome = not_taken;
} else {
lbp_update(&lbp_table[gbh][BRANCH_D], taken);
last_outcome = taken;
}
++c;
}
lbp_update(&lbp_table[gbh][BRANCH_B], taken);
last_outcome = taken;
update_gbh();
++r;
}
lbp_update(&lbp_table[gbh][BRANCH_A], taken);
last_outcome = taken;
update_gbh();
return 0;
}

void print_A(double *p, int n)
{
int i,j;
double *pA;

for (i=0; i<n; i++) {
for(j=0; j<n; j++) {
pA = ROW_MAJOR_ADDR(p, i, j, n);
if (!pA) return;
printf("%d: &A[%d][%d] = %0X,\t", __LINE__, i, j, pA);
printf("%d: A[%d][%d] = %lf\n", __LINE__, i, j, *pA);
}
}
}

void init_gbh(void)
{
int i,j;
lbp_t *lbpP;

gbh = 0;
for(i=0; i<(NBITS_OF_GBH<<3); i++) {
lbpP = (lbp_t*)&lbp_table[i];
for(j=0; j<N_OF_BRANCHES; j++) {
lbpP[j].correctPredictionCount = 0;
lbpP[j].state = weakly_not_taken;
lbpP[j].n_iter = 0;
}
}
}

int main(void)
{
#define N 50
double A[N][N];
int i,j;

init_gbh();
printf("sizeof(double) = %d\n", sizeof(double));
printf("%d: &A = %0X\n", __LINE__, &A[0][0]);
for(i=0; i<N; i++) {
for(j=0; j<N; j++) {
A[i][j] = ROW_MAJOR_ADDR(1, i, j, N);
}
}
fun(&A[0][0], N);
printf("gbh = %0X\n", gbh);
for(i=0; i<N_OF_BRANCHES; i++) {
printf("lbp[%d] iteration = %d\n", i, lbp_table[gbh][i].n_iter);
printf("lbp[%d] correct prediction count = %d\n",
i, lbp_table[gbh][i].correctPredictionCount);
printf("Correct Prediction Rate = %4.2lf%\n\n",
((double)(lbp_table[gbh][i].correctPredictionCount)/(double)lbp_table[gbh][i].n_iter) *100.0);
}
}


Monday, April 27, 2009

Sci-Tech Friendly President

Today, Obama announced the launch of a new agency, ARPA-E which stands for Advanced Research Projects Agency - Energy. The agency is modeled after DARPA (Defense - ARPA). The science-and-technology friendly US president is also planning to increase the allocated budget for science and technology to 3% of GDP, which is translated to about $240 billion.

Obama also said that he wants to make solar cells as cheap as paints, self-power buildings (smart building?) and some other interesting sci-tech researches. We will see breakthroughs in coming years produced by US national labs again, after deteriorated by wrong policies of Bush who is not-science-but-war friendly ex president.

Shall we start buying technology stocks once again? I am thinking that energy-related technologies will be booming, smart building system which can conserver more energy, which includes home automation that can control energy consumption to be more efficient, faster routers (we live in a connected world, don't we?), robotics will be more advanced, etc. Many new hi-tech jobs will be available.

I think 99% scientists and engineers should love this president.

Bravo to Obama!

Thursday, April 16, 2009

Mobile Platforms

  • Nokia’s Symbian OS-based S60 platform has something for everyone — C, C++, Java, Python, WRT widgets, and Flash — but the APIs require some getting used to. SymbianC++ and Open C/C++ (a C programming interface with runtime Posix libraries) programs are packaged as metadata files that must be digitally signed for security checks or the application won’t execute. IT can therefore use security certificates to monitor and control in-house mobile applications.
  • iPhone uses Objective-C — challenging even for experienced C, C++, and C# programmers. Developers coming from other languages face an even steeper learning curve. The Cocoa Touch programming interface and proprietary XCode integrated development environment (IDE) provide a powerful environment that includes a WYSIWYG interface builder. For Web-based apps, the SDK includes the HTML/JavaScript-based Dashcode framework. Everything in the iPhone runs at root level — and every process executing with root privileges can be a security threat. Additionally, the iPhone permits only one third-party app to run at a time. IPhone apps also must be digitally signed before they can execute.
  • Android applications are written in Java, but not Java ME. Instead, the Android SDK is a combination of standard Java SE and Java ME methods and classes, as well as nonstandard ones. This means that there’ s a learning curve, even for seasoned Java developers. The Android Development Tools plug-in lets developers use Eclipse to write and debug applications. Again, Android apps must be signed or they won’t run. The SDK does provide a developer key, but a private key is required for public distribution.
  • BlackBerry applications can be developed several ways: a Java-based IDE that provides access to RIM APIs and an Eclipse plug-in; a rapid application development approach that focuses on Web services using Visual Studio or Eclipse plug-ins and supports any .NET or Java language choice; or a Web-based app approach referred to as Browser Development, which lets developers create apps using existing BlackBerry browser software. The downside to writing apps using BlackBerry API extensions is that it ties the application to a particular device. Still, that’s no different than using the Android’s unique Java classes.
  • Windows Mobile uses the .NET Compact Framework, which makes development relatively straightforward for developers familiar with .NET languages such as C#, Visual Basic .NET, and (for native code) Visual C++. Because the .NET Compact Framework is a subset of the .Net Framework, components from .NET-based desktop clients, application servers, and Web servers are available. The upside is companies that have standardized on Microsoft platforms and developer tools can jump into mobile development. The downside is the the apps run on a single platform — Windows Mobile OS.

Monday, April 13, 2009

Sniper location system

By David F. Salisbury

Published: March 19, 2009

I magine a platoon of soldiers fighting in a hazardous urban environment who carry personal digital assistants that can display the location of enemy shooters in three dimensions and accurately identify the caliber and type of weapons they are firing.

Engineers at Vanderbilt University's Institute for Software Integrated Systems (ISIS) have developed a system that can give soldiers just such an edge by turning their combat helmets into "smart nodes” in a wireless sensor network.

ISIS developed this novel technology with the support of the Defense Advanced Research Project Agency and the university has patented the system's key elements.

Like several other shooter location systems developed in recent years, the ISIS system relies on the sound waves produced when a high-powered rifle is fired. These acoustic signals have distinctive characteristics that allow the systems to pick them out from other loud noises and track them back to their source. Current systems, however, rely on centralized or stand-alone sensor arrays. This limits their accuracy and restricts them to identifying shooters at line-of-sight locations.

By contrast, the ISIS system combines information from a number of nodes to triangulate on shooter positions and improve the accuracy of its location identification process. It also uses a patented technique to filter out the echoes that can throw off other acoustic detection systems, explains Akos Ledeczi, the senior research scientist at ISIS who heads up the development effort.

"When DARPA gave us the assignment of creating a shooter location system using nodes with very limited capabilities, they didn't think we could solve the technical problems,” Ledeczi admits. "At first, I didn't think we could do it either, but we figured out how to make it work!”

Retired U.S. Army Lieutenant Colonel Albert Sciarretta, who assesses new military technologies in urban environments for DARPA, is one of the experts who is impressed by the ISIS system: "It's strong points are that it isn't limited to locating shots fired in direct line-of-sight, it can pick up multiple shooters at the same time, and it can identify the caliber and type of weapon that is being fired.”

Sciarretta adds, "A leader can use the information that this system provides to react tactically to enemy shooters in ways that limit the number of friendly force and non-combatant casualties. The ISIS system could be easily developed into an operational war-fighting system.”

When a high-powered rifle is fired, it produces two different kinds of sound waves. One is the "muzzle blast” that expands outward in a spherical wave from the muzzle. The second is a conical shock wave that is produced by the bullet as it travels at supersonic speeds. Each node of the shooter location system contains an array of four sensitive microphones. If at least three of the microphones in a single node detect the muzzle blast, the information allows the nodes' microprocessor to calculate the direction that the sound came from. If the same array also detects the arrival time and angle of the bullet shockwave, a simple calculation gives the shooter's location.

"Because the microphones on the helmet are so close together, the precision is not very high,” Ledeczi says. "However, the nodes are continuously exchanging the times and angles of arrival for these acoustic signals, along with their own locations and orientations. When two or more nodes detect the shot, they can provide the bearing with better than one degree accuracy. The range is typically within a few meters even from as far as 300 meters. The more sensors that pick up the shot, the more accurate the localization.”

The ISIS system communicates its findings with the personal digital assistants that the soldiers carry. The PDAs are loaded with maps or overhead pictures of the area upon which the shooter locations are displayed.

In 2006, a team from the National Institute of Standards and Technology at the U.S. Army Aberdeen Test Center independently determined the accuracy of the system. Firing positions were located at distances of 50 to 300 meters from a 10-node sensor network. Six different weapons were used. The only shots that the system sometimes failed to track accurately were those that passed to one side of all of the nodes.

The field tests demonstrated that the system can pick out the location of high-powered sniper rifles even when they are firing at the same time as a submachine gun like the AK-47. They also proved that it can identify the window that a rifle is firing through even when the rifle is completely inside the building, the technique preferred by trained snipers.

These tests were performed with sensors in fixed locations. One of the problems with using a mobile network has been keeping track of the positions of the mobile nodes with sufficient precision. Standard GPS locations are inadequate for this purpose and satellite coverage can be spotty in urban environments. The ISIS team has recently solved this problem by adding an inexpensive radio chip that allows them to track the relative position of nodes using high-precision radio interferometry. The university has applied for a patent on the technique.

The ISIS shooter system uses wireless nodes invented at UC Berkeley and produced by Crossbow Technology Inc. of San Jose, Calif. These smart nodes, or motes, form self-organizing wireless-sensor networks and are the realization of the Pentagon's "smart-dust” concept of radically reducing the size and cost of sensor networks for military applications. Current commercial shooter location systems are extremely expensive, with prices ranging from $10,000 to $50,000 per unit. By contrast, an entire node for the ISIS system weighs only slightly more than the four AA batteries that power it and costs about $1,000 to construct using currently available commercial hardware.

Scientiest found The Edge of Space

Canadian technology on NASA mission is a prototype for future, longer mission

Where does space begin? Scientists at the University of Calgary have created a new instrument that is able to track the transition between the relatively gentle winds of Earth's atmosphere and the more violent flows of charged particles in space—flows that can reach speeds well over 1,000 km/hr. And they have accomplished this in unprecedented detail.

Data received from the U of C-designed instrument sent to space on a NASA launch from Alaska about two years ago was able to help pinpoint the so-called edge of space: the boundary between the Earth's atmosphere and outer space.

With that data, U of C scientists confirmed that space begins 118 km above Earth and the results were published this week in the Journal of Geophysical Research.

The instrument—called the Supra-Thermal Ion Imager—was carried by the JOULE-II rocket on Jan. 19, 2007. It travelled to an altitude of about 200 km above sea level and collected data for the five minutes it was moving through the "edge of space."

The Canadian Space Agency invested $422,000 in the development of the Supra-Thermal Ion Imager instrument on JOULE-II.

The ability to gather data in that area is significant because it's very difficult to make measurements in this region, which is too high for balloons and too low for satellites.

"It's only the second time that direct measurements of charged particle flows have been made in this region, and the first time all the ingredients—such as the upper atmospheric winds—have been included," says David Knudsen, associate professor in the Department of Physics and Astronomy at the University of Calgary.

Knudsen and his former PhD student Laureline Sangalli are the lead authors of the paper. Co-authors include: JOULE-II lead scientist Miguel Larsen of Clemson University, Robert Pfaff and Douglas Rowland of NASA Goddard Space Flight Center and T. Zhan of Conseco Inc.

"When you drag a heavy object over a surface, the interface becomes hot. In JOULE-II we were able to measure directly two regions being dragged past each other, one being the ionosphere—being driven by flows in space—and the other the earth's atmosphere," says Knudsen, who also is the head of the Space Physics Division of the Institute for Space Imaging Sciences (ISIS). The institute is a research partnership between the University of Calgary and University of Lethbridge.

The measurements confirmed what other scientists consider the boundary or edge of space.

"The results have given us a closer look at space, which is a benefit to pure research in space science," Knudsen says. "But it also allows us to calculate energy flows into the Earth's atmosphere that ultimately may be able to help us understand the interaction between space and our environment. That could mean a greater understanding of the link between sunspots and the warming and cooling of the Earth's climate as well as how space weather impacts satellites, communications, navigation, and power systems."

The U of C-designed instrument has been adopted by COM DEV, an Ontario-based global designer and manufacturer of space hardware, and is being used as a prototype for three instruments currently being readied to fly on the European Space Agency's "Swarm" satellite mission, set to launch late next year and to collect data for four years. The JOULE-II instrument is one in a long list of more than a dozen instruments designed by U of C scientists in the past forty years which have flown in space. There are at least five more being readied to go on missions in the next two years.

"Understanding the boundary between the Earth's atmosphere and outer space is fundamental to the bigger picture of the effects of space on the Earth's climate and environment," says Russ Taylor, the director of ISIS and head of the Department of Physics and Astronomy at the U of C. "This detection is part of a long history of success by ISIS researchers in designing and building innovative instruments flown on rockets and satellites to image the flow of matter and energy between the Earth and Space."

The paper "Rocket-based measurements of ion velocity, neutral wind, and electric field in the collisional transition region of the auroral ionosphere" was published this week in the Journal of Geophysical Research.

Move over, Newton: Scientifically ignorant computer derives natural laws from raw data

If Isaac Newton had had access to a supercomputer, he'd have had it watch apples fall and let it figure out what that meant. But the computer would have needed to run an algorithm developed by Cornell researchers that can derive natural laws from observed data.

Hod Lipson and Michael Schmidt with double pendulum
Lindsay France/Cornell University Photography
Professor Hod Lipson and graduate student Michael Schmidt adjust a double pendulum. Refectors on the pendulum enable motion-tracking software to record position and velocity as the pendulum swings. From this a new computer algorithm can derive equations of motion.

The researchers have taught a computer to find regularities in the natural world that represent natural laws -- without any prior scientific knowledge on the part of the computer. They have tested their method, or algorithm, on simple mechanical systems and believe it could be applied to more complex systems ranging from biology to cosmology and be useful in analyzing the mountains of data generated by modern experiments that use electronic data collection.

The research is described in the April 3 issue of the journal Science (Vol. 323, No. 5924) by Hod Lipson, associate professor of mechanical and aerospace engineering, and graduate student Michael Schmidt, a specialist in computational biology.

Their process begins by taking the derivatives of every variable observed with respect to every other -- a mathematical way of measuring how one quantity changes as another changes. Then the computer creates equations at random using various constants and variables from the data. It tests these against the known derivatives, keeps the equations that come closest to predicting correctly, modifies them at random and tests again, repeating until it literally evolves a set of equations that accurately describe the behavior of the real system.

Technically, the computer does not output equations, but finds "invariants" -- mathematical expressions that remain true all the time, from which human insights can derive equations.

"Even though it looks like it's changing erratically, there is always something deeper there that is always constant," Lipson explained. "That's the hint to the underlying physics. You want something that doesn't change, but the relationship between the variables in it changes in a way that's similar to [what we see in] the real system."

Once the invariants are found, potentially all equations describing the system are available: "All equations regarding a system must fit into and satisfy the invariants," Schmidt said. "But of course we still need a human interpreter to take this step."

The researchers tested the method with apparatus used in freshman physics courses: a spring-loaded linear oscillator, a single pendulum and a double pendulum. Given data on position and velocity over time, the computer found energy laws, and for the pendulum, the law of conservation of momentum. Given acceleration, it produced Newton's second law of motion.

The researchers point out that the computer evolves these laws without any prior knowledge of physics, kinematics or geometry. But evolution takes time. On a parallel computer with 32 processors, simple linear motion could be analyzed in a few minutes, but the complex double pendulum required 30 to 40 hours of computation. The researchers found that seeding the complex pendulum problem with terms from equations for the simple pendulum cut processing time to seven or eight hours. This "bootstrapping," they said, is similar to the way human scientists build on previous work.

Computers will not make scientists obsolete, the researchers conclude. Rather, they said, the computer can take over the grunt work, helping scientists focus quickly on the interesting phenomena and interpret their meaning.

The research was supported by the National Science Foundation.

Monday, March 30, 2009

Tuesday, March 24, 2009

To Find a Square-root with miniMIPS

###############################################################################
# To find a square-root of an integer
# (c) M. Lutfi, 2009
#
# Platform: miniMIPS
# tested on: MARS simulator
#
# Convention:
# $v0..$v1,$t0..$t9,$a0: destroyed during procedure calls
# $s0..$s9: saved during procedure calls
###############################################################################

.text
main:
la $a0, question
jal print_string # print(question)
addi $v0,$zero,5
syscall # read integer. v0 contains the integer read (x)
add $s0,$v0,$zero # s0 = x
bltu $s0,$zero,error # exit if x <>
beqz $s0,just_print # print "0" if x == 0
beq $s0,1,just_print # print "1" if x=1

addi $t1,$zero,0 # a = 0
add $t2,$s0,$zero # b = x

loop:
add $t3,$t1,$t2 # t3 = (a+b)
sra $t3,$t3,1 # mid = (a+b)/2
beq $t3,$t1,print_sqrt
beq $t3,$t2,print_sqrt # to prevent endless loop and give approx. result
multu $t3,$t3 #(hi,lo) = mid*mid
mflo $t4
mfhi $t5 # (t5,t4) = mid^2
beq $t4,$s0,print_sqrt # if (mid^2 == x) goto print_sqrt
bgtu $t4,$s0,set_b # if (mid^2 > x) goto set_b
bltu $t4,$s0,set_a # if (mid^2 <>

set_a:
add $t1,$t3,$zero # a = mid
j loop

set_b:
add $t2,$t3,$zero # b = mid
j loop

print_sqrt:
la $a0,answer
jal print_string # print "sqrt(x) = "
add $a0,$t3,$zero # mid is the sqrt(x)
jal print_integer # print the result
j main # do it again. To finish, just enter neg number
j exit

error:
la $a0, inv_num
addi $v0,$zero,4
syscall
j exit

just_print:
la $a0,answer
jal print_string # print "sqrt(x) = "
add $a0,$s0,$zero #print_integer(x)
jal print_integer

exit: # no param needed
addi $v0,$zero,10
syscall # exit


#---------------------------------subroutines----------------------------------
print_string: # string address in a0
addi $v0,$zero,4 # a0 and v0 are destroyed
syscall
jr $ra

print_integer: # integer value in a0
addi $v0,$zero,1
syscall
jr $ra



#-------------------data section-----------------

.data

question: .asciiz "\nEnter number to be square-rooted: "
inv_num: .asciiz "\nInvalid number (e.g, negative"
answer: .asciiz "Sqrt(x) = "

Monday, March 23, 2009

LED Blink on PICKit2 Demoboard

The following code will make LED 1 on PICKit2 demoboard (attached to PICKit2 programmer) to blink for about every 500 mSec. Tools needed are: gputils and sdcc (all of them are open sources), and pk2cmd freely available at Microchip website.

Source code:
__sfr __at (0x2007)  CONFIG = _INTRC_OSC_NOCLKOUT & _WDT_OFF & _PWRTE_OFF & _MCLRE_OFF &
   _CP_OFF & _IESO_OFF & _FCMEN_OFF & _BOR_OFF;



unsigned char delay1val;
unsigned char delay2val;

void delay()
{
    __asm
    CLRF        _delay1val
    CLRF        _delay2val
    loop:
    DECFSZ      _delay1val,f
    GOTO        loop
    DECFSZ      _delay2val,f
    GOTO        loop
    __endasm;
}

void main()
{
    // make C0 as output
    TRISC0 = 0;
    do {
       RC0 = 1;
       delay();
       RC0 = 0;
       delay();
    } while (1);
}


Makefile:

OBJS=demo1.o
PRJ=demo1
CHIP=690
ARCH=pic14
PLATFORM=16f$(CHIP)
LIBPATH=-I/usr/local/share/gputils/lkr -I/usr/local/share/sdcc/lib/pic
LINKSCRIPTPATH=/usr/local/share/gputils/lkr
LIBS=libsdcc.lib pic$(PLATFORM).lib libm.lib
CC=sdcc -V -m$(ARCH) -p$(PLATFORM)
LINKER=/usr/local/bin/gplink
CFLAGS=--opt-code-speed --stack-auto --main-return --profile --debug-xtra --no-pcode-opt --funsigned-char --Werror
CPPFLAGS=

.c.o:
  $(CC) $(CFLAGS) -D_16F$(CHIP) -c $<

$(PRJ).hex: $(OBJS)
        $(LINKER) -w -O1 -m -o $(PRJ).hex $(OBJS) $(LIBPATH) -f 0 $(LIBS) -s $(LINKSCRIPTPATH)/$(PLATFORM).lkr
   all: $(PRJ).hex
   clean:
        @echo "cleaning up all generated files..."
        @for obj in $(OBJS); do \             if [ -e $$obj ] ; then rm $$obj ; fi \         done
        @rm *.lst
        @if [ -e $(PRJ).cod ] ; then rm $(PRJ).cod ; fi
        @if [ -e $(PRJ).hex ] ; then rm $(PRJ).hex ; fi
        @echo "done."
install:
        pk2cmd -PPIC$(PLATFORM) -M -F$(PRJ).hex
        pk2cmd -PPIC$(PLATFORM) -T


To build:
make demo1.hex

To install:
make install

Sunday, March 22, 2009

PICKIT2 on OpenSUSE

First, create a new udev rules under /etc/udev/rules.d/, name it as "26-microchip.rules".
Add the following into the file:

# PicKit2
SUBSYSTEM=="usb_device", ACTION=="add", SYSFS{idVendor}=="04d8", SYSFS{idProduct}=="0033"
MODE="660", GROUP="microchip", RUN="/usr/local/bin/pk2cmd I /PPIC16F690", SYMLINK+="pickit2"

(do lsusb to verify the vendor and produc id)

Then, execute this on the shell:

sudo udevadm control --reload_rules

Then, download pk2cmd (search google. It should be linked to Microchip website. or try this: http://ww1.microchip.com/downloads/en/DeviceDoc/pk2cmdv1.20LinuxMacSource.tar.gz), compile and install.

When everything is complete with no error, plug in the PICkit2 USB to PC. Check that a new symbolic link was created under /dev as: pickit2. If it is there, you are good to go. Fire up the pk2cmd.

For example, assume the demo code has been there in the demo board and we just want to turn it on, we just need to type: pk2cmd -T /PPIC16F690. To get to know the attached chip on the demo board, try: pk2cmd -I -PPIC16F690

For example:
#> pk2cmd -I -PPIC16F690

Device ID = 1400
Revision = 0005
Device Name = PIC16F690

Operation Succeeded

Friday, March 20, 2009

SDCC Makefile for PIC14

OBJS=test.o
PRJ=test
PLATFORM=16f690
LIB=-I/usr/local/share/gputils/lkr -I/usr/local/share/sdcc/lib/pic

.c.o:
sdcc -V -mpic14 -p$(PLATFORM) --opt-code-speed --stack-auto --main-return -c $<

$(PRJ).hex: $(OBJS)
gplink -m -s $(PLATFORM).lkr -o $(PRJ).hex $(OBJS) $(LIB) -f 0 libsdcc.lib pic$(PLATFORM).lib libm.lib

clean:
rm $(OBJS)
rm $(PRJ).cod
rm $(PRJ).hex

Small Embedded Linux board

Beagleboard Site:
http://beagleboard.org/

BeagleBoard Shopping List
http://code.google.com/p/beagleboard/wiki/BeagleBoardShoppingList

Wednesday, January 28, 2009

New Wireless Standard Promises Ultra-Fast Media Applications

New Wireless Standard Promises Ultra-Fast Media Applications
Georgia Institute of Technology (01/22/09) Fernandez, Don

The Georgia Institute of Technology's Georgia Electronic Design Center (GEDC) has developed a complementary metal oxide semiconductor (CMOS) chip capable of transmitting 60 GHz digital radio-frequency signals. GEDC researchers say the technology could lead to the rapid transfer of high-definition movies and other large files from a PC to a cell phone, virtually wireless desktop computers and data centers, wireless home DVD systems, in-store kiosks that can download movies to mobile devices, and the ability to move gigabytes of photos or video files from a camera to a PC almost instantly. "We believe this new standard represents a major step forward," says GEDC director Joy Laskar. "Consumers could see products capable of ultra-fast short-range data transfer within two or three years." GEDC's chip provides multi-gigabit wireless transmissions by combining 60 GHz CMOS digital radio capabilities and multi-gigabit signal processing in an ultra-compact device. Laskar says the new technology represents the highest level of integration for 60 GHz wireless single-chip solutions. "Multi-gigabit technology definitely has major promise for new consumer and IT applications," says Microsoft Research's Darko Kirovski. GEDC researchers say they have already achieved high data transfer speeds that could lead to unprecedented short-range wireless speeds, including 15 Gbps at 1 meter, 10 Gbps at 2 meters, and 5 Gbps at 5 meters.