Thursday, 30 October 2014

platform device driver

Your references are good but lack a definition of what is a platform device. There is one on LWN. What we can learn from this page:
  1. Platform devices are inherently not discoverable, i.e. the hardware cannot say "Hey! I'm present!" to the software. Typical examples are i2c devices, kernel/Documentation/i2c/instantiating-devices states:
    Unlike PCI or USB devices, I2C devices are not enumerated at the hardware level (at run time). Instead, the software must know (at compile time) which devices are connected on each I2C bus segment. So USB and PCI are not platform devices.
  2. Platform devices are bound to drivers by matching names,
  3. Platform devices should be registered very early during system boot. Because they are often critical to the rest of the system (platform) and its drivers.
So basically, the question "is it a platform device or a standard device?" is more a question of which bus it uses. To work with a particular platform device, you have to:
  1. register a platform driver that will manage this device. It should define a unique name,
  2. register your platform device, defining the same name as the driver.
Platform driver is for those devices that are on chip.
Not true (in theory, but true in practice). i2c devices are not onChip, but are platform devices because they are not discoverable. Also we can think of onChip devices which are normal devices. Example: an integrated PCI GPU chip on a modern x86 processor. It is discoverable, thus not a platform device.
Normal device driver are for those that are interfaced to the processor chip. before coming across one i2c driver.
Not true. Many normal devices are interfaced to the processor, but not through an i2c bus. Example: a USB mouse.
[EDIT] In your case, have a look to drivers/usb/host/ohci-pnx4008.c, which is a USB host controller platform device (Here the USB host controller is not discoverable, whereas USB devices, which will connect to it, are). It is a platform device registered by the board file (arch/arm/mach-pnx4008/core.c:pnx4008_init). And within its probe function, it registers its i2c device to the bus with i2c_register_driver. We can infer that the USB Host controller chipset talks to the CPU through an i2c bus.
Why that architecture? Because on one hand, this device can be considered a bare i2c device providing some functionalities to the system. On the other hand, it is a USB Host capable device. It needs to register to the USB stack (usb_create_hcd). So probing only i2c will be insufficient. Have a look to Documentation/i2c/instantiating-devices.

Wednesday, 29 October 2014

Difference between instance and object

I was wondering what is difference between instance and object?

ans.

An instance, in object-oriented programming (OOP), is a specific realization of any object. An object may be varied in a number of ways. Each realized variation of that object is an instance. The creation of a realized instance is called instantiation.

Each time a program runs, it is an instance of that program. In languages that create objects from classes, an object is an instantiation of a class. That is, it is a member of a given class that has specified values rather than variables. In a non-programming context, you could think of "dog" as a class and your particular dog as an instance of that class.




It is very simple but very important
Take a general example: what is the general meaning of object? its nothing but which occupies some space right....keep that in mind we now talk about Object in java or C++

example: here I am creating Object     Student std=new Student();
where Student is a Class and std is a Object because we Created a memory for std with the help of new keyWord it means it internally occupies some space in memory right thats y we call std as Object
if you won`t create memory for an object so we call that object as instance.

example: Student std;
here Student is a class and std is a instance(means a just a copy that class),with this we won`t do anything untill unless we create a memory for that.
Thats all about object and Instance :)

make: ****** empty variable name. Stop.

This is make file for rtdm

obj-m           := tut01-skeleton-drv.o
KDIR            := /lib/modules/$(shell uname -r)/build
PWD             := $(shell if [ "$$PWD" != "" ]; then echo $$PWD; else pwd; fi)
EXTRA_CFLAGS := -I$(KDIR)/include/xenomai -I$(KDIR)/include/xenomai/posix           $(ADD_CFLAGS)

all:     
        $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
        $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) clean

Note

-I had kept space between = and $ that caused this error. Remove the space and error would be solved

Make file
$=means value
#=number of

Sunday, 5 October 2014

UART drivers and application programming

Hello Friends,
                      Today is sunday I have got time to Hack UART and make my driver and application with linux.So lets start

Interfacing the Serial/RS232 Port

Introduction
-The Serial Port is harder to interface than the Parallel Port.

Advantages of serial communication over parallel communication
- Serial Cables can be longer than Parallel cables. The serial port transmits a '1'
as -3 to -25 volts and a '0' as +3 to +25 volts where as a parallel port
transmits a '0' as 0v and a '1' as 5v. Therefore cable loss is not going to be as much of a problem for serial cables than they are for parallel.
- You don't need as many wires than parallel transmission
-Microcontroller have built in serial communication interface.Hence it reduces the number for pin.In serial communication there are only transmitter and recevier.

PART-1
Hardware(PC) Properties:
-Devices which use serial cables for their communication have two categories
1)DCE(data communication equipment)e.g modem, TA adapter, plotter etc
2)DTE(data terminal equipment)e.g  Computer or Terminal.

Electrical specification of serial port in RS232C standard
1)A "Space" (logic 0) will be between +3 and +25 Volts.
2.A "Mark" (Logic 1) will be between -3 and -25 Volts.
3.The region between +3 and -3 volts is undefined.
4.An open circuit voltage should never exceed 25 volts. (In Reference to
GND)
5.A short circuit current should not exceed 500mA. The driver should be
able to handle this without damage. (Take note of this one!)

 -serial port comes in 2 sizes 9 and 25 pin


D-type-25 pin no.              D-type-9 Pin No.      Abbreviation
pin2                                     pin3                            TD                            transmit data
pin3                                     pin2                             RD                           receive data
pin4                                     pin7                             RTS                          request to send
pin5                                     pin8                             CTS                          clear to send
pin6                                     pin6                             DSR                         data set ready
pin7                                     pin5                             SG                           signal ground
pin8                                     pin1                             CD                          carrier detect
pin20                                   pin4                             DTR                        data terminal ready
pin22                                   pin9                             RI                             ring indicator


TD-serial data output
RD-serial data input
CTS-this line indiacates that modem is ready to exchange data
DCD-when modem detects a "carrier" from  the modem at the other end of phone line, this line becomes active
DSR-this tell the UART that the modem is ready to establish a link.
DTR-this tell the modem that the UART is ready to establish a link.
RTS- this informs the modem  that  the UART is ready to exchange data
RI-goes active when modem detects a ringing signal  from  the PSTN.

Null Modem:







DTE / DCE Speeds:
-People may talk about DTE-DTE speed and DCE-DTE speed
DCE-DTE speed between your modem and computer,sometimes refereed to as your terminal speed
-This runs faster than DCE-DCE speed is link between between modem knows as line speed
-Today most of modem should have data compression build into them .This has compression ratio of 1:4.
Thus this is why the DCE-DTE should be much higher than your modem's connection speed.

Flow Control
-Software flow control, sometimes expressed as Xon/Xoff uses two characters Xon and Xoff
-This type of flow control has the advantage that it doesn't require any more wires as the characters are sent via the TD/RD lines.
-However on slow links each character requires 10 bits which can slow communications down.
-Hardware flow control is also known as RTS/CTS flow control.
-Thus hardware flow control will not slow down transmission times like Xon-Xoff does. When the computer wishes to send data it takes active the Request to Send line. If the modem has room for this data, then the modem will reply by taking active the Clear to Send line and the computer starts sending data.

Types of UARTS (For PC's)
8250First UART in this series. It contains no scratch register. The 8250A was an
improved version of the 8250 which operates faster on the bus side.
8250A
This UART is faster than the 8250 on the bus side. Looks exactly the same to
software than 16450.
8250B
Very similar to that of the 8250 UART.
16450
Used in AT's (Improved bus speed over 8250's). Operates comfortably at
38.4KBPS. Still quite common today.
16550
This was the first generation of buffered UART. It has a 16 byte buffer, however it
doesn't work and is replaced with the 16550A.
16550A

Is the most common UART use for high speed communications eg 14.4K &
28.8K Modems. They made sure the FIFO buffers worked on this UART.
16650
Very recent breed of UART. Contains a 32 byte FIFO, Programmable X-On / X-
Off characters and supports power management.
16750
Produced by Texas Instruments. Contains a 64 byte FIFO.


Part-2:Serial Port's Register(PC's)
Name                       Address                   IRQ
COM 1                     3F8                           4
COM 2                     2F8                           3
COM 3                     3E8                           4
COM 4                     2E8                           3

-Just like the LPT ports, the base addresses for the COM ports can be read from the BIOS Data Area.

Start Address                          Function
0000:0400                              COM1's Base Address
0000:0402                              COM2's Base Address
0000:0404                              COM3's Base Address
0000:0406                              COM4's Base Address


Transmitter Holding Buffer
Receiver Buffer
Interrupt Enable Register
Divisor Latch High Byte
Interrupt Identification Register
FIFO Control Register
Line Control Register
Modem Control Register
Line Status Register
Modem Status Register
Scratch Register


 Communication
You can always make a user space program for communication of two computer with each other via UART cable.
Two commands are used for configuring UART in computer
1]setserial 
 2]stty
Study both command with man pages

Some command
$setserial -g /dev/ttys0
$setserial /dev/ttys0 uart 16550A
$echo "hello" > /dev/ttys0
$cat /dev/ttys0

stty -F /dev/ttys0 cstopb -cs8 raw -parenb ispeed 9600






Sunday, 28 September 2014

Lecture notes


Lecture notes:
*what is relation of kernel and modules?
Ans-registration,methos,data structure,objects etc
*How do you use api without library
ans symbol table
*what is use of symbol
ans address of data or function
*difference between user space and system space
ans rules are different

image


FRAMEWORKS
-platform subsys
-usb subsys
-LLDM or Device model
-sysfs
-RTOS device model
-RTOS driver model

libraries->system call->VFS->char->my driver model->device
-----------
userspace

*OS concepts
-ISR -process schedulling
-IPC
-wake-up
-device model plays important role in embedded kernel

DERIVERS
-mainly there are three types of device drivers
1)character 2)block 3)network

-Porting involves customization of RTOS for specific board which may involve adding,integrating new set of device drivers.

EOS atch/implementation
-RTOS------->real time,embedded}they can be connected
-Embedded linux--------->
+specific bootloader
+HAL will be very specific
+BSP is very specific
+booting technique is very specific
+custom lib.



MEMORY SPACE

-virtual address space---->page table------->physical address
(memory management)
KERNEL MEMORY MANAGER
-memory allocator
1)buddy allocator
-buddy allocator per zone of physical memory
-each buddy allocator has serveral levels
-each level manages true memory
-memory blocks are multiples of page size according to level each block of true memory
-using ptr to struct page we must pass it to kmap() in the case of low memory region,kmap() will extract the corresponding KVAS address
-using ptr tp struct page we must pass it to kmap() will allocate a KVAS page from KVAS
-kumap is must to use for each page frame.

Limitations:
-it provids multiple off page frames
-minimal granulity-internal fragmentation
-it only provides multiple off page frames.-external fragmentation.

2)non-config allocator
--vmalloc() the API interface
-we may request a size of a single page memory or multiple of page size memory block
-non-config memory allocation will do the following
-allocate one or more page frames,from high memory region
-allocates one or more kvas pages from VMALLOC region!!
-using the kvas pages,map the allocated page frames!!
-kvas pages are strictly contiguous and page frames are not contiguous
-in addition VMALLOC region is also used to map memory space redistor of controller is requestby device drivers once mapped logical|virtual address of VMALLOC region are used by drivers!!!
3)slab allocator
-slab allocator subsystem manage serveral slab cache allocator!!
-each slabcache allocator is provided to support memory docs of specific size or type of object.MOst slab cache allocator provides memory blocks or objects less than a page size.
-system creates serveral slab cache allocator each providing support for allocation of specific system object.
-these slab cache allocator can be used by relevant subsystem or componets
-however the slab cache allocator be used by device or other external componets
-system provides seperate slab cache allocator for device drivers or other external componets
-such generic slab cache allocator can be accessed using kmalloc api
-for eg.kmalloc(size,GFP_KERNEL)
-in the case if OBJECTA,system will round_up the size field to the nearest size slab cache allocator
-each size_n slab cache allocator is manager using a slab cache descriptor.
-each slab cache descriptor manage one or more slab!! each slab is typically
a single page frame or multiple contiguous frame.
-each slab is managed by a slab descriptor.
-each slab contains one or more objects of size.


Image 2


DEVICE MODEL
-several objects repreasenting devices.
-contains hierarchy
-contains several datastructures
-device model is built on top of several objects
-some of these are low,intermediate and high level objects
-all these objects are connected and worked together
some low level objects are
-kobjects,kset,kobj_type_attribute object,many more

-struct kobject is the most primitive object that manage a logical device or a physical device
-following are some of the characterics of kobject
1)It maintains the respective device in a herarchy
2)it maintains usage/refrence count of the respective device
3)it maintains the respective device in an aggregation
4)it enable a device to be connected to sysfs
Kset
-kset object may be used for aggregation a set of kobjects
-kobjects of a kset may also be involved in managing hierary
Kobj-type
-it is another used along with a kobject it does the following
-it enables a destination for the kobject and the respective device
-it enables the sysfs to interact with device attributes
-when we manage kset we do with kobject.
-kset can be used to manage multiple device

module----->device model---------->sysfs
-

FILE SYSTEM
-in memory
-on disk memory

-the sysfs manages and maintains metadata only in memory not on-disk
-In sysfs,a typical directory file or a regular file or a softlink are represented using sysfs_dirent object
-typically for a given kobject when a konject is registering with device model a sysfs directory file
vi fs/
-the kobject and corresponding sysfs_divert are connected to each other.
-a given kobject can have one or more attributes
-attributes are represented by struct attributes objects which are abstact
-however such abstract attributes can be associated with real attributes of physical or logical device represented by Kobject.
-In addition such attributes objects can be associated with high level attributes objects these high level attributes object will support certain methods which can be usefull
-corresponding to each attributes of a kobject there will be a sysfs regular file created under sysfs directory of the kobject
-these sys fs are children of the sysfs directory of the kobject and all these children are siblings of the same level.
-the sysfs_dirent object of an attributes as an pointer pointing toa corresponding struct attributes
-in addition,sysfs_dirent of an attribute also as pointer to sysfs_dirent of the kobject meaning parent sysfs_dirent
-let us assume we want to access a sysfs file(regular file)corresponding to an object of a device(its kobject)
vi fs/sysfs/file.c
sysfs----->kobject
sysfs------>attribute

-kobjects does not define device
another harware entity
driver_struct----->driver()
device_struct----->device()
-certain has resources detail
-blocking | wake-up
-certain loading

-assuming we have registred out platform device,if a matching/compatible driver is loaded into the system,following actions will be taken
-probe() method ,following action are typically done
-collect resources into of the specific device lock the resources
-allocates other objects buffers!!
-In addition we may have to register certain system objects with other frameworks
-we must lock the IO space or memory space or IRQ resources drivers as per rules
-to lock IO space addresses we must use request_mem_region()
-to free we may use release_region() or release_mem_region() respective
-in the case of memory space register addresses IO remap must be used to allocate and map into KVAS
-In the prob() once the basic set_up is done,we must register with another functional frame-work!!!
-Such a functional work may be a char layer or a block layer or a network layer or a RT device layer or some layer!!

Application--->RTOS interface----->RTOS kernel------>RTDM layer----->RTDM driver----->platform driver----->platform device----->platform layer------>HAL

INTRODUCTION TO SLEEPING
-if a driver method is invoked in a process context or a kernel thread context
-driver method may block the current process or kernel thread,if there are no contrains
Constrain
-if a spin-lock is up currently behold by the driver method
-if premption is disabled by the driver method
-if local has interrupts are disable by driver method
-a typical driver may maintain one or more weight queues per device in the private object!!
-however rules are different
-we must use a approval lacking mechanizm as per execution
-we may use spinlock(without disabling interrupts),if the critical section are in process context!!
-when a spinlock is acquired implicitly premption is disable
-we may use mutext if the critical section are in process context one reason may be that critical section are relative longer.
-we must use spinlocks (with interrupts disabling) if critical section are between process context and interrupt context in this case ,spinlock(with int disabling) must be done, in process contexts!!
-as per rules when code executes in one of the above critical section blocking is disallowed!!
-as per kernel language such critical section are said to be atomic context


USB DEVICE
-logical description of an USB device and its charateritics
-Their logical description|picture|characteritics is used by operating system to manage and interact with an USB device!!
-such a logical model is defined by USB specification and mainly for interfacing with os or firmware!! This logical model is very intelligent!!
-A typical USB bus is sourced by a host controller and its root-hub!!
-Host controller is typically resisdent on a less intelligent bus or a more intelligent PCI bus!!
-which means,host controller will be managed by a platform driver or a PCI driver
-In addittion Host controller will be further manage for I/O using a host controller driver
-Root-hub is a logical device of host controller manager by a Hub driver.
-In addition each USB device is treated as physical USB device containing one or more logical USB device. In most case only one logical device is present
-each USB device is manage using the USB physical device driver and one or more corresponding USB logical device drivers.Such logical device or custom drivers!!
-Each USB hub is managed using the USB physical device driver and the hub driver.
-The hub driver manages hub functionality in this context!! Hub driver plays a very important role in device management of USB bus
-A typical USB device is described by the following description implementation by the device firmware
-A device descriptor is used to describe overall charateritics of the device
-A device descriptor represents the physical USB device
-Every USB device may have one or more configuration descriptor
-A configuration descriptor defines power requirement and number of logical device support under the configuration !!
-During operation OS/USB framework will select a configuration may be modified explicitly if needed
-Assuming a configuration is selected it will support one or more interface descriptor each interface descriptor describes one logical device.
-Each logical device may contain one or more end points descriptor
-Each endpoint descriptor manages an endpoint of logical device -an endpoint may be a control endpoint or an IN endpoint or an OUT endpoint
-Every USB device as common controller endpoint known as endpoint o_default control endpoint.
-These descriptor are read/extracted by os/usb frame work ,when an usb device discovered or configured
-Each USB physical device is assigned a dynamic USB device number.This USB device number is unique for a device within usb bus.The range is 1 to 127 is -o is reserved for special address.
-Each endpoint also has an address.This includes endpoint number and endpoint direction.
-During the IO transfer USB framework and driver need to access endpoint descriptor
-To access a specific endpoint of a logical USB device of a physical USB device USB dev number and endpoint address is used
-Hub device plays an important role in device discovery and configuration.
-typically A hub device has a logical hub device .this logical hub device contain a controll end point and an interrupt end point.
-Interrupt end point provides HUB ports status change information
As per hub driver frame work int end points of all the hubs are polled periodically!!
-To do this polling USB frame work /hub driver use an interrupt URB!!In the case of interrupt URB,USB frame work will periodically generate URB request.If there is negative response ,USB request will continious
-If the response is +ve ,another polling must be initiated
-If there is +ve response the URB response is proccessed by kernel thread is woken up when needed other wise in blocked state!!
-This kernel thread continious processing the URB response if new device is connected it will be discovered and configured!!
-Descriptor are read and charactertics are understood
-Usb dev number must be assigned and configured selected
-default control end point
-an usb device is identified using info. Stored in its device descriptor and other descriptor
-in this info commonly used for idebtification is the vendor|product combination anf this combination is not used to bind physical device but used to bing logical device.
-this combination informatiojn is also encoded in the logical device driver
-struct usb_device_id{} is an object used to define supported device by the logical device driver!!
-struct usb_driver{} is allocated and initialized to repreasent an usb physical device
-struct usb_interface object represents an usb logical device .It is also connected to other objects!!
-struct usb_bus() represents an usb bus!!
-this usb_bus() object manages a tree of struct usb_device() object!!
-struct usb_hcd() -it is a superset of struct usb_bus() object!!
-struct hc_driver represents host controller driver . A pointer from USB_HCD() points to this struct hcd_driver
-struct usb_hub() repreasents a usb hub!!!
-this objects internally connects to struct usb_device of the corresponding hub_device
-struct hub_driver() is the object that represents the usb hub driver of the system
-let us typically start with usb_hub_init()
-USB_hub_init() is invoked from usb_init()
-A new kernel thread knows khubd is creaded
-khubd is associated with hub_thread()
-hub_thread() blocks and wake-up when needed when woken-up by hub driver /usb frame work
-hub_event() is the important method executed by hub_thread!
-In the hub driver the prob() method is used when a new hub us detected and the hub driver binds to the logicall devicve of the hub!!
-further invokes hub_configure()!!
-hub_configure set up an interrupt URB for the hubs interrupt end point
-hub_configure also submits the interrupt URB with the USB subsytem
-when the interrupt URB is submitted a compition handler is alsoi submitted a completion handler is a call back which will be invoked by USB frame work

There is response from the hub
-the call back method is known as hub_irq()!!it executes in interru context!!
-Hub_irq does the following action
-collects hub statyus changes went bits-stone it as part of start
RT message queues
-message queues buffer is determinitally allocated and memory
-send/receive API provides strict time-out parameter!!
image 3

GPOS RTOS
-memory protection -No memory protection
problem 1)No overhead
1)overhead 2)smaller foot print
2)footprint

Virtual machine---->physical memory manager----->provides high latency as its api are not designed for real time

RTOS scheduling policy
-typical real time PRIO based
-priority(number of priority are configurable)
-RT RR scheduling will also be supported.

-In a given implementation RR may be enabled or disabled while in free RTOS RR will be enabled if config USE_PREMPTION is
-RT task typically a given RT task will be assigned RT PRIO scheduling policy or RT policy!!
-In addition using certain system API we may provide peridic scheduling as per this our periodic task will woken-up as per period.
-When our RT task is woken-up it will be scheduled as per scheduling policy and priority
-Interrupt priority are higher than task priority
Intrrupt priority
-high dependent on port architechture
-0 is hightest and 31 is lowest
-possible interrupt priority are 0-31
-ISR with interrupt priority 5-31 may use ISR safe API
-ISR with interrupt priority ve 5 cannot use safe API
-interrupt and ISR support nesting and priotization
-RTOS API may disable harware interrupt to implement critical section code
-however they are highy port specific
-such hardware interrupts to disabling must be subject to timing contrains
-sharing interrupts is not accepted in RTOS
-In addition we pass parameter to API the current state of woken up task
-if a higher priority task is woken up and scheduler is invoked it will complete a task switching otherwise not now!!
-In the case of free_RTOS,instead of software generation interrupts is used!! this software generated interrupts is of lowest interrupts priority
-When this interrupts is service it ISR is serviced.This ISR will invoke scheduler

How does BSP differs from port layer
-Port will be modified if we move to another Arch.(port layer is HAL)


Zenomai:-
-Is a typically linux kernel suitable for hard real time os
-Still developers need real time linux a linux based RTOS!! developer using embedded linux-based
-A real-time linux + embedded linux-based
-one such real time linux implementation is know as RT-LINUX
-Another such real time linux is xenomai
-In real time linux implementation a deterministic and low latency interrupts management framwork is added using a micro-kernel or nano kernel to kernel space such a microkernel or nano kernel coexits with linux kernel but takes primary control of hardware of the system!!
-In addtion such a real time system also provides other deterministic and low latency services using a micro-kernel!!
-real time managed under this microkernel will provide real time performance
-linux kernel continious to provide non-rt services as before!!
Xenomai contains
-Task Managment
-Memory management
-IPC feature
-kernel space
userspace
-real time task may have rt task or non rt task
-user space non-rt task is managed using pd
-A userspace rt task is manged using pd and TCB
-A typical non-rt task of user space is managed using Pd and linux scheduler
-A typical RT-task of user space is manged using TCB when rt-task is executing in primary mode of xenomai envitoment
-rt task will keep on execting in primary mode until linux system call is not invoked
-Typically ono rt task is used in user space for initialization and diagnostics!!
-in xenomai rt_pipe and rt_queues are created with predefined size
-the size allocated this rt heap with the pipe/queue
-whenevr buffer is needed for rt pipe or rt queue we must allocate buffer from respective heap.Once used we must free respective buffer.


Wednesday, 24 September 2014

Memory Layout of C Program - Code, Data, .BSS, Stack, and Heap Segments

Memory Layout of C Program

Before talking of memory layout of a C program and its various segments to store data and code instructions we should first understand that a compiler driver (that invokes the language preprocessor, compiler, assembler, and linker, as needed on behalf of the user) can generate three types of object files depending upon the options supplied to the compiler driver. Technically an object file is a sequence of bytes stored on disk in a file. These object files are as follows:
  • Relocatable object file: These are static library files. Static linkers such as the Unix ld program take collection of relocatable object files and command line arguments as input and generate a fully linked executable object file as output that can be loaded into memory and run. Relocatable object files contain binary code and data in a form that can be combined with other relocatable object files at compile time to create an executable object file.
  • Executable object file: These are executable files contain binary code and data in a form that can be copied directly into memory and executed.
  • Shared object file: These special type of relocatable object files are loaded into memory and linked dynamically, at either load time or run time.

Object files have a specific format, however this format may vary from system to system. Some most prevalent formats are .coff (Common Object File Format), .pe (Portable Executable), and elf (Executable and Linkable Format).

Code and Data Segments

However, the actual layout of a program's in-memory image is left entirely up to the operating system, and often the program itself as well. This article focus on the concepts of code and data segments of a program and does not take any specific platform into account. For a running program both the machine instructions (program code) and data are stored in the same memory space. The memory is logically divided into text and data segments. Modern systems use a single text segment to store program instructions, but more than one segment for data, depending upon the storage class of the data being stored there. These segments can be described as follows:
1. Text or Code Segment
2. Initialized Data Segments
3. Uninitialized Data Segments
4. Stack Segment
5. Heap Segment

Text or Code Segment

Code segment, also known as text segment contains machine code of the compiled program. The text segment of an executable object file is often read-only segment that prevents a program from being accidentally modified.

Data Segments

Data segment stores program data. This data could be in form of initialized or uninitialized variables, and it could be local or global. Data segment is further divided into four sub-data segments (initialized data segment, uninitialized or .bss data segment, stack, and heap) to store variables depending upon if they are local or global, and initialized or uninitialized.

Initialized Data or Data Segment

Initialized data or simply data segment stores all global, static, constant, and external variables (declared with extern keyword) that are initialized beforehand.

Uninitialized Data or .bss Segment

Contrary to initialized data segment, uninitialized data or .bss segment stores all uninitialized global, static, and external variables (declared with extern keyword). Global, external, and static variable are by default initialized to zero. This section occupies no actual space in the object file; it is merely a place holder. Object file formats distinguish between initialized and uninitialized variables for space efficiency; uninitialized variables do not have to occupy any actual disk space in the object file.
Randal E. Bryant explains in his famous book on Computer Systems: A Programmer's Perspective, Why is uninitialized data called .bss?
The use of the term .bss to denote uninitialized data is universal. It was originally an acronym for the "Block Storage Start" instruction from the IBM 704 assembly language (circa 1957) and the acronym has stuck. A simple way to remember the difference between the .data and .bss sections is to think of "bss" as an abbreviation for "Better Save Space!"

Stack Segment

Stack segment is used to store all local variables and is used for passing arguments to the functions along with the return address of the instruction which is to be executed after the function call is over. Local variables have a scope to the block which they are defined in; they are created when control enters into the block. Local variables do not appear in data or bss segment. Also all recursive function calls are added to stack. Data is added or removed in a last-in-first-out manner to stack. When a new stack frame needs to be added (as a result of a newly called function), the stack grows downward (See the figure 1).


Code and Data Segments
Fig 1. - Memory layout of a C program

Heap Segment

Heap segment is also part of RAM where dynamically allocated variables are stored. In C language dynamic memory allocation is done by using malloc and calloc functions. When some more memory need to be allocated using malloc and calloc function, heap grows upward as shown in above diagram.
The stack and heap are traditionally located at opposite ends of the process's virtual address space.

Check Size of Code, Data, and .BSS Segments

The size command, a GNU utility, reports the sizes (in bytes) of the text, data, .bss segments, and total size for each of the object or archive files in its argument. By default, one line of output is generated for each object file or each module in an archive. The size command has no information for stack and heap sections because the size of those areas is decided on run-time.
For example, see the following C program and the size of its object file.

#include <stdio.h>
 
int main ()
{
  unsigned int x = 0x76543210;
  char *c = (char*) &x;
 
  if (*c == 0x10)
  {
    printf ("Underlying architecture is little endian. \n");
  }
  else
  {
     printf ("Underlying architecture is big endian. \n");
  }
 
  return 0;
}
For the above mentioned program check-endianness.c (which finds whether the underlying architecture is little endian or big endian) the size of text, data, .bss segments, and the total size is examined as follows with help of the size command. The fourth and fifth columns are the total of the three sizes, displayed in decimal and hexadecimal, respectively. You can read man page of size for more details.
[root@host ~/cprogs]$ gcc check-endianness.c -o check-endianness
[krishaku@adc6140630 ~/cprogs]$ size check-endianness
   text    data     bss     dec     hex filename
   1235     492      16    1743     6cf check-endianness

Last Word

In this tutorial we talked of memory layout of a C program, and its various segments (text or code segment, data, .bss segments, stack and heap segments). Hope you have enjoyed reading this article. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

Tuesday, 23 September 2014

How to formate Pen drive in opensuse?

Today I was wondering how to format pen drive in opensuse I searched some site

Mounting USB pen drive
1. In Ubuntu desktop, the USB pen drive will be detected and mounted automatically. In Ubuntu server command line terminal, a message will appear to notice you that some information about the USB pen drive that has been plug in or alternatively you can use fdisk command to check whether USB has been mounted or not. Here is sample

how to mount usb drive in ubuntu using terminal

1.a. If you get same output as mine then you can get mount location by using mount command

mount USB drive in Linux Mint

2. If Step 1 didn't work for you, then run dmesg command to identify the correct device name corresponding to the USB pen drive

$ dmesg

[19197.235469] sd 25:0:0:0: [sdb] Write Protect is off
[19197.235476] sd 25:0:0:0: [sdb] Mode Sense: 0b 00 00 08
[19197.236972] sd 25:0:0:0: [sdb] No Caching mode page present
[19197.236982] sd 25:0:0:0: [sdb] Assuming drive cache: write through
[19197.242047] sd 25:0:0:0: [sdb] No Caching mode page present
[19197.242055] sd 25:0:0:0: [sdb] Assuming drive cache: write through
[19197.279672] sdb: sdb1 --> Device name
[19197.282401] sd 25:0:0:0: [sdb] No Caching mode page present
[19197.282406] sd 25:0:0:0: [sdb] Assuming drive cache: write through
[19197.282410] sd 25:0:0:0: [sdb] Attached SCSI removable disk
[19199.953227] usb 2-1.1: USB disconnect, device number 28

2.a. Create Mount Point

$ mkdir -p /media/usb

2.b. Mount USB pen drive

$ sudo mount /dev/sdb1 /media/usb

Unmounting USB pen drive


1. To unmount a USB device simply run the following command

$ sudo umount /dev/sdb1

OR

$ sudo umount /media/usb

NOTE: /media/usb is a mount point.

Formatting USB pen drive


1. First make sure that USB device is not mounted, if it is then unmount it.

2. Format USB device in fat32 format

$ sudo mkfs.vfat /dev/sdb1

Note: You can use mkfs.ext3 to format to ext3 filesystem.

Caution: Enter your device name correctly otherwise it will wip out your entire data.

3. Format and change the Label of the USB drive.

$ sudo mkfs.vfat -n 'sandeep' /dev/sdb1




mount -o remount,rw /media/THE_ONE/
rm -R -f /media/THE_ONE/IMAG2781.jpg