Tuesday, December 31, 2013

What is the first function loaded from the kernel?

The first function loaded in the kernel is start_kernel()

Find a value in an array in octave

As intuitive as octave is, the command is find. However, through the standard help spit out by octave it is not very apparent how we can search for a value.

Say we create an array of 10 values rounded off to have numbers between 1 to 10:
octave:27> x = floor(rand(1,10)*10)+1
x =
   7   3   3   4   6   7   6   4   2   6
Now, say we want to find if the array contains the value 3, we would do something like:
octave:28> m = find(x==3, 1)
m =  2
The output m = 2 tells us the index of the location and also the fact that this value is present. If we test for a non-existing value for something like say 10,
octave:29> m = find(x==10, 1)
m = [](1x0)

Sunday, December 29, 2013

Difference between interrupt context and process context

Process context: When the kernel is running code on behalf of some process, we refer to the kernel running in process context. The kernel could be running in process context because of executing a system call like read() or write().

Interrupt context: When the kernel is not running in process context, we say that it is running in interrupt context. The kernel runs in interrupt context because of either of these conditions:

  1. Actually receiving an interrupt on the IRQ line.
  2. Soft-IRQ
  3. Timer firing
Hence, the kernel can be running only in either one of the two.

Friday, December 27, 2013

How interrupt disabling works on Linux

In this post I am going to discuss how the Linux kernel API are used to disable interrupts on the platform. Let us look at an example.

I am going to discuss how an API like local_irq_disable() works on Linux. The definition of this API is in include/linux/irqflags.h. This eventually calls  raw_local_irq_disable() which calls arch_local_irq_disable().


The arch_local_irq_disable() function now has a definition based on the underlying architecture. For example the definition for different architectures would be like:

include/asm-generic/irqflags.h, line52
arch/microblaze/include/asm/irqflags.h, line 28
arch/h8300/include/asm/irqflags.h, line 11
arch/cris/include/arch-v10/arch/irqflags.h, line 13
arch/cris/include/arch-v32/arch/irqflags.h, line 14
arch/powerpc/include/asm/hw_irq.h, line 55


If we consider the powerpc architecture, eventually all that the function does is run assembly code that writes to registers on the platform to disable interrupts on the platform.


55 static inline unsigned long arch_local_irq_disable(void)
56 {
57 unsigned long flags, zero;
58
59 asm volatile(
60 "li %1,0; lbz %0,%2(13); stb %1,%2(13)"
61 : "=r" (flags), "=&r" (zero)
62 : "i" (offsetof(struct paca_struct, soft_enabled))
63 : "memory");
64
 65 return flags;
66 }

Monday, December 23, 2013

Octave file exchange

Using this page as a place holder to track any pages which talk about octave open code discussions.

1. Octave forge: http://octave.sourceforge.net/packages.php
2. Stack overflow http://stackoverflow.com/questions/tagged/octave

Thursday, December 19, 2013

Comparison between kprobes, kretprobes and jprobes

kprobes are the basic structure which are used for debugging. 

kretprobes and jprobes are the two structures which work as wrappers around the kprobes structure providing additional information.

Structure of jprobes is as follows:
struct jprobe {
        struct kprobe kp;
        void *entry;    /* probe handling code to jump to */
};

Jprobes allow you to register a function at the *entry pointer which has the same arguments as jprobe.kp.addr = <func add looked up from kallsyms> or jprobe.kp.symbol_name=<func name> for example jprobe.kp.symbol_name = do_fork.
Jprobes are useful in finding out if the arguments passed to the function we are interested in inspecting are correct?

kretprobes on the other hand are a wrapper around kprobes that allow us to register a function handler that is invoked when the function we are interested in returns.
184 struct kretprobe {
185 struct kprobe kp;
186 kretprobe_handler_t handler;
187 kretprobe_handler_t entry_handler;
188 int maxactive;
189 int nmissed;
190 size_t data_size;
191 struct hlist_head free_instances;
192 raw_spinlock_t lock;
193 };

Linux: Example of per CPU variables

In any kernel module that you are building, try this out. Depending on which core the function is invoked from, different variables will get incremented, changing the prints.

#include <linux/percpu.h>
DEFINE_PER_CPU(int, mypcint);
int test_percpu(void);
/* Increments the counter only on the current valid CPU */
int test_percpu()
{
    int i;
    per_cpu(mypcint, smp_processor_id()) = 0;
    per_cpu(mypcint, smp_processor_id())++;
    printk("%s(%d):===================================== \n", __FUNCTION__, __LINE__);
    for (i = 0; i <2; i++)
        printk("CPU %d | mycpint: %d ", i, per_cpu(mypcint, i));
    return 0;
}
This example can be invoked from any kernel module.

Wednesday, December 18, 2013

What is phy restart? Why is it important in dense RF environments?

Phy restart on radio drivers typically means if the hardware (radio) is able to sync to the preamble of a packet which has a stronger signal strength while it is already in the process of decoding a packet.

This is typically useful in noisy environments to achieve a "capture effect", where the stronger packet is finally decoded at the rx. radio. If the radio does not support PHY restart then typically such a reception would result in a collision on the rx-side at the radio.

Wednesday, November 6, 2013

Solution: must be owned by root and not group or world-writable

I started debugging this problem when I saw a connection refused for ssh.

This is the error that can be seen when you typically see that ssh is dead or some other service is dead and you are not able to remotely connect to your machine.

[root@ZZZZZZ~]# service sshd restart
Stopping sshd:                                             [FAILED]
Starting sshd: /var/empty/sshd must be owned by root and not group or world-writable.   [FAILED]

The solution to this problem is simple. You somehow mucked up the permissions on /var/empty. I fixed my problem by:
# sudo su
# chmod 750 -R /var
# service sshd restart

Solution for gcc makefile error: “No rule to make target”

This error happens when the file needed to make the target is not available.
"No rule to make target ttt.cpp', needed by tttp-ck.o'. Stop."
That's usually because you don't have a file called ttt.cpp available to make. Check that file exists and you are in the right path while running make.
This error can also take the form where it complains:
"No rule to make target ttt.o', needed by tttp-ck.o'. Stop."
In this case check the files needed to build ttt.o, they may be missing.
I migrated from one machine to the other, and I was facing the problem because perforce failed to checkout the file I needed on the new machine.

Quick tutorial: Debug segmentation faults with GDB

1. When you see a segmentation fault (segfault), the first thing you need to debug it is the ability to generate a core file. What is a core file? A core file is an image of a process that has crashed It contains all process information pertinent to debugging: contents of hardware registers, process status, and process data. Gdb will allow you use this file to determine where your program crashed. To ensure that you can generate a core, run the following command (if you are using bash):
ulimit -c unlimited
if using (tcsh):
limit coredumpsize unlimited
2. Once this is done, run the program again (which shows the segmentation fault). After the binary is run and it crashes, you should see a file with the name core.XXXX  in the same directory. Here XXXX is some number.

3. Read the core file using GDB. All you need to do now is run GDB with the program and the core file as gdb program core. So an example would be as shown below:
gdb path/to/the/binary path/to/the/core

4. Finally you can run the GDB backtrace command (bt) in the GDB shell to see the exact location where the program crashed. In the backtrace, each function call is assigned a  different number. These frame numbers can be used to select a particular stack frame. You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.






Thursday, August 29, 2013

Why tesla motors uses AC induction motor instead of a DC motor?

DC motors are conventionally known to provide higher torque making them an obvious choice for electric automobiles. However, they are not used in pure electrics (as opposed to hybrids) for a certain reason.

Conventional DC motors are not used due to their maintenance problems with the brush and commutator mechanism. Instead brushless DC motors are used. Came across this comparison on the tesla blog saying why AC motors are preferred over brushless DC. The main reason is the ability to control the magnetic field B which is proportional to V/f as opposed to using a static magnetic field in the stator in brushless DC and the other aspect is cheapness (lack of a permanent magnet in the rotor of a AC motor as opposed to brushless DC).

Excerpt from this blog:
Both DC brushless and induction drives use motors having similar stators. Both drives use 3-phase modulating inverters. The only differences are the rotors and the inverter controls. And with digital controllers, the only control differences are with control code. (DC brushless drives require an absolute position sensor, while induction drives require only a speed sensor; these differences are relatively small.)
One of the main differences is that much less rotor heat is generated with the DC brushless drive. Rotor cooling is easier and peak point efficiency is generally higher for this drive. The DC brushless drive can also operate at unity power factor, whereas the best power factor for the induction drive is about 85 percent. This means that the peak point energy efficiency for a DC brushless drive will typically be a few percentage points higher than for an induction drive.

Friday, June 21, 2013

Difference between single and multiple protection settings in the duration ID

A single protection setting is used to protect the transmission until the end of any following data management or response frame. In multiple protection setting the NAV protects until the estimated end of multiple sequence of frames.

Why are agricultural economies mostly patriachal?

These are just my 2 cents and may not match with everyone's reasoning. I am not saying things are right or wrong either way.

Human species came about 2.5million years ago, and they mostly did hunting and gathering. Males would hunt and females would gather seeds and grains. Thus woman had an important role in the economy and in general in the household.

Patriachal society is a society where the males play the main role. They are the opposite of a matriachal society.

Agriculture began around 9000BCE. Required the community to stay at one place. Required individuals to work on the fields. Needed more workers, so the focus was on reproduction. Hence the females in the family would bear children while the men the did the work of generating the bread. This lead to a developing of more patriachal society within agricultural economies.


Sunday, June 9, 2013

Properly format java floating points or double while displaying

The question being addressed here is how to print these doubles or floats nicely in Java?
String.format("%f", value) works in most cases, but there will be a lot of trailing zeros for small values.

Here's an example output of of %f
55.00000000
0.18000000000
1237875192.0
4.58900000000
0.00000000
1.23450000

Instead, the desired output is:
232
0.18
1237875192
4.589
0
1.2345

Here is the piece of code that can do this efficiently and correctly:

public static String fmtDouble(double inp){    if(inp == (int)inp)        return String.format("%d",(int)inp);    else        return String.format("%s",inp);}
Also this mechanism does not require any separate string manipulation. This solution is based on a code snippet I read somewhere.

Sunday, June 2, 2013

C++ No new line at end of file

This happened when I was moving a project from Microsoft visual studio to a linux machine.

When I ran g++ or even gcc for that matter, I got a bunch of errors:
In file included from Game.cpp:13:
treasure.h:22:7: warning: no newline at end of file
item.cpp:17:2: warning: no newline at end of file
player.cpp:66:2: warning: no newline at end of file
In file included from potion.cpp:5:
potion.h:17:7: warning: no newline at end of file
potion.cpp:21:2: warning: no newline at end of file
The reason for this problem is the studio editor did not seem to insert a new line at the end of the file and older c++ compilers require this line to delimit where the header file ends when including it.

I got around this problem by:
[test_comp53]$ for f in *.cpp; do echo "" >> $f; done
[test_comp53]$ for f in *.h; do echo "" >> $f; done

Saturday, June 1, 2013

How to use vim to substitute from current line

Most folks use the command
:%s/SEARCHSTRING/REPLACESTRING/gc
to search for the string SEARCHSTRING and replace it with REPLACESTRING. However, the problem with this command is that it starts from the beginning of the file and replaces right through. How do we do this if we do not want to start from the beginning of the file, but only from the current line to the end of file.
Replace the %, which is short hand for 1,$ meaning the entire file. To go from the current line to the end you use .,$. The period means current line and $ means the last line. So the command would be:
:.,$s/SEARCHSTRING/REPLACESTRING/gc
But the . or current line can be assumed therefore can be removed:
:,$s/SEARCHSTRING/REPLACESTRING/gc
For more help see
:h range

Monday, May 27, 2013

How to use IS_ERR and PTR_ERR? What do they mean?

From the kernel definition there are three macros: 
IS_ERR - used to check,
- Returns non-0 value if the ptr is an error. Otherwise 0 if it's not an error
PTR_ERR - used to print.
- Current value of the pointer.
Used as follows- if ptr is the pointer you want to check then use it as follows:
if (IS_ERR(ptr))
     printk("Error here: %ld", PTR_ERR(ptr));
Code definitions:

#define IS_ERR_VALUE(x) unlikely((x) >= (unsigned long)-MAX_ERRNO)

static inline void * __must_check ERR_PTR(long error)
{
    return (void *) error;
}

static inline long __must_check PTR_ERR(const void *ptr)
{
    return (long) ptr;
}

static inline long __must_check IS_ERR(const void *ptr)
{
    return IS_ERR_VALUE((unsigned long)ptr);
}

static inline long __must_check IS_ERR_OR_NULL(const void *ptr)
{
    return !ptr || IS_ERR_VALUE((unsigned long)ptr);
}

Sunday, April 28, 2013

Difference between a Markov model and Hidden Markov Model


* In a markov model, the states are known and the output of each state is deterministic.


* In a hidden markov model, the states are unobservable. Also, the output from each state is not deterministic, rather it is probabilistic. Hence a HMM is also referred to as a double embedded stochastic process with two levels. Different markov states will have different markov observation probabilistic functions.




Monday, April 22, 2013

Feynman lectures in physics: Ch1 - Atoms in motion

I am reading this lecture series and putting together a summary of the information in there. This is my own interpretation and a few things could be amiss. Please use your own judgement.


  • Experiment is the sole judge of scienti c truth
  • Mass increases appreciably as velocity nears speed of light. Mass is not always constant.
  • Water has two atoms of hydrogen and one atom of oxygen forming a molecule.
  • Intermolecular forces keep the substance together. When you heat something the distance between molecules increases.
  • Force = pressures area
  • Volume of ice (and some type metals) decreases when melted (unlike most substances) to water because the crystaline structure in ice has a lot of "holes decreasing the packing density.
  • Why does a liquid cool as it evaporates: Molecues that had max energy leave the liquid during evaporation, so the ones left are the ones with lesser energy. Hence you blow on the soup to cool it.
  • Ion is an atom which has few extra electrons (than protons) of few electrons less.
  • Molecules exists only for certain substances. No molecules in salt, but there are molecules in water.
  • Why burning generates heat and light: Carbon attracts oxygen a lot causinga snapping together of atoms, generating kinetic energy. Ordinarily seen in molecular motion of hot gas, but sometimes too much energy is also seen in the form of light (flames).
  • Organic chemistry is useful to discover arrangement of atoms by mixing substances and checking color for example.

Sunday, April 21, 2013

Does blowing air on a spoon of hot soup cool it?

As explained by Fenyman way back in 1960s, blowing acually speeds up evaporation from the surface of a hot liquid, causing molecules with more energy to leave the liquid and not return back. This decreases overall energy (and heat) in the liquid.

Beware this may reduce the overall soup you drink though :)

Tuesday, April 16, 2013

When to use skb_clone versus skb_copy

Using skb_copy will copy both the sk_buff and the packet to new memory. Meaning when the kernel frees the other one, the copy will not be affected.
skb_clone in the other hand copies the sk_buff structure to new memory, but not the packet. Meaning when the old one is freed, your copy will have the packet also freed.

In most cases please try to use skb_clone() as it will save your system the additional overhead of copying an entire packet. This may not seem like much but under heavy loads this can severely affect performance and even lead to soft-lockups.

Wednesday, April 10, 2013

When to use strlcpy and strncpy (strlcat and strcat)


  • Found a large number of overflows due to unbounded string copies using sprintf(), strcpy() and strcat(), as well as loops that manipulated strings without an explicit length check in the loop invariant.
  • The most common misconception is that strncpy() NUL-terminates the destination string. This is only true, however, if length of the source string is less than the size parameter.  The safest way to use strncpy() in this situation is to pass it one less than the size of the destination string, and then terminate the string by hand.
  • Both strlcpy() and strlcat() guarantee to NUL-terminate the destination string for all strings where the given size is non-zero. 
  • Both functions take the full size of the destination string as a size parameter

Locking in Linux SMP - When to use what?


  • For kernels compiled without CONFIG_SMP, and without CONFIG_PREEMPT spinlocks do not exist at all.
  • If the kernel is compiled without CONFIG_SMP, but CONFIG_PREEMPT is set, then spinlocks simply disable preemption, which is sufficient to prevent any races.
  • Remember the advice above: you can always use spin_lock_irqsave(), which is a superset of all other spinlock primitives.

Monday, April 8, 2013

Internet works directly through modem but not on wireless router

- The problem is likely with the fact that your modem is keeping a cached MAC address of the laptop that you used to test your connection.
- Solution1: Disconnect all cables on the modem (including the coax) and let it stay for a minute. This allows the modem to completely discharge irrespective of a bad bleeder resistor.
- Solution2: Check  if your modem has a reset button. If it does keep it pressed when the modem is powered on for at least 20secs and then reconnect the wireless router once the modem is up.

Monday, April 1, 2013

Hybrid power save in 802.11 (difference from UAPSD)


Do both legacy power save and WMM power save. This allows some classes of traffic to be trigger enabled and some other classes to be supported by legacy PS. This could possibly allow the client to make its PS scheme more effective. E.g. consider this it could tell the AP to make VO traffic trigger enabled and the rest supported by legacy. So when it is critical, the client always sends trigger for VO class and gets appropriate frames. When the client sees TIM bit set and decides it can take some other traffic, it sends PS-POLL to which the AP appropriately responds with highest priority of non-trigger enabled WMM class frames.

Note that in response to the PS-POLL the AP should only send non-trigger enabled classes of traffic to the client.

Saturday, March 30, 2013

Check enabled compile time flags (hack)


A quick hack to check all the enabled compile time flags.

make -C  /that/dir V=1

This makes verbose, if everything is built, you will not see the flag.

Just touch one of the file in /that/dir and try it out. 

Sunday, March 24, 2013

Lowering resting heart rate

Heard about this in an interesting TED talk. The average heart beats 2.5 Billion times in a life time. 80beats per min, 79 years of average age. The theory is that if you do cardio which elevates your heart rate for sometime, your resting heart rate goes down. Thus giving you a longer life time to expend your 2.5Billion heart beats. If you lower your heart rate by a few beats, you will get a few extra years!!

Saturday, March 16, 2013

What is function cloning? Name.clone.XX seen in crash or symbols?


In the case of the gcc compiler, it make a copy of a function with some modifications for faster execution.For example, if the compiler discovers that a function is called many different times with the same couple of initial parameters, then it may clone the function to produce a version which takes fewer parameters, and then change all the invoking functions to call the cloned function named as fn-name.clone instead.

Also found this from another post:
"Another example is that a compiler may make several clones of a function and compile them tuned for different microarchitectures, and then arrange for the appropriate one to be used at runtime based on some sort of CPU test."

Sunday, February 24, 2013

Steve Jobs's Innovation Secrets

Carmine Gallo, in one of his secrets books “The Innovation Secrets of Steve Jobs,” outlines Jobs “insanely different principles for breakthrough success.” 



  • Do what you love. Think differently about your career. Steve Jobs followed his heart his entire life and that, he said, made all the difference. Innovation cannot occur in the absence of passion and, without it, you have little hope of creating breakthrough ideas.
  • Put a dent in the Universe. Think differently about your vision. Jobs attracted like-minded people who shared his vision and who helped turn his ideas into world-changing innovations. Passion fueled Apple’s rocket and Jobs’ vision created the destination.
  • Kick start your brain. Think differently about how you think. Innovation does not exist without creativity, and for Steve Jobs, creativity was the act of connecting things. Jobs believed that a broad set of experiences broadened the understanding of the human experience.
  • Sell dreams, not products. Think differently about your customers. To Jobs, people who bought Apple products were never “consumers.” They were people with dreams, hopes, and ambitions. Jobs built products to help them fulfill their dreams.
  • Say no to 1,000 things. Think differently about design. Simplicity is the ultimate sophistication, according to Jobs. From the designs of the iPod to the iPhone, from the packaging of the Apple’s products to the functionality of the Apple Web site, innovation means eliminating the unnecessary so that the necessary may speak.
  • Create insanely great experiences. Think differently about your brand experience. Jobs made Apple stores the gold standard in customer service. The Apple store has become the world’s best retailer by introducing simple innovations any business can adopt to make deep, lasting emotional connections with their customers.
  • Master the message. Think differently about your story. Jobs was a great corporate storyteller, turning product launches into an art form. You can have the most innovative idea in the world, but if you cannot get people excited about it, it doesn’t matter.
  • Tuesday, January 1, 2013

    Average age for mothers across countries

    The general correlation seems to be that the more developed the country the later women are becoming first time mothers.
    Average age for first time mothers across countries

    Nerd jokes: Scientist Physicist and Mathematician

    Questioner: "Approximate n + n^2"

    Physicist: "n"
    Computer Scientist: "n^2"
    Mathematician: "Explain what you mean by 'approximate'"