Wednesday, 14 January 2015

Device tree with beaglebone black

I want to interface bmp085 with beaglebone black at i2c1(pin17 and pin18)
So made following changes
-I made changes in /ksrc/arch/arm/boot/dts/am335x-bone-common.dtsi

i2c0_pins:pinmux_i2c0_pins{
         pinctrl-single,pins=<
          0x188 0x70 /*i2c0_sda, SLEWCTRL_SLOW | INPUT_PULLUP | MODE0 */
          0x18c 0x70 /* i2c0_scl, SLEWCTRL_SLOW | INPUT_PULLUP | MODE0*/
          >;
};
/*changed by jaikothari10@gmail.com*/
i2c1_pins:pinmux_i2c1_pins{
         pinctrl-single,pins=<
             0x158 0x72 /* (PIN_INPUT_PULLUP | MUX_MODE2) */
             0x15c 0x72 /* (PIN_INPUT_PULLUP | MUX_MODE2) */
             >;
};
/******************************/
i2c2_pins: pinmux_i2c2_pins {
pinctrl-single,pins = <
        0x178 0x73 /*uart1_ctsn,i2c2_sda,SLEWSTRL_SLOW | INPUT_PULLUP | MODE3*/
        0x17c 0x73 /*uart1_rtsn,i2c2_scl,SLEWCTRL_SLOW | INPUT_PULLUP | MODE3 */
       >;
};

Now look at binding document of bmp085 module. (ksrc/Document/devicetree/bindings/misc/bmp085.txt and then make change

/********added by jaikothari10@gmail.com********/
&i2c1 {
   pinctrl-names="default";
  pinctrl-0= <&i2c1_pins>;

  status = "okay"
  clock-frequency=<100000>;
  pressure@77{                                  /*client module for i2c */
              compatible="bosch,bmp085";
              reg=,0x77>;
             chip-id=<10>;
             temp-measurement-period = <100>;
             default-sampling = <2>;
 };

Now look at file am33xx.dtsi file (This is master /ksrc/drivers/i2c/buses)
i2c1:i2c@4802a000 {
 compatible="ti,omap4-i2c";
  #address-cells=<1>;
  #size-cell=<0>;
 ti,hwmods="i2c2",
 reg=<04802a000 0x1000>;
 status= "disable";
};

After doing the following steps I compiled the dts file to dtb by dtc (device tree compiler)

$dtc -O dtb -o am335-boneblack.dtb am335x-boneblack.dts

After compile put the dtb file in /boot of BBB rootfs

Then Reboot BBB

Now you will find the /dev/i2c1 entry. Also your bmp085 module would be loaded automatically.

Amazing!!!!!!! Keep smiling :)

For device tree information you can refrer device tree documentation in kernel.More refreances I would add latter.
You can even post comment to this blog if any query?


BeagleBone Black startup

This post is just to list some example initial things to do with the BBB, to prepare it for development. Others may have different suggestions to suit various working methods. The official getting started page is here.

Powering up the board for the first time

(Instructions here are Windows based, but the official page has instructions for Linux and MAC too; For Linux, no drivers are needed but they suggest using this script):
  1. Plug in the USB, let it boot up. Some drivers will not install (CDC Serial and RNDIS)
  2. Download BONE_D64.exe for Win 7 64-bit and run it. It will prompt a few times. Now all drivers will be installed.
  3. In a Windows command prompt, ipconfig /all will reveal a "Linux USB Ethernet/RNDIS Gadget" interface has been created on the PC with IP address 192.168.7.1; the BBB IP address will be 192.168.7.2
  4. It is now possible to use a web browser to navigate to http://192.168.7.2.

Using a serial cable

The J1 row of pins on the BBB allows connection to a PC for serial comms.
This is a small hardware mod to use a powered USB-serial adapter:
Solder a red wire from J1 pin 2 to P9 pin 4
The communications pins and direction of data is:
Beagleboard J1 pin 4 <---------------PC
Beagleboard J1 pin 5---------------->PC
J1 pin 1 is 0V.

Information on various serial cables is here. Connecting up a FTDI TTL-232RG-VIP-WE cable (these colors were different to the ones on that page):
Pin on J1    Color
1            Black
2            Red
4            Orange
5            Yellow

Plug in the FTDI cable into the PC. (On Window 7 64-bit; the driver will install automatically after a while - no need to download any driver.
Check the port number in Device Manager).
Start up serial terminal software on your PC, set to 115200 baud, no DTR/DSR/RTS/CTS/XON/XOFF
Power up board and observe it booting up; after around 10 sec it will be at the login prompt
Login as root (there is no password)

Updating the software

The getting started page has this detail and it works well. It requires a microSD card and a way to program it from a PC (e.g. a small SD to MicroSD adapter if your PC has an SD card slot). It takes almost exactly 45 minutes for the flash to be programmed on the board.

Setting the date

Check the date by typing date
Set the date, e.g. date -s "May 21 22:49 UTC 2013" (you may wish view http://www.timeanddate.com/worldclock/ )

Using SSH

From the PC, it may be possible to SSH to 192.168.7.2 (username is root, no password)
If it is not possible on a new board (like my board) then this was the fix:
  1. Connect via the USB-Serial adapter
  2. /etc/init.d/dropbear stop (dropbear is the name of the SSH server software)
  3. cd /etc/dropbear/
  4. There will be a file in this folder
  5. rm dropbear_rsa_host_key
  6. /etc/init.d/dropbear start
  7. The dropbear_rsa_host_key will be recreated, and this time will be a few hundred bytes in size
  8. Now the SSH should work

Powering down the board

At the shell prompt, issue shutdown now to power down the board; otherwise you risk file system corruption.
There is a power button on the board, that  could issue this for an automatic shutdown if someone writes the code (the button is described in  the BBB SRM doc that can be found here).

Some shell and vi changes

To have a better shell:
vi /etc/passwd

edit the first line (the root user line) to say /bin/bash instead of /bin/sh
Then, issue a reboot command.

vi
For me, the vi on the BBB behaved slightly different, but enough to make it uncomfortable for long use. I made these changes to suit personal tastes:
Make tabs equal to 2 columns instead of 8:
  1. Go to /usr/share/vim and edit the vimrc file there
  2. At the end of the file, add a new line with this content (including the colon):
:set ts=2

Disable the incsearch if you want traditional vi search behaviour (Otherwise, get used to pressing enter after a search):
Search for incsearch, and comment it out with a speech-mark at the beginning (i.e. " )
Disable the autoindent:
Search for autoindent and comment it out and comment out the else line above it too
Also, search for filetype plugin indent on and comment that line out too.

Setting the console width:
stty cols 100

Mounting file systems

Unusually the busybox version of mount is needed. Basically, this command worked:
cd mnt
mkdir shared
chmod 777 shared
busybox mount -o port=2049,nolock,proto=tcp -t nfs 192.xxx.xxx.xxx:/volume1/public /mnt/shared



Refreace:http://www.element14.com/community/community/designcenter/single-board-computers/next-gen_beaglebone/blog/2013/05/22/some-quick-start-things-to-do-for-developing-on-the-bbb

Sunday, 4 January 2015

I2c Learning

https://www.kernel.org/doc/htmldocs/device-drivers/i2c.html

http://pete.akeo.ie/2011/08/writing-linux-device-driver-for-kernels.html#uds-search-results



Writing I2C Bus driver
-I2c was developed by Philips
-System management Bus(SMBus) is based on this protocol
-I2c has two line bus.One is Serial Data Line(SDL) and other is Serial Clock Line(SCL).
-Pull up resister are requied in SDL and SCL because pin in the chip can only put the line low or other wise the are floating VDD.
-In I2C mechanism, all the devices are considered as node connected to same medium.
-If a node wants to transmit some data, it can determine whether any other node is transmitting data by letting the pull up resistor to make the logical line to1 and monitor the line state.If any nodes pulls the line to 0, then other nodes can detect that some node is transmitting data.
-I2C protocol supports 10 bit addressing but most of the devices supports only 7 bit addressing (slave addresses). So a maximum of 127 devices can connect on a single bus.
Speed
Standard mode : 100 kbps
Fast mode : 400 kbps
 

More about I2C

  1. Every device connected to I2C lines has a unique address.
  2. Master-slave relationship exist between device and the chip.
  3. Master can be either transmitter or receivers.
  4. I2C is a multi-master bus which has collision detection and mechanisms to prevent data corruption when 2 or more master initiates data transfer at same time. 
  5. It is an 8 bit serial bus which bidirectional data transfer is possible.
Many number of devices can be connected to the same bus.                                        We can just try to see how we can configure I2C adapter, bus driver etc.            

Terminology
===========

When we talk about I2C, we use the following terms:
  Bus    -> Algorithm
            Adapter
  Device -> Driver
            Client


-An Algorithm driver contains general code that can be used for a whole class
of I2C adapters. Each specific adapter driver either depends on one algorithm
driver, or includes its own implementation

-A Driver driver (yes, this sounds ridiculous, sorry) contains the general
code to access some type of device. Each detected device gets its own
data in the Client structure. Usually, Driver and Client are more closely
integrated than Algorithm and Adapter.

-A Driver driver (yes, this sounds ridiculous, sorry) contains the general
code to access some type of device. Each detected device gets its own
data in the Client structure. Usually, Driver and Client are more closely
integrated than Algorithm and Adapter.

-At this time, Linux only operates I2C (or SMBus) in master mode; you can't
use these APIs to make a Linux system behave as a slave/device, either to
speak a custom protocol or to emulate some other device.

                                                                                                                    
Writing an I2C Driver
struct i2c_driver {
  unsigned int class;
  int (* attach_adapter) (struct i2c_adapter *);
  int (* probe) (struct i2c_client *, const struct i2c_device_id *);
  int (* remove) (struct i2c_client *);
  void (* shutdown) (struct i2c_client *);                               /* optional */
  int (* suspend) (struct i2c_client *, pm_message_t mesg);             /* optional */
 int (* resume) (struct i2c_client *);                                   /* optional */
  void (* alert) (struct i2c_client *, unsigned int data);
  int (* command) (struct i2c_client *client, unsigned int cmd, void *arg);/* optional deprecated */
  struct device_driver driver;
  const struct i2c_device_id * id_table;
  int (* detect) (struct i2c_client *, struct i2c_board_info *);
  const unsigned short * address_list;
  struct list_head clients;
};
 
struct i2c_client {
  unsigned short flags;
  unsigned short addr;
  char name[I2C_NAME_SIZE];
  struct i2c_adapter * adapter;
  struct device dev;
  int irq;
  struct list_head detected;
  i2c_slave_cb_t slave_cb;
}; 
 
-you will implement a single driver structure, and instantiate all clients from it.  
-a driver structure contains general access routines, and should be zero-initialized except for fields with data you provide.
-A client structure holds device-specific information like the driver model device node, and its I2C address.
-In driver strucure,Name field should match the module name.  If the driver name doesn't match the module name, the module won't be automatically loaded (hotplug/coldplug).


Accessing the client
====================
-To write/read information to client

-I have found it useful to define foo_read and foo_write functions for this.
For some cases, it will be easier to call the i2c functions directly,
but many chips have some kind of register-value idea that can easily
be encapsulated.
 

The below functions are simple examples, and should not be copied
literally. 

 int foo_read_value(struct i2c_client *client, u8 reg)
{
        if (reg < 0x10) /* byte-sized register */
                return i2c_smbus_read_byte_data(client, reg);
        else            /* word-sized register */
                return i2c_smbus_read_word_data(client, reg);
}

int foo_write_value(struct i2c_client *client, u8 reg, u16 value)
{
        if (reg == 0x10)        /* Impossible to write - driver error! */
                return -EINVAL;
        else if (reg < 0x10)    /* byte-sized register */
                return i2c_smbus_write_byte_data(client, reg, value);
        else                    /* word-sized register */
                return i2c_smbus_write_word_data(client, reg, value);
}
 


Device/Driver Binding
---------------------
-System infrastructure , typically  board-specific initialization code or boot firmware, reports what I2C devices exist.  For example, there may be a table, in the kernel or from the boot loader, identifying I2C devices and linking them to board-specific configuration information about IRQs and other wiring artifacts, chip type, and so on.

 That could be used to create i2c_client objects(device file) for each I2C device.

-I2C device drivers using this binding model work just like any other
kind of driver in Linux:  they provide a probe() method to bind to
those devices, and a remove() method to unbind.

        static int foo_probe(struct i2c_client *client,
                             const struct i2c_device_id *id);//for binding
        static int foo_remove(struct i2c_client *client);//for unbinding



-Remember that the i2c_driver does not create those client handles.  The handle may be used during foo_probe().  If foo_probe() reports success (zero not a negative status code) it may save the handle and use it until foo_remove() returns.
 

-The probe function is called when an entry in the id_table name field
matches the device's name. It is passed the entry that was matched so
the driver knows which one in the table matched.


Device Creation
---------------
-If you know for a fact that an I2C device is connected to a given I2C bus, you can instantiate that device by simply filling an i2c_board_info structure with the device address and driver name, and calling i2c_new_device(). This will create device.

-Then the driver core will take care of finding the right driver and will call its probe() method.
-If a driver supports different device types, you can specify the type you want using the type field.  You can also specify an IRQ and platform data if needed.
-Sometimes you know that a device is connected to a given I2C bus, but you don't know the exact address it uses.
-Sometimes you know that a device is connected to a given I2C bus, but you
don't know the exact address it uses.

- In that case, you can use the i2c_new_probed_device() variant, which is
similar to i2c_new_device(), except that it takes an additional list of
possible I2C addresses to probe.

-The call to i2c_new_device() or i2c_new_probed_device() typically happens
in the I2C bus driver.




Device Detection
----------------





Device Deletion
---------------

-Each I2C device which has been created using i2c_new_device() or i2c_new_probed_device() can be unregistered by calling i2c_unregister_device(). 
- If you don't call it explicitly, it will be called automatically before the underlying I2C bus itself is removed, as a device can't survive its parent in the device driver model.

Initializing the driver
=======================
static int __init foo_init(void)
{
        return i2c_add_driver(&foo_driver);
}

static void __exit foo_cleanup(void)
{
        i2c_del_driver(&foo_driver);
}

/* Substitute your own name and email address */
MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>"
MODULE_DESCRIPTION("Driver for Barf Inc. Foo I2C devices");

/* a few non-GPL license types are also allowed */
MODULE_LICENSE("GPL");

module_init(foo_init);
module_exit(foo_cleanup);
-Note that some functions are marked by `__init'.  These functions can be removed after kernel booting (or module loading) is completed. Likewise, functions marked by `__exit' are dropped by the compiler when the code is built into the kernel, as they would never be called.



Power Management
================
-activating a system wakeup mechanism -- do that in the suspend() method.
The resume() method should reverse what the suspend() method does.




System Shutdown
===============

If your I2C device needs special handling when the system shuts down
or reboots (including kexec) -- like turning something off -- use a
shutdown() method.

Again, this is a standard driver model call, working just like it
would for any other driver stack:  the calls can sleep, and can use
I2C messaging.

Command function
================

A generic ioctl-like function call back is supported. You will seldom
need this, and its use is deprecated anyway, so newer design should not
use it.


Sending and receiving
=====================

If you want to communicate with your device, there are several functions
to do this. You can find all of them in <linux/i2c.h>.

If you can choose between plain I2C communication and SMBus level
communication, please use the latter. All adapters understand SMBus level
commands, but only some of them understand plain I2C!



Documentation of I2C (user space):(ref dev-interface)

- i2c devices are controlled by a kernel driver. But it is also possible to access all devices on an adapter from userspace, through the /dev interface.
-Each registered i2c adapter gets a number, counting from 0.
-You can examine /sys/class/i2c-dev/ to see what number corresponds to which adapter.
-Alternatively, you can run "i2cdetect -l" to obtain a formated list of all
i2c adapters present on your system at a given time.

-I2C device files are character device files with major device number 89
and a minor device number corresponding to the number assigned as
explained above.


C example
=========
-So let's say you want to access an i2c adapter from a C program

-The first thing to do is "#include <linux/i2c-dev.h>".

-Please note that there are two files named "i2c-dev.h" out there, one is distributed
with the Linux kernel and is meant to be included from kernel driver code, the other one is distributed with i2c-tools and is meant to be included from user-space programs. You obviously want the second one here 


-Next thing, open the device file, as follows:

  int file;
  int adapter_nr = 2; /* probably dynamically determined */
  char filename[20];

  snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
  file = open(filename, O_RDWR);
  if (file < 0) {
    /* ERROR HANDLING; you can check errno to see what went wrong */
    exit(1);
  }

-When you have opened the device, you must specify with what device
address you want to communicate:

  int addr = 0x40; /* The I2C address */

  if (ioctl(file, I2C_SLAVE, addr) < 0) {
    /* ERROR HANDLING; you can check errno to see what went wrong */
    exit(1);
  }

-Well, you are all set up now. You can now use SMBus commands or plain I2C to communicate with your device. SMBus commands are preferred if the device supports them. Both are illustrated below.


 __u8 register = 0x10; /* Device register to access */
  __s32 res;
  char buf[10];

  /* Using SMBus commands */
  res = i2c_smbus_read_word_data(file, register);
  if (res < 0) {
    /* ERROR HANDLING: i2c transaction failed */
  } else {
    /* res contains the read word */
  }

  /* Using I2C Write, equivalent of
     i2c_smbus_write_word_data(file, register, 0x6543) */
  buf[0] = register;
  buf[1] = 0x43;
  buf[2] = 0x65;
  if (write(file, buf, 3) ! =3) {
    /* ERROR HANDLING: i2c transaction failed */
  }

  /* Using I2C Read, equivalent of i2c_smbus_read_byte(file) */
  if (read(file, buf, 1) != 1) {
    /* ERROR HANDLING: i2c transaction failed */
  } else {
    /* buf[0] contains the read byte */
  }
-Note that only a subset of the I2C and SMBus protocols can be achieved by the means of read() and write() calls. In particular, so-called combined transactions (mixing read and write messages in the same transaction) aren't supported. For this reason, this interface is almost never used by user-space programs.


I2C Core-The I2C core is a code base consisting of routines and data structures available to host adapter drivers and client drivers.

Comment to this blog if any query




Saturday, 3 January 2015

What is MODULE_ALIAS in Linux device driver code?


MODULE_ALIAS is macro, added in 2002 with update of linux kernel module loaders, and used since 2003. This macro allows module creator to define additional names of the module (aliases), for example to make autoloading of the module easier.
The aliases are used to give some special name, e.g. "block-major-100" directly in the module source, instead of using /etc/modules.conf for defining aliases. When user program accesses the block device with major number 100, kernel will try to load "block-major-100". Without MODULE_ALIAS kernel should go to userspace and read /etc/modules.conf with helper. And with MODULE_ALIAS("block-major-100") kernel will solve the search by itself.
You can read more about this macro in http://lwn.net/Articles/47412/ "MODULE_ALIAS" article by corbet, 2003-09-03.
There are several more special versions of the MODULE_ALIAS, listed by corbet:
The actual variants used depend on the subsystem; block drivers use MODULE_ALIAS_BLOCKDEV, for example, while char devices use MODULE_ALIAS_CHARDEV or MODULE_ALIAS_MISCDEV and network protocols use MODULE_ALIAS_NETPROTO.
According to 2011 patch from Mans Rullgard (linaro), or to commit by Kay Sievers (vrfy), MODULE_ALIAS with argument like "platform:... is used to enable module auto-loading "when platform devices are scanned.". In SPI drivers, it is used for "hotpluggable SPI platform drivers, to allow module auto loading.", since 43cc71eed1250755986da4c0f9898f9a635cb3bf by Kay Sievers - "platform: prefix MODALIAS with "platform:"":
Prefix platform modalias strings with "platform:", which modprobe config to blacklist alias resolving if userspace configures it.
Driver aliases with "platform:" are used in drivers/base/platform.c file, function modalias_show(...) (snprintf(buf, PAGE_SIZE, "platform:%s\n", pdev->name);) and in platform_uevent(...) add_uevent_var(env, "MODALIAS=%s%s", PLATFORM_MODULE_PREFIX, pdev->name); where PLATFORM_MODULE_PREFIX macro is defined as "platform:" (so, colon mark is significant).


What is the use of 'i2c_get_clientdata“ and ”i2c_set_clientdata"?

Those functions are used to get/set the void *driver_data pointer that is part of the struct device, itself part of struct i2c_client.


driver_data
Private pointer for driver specific info.


struct i2c_client {
  unsigned short flags;
  unsigned short addr;
  char name[I2C_NAME_SIZE];
  struct i2c_adapter * adapter;
  struct device dev;
  int irq;
  struct list_head detected;
  i2c_slave_cb_t slave_cb;
}; 
 
struct device {
  struct device * parent;
  struct device_private * p;
  struct kobject kobj;
  const char * init_name;
  const struct device_type * type;
  struct mutex mutex;
  struct bus_type * bus;
  struct device_driver * driver;
  void * platform_data;
  void * driver_data;
  struct dev_pm_info power;
  struct dev_pm_domain * pm_domain;
#ifdef CONFIG_PINCTRL
  struct dev_pin_info * pins;
#endif
#ifdef CONFIG_NUMA
  int numa_node;
#endif
  u64 * dma_mask;
  u64 coherent_dma_mask;
  unsigned long dma_pfn_offset;
  struct device_dma_parameters * dma_parms;
  struct list_head dma_pools;
  struct dma_coherent_mem * dma_mem;
#ifdef CONFIG_DMA_CMA
  struct cma * cma_area;
#endif
  struct dev_archdata archdata;
  struct device_node * of_node;
  struct acpi_dev_node acpi_node;
  dev_t devt;
  u32 id;
  spinlock_t devres_lock;
  struct list_head devres_head;
  struct klist_node knode_class;
  struct class * class;
  const struct attribute_group ** groups;
  void (* release) (struct device *dev);
  struct iommu_group * iommu_group;
  bool offline_disabled:1;
  bool offline:1;
};   

Friday, 2 January 2015

Blink external LED on Beaglebone Black using C programming


LED connected to GPIO0_23 (P8.13) through 470 ohm resistor.
Do not use lesser value resistors in series with the LED.
GPIO0_23 means 0*32 + 23 = 23. Hence pass this value to the 'export' file.

Connect BBB to computer as explained here.
In terminal/ Putty, type nano Blink_external_LED.cpp
Paste the below code, press Ctrl+X, Y and Enter.
Type g++ Blink_external_LED.cpp -o Blink_external_LED and compile
Type ./Blink_external_LED and run

Code:

#include <unistd.h>
#include <stdio.h>
using namespace std;

int main()
{
        FILE *export_file = NULL;        //declare pointers
        FILE *IO_direction = NULL;
        char str1[] = "low";
        char str2[] = "high";
        char str[] = "23";                       //value to pass to export file
        export_file = fopen ("/sys/class/gpio/export", "w");
        fwrite (str, 1, sizeof(str), export_file);
        fclose (export_file);

for (int i=0; i<10; i++){        //blink LED 10 times
        IO_direction = fopen ("/sys/class/gpio/gpio23/direction", "w");
        fwrite (str2, 1, sizeof(str1), IO_direction);   //set the pin to HIGH
        fclose (IO_direction);
        usleep (1000000);

        IO_direction = fopen ("/sys/class/gpio/gpio23/direction", "w");
        fwrite (str1, 1, sizeof(str1), IO_direction);   //set the pin to LOW
        fclose (IO_direction);
        usleep (1000000);}

        export_file = fopen ("/sys/class/gpio/unexport", "w");   //remove the mapping
        fwrite (str, 1, sizeof(str), export_file);
        fclose (export_file);
}

Thursday, 25 December 2014

Device Tree Blog

Today I would be talking about device tree:

Device Tree is a data structure by which bootloaders pass
hardware layout to Linux in a device-independent manner, simplifying hardware
probing.
Mailing list for device tree is mailing list at:
https://lists.ozlabs.org/listinfo/devicetree-discuss

Introduction:
During development of Linux/ppc64 kernel it was decided to enforce some strict rules regarding the kernel entry point and bootloader <-> kernel interface,in order to avoid degeneration that become the ppc32 kernel entry point and the way a new platform should be added to the kernel.

-device-tree whose format is defined after Open Firmware specification.
-To make easy the kernel does not required the device tree to represent  every device.Only some nodes and properties to be present.
-For example the kernel does not require to create a node for every PCI device.It will create node for PCI Host bridges which provides information for interrupt routing information and memory I/O ranges among others.
-It is recomended to specify nodes for chip devices and other devices and other Bus that does not fit into existing OF specification.
-This creates the flexibility in the way the kernel can then probe those and match drivers to device,without having hard code all sorts of tables.
-Also makes flexible for board vendors to do minor hardware upgrades without significanltly impacting the kernel code or clustering it with special cases.

1)Entry point for arch/arm:
There is single entry point to the kernel,at the start of the kernel image.That entry point has two calling convention.

a)ATAGS interface:
Minimal information is passed from firmware ->kernel with a tagged list of predefined parameters.
r0=0
r1=Machine type number
r2=Physical address of tagged list in system RAM

b)entry of device tree.Firmware loads the physical address of the device tree block(dtb) into r2.R1 is not used but it is considers as good practice to use valid machine number.
 r0=0
r1=valid machine type number. When using device tree a single machine type number will often be assigned to represent a class or family of SOCs.
r2=physical pointer to the device tree in RAM.It can be located on anywhere in system RAM, but it should be aligned on 64-bit boundary.

-Kernel will differentiate between ATAGS and device tree booting by reading the memory pointed to by r2 and looking for either the device tree Block magic value(0xd00dfeed) or the ATAG_CORE value at offset 0x4 from r2(0x54410001)


 The kernel is passed the physical address pointing to an area of memory
   that is roughly described in include/linux/of_fdt.h by the structure
   boot_param_header:

struct boot_param_header {
        u32     magic;                  /* magic word OF_DT_HEADER */
        u32     totalsize;              /* total size of DT block */
        u32     off_dt_struct;          /* offset to structure */
        u32     off_dt_strings;         /* offset to strings */
        u32     off_mem_rsvmap;         /* offset to memory reserve map
                                           */
        u32     version;                /* format version */
        u32     last_comp_version;      /* last compatible version */

        /* version 2 fields below */
        u32     boot_cpuid_phys;        /* Which physical CPU id we're
                                           booting on */
        /* version 3 fields below */
        u32     size_dt_strings;        /* size of the strings block */

        /* version 17 fields below */
        u32     size_dt_struct;         /* size of the DT structure block */
};

/* Definitions used by the flattened device tree */
#define OF_DT_HEADER            0xd00dfeed      /* 4: version,4: total size */
#define OF_DT_BEGIN_NODE        0x1             /* Start node: full name*/
#define OF_DT_END_NODE          0x2             /* End node */
#define OF_DT_PROP                    0x3             /* Property: name off,size, content */
#define OF_DT_END                       0x9

   - magic

     This is a magic value that "marks" the beginning of the
     device-tree block header. It contains the value 0xd00dfeed and is
     defined by the constant OF_DT_HEADER

- totalsize

     This is the total size of the DT block including the header. The
     "DT" block should enclose all data structures defined in this
     chapter (who are pointed to by offsets in this header). That is,
     the device-tree structure, strings, and the memory reserve map.

 -off_dt_struct

     This is an offset from the beginning of the header to the start
     of the "structure" part the device tree.   

 - off_dt_strings

     This is an offset from the beginning of the header to the start
     of the "strings" part of the device-tree

 - off_mem_rsvmap

     This is an offset from the beginning of the header to the start
     of the reserved memory map. This map is a list of pairs of 64-
     bit integers. Each pair is a physical address and a size. The
     list is terminated by an entry of size 0. This map provides the
     kernel with a list of physical memory areas that are "reserved"
     and thus not to be used for memory allocations, especially during
     early initialization. The kernel needs to allocate memory during
     boot for things like un-flattening the device-tree, allocating an
     MMU hash table, etc... Those allocations must be done in such a
     way to avoid overriding critical things like, on Open Firmware
     capable machines, the RTAS instance, or on some pSeries, the TCE
     tables used for the iommu. Typically, the reserve map should
     contain _at least_ this DT block itself (header,total_size). If
     you are passing an initrd to the kernel, you should reserve it as
     well. You do not need to reserve the kernel image itself. The map
     should be 64-bit aligned.

   - version

     This is the version of this structure. Version 1 stops
     here. Version 2 adds an additional field boot_cpuid_phys.
     Version 3 adds the size of the strings block, allowing the kernel
     to reallocate it easily at boot and free up the unused flattened
     structure after expansion. Version 16 introduces a new more
     "compact" format for the tree itself that is however not backward
     compatible. Version 17 adds an additional field, size_dt_struct,
     allowing it to be reallocated or moved more easily (this is
     particularly useful for bootloaders which need to make
     adjustments to a device tree based on probed information). You
     should always generate a structure of the highest version defined
     at the time of your implementation. Currently that is version 17,
     unless you explicitly aim at being backward compatible.

 - last_comp_version

     Last compatible version. This indicates down to what version of
     the DT block you are backward compatible. For example, version 2
     is backward compatible with version 1 (that is, a kernel build
     for version 1 will be able to boot with a version 2 format). You
     should put a 1 in this field if you generate a device tree of
     version 1 to 3, or 16 if you generate a tree of version 16 or 17
     using the new unit name format.

   - boot_cpuid_phys

     This field only exist on version 2 headers. It indicate which
     physical CPU ID is calling the kernel entry point. This is used,
     among others, by kexec. If you are on an SMP system, this value
     should match the content of the "reg" property of the CPU node in
     the device-tree corresponding to the CPU calling the kernel entry
     point (see further chapters for more information on the required
     device-tree contents)

   - size_dt_strings

     This field only exists on version 3 and later headers.  It
     gives the size of the "strings" section of the device tree (which
     starts at the offset given by off_dt_strings).

   - size_dt_struct

     This field only exists on version 17 and later headers.  It gives
     the size of the "structure" section of the device tree (which
     starts at the offset given by off_dt_struct).


             ------------------------------
     base -> |  struct boot_param_header  |
             ------------------------------
             |      (alignment gap) (*)   |
             ------------------------------
             |      memory reserve map    |
             ------------------------------
             |      (alignment gap)       |
             ------------------------------
             |                            |
             |    device-tree structure   |
             |                            |
             ------------------------------
             |      (alignment gap)       |
             ------------------------------
             |                            |
             |     device-tree strings    |
             |                            |
      -----> ------------------------------
      |
      |
      --- (base + totalsize)

  (*) The alignment gaps are not necessarily present; their presence
      and size are dependent on the various alignment requirements of
      the individual data blocks.

2:Device Tree generalites
This device-tree itself is separate in two different blocks:
1)structure block
2)string block
Both are alinged to 4 byte boundary

 What is device-tree?
-Its basically a tree of nodes, each node having two or more named properties.A property can have value or not.
-It is a tree so each node has one parent while otherwise they dont have node.
-Node has two names.
Actual node name is generally contained in the property "name" in the node property list(whose value is zero terminated and it is mandatory in for version 1 to 3)
-from version 16 its optional.(it generates from unit name defined below)
-Another name is "unit name" that is used to differentiate nodes with same name at the same level.
-It is usually made of "nodes name" then @ then "unit address",which defination is specific to bus type the node sits on.
-Unit name does not exist as property per-se but it is included in device tree structure.That is typically used to represent path in device-tree.
-Kernel generic code does not uses unit address so the only real requirment here for unit address is to ensure uniqueness of the node unit name at the given level of the tree.
-The node with no notion of address and no possible sibling of the same name may omit the unit address in the context of the specification or use "@0" defualt unit address.
- The unit name is used to define a node "full path", which is the concatenation of all parent node unit names separated with "/".
Root node
-The root node doesn't have a defined name.It also has no unit address.The root node unit name is thus an empty string. The full path to the root node is "/".


-Every node which actually represents an actual device is also required to have a "compatible" property indicating the specific hardware and an optional list of devices it is fully backwards compatible with.
-every node that can be referenced from a property in another node is required to have either a "phandle" or a "linux,phandle"




-Here is the example of the device tree


/ o device-tree
      |- name = "device-tree"
      |- model = "MyBoardName"
      |- compatible = "MyBoardFamilyName"
      |- #address-cells = <2>
      |- #size-cells = <2>
      |- linux,phandle = <0>
      |
      o cpus
      | | - name = "cpus"
      | | - linux,phandle = <1>
      | | - #address-cells = <1>
      | | - #size-cells = <0>
      | |
      | o PowerPC,970@0
      |   |- name = "PowerPC,970"
      |   |- device_type = "cpu"
      |   |- reg = <0>
      |   |- clock-frequency = <0x5f5e1000>
      |   |- 64-bit
      |   |- linux,phandle = <2>
      |
      o memory@0
      | |- name = "memory"
      | |- device_type = "memory"
      | |- reg = <0x00000000 0x00000000 0x00000000 0x20000000>
      | |- linux,phandle = <3>
      |
      o chosen
        |- name = "chosen"
        |- bootargs = "root=/dev/sda2"
        |- linux,phandle = <4>



o -represents the device tree. Followed by the node unit name
property are followed by the name and then followed by the content.
"content"-represents as ACSII type
<>-represents a 32 bit value in decimal or hexadecimal.

3:Structure Block
The structure of the device tree is linearized tree structure.
"OF_DT_BEGIN_NODE" token starts a new node
"OF_DT_END_NODE" ends that node definition
Child nodes are simply defined before "OF_DT_END_NODE"

Here's the basic structure of a single node:

     * token OF_DT_BEGIN_NODE (that is 0x00000001)
     * for version 1 to 3, this is the node full path as a zero
       terminated string, starting with "/". For version 16 and later,
       this is the node unit name only (or an empty string for the
       root node)
     * [align gap to next 4 bytes boundary]
     * for each property:
        * token OF_DT_PROP (that is 0x00000003)
        * 32-bit value of property value size in bytes (or 0 if no
          value)
        * 32-bit value of offset in string block of property name
        * property value data if any
        * [align gap to next 4 bytes boundary]
     * [child nodes if any]
     * token OF_DT_END_NODE (that is 0x00000002)

So the node content can be summarized as a start token,full path, a list of properties, a list of child nodes, and a end token.Every child node is the full structure itself as defined above.

4:Device tree "string" block
-In order to save space,property names,which are generally redundant are stored seperatly in the "strings" block.
-This block is simply whole bunch of zero terminated strings for all properties name concatenated together.
-The device-tree property definition in the stucture block will contain offset values from beginning of the string block.
--------------------------------------------------------------------------------------------------------------------
Required content of the device tree:
WARNING:All 'linux' properties defined in this document apply to device tree.If your platform uses a real implementation of open firmware or an implementation compatible with the open firmware client interface,those properties will be created by the trampoline code in the kernel prom_init() file For example, that's where you'll have to add code to detect your board model and set the platform number. However, when using the flattened device-tree entry point, there is no prom_init() pass, and thus you have to provide those properties yourself.
1)Note about cells and address representation:
The general rule is documentaed in open firmware documentation.
-If you choose a bus with the device tree and there exit OP bus binding,then you should follow specification.However kernel does not need to describe every device in device tree.

Format of address is defined my the parent bus type,based on #address-cell and #size-cell. These address are not inherited from parent so note that so every node with children must specify them.

What is cell?
Those 2 properties define 'cells' for representing an address and a size. A "cell" is a 32-bit number. For example, if both contain 2 like the example tree given above, then an address and a size are both composed of 2 cells, and each is a 64-bit number (cells are concatenated and expected to be in big endian format). Another example
is the way Apple firmware defines them, with 2 cells for an address and one cell for a size.  Most 32-bit implementations should define #address-cells and #size-cells to 1, which represents a 32-bit value. Some 32-bit processors allow for physical addresses greater than 32 bits; these processors should define #address-cells as 2.





2)Note about "compatiblle" property
These properties are optional, but recommended in device and the root node. The format of "compatible" property is a list of concatenated zero terminated strings. They allow a device to express its compatibility with family of similar device.n some cases,allowing a single driver to match against several devices regardless
of their actual names.
3)Note on "name" property
-While earlier users of Open Firmware like OldWorld macintoshes tended
to use the actual device name for the "name" property, it's nowadays
considered a good practice to use a name that is closer to the device
class (often equal to device_type). For example, nowadays, Ethernet
controllers are named "ethernet", an additional "model" property
defining precisely the chip type/model, and "compatible" property
defining the family in case a single driver can driver more than one
of these chips. However, the kernel doesn't generally put any
restriction on the "name" property; it is simply considered good
practice to follow the standard and its evolutions as closely as
possible.

-Note also that the new format version 16 makes the "name" property
optional. If it's absent for a node, then the node's unit name is then
used to reconstruct the name. That is, the part of the unit name
before the "@" sign is used (or the entire unit name if no "@" sign
is present).

4) Note about node and property names and character set
-------------------------------------------------------
 The root node requires some properties to be present:

    - model : this is your board name/model
    - #address-cells : address representation for "root" devices
    - #size-cells: the size representation for "root" devices
    - compatible : the board "family" generally finds its way here,
      for example, if you have 2 board models with a similar layout,
      that typically get driven by the same platform code in the
      kernel, you would specify the exact board model in the
      compatible property followed by an entry that represents the SoC
      model.

  The root node is also generally where you add additional properties
  specific to your board like the serial number if any, that sort of
  thing. It is recommended that if you add any "custom" property whose
  name may clash with standard defined ones, you prefix them with your
  vendor name and a comma.

  b) The /cpus node

  This node is the parent of all individual CPU nodes. It doesn't
  have any specific requirements, though it's generally good practice
  to have at least:

               #address-cells = <00000001>
               #size-cells    = <00000000>

  This defines that the "address" for a CPU is a single cell, and has
  no meaningful size. This is not necessary but the kernel will assume
  that format when reading the "reg" properties of a CPU node, see
  below

 c) The /cpus/* nodes
-So under /cpus, you are supposed to create a node for every CPU on
  the machine.
-So under /cpus, you are supposed to create a node for every CPU on
  the machine
-So under /cpus, you are supposed to create a node for every CPU on
  the machine
-the Generic Names convention suggests that it would be
  better to simply use 'cpu' for each cpu node and use the compatible
  property to identify the specific cpu core.


 Required properties:
- device_type : has to be "cpu"
    - reg : This is the physical CPU number, it's a single 32-bit cell
      and is also used as-is as the unit number for constructing the
      unit name in the full path. For example, with 2 CPUs, you would
      have the full path:
        /cpus/PowerPC,970FX@0
        /cpus/PowerPC,970FX@1
      (unit addresses do not require leading zeroes)
    - d-cache-block-size : one cell, L1 data cache block size in bytes (*)
    - i-cache-block-size : one cell, L1 instruction cache block size in
      bytes
    - d-cache-size : one cell, size of L1 data cache in bytes
    - i-cache-size : one cell, size of L1 instruction cache in bytes

(*) The cache "block" size is the size on which the cache management instructions operate. Historically, this document used the cache "line" size here which is incorrect. The kernel will prefer the cache block size and will fallback to cache line size for backward compatibility.














Recommended properties:

    - timebase-frequency : a cell indicating the frequency of the
      timebase in Hz. This is not directly used by the generic code,
      but you are welcome to copy/paste the pSeries code for setting
      the kernel timebase/decrementer calibration based on this
      value.
    - clock-frequency : a cell indicating the CPU core clock frequency
      in Hz. A new property will be defined for 64-bit values, but if
      your frequency is < 4Ghz, one cell is enough. Here as well as
      for the above, the common code doesn't use that property, but
      you are welcome to re-use the pSeries or Maple one. A future
      kernel version might provide a common function for this.
    - d-cache-line-size : one cell, L1 data cache line size in bytes
      if different from the block size
    - i-cache-line-size : one cell, L1 instruction cache line size in
      bytes if different from the block size