網頁

2011年8月11日 星期四

kernel- hash list

The overall structure of the hash list in kernel is shown as blow.

Here is the data structure.

struct hlist_head {
struct hlist_node *first;
};

struct hlist_node {
struct hlist_node *next, **pprev;
};

Kernel provides some interface to build a whole hash list quickly and they are more useful.

Some figures are illustrated to desrcbie how to use these function calls for the hash list. 

static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
{
struct hlist_node *first = h->first;
n->next = first;
if (first)
first->pprev = &n->next;
h->first = n;
n->pprev = &h->first;
}

Insert  a node to the head of hash list.

There are 2 case for this operation and please see below.

Case 1:

no any node exists in the hash list.

Case 2:

Otherwise , there are  more than one nodes  at least in the list.

static inline void hlist_add_before(struct hlist_node *n,
struct hlist_node *next)
{
n->pprev = next->pprev;
n->next = next;
next->pprev = &n->next;
*(n->pprev) = n;
}

Add the node N before the Node next.

 

static inline void hlist_add_after(struct hlist_node *n,
struct hlist_node *next)
{
next->next = n->next;
n->next = next;
next->pprev = &n->next;

if(next->next)
next->next->pprev = &next->next;
}

Add the node Next after node N.

static inline void hlist_del(struct hlist_node *n)
{
__hlist_del(n);
n->next = LIST_POISON1;
n->pprev = LIST_POISON2;
}

Remove the node N from the list.

2011年8月9日 星期二

Linux kernel - contain_of

This marco is mostly used in kernel .
The figure is illustrated to descible how the marco "contain_of" work.

The following is the  source code using the marco "contain_of".

#include <stdio.h>

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({            \
     const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
     (type *)( (char *)__mptr - offsetof(type,member) );})

struct  St_Inner{
    int         dw_a;
};

struct St_Outer {
    int         dw_a;
    struct St_Inner    St_b;
    int         dw_c;
};

     
int main ()
{
    struct St_Outer  src;
    struct St_Outer  *p_dest;
    struct  St_Inner *p_Inner;
    p_Inner = &src.St_b;
    
    
    p_dest = container_of (p_Inner,struct St_Outer, St_b);
    
    printf ("p_dest %x == src %x\n",p_dest,&src);
    return 0;
}

2011年7月20日 星期三

Interesting callback function

typedef void( *fp_t )(char *);
fp_t( *fp) [2];

It is easy to understand to expand it shown as the following.
void(*(*fp)[4])(char*);
Here is an example to show  where this callback function can be used.
#include <stdio.h>

typedef void( *fp_t )(char *);

void  spi_read(char *data)
{
printf ("spi_read\n");
}
void  spi_write(char *data)
{
printf ("spi_write\n");
}
void  nand_read(char *data)
{
printf ("nand_read\n");
}
void  nand_write(char *data)
{
printf ("nand_write\n");
}
void (*spi_fp[2]) (char *);
void (*nand_fp[2]) (char *);
int main()
{
    int i;
 
    fp_t( *fp) [2];
    spi_fp[0] = spi_read;    
    spi_fp[1] = spi_write;    
    nand_fp[0] = nand_read;    
    nand_fp[1] = nand_write;    
    
    fp = &spi_fp;
    for (i=0;i<2;i++)
    {
        (*fp)[i] (0);
    }
    return 0;
}

2011年6月14日 星期二

LD_DEBUG and LD_LIBRARY_PATH

It is useful to find out which library are loaded when running the program.
LD_DEBUG = help ./a.out
Vaild option for LD_DEBUG
libsdisplay library search paths
relocdisplay relocation processing
filesdisplay progress for input file
symbolsdisplay symbol table processing
bindingsdisplay information about symbol binding
versionsdisplay version dependencies
allall previous options combined
statisticsdisplay relocation statistic
unuseddetermined unused DSOs
helpdisplay this help message and exit
LD_DEBUG=libs ./a.out
17315:    find library=libc.so.6 [0]; searching
17315:     search cache=/etc/ld.so.cache
17315:      trying file=/lib/tls/i686/cmov/libc.so.6
17315:
17315:
17315:    calling init: /lib/tls/i686/cmov/libc.so.6
17315:
17315:
17315:    initialize program: ./a.out
17315:
17315:
17315:    transferring control: ./a.out
17315:
17315:
17315:    calling fini: ./a.out [0]
17315:
17315:
17315:    calling fini: /lib/tls/i686/cmov/libc.so.6 [0]
17315:
From above result, it will find the file "ld.so.conf" to know where the standard library is located.
In this case, the library I only use is glibc. So it is a simple code.
But it is handy tool if your program is very complex and you want to know which library is linked.
gcc --share b.c -o libb.so
gcc -o a{,.c} -lb -L.
Then you should export libary PATH "LD_LIBRARY_PATH"
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH;./
The program will be executed successfully.
You can try LD_DEBUG again and the loader will search additional path "./" you assigned  and load the specific library to memory.

2011年6月7日 星期二

Overlay attribute in LDScript

For each section within the OVERLAY, the linker automatically defines two symbols. The symbol __load_start_secname is defined as the starting load address of the section. The symbol __load_stop_secname is defined as the final load address of the section. 
OVERLAY 0x1000 : AT (0x4000)
{
   .text0 { o1/*.o(.text) }
   .text1 { o2/*.o(.text) }
}
This will define both `.text0' and `.text1' to start at address 0x1000. `.text0' will be loaded at address 0x4000, and `.text1' will be loaded immediately after `.text0'. The following symbols will be defined: __load_start_text0, __load_stop_text0,__load_start_text1, __load_stop_text1.
C code to copy overlay .text1 into the overlay area might look like the following.
extern char __load_start_text1, __load_stop_text1;
memcpy ((char *) 0x1000, &__load_start_text1,
          &__load_stop_text1 - &__load_start_text1);
Note that the OVERLAY command is just syntactic sugar, since everything it does can be done using the more basic commands. The above example could have been written identically as follows.
.text0 0x1000 : AT (0x4000) { o1/*.o(.text) }
__load_start_text0 = LOADADDR (.text0);
__load_stop_text0 = LOADADDR (.text0) + SIZEOF (.text0);
.text1 0x1000 : AT (0x4000 + SIZEOF (.text0)) { o2/*.o(.text) }
__load_start_text1 = LOADADDR (.text1);
__load_stop_text1 = LOADADDR (.text1) + SIZEOF (.text1);
. = 0x1000 + MAX (SIZEOF (.text0), SIZEOF (.text1));
Reference from The GNU linker.

2011年6月4日 星期六

Weak function

From gnu gcc document:
The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations.

libweak.c
#include <stdio.h>

void weakfunc() __attribute__((weak));

void weakfunc()
{
    printf ("default weak function\n");

}
main.c
#include <stdio.h>
void weakfunc()
{
    printf ("weak function from main\n");    
}

int main ()
{
    weakfunc();
    return 0;
}
Compile the library and main function.
#gcc -shared -o libweak.so weakfunc.c
#gcc  -o weakfunc{,.c} -lweak -L.
#LD_LIBRARY_PATH=. ./main
weak function from main 
From above, it is very clear that the weak function of the library is replaced.
#objdump -t libweak.so |grep weakfunc
0000046c  w    F .text 00000014   weakfunc
In the library, this function has weak attribute.
#objdump -t main |grep weakfunc
080484e4  g    F .text 00000014   weakfunc
However, this function is presented as  global attribute.

2011年6月2日 星期四

Andriod 專有名詞整理

最近研究了Andriod,整理了一些專有名詞如
IPL (InitialProgramLoader):
Initialize the hardware setting, such as memory, cpu clock , flash, about the development board.
It is similar with the bootloader in the embedded system, like u-boot.

SPL (Second Program Loader):
The main goal is to load system OS to memory.
In addition, some features is provided as the below list.
(1) check hardware, like LCD, led.
(2) search the active partion and load it to memory.
(3) connection with PC and recieve commands from PC host.

HBoot:
This is  HTC’s SPL
fastboot:
Fastboot is protocol used to update the flash filesystem in Android devices from a host over USB.
The command "fastboot.exe" you can run on your host after fastboot has been started on a device connected via USB.
e.g.
$ fastboot erase boot

Andriod Recovery:
The recovey of  the mainstream andriod can provide some options to recovery your systems or factory-to-default, even
though it can load official ROM in the zip file of SD card and recovey the system.
ClockworkMod recovery is one of the widely used custom andriod recovery and it provide more options to recovery unofficial or official
ROM from the zip file of SD card.

2009年10月26日 星期一

CGI debug

Web server will redirect STDIN, STDOUT and STDERR to CGI interface so the following function is used to print out debug messages from C code.

Function 1:
void debug_printf(const char *degmsg, ... )  
 {  
     int old = dup(STDOUT);  
     int ttyfd ;  
     int ret;  
     va_list ap;  
     char msg[512];  
     
     ttyfd = open("/dev/ttyS0", O_RDWR);  
     va_start(ap,degmsg);  
     ret = vsprintf(msg,degmsg,ap);  
     va_end(ap);  
     dup2(ttyfd, STDOUT);  
     close(ttyfd);  
     printf("%s",msg);  
     dup2(old, STDOUT);   }

Function 2:

void debug_printf(const char *degmsg, ... ){  
     va_list ap;  
     int ret;  
     FILE *con_ptr;  
     char msg[512];  
     
     va_start(ap,degmsg);  
     ret = vsprintf(msg,degmsg,ap);  
     va_end(ap);  
     con_ptr = fopen("/dev/ttyS1","w+");;      
     if (!con_ptr) {  
         perror("fopen");  
     }  
     fprintf(con_ptr,"%s",msg);  
     fflush(con_ptr);  
     fclose(con_ptr);  
 }

2009年10月1日 星期四

How to mount JFFS2 image

Use memory to emulate the MTD device
mknod /tmp/mtdblock0 b 31 0
modprobe mtdblock
modprobe mtdram total_size=65536 erase_size=256

modprobe jffs2

dd if=image.jffs2 of=/tmp/mtdblock0

mkdir /mnt/jffs2
mount -t jffs2 /tmp/mtdblock0 /mnt/jffs2

2009年7月3日 星期五

IPV6 DHCPV6 Configuration

Router Advertisement Daemon (radvd)
/etc/radvd.conf

interface eth0 { 
  AdvSendAdvert on; 
  MinRtrAdvInterval 3; 
  MaxRtrAdvInterval 10; 
  prefix 2001:0db8:0100:f101::/64 { 
     AdvOnLink on; 
    #Disable Stateless Address Autoconfiguration 
    #AdvAutonomous on; 
    AdvRouterAddr on; 
  }; 
};
 
Wide-DHCPv6
Server configuration: dhcp6s.conf

option domain-name-servers 2001:470:1f01:2191::1 2001:470:1f01:2191::2; 
option domain-name "dean.net"; 
interface eth0{ 
  address-pool pool1 3600; 
}; 
pool pool1 { 
  range 2001:5c0:1101:b700::1000 to 2001:5c0:1101:b700::2000 ; 
}; 
host host0 { 
  duid 00:00:00:00:a0:a0; 
  prefix 3ffe:ffff:102::120/64 infinity; 
};
Client configuration
DHCPV6 client for the stateful autoconfigutation

interface eth0 {
         send ia-na 0;
         request domain-name-servers;
         request domain-name;
         script "/tmp/dean/dhcp6c-script";
};
id-assoc na 0 {
         # non-temporary addresses
};
DHCPV6 client for the stateless autoconfigutation
interface eth0
{
 information-only;


 request domain-name-servers;
 request domain-name;
 script "/tmp/dean/dhcp6c-script";

};
DHCPV6 script
update DNS in resolv.conf
#!/bin/sh

if [ -n "$new_domain_name" -o -n "$new_domain_name_servers" ]; then
    new_resolv_conf=/tmp/resolv.conf.dhcp6c-new
    rm -f $new_resolv_conf
    if [ -n "$new_domain_name" ]; then
        echo search $new_domain_name >> $new_resolv_conf
    fi
    if [ -n "$new_domain_name_servers" ]; then
        for nameserver in $new_domain_name_servers; do
            echo nameserver $nameserver >> $new_resolv_conf
        done
    fi

    # To preserve IPv4 informations...
    cat /etc/resolv.conf >> $new_resolv_conf
    mv -f $new_resolv_conf /etc/resolv.conf
fi

exit 0







2009年6月25日 星期四

Shell script tricks

1. The array of shell script 
names=( Jennifer Tonya Anna Sadie )
for name in ${names[@]}
do
   echo $name
done
names=( Jennifer Tonya Anna Sadie )
for (( i = 0 ; i &lt; ${#names[@]} ; i++ ))
do
    echo ${names[$i]}
done
2. Variable substitution for shell script 
$DEVICE0=eth0
$echo "Configure interface " ${!DEVICE${i}}
$n=1
$ eval echo \${$n}
$ n="date"
$ echo $($n)
Output :Wed May 21 20:39:00 EEST 2008
3. Increment i in the while loop 
i=$(($i+1))
i=`expr i + $i`

2009年6月15日 星期一

Re-entrant vs Thread safe

Both concepts of reentrancy and thread safety relate to the way functions handle resources. However, they are not the same. While the concept of reentrancy can affect the external interface of a function, thread safety only concerns the implementation of the function and not its external interface.
  • In most cases, to make a non-reentrant function reentrant, its external interface must be modified such that all data is provided by the caller of the function.
  • To make a thread-unsafe function thread-safe, only the implementation needs to be changed, usually by addingsynchronization blocks to protect shared resources from concurrent accesses by different threads.
Therefore, reentrancy is a more fundamental property than thread-safety and by definition, leads to thread-safety: Every reentrant function is thread-safe; however, not every thread-safe function is reentrant.
Reference from http://en.wikipedia.org/wiki/Reentrant_(subroutine)

2009年6月9日 星期二

How to show the page table entry


excerpt from arch/arm/mm/fault.c
void show_pte(struct mm_struct *mm, unsigned long addr)
{
pgd_t *pgd;

if (!mm)
mm = &init_mm;

printk(KERN_ALERT "pgd = %p\n", mm->pgd);
pgd = pgd_offset(mm, addr);
printk(KERN_ALERT "[%08lx] *pgd=%08lx", addr, pgd_val(*pgd));

do {
pmd_t *pmd;
pte_t *pte;

if (pgd_none(*pgd))
break;

if (pgd_bad(*pgd)) {
printk("(bad)");
break;
}

pmd = pmd_offset(pgd, addr);
#if PTRS_PER_PMD != 1
printk(", *pmd=%08lx", pmd_val(*pmd));
#endif

if (pmd_none(*pmd))
break;

if (pmd_bad(*pmd)) {
printk("(bad)");
break;
}

#ifndef CONFIG_HIGHMEM
/* We must not map this if we have highmem enabled */
pte = pte_offset_map(pmd, addr);
printk(", *pte=%08lx", pte_val(*pte));
printk(", *ppte=%08lx", pte_val(pte[-PTRS_PER_PTE]));
pte_unmap(pte);
#endif
} while(0);

printk("\n");
}

crontab

Crontab command
#export to the file
crontab -l > filename
# import from the file
crontab filename 
# import from the file for the specific user
crontab -u user filename 
# edit
crontab -e 
# delete all
crontab -r 

Crontab special usage 


EntryDescriptionEquivalent To
@rebootRun once, at startup.None
@yearlyRun once a year0 0 1 1 *
@annually(same as @yearly)0 0 1 1 *
@monthlyRun once a month0 0 1 * *
@weeklyRun once a week0 0 * * 0
@dailyRun once a day0 0 * * *
@midnight(same as @daily)0 0 * * *
@hourlyRun once an hour0 * * * *


Crontab Example

# .---------------- minute (0 - 59) 
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * command to be executed

minhourday/monthmonthday/week Execution time
30011,6,12*-- 00:30 Hrs  on 1st of Jan, June & Dec.

:

020*101-5--8.00 PM every weekday (Mon-Fri) only in Oct.

:

001,10,15**-- midnight on 1st ,10th & 15th of month

:

5,10010*1-- At 12.05,12.10 every Monday & on 10th of every month
:

 
*/8 * * * * root init 6  After 8 minutes , execute "reboot" command
ps: "*/8" in the minute time field is equivalent to "0,8,16,24,32,48,56"

2009年6月8日 星期一

Linux 2.6 Driver Template


#include <linux/module.h>
#include <linux/config.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <asm/io.h>

#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>

typedef struct
{
void **data;
struct cdev *cdev ;

}DBG_Dev_Tag;

#define DBG_MAJOR 111
#define DBG_MINOR 1
#define MAXDEVICENUM 1

#define DEBUG_IOC_MAGIC 'D'
#define DEBUG_IOCSHOWDEB _IOR(DEBUG_IOC_MAGIC, 1, int)

DBG_Dev_Tag *DBG_devices;


int dbg_major = DBG_MAJOR;
int dbg_minor;

static struct file_operations DBG_fops =
{
.ioctl = DBG_ioctl,
.read = DBG_read,
.write = DBG_write,
.open = DBG_open,
.release = DBG_release,
};

int DBG_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)
{
struct net_device *dev = &_wpcm450_netdevice;

switch (cmd)
{
case DEBUG_IOCSHOWDEB:
//show something

break;
default:
break;
}

return 0;
}

ssize_t DBG_read (struct file *filp, char *buf, size_t count, loff_t *offset)
{
return 0;
}

ssize_t DBG_write (struct file *file, const char *buf, size_t count, loff_t *offset)
{
return 0;
}

static int DBG_open(struct inode *inode, struct file *filp)
{
DBG_Dev_Tag *dev;

dev = container_of (inode->i_cdev,DBG_Dev_Tag,cdev);

filp-> private_data = dev;

return 0;
}

static int DBG_release(struct inode *inode, struct file *filp)
{


return 0;
}



static void dbg_setup_cdev(DBG_Dev_Tag *dev,int index)
{
int err;
int dev_id = MKDEV(dbg_major,dbg_minor + index );

cdev_init(dev->cdev,&DBG_fops);

dev->cdev->owner = THIS_MODULE;

dev->cdev->ops = &DBG_fops;

err = cdev_add(dev->cdev,dev_id,1);

if (err)
printk ("error %x adding dbg%x\n",err,index);

}


static int __init DBG_init(void)
{
int result;
dev_t dev_id;


DBG_devices = kmalloc (sizeof (DBG_Dev_Tag) * MAXDEVICENUM ,GFP_KERNEL);

if (DBG_devices == NULL)
{
result = -ENOMEM;
return result;
}

memset(DBG_devices, 0, MAXDEVICENUM * sizeof(DBG_Dev_Tag));

if (dbg_major)
{
dev_id = MKDEV(dbg_major,dbg_minor);

result = register_chrdev_region(dev_id, 1, "debug");
}
else
{
result = alloc_chrdev_region(&dev_id,DBG_MINOR,1,"dbg");
dbg_major = MAJOR(dev_id);
}

if (result < 0 )
{
printk ("can't get major %d\n",dbg_major);
return result;
}

DBG_devices->cdev = cdev_alloc();

dbg_setup_cdev(DBG_devices,1);

return 0;
}

static void __exit DBG_exit(void)
{
dev_t dev_id;

kfree(DBG_devices);

cdev_del(DBG_devices ->cdev);

dev_id = MKDEV(dbg_major,dbg_minor);
unregister_chrdev_region(dev_id,1);
return;
}

MODULE_AUTHOR("XXXXXXXXXX");
MODULE_DESCRIPTION("Debug driver");
MODULE_LICENSE("GPL");

module_init(DBG_init);
module_exit(DBG_exit);

//**************************Makefile *******************************
KERNELDIR =   obj-m := test_drv.o
#combine two drivers into the one. 
#test_drv-objs := testA_drv.o testB_drv.o  
ifneq ($(KERNELRELEASE),)  
CFLAGS +=  -D__KERNEL__ -DMODULE  -Wall -DEXPORT_SYMTAB -O2  
else  
all:  
 $(MAKE) -C $(KERNELDIR) M=$(shell pwd) modules endif