Monday, September 19, 2011

#C_CODE: Palindrome

#include <stdio.h>
#include <string.h>


int pali(char *s)
{
    char *s2 = s + strlen(s) - 1;

    if(!*s) return 0;

    while(*(s2--) == *(s++) && *s);
    return (!*s && *(++s2) == *(--s));
}

int main()
{  
    char buff[32];
    fputs("Enter the string: ",stdout);
    fgets(buff,sizeof(buff),stdin);  
    *(buff + strlen(buff) - 1)  = '\0';
    printf("Is the string \"%s\" palindrome?%s\n",  

    buff,pali(buff)?"YES":"NO");
    return 0;
}

Tuesday, September 13, 2011

Linux commands

who am i
who
w - extended who command
who -b
fuser /dev/ttyS0
ps proc_id
fuser -k /dev/ttyS0
vmstat - virtual memory status
find
file
wc - count lines,words,characters in a file
df - filesystem statistics
netstat
iostat
diff
sdiff
lshalb  - dynamic database of connected hardware devices

RENAME exe to exe1
find . -name "*.exe" | while read i;
  do
	mv "$i" "${i%.exe}.exe1";
  done

Sunday, September 11, 2011

Find the process that is currently using the serial port


Run as root


$ fuser /dev/ttyUSB0 [or /dev/ttyS0]
> /dev/ttyUSB0:         1761


$ ps 1761
>  PID TTY      STAT   TIME COMMAND
   1761 pts/0    S+     0:00 minicom


This process can also be killed directly with fuser as root
$ fuser -k /dev/ttyUSB0


To quickly connect to board using GNU screen:
$ screen /dev/ttyUSB0 115200

Wednesday, September 7, 2011

CACHE Memory

CACHE (pronounced "CASH")

Cache is used by the processor to reduce the average time to access main memory.
Cache is a smaller, faster memory which stores copies of the data from the most frequently used main memory locations.
When the processor needs to read from or write to a location in main memory, it first checks whether a copy of that data is in the cache.If so, the processor immediately reads from or writes to the cache, which is much faster than reading from or writing to the main memory.

Most CPU's have at least 3 independent caches:
     1. Instruction cache - Speed up executable instructin fetch
     2. Data cache - Speed up data fetch and store
     3. Translation lookaside buffer(TLB) - Speed up virtual-to-physical address translation for both executable instructions and data.

     NOTE: Data cache is organized as a hierarchy of more cache levels - L1,L2 etc.
     NOTE: Cache built into CPU itself is referred to as Level 1(L1) cache.Cache that resides on a separate chip next to the CPU is called Level 2(L2) cache. Some CPUs                 have both L1 & L2 cache built-in and designate the separate cache chip as Level 3(L3) cache.
     NOTE: Cache coherence
                The data in main memory being cached may be changed by other entities (e.g: peripherals usind DMA or multi-core processor), in which case the copy in                     the cache may become out-of-date or stale. 
                Cache coherence protocols should be used for this.

cache hit and cache miss:
      These are just simple terms for the accuracy of what goes into the CPU's cache. If the CPU accesses its cache looking for data it will either find it or it won't. If the CPU finds what's its after that's called a cache hit. If it has to go to main memory to find it then it is called a cache miss. The percentage of hits from the overall cache requests is called the hit rate.

TLB & MMU
    Most CPUs implement some form of virtual memory.
    Each program running on the machine sees its own simplified address space, which contains code and data for that program only. Each program uses this virtual address space without regard for where it exists in physical memory.
    Virtual memory requires the processor to translate virtual addresses generated by the program into physical addresses in main memory. The portin of the processor that does this translation is known as the memory management unit(MMU). The fast path through the MMU can perform those translations stored in the translation lookaside buffer(TLB), which is a cache of mappings from the operating system's page table.

Freescale - i.Mx
Marvel - XScale
Nvidia - Tegra
ST-Ericsson - Nova & NovaThor
Qualcomm - Snapdragon
TI - OMAP
Samsung - Hummingbird
Apple - A4,A5

#ifdef MY_DBG_EN
    #define MY_DBG printf
#else
    #define MY_DBG(fmt, ...) do {} while(0)

Sunday, September 4, 2011

Linux Device Driver

Reference
[Anil Kumar Pugalia]

A device driver is a piece of software that drives a device.

Device - Device Controller - Bus - CPU
Devices are connected to device controller.
Device controllers are typically connected to the CPU through their respectively named buses (IDE, PCI, USB, SPI, I2C...).

Two types of drivers:
        1. Device driver
        2. Bus driver

1. Device Driver
Fig: Linux device driver partition
A device driver has two parts:
    1. Device specific  [Understand & decode device datasheet]
    2. Operating System(OS) specific [Tightly coupled with the OS mechanisms of user interface]

A device driver provides a 'systemcall', interface to the user; this is called the boundary line between the so called kernel space and user space of Linux.

In Linux a driver is broadly classified into three verticals:
Fig: Device Driver Classification
Network Vertical
     1. Network protocol stack
     2. Network interface card device drivers

Storage Vertical
  1. File System drivers   [ To decode various formats on different partitions]
  2. Block device drivers.[ For various h/w storage protocols like IDE,SCSI,MTD]

2. Bus Driver

In Linux, Bus drivers (or the horizontals) are often split into two parts:
          1. A device controller specific
          2. An abstraction layer over that for the verticals to interface, commonly
              called cores.
              [e.g.:   1. USB controller drivers - ohci, ehci etc,
                         2. USB abstraction - usbcore 
              ]


Dynamic Loading in Linux
In Linux, we can load or unload a driver on the fly, and it is active for use instantly after loading. Also it is instantly, disabled when unloaded. This is called dynamic loading and unloading of drivers in Linux.

* Linux kernel is an object oriented implementation in C.

Commands: insmod, lsmod, rmmod, modprobe, modinfo

Simple kernel module/driver
/* simple driver code
 * Author: Vinod Sasidharan
 */

#include
#include
#include

static int __init hello_init(void)
{
    printk(KERN_INFO "Hai: Hello connected");
    return 0;
}

static void __exit hello_exit(void)
{
    printk(KERN_INFO "Bye: Hello disconnected");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Vinod Sasidharan");
MODULE_DESCRIPTION("Simple kernel module");

Makefile [Use this for all kernel modules; do change the name(hello.o)]

obj-m+=hello.o
all:
    make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
install:
    make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules_install
Commands
$ sudo su
$ make
$ insmod hello.ko
$ lsmod | grep hello
$ dmesg | tail -10
$ rmmod hello
$ dmesg | tail -10
$ objdump -d hello.ko
$ nm hello.ko

Tested on: Ubuntu 11.04 - the Natty Narwhal



 printk n kernel c
  • Floating point is not supported in Linux kernel.
  • When programming for the kernel, we don't bother about the float formats %f, %lf.
  • All printk calls put their output into the (log) ring buffer of the kernel. Then the syslog daemon running in the user-space picks them up for final processing and re-direction to various devices as configure in the configuration file /etc/syslog.conf [Ubuntu: /etc/sysctl.conf]
  • Typical destination: /var/log/messages
  • A user space utility 'dmesg' is provided to directly parse the kernel ring buffer, and dump it to standard output.
  • Kernel C is just standard C with some additional extensions from the C compiler.
  • All functions with __init are supposed to be executed only once during boot up. So after their execution, kernel frees up RAM by removing them.
  • Functions in the exit section are supposed to be called during system shut down.

Character Drivers

Fig: Character driver

If we write drivers for byte-oriented operations (or character oriented operations) then we refer to them as character drivers.

4 entities
  1.     Application
  2.     Character device file
  3.     Character device driver
  4.     Character device
  • Character driver usage is done by the user space application through the character device file linked to it through the virtual file system (VFS).
  • An application does the usual file operations on the character device file.
  • Those operations are translated to the corresponding functions in the linked character device driver by the VFS.
  • Those functions then do the final low-level access to the actual device to achieve the desired results.












OS Functions

1. Process Management
2. Memory Management
3. Device Management
4. Storage Management
5. Network Management

Root File System (RFS) in Linux


File system: Place to store data in form of files


The root file system refers to the file system mounted at the base of the file system hierarchy 
designated simply as /.

A minimal RFS should contain the following:

        Binaries (/bin,/sbin)
        Libraries (/lib)
        Devices (/dev)
        Configurations (/etc)
        Virtual File Systems (/proc, /sys)
        Applicaiton temporary file (/tmp)
        variable data from daemons & utilities (/var)
        user data (/root, /home) - Optional
        Mount points (/mnt, /media) - optional
        Additional software (/usr,/opt) - optional
        Bootloader files (/boot) - optional


bin - Binary executables, used by all users on the system
dev - Device nodes
etc - local system configuration files
home - user account files
lib - system libraries such as the  C library and many others.
sbin - binary executables usually reserved for superuser accounts on the system.
tmp -temporary files
usr - a secondary file system hierarchy for application programs, usually read-only.
var - contains variable files, such as system logs and temporary configuration files.
proc - a special file system containing system information
mnt - a placeholder for user-mounted devices and file systems.

Links:
1. http://libraryopt.sourceforge.net/
2. http://www.openembedded.org/wiki/Main_Page
3. http://buildroot.uclibc.org/