2013 in review of the blog

The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 11,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 4 sold-out performances for that many people to see it.

Click here to see the complete report.

Backbone.js – Listening to DOM events using backbone.views

Writing Backbone.js applications requires three dependies , the Jquery Library , Underscore.js and Backbone.js libraries , this illustrates the simple task of associating a listener for the click event on the checkbox element on the DOM, Backbone.js provides all the necessary functionalities to make a fully fledge web applications , it is well known for the implementation of the MVc architecture , use Ctrl+shift+K in the firefox browser to open the Javascript console and view the console log

	<meta charset="UTF-8">

	<script src="http://code.jquery.com/jquery-1.10.2.js">
	<script src="http://underscorejs.org/underscore-min.js">

	<script src="http://backbonejs.org/backbone-min.js">
		$( document ).ready(function() {
		/*Enclose the script under Jquery Document.ready , this makes sure that the script is executed after the DOM 
		elements on the browser is loaded */
    		var View = Backbone.View.extend({

			el : '#listen_to_box' , 
			/*associate  DOM element on which you want to work on , 
			In this case #listen_to_box is the ID of the div element with the  checkbox */
			events: { 
				'click [type="checkbox"]':'clicked', 
				/*associate an event listener 'clicked' for 
				the click event on the checkbox , this is done using the Views events property*/
		clicked : function(event ) { /*The Handler function for the click event on the checkbox*/
			console.log("events handler for "+  this.el.outerHTML);
			/* el.outerHTML has the markup or the HTML code of the DOM element associated with el, 
				in this case the 'div' element with the id of #listen_to_box is assigned to el */ 
	var view = new View();
	<div id="listen_to_box">
		<input type="checkbox" />


Js console
Js console

Using Semaphores and Mutex in Linux Device drivers to tackle concurency

Semaphores provide a satisfactory solution for issues related to concurrency . Access to critical section is controlled by enforcing threads to hold a lock before entering the critical section , Without a semaphore being unlocked no thread is allowed access to execute in the critical section .

Semaphore is a single integer value bound to two functions P and V . P is called down or some variation of that name and V is called up . Function P is used to lock the critical region and V is used to unlock . Function P decreases the count of semaphores , for example from 1 to 0 . When the value of the semaphore still remains 0 or less no other threads are allowed to execute in the critical region . There are made to wait or even may be put to sleep till the region is unlocked .

Functions of type V releases the semaphores that’s being help , these category of functions increases the value count of the semaphore and may even wake up the processes waiting for the access into the critical region .

Semaphores are generally and mostly used for the purpose of mutual exclusion , that is to make sure that only one thread of execution or a process executes in the critical section .

 Linux Implementation of Semaphores

<asm/semaphore.h> defines several functionalities for semaphore and mutex implementation ( Mutexes are just a special case of semaphores ) .

To initialize a declared semaphore ,

void sema_init(struct semaphore *sema, int val) can be used ,

 this initializes the declared mutex to value val ( The second argument to the function ) ;

But , as i had mentioned earlier semaphores are generally used for implementation of mutex ,

the following two functions declare and initialize the mutex

DECLARE_MUTEX(mutex_name ) ;


 These functions declares mutex named as ‘mutex_name’ , the function DECLARE_MUTEX declares the mutex and initializes it to 1 ( 1 is the unlocked state , a thread or a process can possibly lock the critical region ) , wherein the later function declares the mutex and initializes it to 0 ( 0 is the locked state ) , mutex has to be explicitly unlocked before it can be used for locking .


 For initializing the mutex at runtime the following functions can be used ,

void init_MUTEX(struct semaphore *sema ) ;

void init_MUTEX_LOCKED(struct semaphore *sema) ;

 Holding and releasing Mutex ( The version of P [down] and V[up] functions )

 Linux kernel provides three versions of down function

  1. void down(struct semaphore *sema) ;

  2. int down_interruptible(struct semaphore *sema) ;

  3. int down_trylock(struct semaphore *sema ) ;

As briefed earlier down decrements the value of the semaphore , successful exection of any version of down function leads to locking of the critical region of the code , and the thread of execution or the process is said to have acquired the lock . Other user space process trying to access the critical region of code will be made to wait .

In case of the first version of down ( void down_interruptible() ) , the user space process waiting for the mutex to be released cannot to interrupted , it’ll be running in a dreaded state . This is not desirable in many cases , so the second version of down allows the waiting user space process to be interrupted .

The third version can used to test and lock , if the lock is already being held the function returns with a negative value , If no other thread is holding the lock , the lock will be acquired . Using down_trylock() the process wont wait for the acquired lock to be released , it returns immediately .

void up(struct semaphore * sema) is used to unlock the acquired lock and even wake up the processes waiting on the semaphore .

When executing in the critical region on occurance of error its very important to unlock the region before returning






Concurrency issues in Linux Device Drivers and protection from concurrency

Concurrency was not a big issue till kernel support was introduced for SMP systems . Before there were only few sources of concurrency like the interrupt handling context , but with introduction of kernel support for SMP systems it also drastically increased the chances of  code being vulnerable for concurrency issues .SMP (Symmetric Multi Processing ) systems involve architecture with multiple processors , this introduces the possibility of the same code snippet being run in more than one processors at a given point of time . Codes running in kernel context are pre-emtible too , it may lose the processor at any point of time and the process scheduled next may run in your driver .There are surprisingly many ways where the Device Driver or a program running in kernel context becomes vulnerable for concurrency related issues , In the computing world where one in a million probable event too can happen every second bugs related to concurrency are difficult to identify even for expert kernel developers .

Reasons for concurrency

Consider this small code snippet in your driver

if(!dptr->data[block]) { //1.check whether memory is already allocated 
    dptr->data[block] = kmalloc(block_size , GFP_KERNEL); //2.allocate memory if its not allocated 
    if(!dptr->data[block] ) //3.check whether the memory allocation was successful 
         end the program ; 4.//exit if memory allocation fails 

Consider the case wherein processes A and B both try to access the driver . When both A and B arrives at the condition to check for memory allocation (line 1 ) , both predicts the memory to be not to be allocated and moves ahead executing the lines to follow allocating the memory .

The second process to allocate memory by executing kmalloc() wipes out the memory allocated by the first process . The second process gets the inconsistent view of the variable .

Such piece of code which is vulnerable for concurrency related bugs should be protected , such snippet of code is called as critical region of code . Critical region code should be protected from concurrent access , access to the critical region of code should be controlled and managed .

There are few rules following which the concurency related issues can be minimized and solved .Reduce the use of shared resources

  1. Hardware resources are shared and likewise many structures and variables too are accessible for any no.of.threads of execution , unless there is a strong reason its better not to make use of shared resoures ( like global variables ) .If there are no shared resources there wont be any concurrency issues , but sharing is often required and all varialbles in the driver by default is accessible all threads of execution .

  2. Use kernel’s locking primitives to manage and control access to critical region, if critical section of code is secured or prevented from multiple processes to execute simultaneously the issue can be solved .Kernel Provides different primitives to handle concurrency related issues since the triggering factor for all concurrency related issues are not same . Concurrency in the driver may be purely due to access from user space or code executed by asynchronous events like interrupt handling or kernel timer mechanisms . 

Ways of protecting critical section of code from concurrent access and kernel primitives and API’s that can be used in device drivers to protect the critical section of code will be discussed in the next post . Till then have great time coding ……….. 🙂

Simple CSS3 Transformations – transitions , translations and rotation

 W3C consortium was setup to standardize different browser interpreted languages , but different browser vendors wanted to provide support for experimental css3 features till they are standardized by W3C , such experimental and browser specific css3 features are to used with the prefix provided the vendor , -webkit-(chrome and safari),-o-(opera),-moz-(firefox),-ms-(IE), in the following code snippet i’ve just used -webkit- prefixes , so the code just works in Google chrome browser , to make it work in other browsers , just repeat the attributes with the vendor specific prefixes 


<!DOCTYPE html>
<title>First Transform </title>
h1 {
text-align : center ;
font-family : Futura ;

h1:hover {

-webkit-transition :6s all steps(6,end);
-webkit-transform : translateX(600px);
/* the header (h1 ) moves on X-axis (translates) 600px to the right , but the transition(webkit-transition) effect in place
makes sure that this transition takes place over a time of 6 seconds and 6 steps on mouse hover */
img.tilt:hover {
-webkit-transform : rotate(9.0deg); /*Rotates the image by 9 degrees on mouse hover and transition makes the effect take place smoothly over a period of 5 seconds */
-webkit-transition : 5s all;
<h1>CSS3 Testing</h1>
<p><img src = “deb.jpg” style= “width:300px;height:200px; margin: 0 2em 2em 0;”class=”tilt” >Hi , this is Debian , Debian is a free Operating system , the kernel used by debian is the kernel written Linux torwals .Debian is a free and universal operating system where everything , i repeat , everything in the operating system is free , the source for every binary in DEBIAN is available, All the softwares for debian comes packaged in .deb(.debian) files where these are hosted in their official repositories </p>


Intro to HTML 5 Geolocation :Find the locational data and getting it on the Map

HTML 5 brings in lot of powerful features along with it , one of such fascinating feature is the capability to code locational based applications using the `Geolocation and Goolge MAPS API’s `

In this post i’ll be briefing you folks on obtaining your locational reference in terms of latitude and longitude and using the same to get the MAP on the webpage centred around your current location

There are 3 parts to be coded to achieve the objective.The HTML5 code where the execution starts and links to the Java Script file and the CSS stylesheet

Here is the HTML5 code which is pretty much straigh forward

<!doctype html>
	<meta charset = "utf-8">
	<script src="http://maps.google.com/maps/api/js?sensor=true"></script> 
        <!-- To link to the google map API's -->
	<script src="loc.js"></script>          
	<link rel = "stylesheet" href="myLoc.css">
	<div id="Location">
		Here comes the location              <!-- Place Holder for the locational data -->
	<div id="map">				     <!-- Place holder for the Map -->	


The Java script part is the most important snippet to get this working , here goes the Java Script Code 😀

var map=null;

window.onload = getLocation ;

function showMap(coords) {
	var googleLatAndLong = new google.maps.LatLng(coords.latitude,coords.longitude);
	var mapOptions	= {
		zoom: 10, 
		center: googleLatAndLong ,
		mapTypeId: google.maps.MapTypeId.ROADMAP	
	};//The option object specifying the options for the map
	var mapDiv = document.getElementById("map");
	map = new google.maps.Map(mapDiv,mapOptions);//API which gets the map

function getLocation() {
	if(navigator.geolocation) {
//The API calls the display location function with position object containing the positional parameters
	else {
		alert("Doesnt support Geolocation");
function displayLocation(position) {
	var latitude = position.coords.latitude ; 
	var longitude = position.coords.longitude ;

	var div = document.getElementById("Location");
	div.innerHTML = "You are at latitude: " + latitude + " Longitude: " + longitude;
	//showMap function takes in the positional parameters and displays the map

Here the CSS code for the map id

div#map {
	margin: 5px;
	width: 400px;
	height: 400px;
	border: 1px solid black;

Writing A Simple WebServer using NODEJS

Well , we should consider ourselves lucky to be in this age of computing where a programmers job is made very easy with usage of modern languages . Writing a Web Server using C was and is a herculian task . With issues like limited buffer size , spawing threads or new processes to cater new clients and bulky system calls with complex structures to pass as parameters everthing has to be explicitly managed . One of the easiest way which i’ve found out to write webservers is by using NODEJS . Concurrency handling mechanisms are taken care of implicitly and programming becomes easy since Java Script is used .Here is a simple webserver written using NODEJS

var http=require('http'),
	url = require('url'),
	mime = require('mime'),//npm install mime
	fs = require('fs'),
http.createServer(function(req,res) { 
	 pathname = search_path + req.url;

	fs.stat(pathname , function(err,stats){
	  if(err) { 
		res.write('Bad Request , Request cannot be accepted');
	else if(stats.isFile()) {
		var type = mime.lookup(pathname);

		// 200 status - found , no errors 
		res.statusCode = 200;
		//create a readable stream and pipe to the http response 
		var file = fs.createReadStream(pathname);
		file.on("open",function() { 
		file.on("error",function(err) {
	else {
		res.write('Cannot Access Directory');
}).listen(8324);//listen to port 8324
console.log('Server running at 8324');

LIBUSB-1:Intro to LIBUSB , Writing and compiling the Hello World LIBUSB code in Ubuntu

Hello Friends ……..Recently a tiny bug in the Linux USB Device Driver had crashed my kernel , Its very common that bugs in the Device Drivers written brings down the system by crashing the kernel.The reason being that  unlike the usual programs we write Drivers run in kernel space.When programs run in user space and when we commit common programming snags like segmentation faults  or any invalid memory reference the kernel handles it to maintain the system stability , but in case of drivers which run in kernel space there is no one to monitor  since the kernel forms the core of the OS hierarchy .

Because of the above reasons its not safe to code in kernel space and better not unless there are no alternative ways to achieve the purpose.In driver writing , A simple unnoticed bug in a line of code could compromise the whole system.

Recently i came across a open source project by name LIBUSB . At first glance i assumed LIBUSB to be not so handy library to use and program with , but when i realized that using LIBUSB Linux USB Drivers can be written completely from user space i was amused to start using it to write USB Device Drivers under LINUX. 

What is LIBUSB ???

The official site  http://www.libusb.org/ quotes that “Libusb is a C library that gives applications easy access to USB devices on many different operating systems. libusb is an open source project, the code is licensed under the GNU LESSER GENERAL PUBLIC LICENSE or later.”

We’ll after realizing the importance of LIBUSB i was very curious on starting off with my first USB driver using LIBUSB libraries. So i installed LIBUSB libraries by issuing the following command on the terminal of my KUBUNTU machine

sudo apt-get install libusb-dev

we’ll the first of installing the LIBUSB library is over , now i wrote my HELLO WORLD libusb driver .

#include <stdio.h>
#include <stdlib.h>
#include <usb.h>
int main(){
    printf("Hello world!\n");
    return 0;

Writing the hello world LIBUSB program was a piece of cake , a trivial task 😀 But the smile didnt remain longer since i couldnt find a way to compile the code 😦

During compiling the code using gcc/g++ the LIBUSB library had to be linked by using -L option . But i couldnt find the libusb libraries under /usr/lib where usually all the libraries reside.All the online resources i  referred stated the libraries to reside in /usr/lib .

Later i found out that the path where LIBUSB libraries (.a) and headers and their names differ with few versions of LIBUSB . So the best way out was to search where the current LIBUSB package installed its headers and library.

Since Debain based distributions (ubuntu , kubnutu , MINT ) use .deb packages which gets installed using the `dpkg` mechanism , i tried the following command to know the list of directories used by the libusb-dev package

dpkg -L libusb-dev

Now focus on the last few lines of the output and find the path where the library libusb.a and the header file usb.h/libusb.h is installed.


Now make sure that you add the header name in the code and  , during compilation just add the parent directory of libusb.so along with the -L option of gcc/g++ .Also dont miss to add -lusb option during compilation.

gcc basiclusb.c -o basic -L/usr/lib/x86_64-linux-gnu/ -lusb


This succesfully compiles the Hello World LIBUSB code to give out the executable 😀 I hope this post would come pretty handy for those who want to start of with Writing USB device drivers in Linux using LIBUSB libraries.Catch u folks with more insights on wrting USB drivers under LINUX using LIBUSB in the posts to come 🙂




A simple Linux Driver : Allocating the Major Minor number

The first step in writing any Linux Device driver is to allocate a Major , Minor pair for the driver , this is a simple Linux Device Driver which allocates the Major , Minor pair and prints the same into DMESG

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/types.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>

static dev_t first;

static int __init my_init(void) /*constructor*/
    int ret;

    printk(KERN_INFO "Drivre is being registered");
    if((ret = alloc_chrdev_region(&first,0,3,"Rao")) < 0) /*dynamic allocatin of Major , minor numbers*/

        return ret;
    printk(KERN_INFO "<MAJOR , MINOR ><%d %d>\n" , MAJOR(first),MINOR(first)); /*printing the Major , Minor pair into the dmesg*/
    return 0;

static void __exit my_exit(void) /*destructor function , executed when the driver is removed*/


here is the MAKEFILE for the driver

# If called directly from the command line, invoke the kernel build system.

	KERNEL_SOURCE := /usr/src/linux-headers-$(shell uname -r)
	PWD := $(shell pwd)


# Otherwise KERNELRELEASE is defined; we've been invoked from the
# kernel build system and can use its language.

	obj-m := simple_driver.o