Saturday, 18 April 2015

REGISTER STORAGE CLASS IN C


Register Storage Class in C
(1) when & why register storage class should be used ?
(2) How many register variables can be declared ?
(3) why register storage class have been provided in c ? whatever functionality is provided by register storage class could it have been provided without the same?
(4) As register allocation is done for auto variables can it be done for global variables ? if yes how, otherwise why it is not allowed ? what kind of variables can be given register allocation ?
(5) can register storage class be used for all kind of data types ?
(6) Can we access address of register variables ? what if compiler deny to store variable in registe r & store it in memory, if not why not ? what if same question is repeated for c++ ?
(7) Features of register storage class?
(8) Disadvantage of register storage class?
(9) Initialisation of register variables?
(10) Should register variables be used with modern day compilers ? what about conventional compilers?

ANSWERS:
(1) Register storage class can be useful When you want to refer a variable frequently & when you think it’s necessary to put the variables into the computer registers You can apply register specifier to variables .you can ( not always compiler have authority) allocate fast memory in the form of a register to that variable. e.g. For variables such as loop counters, register allocation may be useful .
Each computer (processor) has a certain number of registers to hold temporary data and perform calculations. The access time of the register is much less than main memory since extra CPU cycle is
required to access data from main memory .Therefore, storing variables in registers might help to speed up program execution. Thus, register variables provide a certain control over efficiency of program execution.
(2) Total number and types of variables actually allocated memory in register may vary from machine to machine ( since different machine may have different no , size of registers & also different specific purpose of some registers ) and compiler to compiler since the processor has a limited number of registers .The register specifier only gives the compiler a suggestion (acts as a directive).In other words, it does not guarantee the allocation of a register for storing value of that variable .The compiler can ignore the suggestion if there is no register available, or if some other restrictions ( like variable can't fit in) apply and treat variables as if they were normal automatic variables without issuing any error message . we need not to worry about declaring too
many register variables because the compiler automatically transforms register variables into automatic variables when the limit is reached.
(3) Register specifier had been provided to give programmers some control over efficiency of program execution taking advantage of memory hierarchy in the system .The keyword register gave the compiler-writer a clue about what variables the programmer thought were frequently referenced, and hence could usefully be kept in registers . Having a register keyword simplifies
the compiler design by transferring this burden to the programmer. ( Thats what have been also done for printf(), scanf() functions to provide them clue in form of format specifiers abour number & type of variables to be dealt with .many more such examples can be given .).
yes it can be done without using register keyword , modern optimizing compilers does the same thing without any hint from the programmer rather we can say it does better job by allocating registers for individual uses of a variable, rather than reserving them for its entire lifetime at declaration.

(4) You cannot use register allocation for global variables because memory is allocated to the global variable at the beginning of the program execution. At that time, it is not certain which function is invoked and which register is used. Function code may use the register internally, but it also has access to a global variable , which might also use the same register. This leads to contradiction, so global register variables are not allowed.
You can only apply the register specifier to local variables and to the formal parameters in a function . The register specifier also can be used only with variables of block scope. It puts a variable into the register storage class, which amounts to a request that the variable be stored in a register for faster access. It also prevents you from taking the address of the variable.

(5) The types of variables that can be assigned to registers vary among machines. Generally the basic data types (int , char) can usually be assigned to registers, as well as pointers to any data type because size of registers to hold no of bytes required for storage of data type may be sufficient to hold these data types only. if the processor has special register (as for most pentium machines ) that can hold float & double type variables & if such register are sufficient in number such that some of those registers may be free at any instant of time & compiler have allowed then definitely register storage clas can be used for these data types also .
if we use register storage class for a data type which require large space than register we dont get any error message compiler would treat those variable to be of auto storage class.Therefore ,in practice, Larger objects, such as arrays, structure , union etc obviously cannot be stored in a register.

(6) In C , It’s illegal to take the address of a variable that is declared with the register specifier by using the unary & operator either explicitly or implicitly, because a register variable is intended to be stored in a register of the CPU, not in memory. A CPU register does not have a memory address usually that you can access.
This restriction applies even when the compiler ignores the request and puts the variable in addressable memory. it has been done to simplify compiler design .
Other than that, register variables behave just as ordinary automatic variables .
C++ lets you take the address of an object with the register storage class.
For example:
register int x;
int* y = &x; // valid in C++, but invalid in C ( you can think how it would have been implemented )
For example:
If you try to access address of a variable declared to be of register storage class we get compilation error.Its true even though request for allocation of register have been denied by the compiler.
  1. #include<stdio.h>
void main()
{
register int x=6;
int *ptr;
ptr=&x;
printf("address of register variable x= %u\n",ptr);
}
Output: Compilation error
  1. we get error message also when we want to access address of register variable in scanf() statement.
#include<stdio.h>
void main()
{
register int x;
printf("\n enter value of register variable x\n");
scanf("%d",&x);
printf(" value of register variable x=%d\n",x);
}
Output: Compilation error
(iii)
it seems from above program that we can not enter value through keyboard for a variable of register storage class. But we can do it alternatively as in program below.
#include<stdio.h>
void main()
{
register int i;
int j;
printf("enter value for register variable\n");
scanf("%d",&j);
i=j;
printf("\n value of register variable i=%d \n",i);
}



(7) Properties of variable defined to have register storage class in c prorgramming language
Storage - Cpu register if allocated otherwise in main memory
Default initial value - garbage /unpredicted
Scope - Local to the block in which the variable is defined.
Life - till control remains in the block in which variable is defined

(8) A limitation of register variables is that you cannot generate pointers to them ( i.e can't take address of a register variable ) using the & operator (This is because, on most machines, pointers are implemented as memory addresses, and CPU registers usually do not have memory addresses.), a register is allocated for the variable if granted for entire lifetime of variable this is also a disadvantage .
But the 'register' storage class doesn't provide much of an advantage when it is used: the compiler is permitted to ignore it when selecting placement of variables, compiler optimization of generated code may do a better job of optimizing placement than the programmer can, and the language imposes restrictions on the use of variables defined as register .

(9) You can initialize any register object except parameters. If you do not initialize an register object, its value is garbage. If you provide an initial value, the expression representing the initial value can be any valid C expression. Formal arguments in a function definition may have class register, in
which case they are copied from the calling stack into a register, where possible.
NOTE :- The register class is the only storage class that can be explicitly specified for function parameters.

(10)
Explicit register declarations should not be used now a days, because modern compilers generally do an excellent (better than most of programmers does optimization) all by themselves and without any hints, of deciding which variables should be kept in machine registers & uses sophisticated register allocation techniques that make the use of the register keyword unnecessary .In fact, such compilers usually ignore register allocation part of the register keyword semantics and only retain the "no unary & operator" semantics .However, for portability all other semantics associated with the register keyword are honoured by the compiler. hence better style should be not to use register storage class with such compilers unless it is desired to loose / not required the fascility of accessing variable through pointer ( if any ) .
i.e. The register storage class specifier keyword does not influence the optimization and performance of generated code for modern day compilers It only prohibits (for C code) the unary prefix addess-of operator & register keyword be used on arrays , or if any other. hence in future C & C++ standards the register keyword might change its meaning or may no longer be used.
probably it have not been done for the sake of portability.
The compiler should use as few registers in the register set as possible( if u are interested can think of such algorithms) if the number of registers needed is significantly greater than the number of registers available, each of these register allocation methods generates a large number of , the loads and stores to memory generated by the register allocator.The compiler should assign temporaries to registers so that the number of LOAD and STORE instructions inserted by the register allocator are as small as possible during the execution of the program.hence to a good optimising compiler, forcing a variable to be kept in a register for the whole duration of a function's execution is usually a disadvantage because register allcator can decide better when keeping that variable in a register makes sense.hence,forced allocation of register variables could actually result in slower execution.
Even the availability of register storage does not guarantee faster execution of the program. For example, if too many register variables are declared, or there are not enough registers available to store all of them, values in some registers would have to be moved to temporary storage in memory in order to clear those registers for other variables. Thus, much time may be wasted in moving data back and forth between registers and memory locations.
Also, the use of registers for variable storage may interfere with other uses of registers by the compiler, such as storage of temporary values in expression evaluation. hence register variables can be used better if you have a detailed knowledge of the architecture and compiler for the computer you are using.

Register storage class was useful for useful for old day compilers . In 1972 when c was invented there was not too much difference between accessing time of register & main memory but still Dennis ritchie implemented functionality of register storage class to make C language what it is, what a genius man , its mental effort of dennis ritchie that C is still so much powerful & useful even after so much change in hardware technology ( like now a days there is so much difference in accessing time of register & main memory ).

Sunday, 12 April 2015

How to fix read only USB pen drive(read only mode) in Linux?


While copying some large file I mistakenly taken out USB pen drive before the copy get completed.Later I again attached the USB pen drive in Ubuntu system but found that the USB pen drive showing read only filesystem message. I was not able to copy,create and delete any file.To solve this issue I followed some steps which I am sharing with this post.
To fix USB pen drive read only in Ubuntu,follow the given below steps
Step 1: Attach USB pen drive in system’s USB port. Automatically the Ubuntu will mount the USB pen drive and show icon on Desktop or Menu bar.

Open the terminal and become super user by running below given command
sudo su -
Step 2: First we have to find out in which directory the USB pen drive has been automatically mounted.For this run the df -Th command.
In given below output you can see,in my system the USB pen drive is mounted in /media/linux/C38C-099C,partition is /dev/sdd1 and filesystem is vfat.
Note: When you run df -Th command in your system,the USB pen drive may mount in different directory and the partition might also be different.Hence the output value which you will get, use the same values in further steps.
root@tuxworld:~# df -Th
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/sda5      ext4       28G   25G  1.3G  96% /
udev           devtmpfs  2.0G  4.0K  2.0G   1% /dev
tmpfs          tmpfs     796M  1.1M  795M   1% /run
none           tmpfs     5.0M  8.0K  5.0M   1% /run/lock
none           tmpfs     2.0G  528K  2.0G   1% /run/shm
none           tmpfs     100M  104K  100M   1% /run/user
cgroup         tmpfs     2.0G     0  2.0G   0% /sys/fs/cgroup
/dev/sda7      ext4      9.2G  8.2G  539M  94% /partition7
/dev/sda8      ext3       46G   38G  6.2G  86% /partition8
/dev/sda9      ext3       74G   67G  3.1G  96% /partition9
/dev/sda21     ext4       14G  4.9G  8.3G  37% /partition10
/dev/sdd1      vfat       15G   12G  3.6G  77% /media/linux/C38C-099C 
Step 2: Now unmount the directory in which the USB pen drive is automatically mounted . (As you can see mounted directory path in above ‘Step 1′)
Note: Replace the/media/linux/C38C-099C with the mounted USB pen drive directory path which is showing output in your system after running df -Th command.
umount /media/linux/C38C-099C
Step 3: As we know the USB pen drive got /dev/sdd1 partition
and filesystem is vfat(see in Step 1). Now we will run dosfsck command to check and repair the filesystem
Note: The dosfsck command check and repair MS-DOS filesystems.Because the filesystem of USB pen drive is vfat hence we are using this command
dosfsck -a /dev/sdd1
Step 4: After the dosfsck command get completed.Remove the USB pen drive from system and then re-attach back to system.Now your USB pen drive should working and it should not have read only filesystem.
Note** After mounting the USB pen drive you may see a new file with extension .REC which was created because of dosfsck command.

Thursday, 15 January 2015

Memory Managment in kernel

I am reading Linux Kernel Development for undertsanding memory managment in kernel

-kernel cannot easily deal with memory allocation errors, and the kernel often cannot sleep.

Pages
-The kernel treats physical pages as the basic unit of memory management.
-MMU smallest unit is pages
-Most 32-bit architectures have 4KB pages.
-64-bit architectures have 8KB pages.
-kernel represents every physical page on the system with a struct page structure.
<linux/mm_types.h>.
structpage {
              unsigned long  flags;
              atomic_t   _count;  //stores the usage count of the page(-1 no one use the
              atomic_t _mapcount;                                                                     page)
              unsigned long private;
              struct address_space *mapping;//page cache
              pgoff_t index;
              struct list_head lru;
              void *virtual;(//pointer to virtual address space//NULL if not permanently    mapped)
};

 page_count()
-this structure to keep track of all the pages in the system, because the kernel needs to know whether a page is free
-If page is not free kernel must know who owns the page.
- Possible owners include
user-space processes, dynamically allocated kernel data, static kernel code, the page cache, and so on.

Zones-Because of hardware limitations, the kernel cannot treat all pages as identical. Some pages,because of their physical address in memory, cannot be used for certain tasks.
-to overcome this limitation,the kernel divides pages into different zones(similar properties).

Linux has four primary memory zones:
ZONE_DMA—This zone contains pages that can undergo DMA.
ZONE_DMA32—Like ZOME_DMA, this zone contains pages that can undergo DMA.Unlike ZONE_DMA, these pages are accessible only by 32-bit devices. On some architectures, this zone is a larger subset of memory.
ZONE_NORMAL—This zone contains normal, regularly mapped, pages.
ZONE_HIGHMEM—This zone contains “high memory,” which are pages not permanently mapped into the kernel’s address space.
<linux/mmzone.h>.
-actual use and layout of the memory zones is architecture-dependent.
- 32-bit x86 systems, ZONE_HIGHMEM is all memory above the physical 896MB mark.
-The memory contained in ZONE_HIGHMEM is called high memory. The rest
of the system’s memory is called low memory.
- On x86, for example, ZONE_NORMAL is all physical memory from 16MB to 896MB.
-

Patching Xenomai with linux

Xenomai on the Beaglebone Black in 14 easy steps

EDIT: Mark wrote an updated guide here.
The BeagleBone Black is an amazingly cheap and powerful development platform that is being used by many people in a lot of projects. That was intentionally vague, because I know that if you ended up here you already know what a BeagleBone Black is.
In this post I’ll explain how I got Xenomai to run on my BeagleBone.
First of all I tried these instructions, but couldn’t get past the kernel compilation step. I believe that this is due to the instructions being six months old, which are like two and a half centuries in computer time. So I continued searching and found a post in a Japanese blog. Using my fluent Japanese Google Translator I could understand what was going on and could successfully reproduce the steps and get Xenomai up and running (big thanks to the author!). Here I’ll reproduce the steps. I’m assuming that you are on a computer running Ubuntu (like mine) and are familiar with the command line.

Getting the tools

Step 0: Get all the tools that will be needed (cross-compiler and dev libraries).

Building the Kernel

Step 1: First of all, make a directory to hold all of our development files. I’ll call mine bbb. 
Step 2: Get the Linux kernel for the BeagleBone and the Xenomai sources. This might take a while.
Step 3: Checkout kernel 3.8 version branch. Apply BeagleBone’s patches.
Note: In this step I revert to a specific commit because newer ones are known to cause problems.
Step 4: Get a firmware that the kernel config will need (I’m not sure whether this firmware is really needed).
Step 5: Copy the BeagleBone default config as the running config.
Step 6: Apply I-pipe patches to the BeagleBone kernel.
Step 7: Run the Xenomai prepare-kernel  script for the BeagleBone kernel.
Step 8: Configure the kernel to be built.
Under  CPU Power Management --->  CPU Frequency scaling, disable  [ ] CPU Frequency scaling . (Note: Don’t know if it’s better to leave it enabled, read the comments!)
Under  Real-time sub-system  ---> Drivers ---> Testing drivers, enable everything.
Step 9: Compile the kernel.
Note: I chose 16 to the -j  option, because my computer has 8 cores. Choose a value appropriate to your computer. I read somewhere that 2 times the number of cores is a good number.
Note: If there were errors in the compilation, the messages will probably be lost among all other output. To see them, simply run the command again.

Preparing an SD Card

Now let’s get an SD Card ready with the Angstrom distribution and our kernel. If you want to use this kernel with the distribution on the eMMC memory, just put it in the appropriate place.
Step 10: Download and copy the default Angstrom distribution to your SD Card. Replace /dev/sdX  with the path to your SD Card.sudo fdisk -l  is your friend. Note: I used a SanDisk 4GB SD Card.
CAUTION: YOU WILL LOSE ALL YOUR PREVIOUS DATA ON THE DEVICE /dev/sdX !
Step 11: Mount the Angstrom partition. Copy kernel and kernel modules (thanks for your comment, Jurg Lehni!), Xenomai modules and source folder to that partition. Replace  /dev/sdX2  with your actual path to the partition.

Testing

Now put the SD card on the BeagleBone, boot it, ssh into it and test Xenomai.
Step 12: Configure the date and compile Xenomai
Note: an example for the date command would be  date -s "21 May 2014 13:25 GMT-3" 
Step 13: Load the testing driver
Step 14: Run some tests!
User-mode latency:
In-kernel Latency:
Poke around:
Change parameters:
Great, huh? Now go develop something real time =)
Reference: 
http://brunosmartins.info/xenomai-on-the-beaglebone-black-in-14-easy-steps/