Você está na página 1de 118

(

::

::

) Page -1-

Electronics Engineering N2NO


Newbie-2-Novice-Outline
Written By: Thomas G (08/2014)
Feel free to use: no strings attached (text content only / images respectfully referenced)

Table of Contents
1. INTRODUCTION...................................................................................................................................................2
2. SYSTEM CIRCUITS.............................................................................................................................................3
2.1 Processors........................................................................................................................................................3
2.1.1 Market........................................................................................................................................................4
2.1.2 Instruction Set Architecture (ISA)......................................................................................................5
2.1.3 Micro-Architecture (uArch)...................................................................................................................6
A. Control Unit (CU).....................................................................................................................................6
B. Algorithmic Logic Unit (ALU)................................................................................................................6
C. Interrupt Requests (IRQ).......................................................................................................................6
D. Bit-Numbering (Endianness)...............................................................................................................7
E. Timing..........................................................................................................................................................7
2.2 Memory..............................................................................................................................................................7
2.2.1 Market........................................................................................................................................................7
2.2.2 Hierarchy...................................................................................................................................................7
A. Processor Registers...............................................................................................................................8
B. Cache..........................................................................................................................................................8
C. Main Memory............................................................................................................................................9
D. Secondary Memory................................................................................................................................9
2.2.3 Management............................................................................................................................................9
A. Memory Management Unit (MMU)....................................................................................................9
B. Memory Controller (MEMC) ............................................................................................................10
2.3 Peripheral Buses..........................................................................................................................................10
2.3.1 Overview.................................................................................................................................................11
2.3.2 I2C............................................................................................................................................................11
2.3.3 Industry Standard Architecture (ISA).............................................................................................12
2.3.4 General Purpose I/O (GPIO)............................................................................................................12
2.3.5 Serial Peripheral Interface (SPI).....................................................................................................12
2.3.6 Joint Test Action Group (JTAG).......................................................................................................12
2.3.7 Peripheral Component Interconnect (PCI / PCIe).....................................................................12
2.3.8 Serial Communication Interfaces (SCI / RS-XXX).....................................................................12
2.3.9 Serializer/Deserializer (SERDES)..................................................................................................13
2.3.10 Universal Async Receiver/Transmitter (UART)........................................................................13
2.3.11 Universal Serial Bus (USB)............................................................................................................14
A. Abstraction Layers................................................................................................................................14
B. Functional Layer....................................................................................................................................14
C. Logical Layer..........................................................................................................................................15
D. Physical Layer.......................................................................................................................................16
2.3.12 VGA Interface Spec..........................................................................................................................18
3. CIRCUIT THEORY.............................................................................................................................................18
3.1 Analog..............................................................................................................................................................18
3.1.1 Analysis...................................................................................................................................................18
3.1.2 Transistors..............................................................................................................................................19
A. CE Amp (DC Analysis)........................................................................................................................20
B. Dual Stage NPN PNP Amplifier (AC Analysis).............................................................................20
3.1.3 Inductors/Coils......................................................................................................................................23
A. Series RL AC Circuits - Low Pass Filtering..................................................................................23
3.2 Digital...............................................................................................................................................................23
3.2.1 Sequential Logic (RTL)......................................................................................................................24
A.1 Synchronous (In-Sync).............................................................................................................24
A.2 Asynchronous (Transparent)..................................................................................................24
A.3 Implementation............................................................................................................................24
A.3.1 Finite State Machine (FSM)...............................................................................................24
A.3.2 Pipe-Lining...............................................................................................................................24
3.2.2 Combinational Logic...........................................................................................................................24
A. Algorithmic Circuits..............................................................................................................................25
B. Arithmetic Circuits.................................................................................................................................25
B.1 Negative numbers (0x7F).........................................................................................................25
B.2 Adder..............................................................................................................................................25
B.3 Boolean Algebra..........................................................................................................................25
3.2.3 Logic Gates............................................................................................................................................26
3.2.4 Discrete Logic.......................................................................................................................................26
A. 7400-Series ICs.....................................................................................................................................26
3.3 Mixed-Signal ( Analog & Digital )............................................................................................................27
4. CIRCUIT DESIGN STEPS...............................................................................................................................27
4.1 Planning..........................................................................................................................................................28
4.1.1 System Buses.......................................................................................................................................28

4.1.2 IP-Cores (Re-Use)...............................................................................................................................28


4.1.3 Design For Testability (DFT).............................................................................................................29
4.2 Schematic Entry...........................................................................................................................................29
4.3 HDL Entry.......................................................................................................................................................30
4.3.1 Verilog......................................................................................................................................................31
A. Module......................................................................................................................................................31
B. Parameter................................................................................................................................................31
C. Connectors..............................................................................................................................................31
D. Bit-Literals...............................................................................................................................................31
E. Logic Gates.............................................................................................................................................31
F. Algorithmic...............................................................................................................................................31
G. Abstraction (Generate, Sub, etc).....................................................................................................31
H. Compiler Directives..............................................................................................................................32
I. Behavioral (Always@)...........................................................................................................................32
I.1 If Else...............................................................................................................................................32
I.2 Case.................................................................................................................................................32
J. Task............................................................................................................................................................32
4.3.2 VHDL Syntax.........................................................................................................................................32
A. Include (LIBRARY / USE)..................................................................................................................32
B. External I/O (ENTITY...GENERIC/PORT).....................................................................................32
C. ARCHITECTURE (Declarations).....................................................................................................33
C.1 COMPONENT ............................................................................................................................33
C.2 CONFIGURATION.....................................................................................................................33
D. BEGIN (Structural Design)................................................................................................................34
D.1 <= and => (SIGNAL Assignment)..........................................................................................34
D.2 Logic Gates..................................................................................................................................34
D.3 GENERATE..................................................................................................................................34
D.4 WHEN...ELSE.............................................................................................................................34
D.5 WITH...SELECT..........................................................................................................................34
D.6 Arithmetic & Casting..................................................................................................................34
E. PROCESS (Sequential Design).......................................................................................................34
E.1 VARIABLE.....................................................................................................................................34
E.2 IF...THEN.......................................................................................................................................35
E.3 WAIT................................................................................................................................................35
E.4 CASE...WHEN.............................................................................................................................35
E.5 FOR...LOOP.................................................................................................................................35
E.6 WHILE...LOOP.............................................................................................................................35
F. PACKAGE................................................................................................................................................36
4.3.3 VHDL Usage..........................................................................................................................................37
A. Simulation (TestBench).......................................................................................................................37
B. ClockDiv Circuit.....................................................................................................................................37
C. Package Example.................................................................................................................................38
D. Common Errors.....................................................................................................................................38
4.4 Synthesis ( Decoding / Compiling )........................................................................................................39
4.5 Verification .....................................................................................................................................................39
4.5.1 Simulation ( SPICE / NetList )..........................................................................................................40
4.6 Target Hardware ( Fitting / Layout )........................................................................................................40
4.6.1 Integrated Circuits (IC) ......................................................................................................................40
A. Data-Base Release (DBR).................................................................................................................41
B. Wafer Fabrication (FAB).....................................................................................................................41
C. Wafer Sort (Probe)...............................................................................................................................41
D. Dice & Packaging.................................................................................................................................43
E. Final / Back-End Test...........................................................................................................................43
4.6.2 Programmable IC(s)............................................................................................................................43
A. Field Programmable Gate Array (FPGA)......................................................................................43
B. Programmable Logic Devices (PLD)..............................................................................................45
4.6.3 Printed Circuit Assemblies (PCA)...................................................................................................46
5. CIRCUIT DESIGN SOFTWARE (EDA / ECAD)........................................................................................46
5.1 Altera Quartus-II...........................................................................................................................................47
5.1.1 Qsys Designer (SOPC)......................................................................................................................49
5.1.2 Soft Core Processors..........................................................................................................................50
5.1.3 IP-Cores..................................................................................................................................................51
5.1.4 Schematic & HDL Editors..................................................................................................................52
5.1.5 Design Simulation ( Debug / Performance )................................................................................52
A. Simulation...............................................................................................................................................52
B. TimeQuest Timing Analyzer...............................................................................................................52

( 1. INTRODUCTION :: INTRODUCTION :: INTRODUCTION ) Page -2C. ELA Embedded Logic Analyzer....................................................................................................52


5.1.6 Bugs / Gotchas.....................................................................................................................................53
5.2 Xilinx ISE / Vivado.......................................................................................................................................53
A. System-Level Tools..............................................................................................................................53
B. Circuit-Level Tools.................................................................................................................................53
5.3 ModelSim........................................................................................................................................................54
6. SYSTEM SOFTWARE......................................................................................................................................55
6.1 Bootloaders....................................................................................................................................................55
6.2 Board Support Package (BSP/HAL)......................................................................................................57
6.3 Operating Systems (OS)...........................................................................................................................59
6.3.1 Market......................................................................................................................................................59
6.3.2 Windows.................................................................................................................................................60
A. Executive and Kernel (Ntoskrnl.exe)..............................................................................................61
B. Inter-process Communications (IPC Ntdll.dll)..........................................................................62
C. Environmental Subsystems...............................................................................................................62
C.1 Windows API (SCI).....................................................................................................................63
6.3.3 Memory Management.........................................................................................................................63
6.3.4 Process Management.........................................................................................................................63
A. Multiprocessor Platforms....................................................................................................................63
B. Scheduling...............................................................................................................................................64
6.3.5 Inter-Process Communication (IPC)..............................................................................................64
A. General IPC (CORBA/ORB).............................................................................................................65
B. Microsoft IPC (LPC/COM/IDL)..........................................................................................................66
C. Remote Procedure Call (RPC).........................................................................................................68
6.4 I/O Management...........................................................................................................................................69
A. Plug and Play Devices (PnP)............................................................................................................69
6.5 Unix/Linux.......................................................................................................................................................70
7. SOFTWARE DEVELOPMENT.......................................................................................................................70
7.1 Overview.........................................................................................................................................................70
7.1.1 Compilers/Interpreters........................................................................................................................72
7.1.2 Common Notations..............................................................................................................................72
7.1.3 File Extensions.....................................................................................................................................72
7.1.4 Object Oriented Programming (OOP)...........................................................................................72
7.1.5 Toolkits / Libraries................................................................................................................................74
A. Microsoft .NET.......................................................................................................................................74
B. C++............................................................................................................................................................76
7.1.6 Language Comparisons.....................................................................................................................77
7.1.7 Data Models (Serialization)...............................................................................................................77
7.2 OS Shells........................................................................................................................................................78
7.2.1 MS-DOS..................................................................................................................................................78
A. >path.........................................................................................................................................................78
7.3 Device Driver Development......................................................................................................................78
7.3.1 Driver Development Kits (DDK).......................................................................................................79
7.3.2 Kernel-Mode Driver Framework (KMDF)......................................................................................79
A. DriverEntry()...........................................................................................................................................82
B. EvtDeviceAdd()......................................................................................................................................82
B.1 Plug and Play (PnP)...................................................................................................................85
B.2 Power Management...................................................................................................................86
B.3 File / Context...............................................................................................................................88
B.4 Device.............................................................................................................................................88
B.5 Interface.........................................................................................................................................88
B.6 I/O Handling..................................................................................................................................88
C. Callback Functions...............................................................................................................................91
7.3.3 User-Mode Driver Framework (UMDF).........................................................................................96

A. Reference................................................................................................................................................96
7.3.4 Linux.........................................................................................................................................................96
A. Overview..................................................................................................................................................96
B. Code..........................................................................................................................................................96
7.4 Assembly Language (ASM)......................................................................................................................97
7.5 C & C++..........................................................................................................................................................98
7.5.1 Compilers (GCC/MSVC)....................................................................................................................99
7.5.2 C++...........................................................................................................................................................99
A. Header File...........................................................................................................................................100
A.1 #Pre-processor directives......................................................................................................100
A.2 #Include/Using..........................................................................................................................100
A.3 Namespace/Class/Struct/Union..........................................................................................100
B. Source File............................................................................................................................................101
B.1 Details..........................................................................................................................................102
C. Qt.............................................................................................................................................................103
D. Makefile.................................................................................................................................................103
7.6 Java...............................................................................................................................................................104
7.7 C#...................................................................................................................................................................105
7.8 VB6 & VBA..................................................................................................................................................105
7.8.1 VB(6&A) Learned Items...............................................................................................................105
8. INDUSTRIAL CONTROL SYSTEMS (ICS)..............................................................................................108
8.1 Allen-Bradley PLC.....................................................................................................................................108
8.2 Siemens........................................................................................................................................................109
8.3 Omron...........................................................................................................................................................109
8.4 Ladder-Logic on PLC...............................................................................................................................109
8.5 Human Machine Interface (HMI)..........................................................................................................110
8.6 Instrumentation..........................................................................................................................................110
9. NETWORKING..................................................................................................................................................111
9.1 IT Distributed Management (DMTF)....................................................................................................111
9.2 Cellular Networking...................................................................................................................................112
9.3 Area Networking (LAN/WAN)................................................................................................................113
9.3.1 OSI Protocol Model...........................................................................................................................115
A. Application Layer-7 (HTTP/POP3)...............................................................................................116
B. Presentation (Layer-6)......................................................................................................................117
C. Session (Layer-5)...............................................................................................................................117
D. Transport Layer-4 (TCP/UDP Data Segment)......................................................................117
E. Network Layer-3 (IP Packet Data).............................................................................................118
E.1 Internet Protocol (IP)...............................................................................................................118
E.2 Subnet..........................................................................................................................................119
F. Data-Link Layer-2 (MAC Frame Data)......................................................................................119
G. Physical Layer-1 (PHY Bit Data)...............................................................................................121
G.1 WAN Physical Layer...............................................................................................................121
9.4 Reference / Tools.......................................................................................................................................122
9.5 Cisco Systems............................................................................................................................................122
10. RESOURCES..................................................................................................................................................122
10.1 Engineering Models...............................................................................................................................123
10.2 Market Segments....................................................................................................................................123
10.2.1 Market-Specific Standards...........................................................................................................124
10.2.2 General Purpose Standards........................................................................................................125
10.3 Embedded System IDE.........................................................................................................................125
10.4 Symbols.....................................................................................................................................................126
10.4.1 Timing Diagrams.............................................................................................................................126
10.4.2 Schematic Symbols........................................................................................................................126

1. INTRODUCTION
Electronics Engineering Newbie-2-Novice Outline (N2NO) provides a quick outline of subjects related to the electronics engineering field. Topics will be touched upon briefly in a bullet
type format. Finer details will be left up to the reader to investigate at-will using supplied web-links.
Top-Level Terms
Architecture
Circuit
System
Component
Interface
Protocol
Bus

- Model
- Electrical Network
- Integrated Whole

= A model that defines structure, components, behavior and/or view of a system.


= An electrical network of interconnected discrete electronic elements.
= A set of interacting independent components forming an integrated whole.

- Part or Element
- Interacting Boundary
- Interface Standards
- Collective

= Relative term; A smaller, self-contained part of a larger entity. (e.g. The parts of an integrated whole)
= The shared boundary across which two separate components exchange information.
= Predefined standard of rules & regulations that determines how an interface exchanges information.
= Term that entails all related connections, software and protocols used to interface components.

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Discrete Components


http://en.wikipedia.org/wiki/Electronic_component
Wiki Dictionary Component
http://en.wiktionary.org/wiki/component
Wiki Interface
http://en.wikipedia.org/wiki/Interface_%28computing%29
Wiki Bus
http://en.wikipedia.org/wiki/Bus_%28computing%29
Wiki Protocols
http://en.wikipedia.org/wiki/Protocol

( 2. SYSTEM CIRCUITS :: SYSTEM CIRCUITS :: SYSTEM CIRCUITS ) Page -3-

2. SYSTEM CIRCUITS
Categories
Computer System
Embedded System
Consumer Electronics

- Software Operated
- Firmware Operated
- Circuit Operation

= Preforms a variety of functions by means of loading a list of execution instructions (ie: Software)
= Dedicated function by means of fixed-in-hardware list of execution instructions (ie: Firmware)
= Electronic equipment for everyday use that may or may not contain a Computer or Embedded System.

Implementation Hardware
SOC
SOPC
PCA

+ System On a Chip
+ System On a Programmable Chip
+ Printed Circuit Assembly

System Components
Processor
Memory
Peripheral Buses
System Buses

- Obeys Instructions
- Stores Instructions / Data
- Processor IO
- Internal Processor IO

= Hard-Processor, Memory and Peripherals integrated on a single IC ( e.g. Microcontroller )


= Soft-Processor, Memory and Peripherals integrated on a single Programmable IC
= System implemented on a Printed Circuit Assembly (PCA) like a PC-Motherboard or Daughter Card

= Named circuits that processes instructions as defined by a processor's Instruction Set Architecture (ISA)
= Electrical signal storage typically used to store the list of instructions and other data
= Communication (ie: Input/Output(IO)) bus between processor and an Internal/External devices
= Embedded Systems can use standard interconnect fabric between internal components

System Software
Implementation Categories
Software
= Dynamic execution instructions typically for computer systems.
Firmware
= (ie: Embedded Software); Static Instructions that are an essential part to hardware control.
Purpose Categories
System Software
Application Software

= Software or Firmware designed to Isolate Application Software from hardware control by providing a standard platform.
= Software or Firmware designed for the system user; Including the programming languages used to create system software.

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Covers many details of low/high level programming and Processor architectures http://en.wikipedia.org/wiki/Computer
Details including ASIC and FPGA solutions
http://en.wikipedia.org/wiki/Embedded_system
(Example of an Embedded System / Microcontroller ) Automotive Engine Controller http://en.wikipedia.org/wiki/Electronic_control_unit

2.1 Processors
Processor tasks
1. Drive Address Bus
2. Activate Enable
3. Fetch Data from Data Bus
4. Control Unit - receives instructions from RAM
5. Interrupt Handling (IRQ)

Implementation Groups
Microprocessor
Microcontroller
HPS
SPS

- Discrete component
- Hardware control purpose
+ Hard-Core Processor System
+ Soft-Core Processor System

= Processor is a discrete device physically separate from the main memory.


= Typically any Processor + Memory integrated circuit (IC) centered at controlling hardware.
= Processor is implemented into a hard-wired circuit
= Processor is loaded onto a Programmable IC (ie: SOPC)

Architectures
Von Neumann
Harvard

= (ie: Princeton) Any control circuit that can store, load and execute instructions dynamically from memory using a single pathway
= A Von Neumann with two physically separate storage and pathways; one for data and one for instructions

Instruction Set Architecture (ISA)


= Defines processors machine language, word size, memory addressing, registers and data formats.
CISC
+ Complex Instruction Set Computer
= Less registers, more clock cycles, more circuitry for heavy-use functions, variable bit-width instructions
RISC
+ Reduced Instruction Set Computer
= More registers, less clock cycles, compiler optimization, fixed bit-width instructions (16/32/64-bits)
uArch

+ Micro-Architecture

= The processors hardware (ie: circuit design) that implements the tasks of the ISA

( 2.1 SYSTEM CIRCUITS :: Processors :: Processors ) Page -4-

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Computer Architectures


http://en.wikipedia.org/wiki/Computer_architecture
Wiki List of Architectures
http://en.wikipedia.org/wiki/List_of_CPU_architectures
Wiki Micro-Architecture
http://en.wikipedia.org/wiki/Microarchitecture
YouTube; How a CPU works
https://www.youtube.com/watch?v=cNN_tTXABUA

2.1.1 Market
Purpose Groups
CPU
MCU
DSP
GPU

+ Central Processing Unit


+ Microcontroller Unit
+ Digital Signal Processor
+ Graphics Processor Unit

= CPU can infer box, board or processor chip that performs different tasks under software control.
= Processor + Memory + IO Control integrated on one chip
= Optimized for digital signal processing generally from an analog source
= Optimized for displaying image and frame buffers

Common Processors
AMD
ARM
- Acorn Computers Ltd
= A fab-less design company that sells power optimized processor designs
Broadcom
Intel
RISC based ARM (by ARM Holding Co), AVR (by Atmel Technologies), PowerPC, SPARC/LEON, MIPS, Nios

Development Tools
Bochs
QEMU
Galileo
Shark Cove

- x86, x64 Emulator


- x86, ARM, SPARC, Power-PC Emulator
- Intel Quark SoC X1000 Processor
- Intel Atom Processor

http://en.wikipedia.org/wiki/Bochs
http://en.wikipedia.org/wiki/QEMU
http://www.intel.com/content/www/us/en/do-it-yourself/galileo-maker-quark-board.html
http://www.sharkscove.org/

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------About Microcontroller


http://en.wikipedia.org/wiki/Microcontroller
List of Micro-controllers
http://en.wikipedia.org/wiki/List_of_common_microcontrollers
List of Microprocessors
http://en.wikipedia.org/wiki/Category:Lists_of_microprocessors
List of Soft-Core Processors
http://en.wikipedia.org/wiki/Soft_microprocessor
List of Processor Emulators
http://en.wikipedia.org/wiki/Comparison_of_platform_virtual_machines
List of Development Boards
http://en.wikipedia.org/wiki/Microprocessor_development_board
Single-Board Computers
http://en.wikipedia.org/wiki/Single-board_computer
MS-Windows compatible development boards
http://msdn.microsoft.com/en-US/windows/hardware/dn770216
ARM Processors
http://www.arm.com/products/processors/

2.1.2 Instruction Set Architecture (ISA)


ISA Models
Controller Model
Data-path Model
Finite State Machine w/Data-path (FSMD)
Java Virtual Machine (JVM)
Parallelism ISA Model
Single Instruction Multiple Data (SIMD)
Super-scalar Machine
Very Long Instruction Word (VLIW)

= Application-Specific purpose; simple slave processors (e.g. TV receiver board, GPU, etc...)
= Repeatedly preforms same computations on a stream of data (e.g. Digital Signal Processors - DSP's)
= Combination of Controller/Data-path typically implemented on FPGA(s) and/or PLD(s) (e.g. MPEG Decoder)
= Some processor's ISA can run Java byte-code via hardware (e.g. aJile's aj-80, aj-100)

= Processes a single OpCode on multiple Operands


= Processes multiple OpCodes per clock cycle through multiple functional components
= Combines single operations into a multiple OpCode which are later broken and executed in parallel

Items of an Instruction Set Architecture (ISA)


Memory
- Memory Access
= Defines how internal registers/cache memory is accessed and lay-ed out
IRQ
+ Interrupt Request
= Defines how interrupt requests are processed and activated
Machine Language
= The processors available instructions as a sequence of signals (e.g. 1's High / 0's Low)
Assembly Language
= The processors available instructions as a human readable representation of the processors machine language
OpCode
- Operation Code
= Instruction/Command to be executed

( 2.1.2 SYSTEM CIRCUITS :: Processors :: Instruction Set Architecture (ISA) ) Page -5 Operand

- Data

= Data or memory location the OpCode applies to

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Instruction Set


http://en.wikipedia.org/wiki/Instruction_set
Wiki List of Instruction Sets
http://en.wikipedia.org/wiki/List_of_instruction_sets
A. Control Unit (CU)
Control Unit (CU) Tasks
1. Generates Timing Signals
2. Reset Vector Offset
3. Run-Cycle
4. Program Increment
Controls Data-path
Maintains State History

Address of very first instruction after Power-On / Reset De-Assert


Fetch Decode (May route to ALU) Execute the Instructions on Data
Increments the Instruction Pointer (IP) or Program Counter (PC) register
Controls the control bus of the data-path using a finite state machine (FSM) and thus is a Sequential Circuit
Which accommodates Interrupts and Exception handling

Containing Circuits
Address Generation Unit
Branch Prediction Unit
Sequencer
Instruction Queue

Processes branch instructions


Centralized control of Instruction flow
Stores the next instruction to be processed and dispatches next instruction to the queue to appropriate execution

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Control Unit


http://en.wikipedia.org/wiki/Control_unit
B. Algorithmic Logic Unit (ALU)
Preforms
Mathematical operations
Comparison operations
Logic operations

ALU is typically an asynchronous circuit


Does not store/transfer; Two inputs One output
Inputs do have bus registers to hold data (Input A, Input B(temp register to store from bus), Input TYpe of OPeration, COmpare Flags - CU, Output f)

C. Interrupt Requests (IRQ)


Interrupts

Stop standard execution to execute event-based (ie: OnEvent) functions (e.g. hardware issues, resets)

D. Bit-Numbering (Endianness)
8-bits = 1-byte
Word = 16-bits (2-bytes) (0xFFFF)
Double Word = 32 bits (4-bytes) (0xFFFF_FFFF)
Endianness is also called byte-ordering
Endianness = Is a BYTE(8-bits) level order (2-digit HEX Swap)
Little-endian
= Least significant byte is at byte(0) in Left Right.
Big-endian
= Most significant byte is at byte(0) in Left Right.
Bit-Significance
LSB
+ Least significant bit
MSB + Most significant bit
Timing
Time handling makes sure logic-element-1 has evaluated before its output is fed into logic-element-2
Register = Is a Flip-Flop circuit that holds it's output state (has memory).

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Bit_numbering


E. Timing
--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Processor_register
http://computer.howstuffworks.com/microprocessor2.htm
http://en.wikipedia.org/wiki/Register_transfer_level
Firmware::Assembly Language
https://www.youtube.com/watch?v=cNN_tTXABUA
http://en.wikipedia.org/wiki/Microarchitecture

2.2 Memory
Market
Hierarchy

= Types of memory that are available


= Usage of memory

( 2.2 SYSTEM CIRCUITS :: Memory :: Memory ) Page -6 Management


MMU
MPU
MEMC

= How memory is visualized, partitioned and accessed by the system


- Memory Management Unit
- Memory Protection Unit
- Memory Controller

2.2.1 Market
Volatile Memory (ie: non-permanent)
DRAM + Dynamic random-access memory
= Capacitor Storage
SDRAM
+ Synchronous Dynamic RAM = Requires a refresh clock and synchronous clock (storage cells are made of capacitors)
RDRAM
+ Rambus DRAM
DDR-SDRAM
+ Double Data Rate SDRAM
FPM-DRAM
+ First Page Mode DRAM
EDO-DRAM
+ Extended Data Out DRAM
VRAM
+ Video RAM
SGRAM
+ Synchronous Graphics RAM
PSRAM
+ Pseudostatic RAM
SRAM

+ Static random-access memory

= A network of digital flip-flops for memory storage

Permanent Memory (ie: non-volatile memory (NVM))


ROM
MROM
PROM
OTP
EPROM
EEPROM

+ Read Only Memory


+ Mask ROM
+ Programmable ROM
+ One-Time Programmable
+ Erasable PROM
+ Electronic EPROM

= Manufacturing etching facility etches data into the memory circuit


= Programmed once; outside the manufacturing etching facility
= Alias term to PROM
= Ultra-violet light to erase selective or the entire memory & electronic programming. (Uses FAMOS transistors)
= Electronic erase and programming (Uses FLOTOX transistors) must be erased entirely

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Static_random-access_memory


http://en.wikipedia.org/wiki/Semiconductor_memory

2.2.2 Hierarchy
Memory Hierarchy
Processor Registers
Cache
Main Memory
Secondary Memory

= (ie: Register File) Is the fastest closest memory to store operands that are being frequently used

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Memory Hierarchy


http://en.wikipedia.org/wiki/Memory_hierarchy
A. Processor Registers
Common Registers
User-Accessible
Data
Address
GPR
+ General Purpose Registers
Conditional
FPR
+ Floating Point Registers
Constant
Vector
SPR
+ Special Purpose Registers
Control
Status
IAP
- Instruction Address Pointer
Flags
- Bit-wise control/status
MTRR
Shift
Counter

+ Memory Type Range Registers


- Specifically for bit shifting
- Specifically for increments or decrements

Internal
Instruction
MBR
+ Memory Buffer Register
MDR
+ Memory Data Register
MAR
+ Memory Address Register
Memory Data (
Accumulator
- (ie: Summation) Stores numeric values Floating Point
Load-Store Model (RAM -> Register)
In-line barrel shift-er
MMIO + Memory Mapped Input Output

= Peripheral control is accessed by vendor implemented memory addresses (ie: Registers)

( 2.2.2 SYSTEM CIRCUITS :: Memory :: Hierarchy ) Page -7-

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Processor Registers


http://en.wikipedia.org/wiki/Processor_register
Wiki Digital Registers
http://en.wikipedia.org/wiki/Category:Digital_registers
B. Cache

Cache
Cache Hit
Cache Miss

= Memory data resides in the cache


= Memory data must be gotten from a higher-level memory source

Cache Schemes
Direct Mapped = Data in cache is located by its associated block address in memory (ie: Tagged)
Set Associative = Cache is divided into sets where multiple blocks can be placed; Blocks are located according to an index field that maps into a set
Full Associative = Blocks are placed anywhere in cache and must be located by searching the entire cache memory each time
Transfers from main-memory using one-word or multi-word blocks; Blocks contain the data and main memory location (ie: Tags)
Cache Levels
L0 Micro-operations cache
L1 Separate Instruction/Data Cache
L2 Shared Instruction/Data Cache
L3 Shared Cache; 6MiB; 100 GB/s
L4 Shared Cache; 128Mib; 40GB/s

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki CPU Cache http://en.wikipedia.org/wiki/CPU_cache


Cache
http://en.wikipedia.org/wiki/Cache_%28computing%29
C. Main Memory
Main Memory
Permanent Memory

Only implemented On-Chip on Micro-Controllers


Only implemented On-Chip via Flash on Micro-Controllers

D. Secondary Memory
Memory Hardware
Hard Disk Drive
Tape Backup
Flash Memory

2.2.3 Management
Memory Management Groups
Hardware Memory Management
- Typically resides in the Processor IC but can reside as a separate IC.
OS Memory Management
Windows
= Virtual Memory Scheme
Linux
Application Memory Management

Memory Architecture
Linear
Segmented

= Memory address arranged 0 2^(N-1)


= Memory address arranged with offsets

Base Address::Offset

Addressing Architecture
Load-Store
Register-Memory

= Only allows OpCodes on Operands in register memory


= Allows OpCodes on both register and other memory locations

Memory Addressing
= A Processors ISA defines how the processor sees the data (ie: Operand) storage and addressing modes
Logical
Virtual
= Memory Addresses are Virtual. Addressing to physical memory is handled by look-up tables in the memory manager.
Physical
= Actual (Row,Col) addressing; no encoding/decoding of addresses
Memory Map (MM)
= Processor/Software treats memory as one large one-dimensional array
Direct Mapping
= TAG / CACHE / OFFSET
Associative Cache
=

( 2.2.3 SYSTEM CIRCUITS :: Memory :: Management ) Page -8-

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Subject 6.3.3 (pg) System Software :: Operating Systems (OS) :: Windows :: Memory Management
http://en.wikipedia.org/wiki/Category:Memory_management
https://www.kernel.org/doc/gorman/pdf/understand.pdf
MSDN Virtual Address Space Explained
https://msdn.microsoft.com/en-us/library/windows/hardware/hh439648%28v=vs.85%29.aspx
A. Memory Management Unit (MMU)
Cache memory can be behind an MMU or skip the MMU
Memory Scheme
segmentation
paging
both

= Schemes in translating addresses (Determined by the OS Software MMUs and OS manage virtual memory)
= Dividing logical memory into large variable-size sections
= Dividing logical memory into smaller fixed-sized units

Features
DMA
MM
TLB
Bus Arbitration
Exceptions
Security
Shared
Page Fault

+ Direct Memory Access


+ Memory Mapping
+ Translation Look-Aside Buffer

= Off-chip memory can be accessed directly by slave processors w/o going through the main processor
= Translates logical addressing into physical addressing
= Cache memory allocated for mapping logical addresses into physical addresses

= Supplies memory protection schemes


= Read/Write or Read/Only access to various pages/segments of memory; Throws an interrupt if access permission is violated
= A page/segment isn't accessible during address translation (secondary memory may need to be used)

Note:: Some chips don't have Memory-Mapped I/O (have instruction 'OUT' and 'IN') this route is mostly historical. (x86 has it?)

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Memory Management Unit


http://en.wikipedia.org/wiki/Memory_management_unit
Wiki Page Table
http://en.wikipedia.org/wiki/Page_table
B. Memory Controller (MEMC)
Manages/Merges the many banks of different types of memory
DRAM Controller
= MEMC that manages only DRAM type memory
Cache Controller
= MEMC that manages only Cache type memory
Physical addressing
Glue-less interface
One set of addresses for many different types of memory (Manages/Merges the many banks of memory)
Synchronizes access
Verifies integrity
RAM Address Data
BUS Registers / Latches
Just like RAM but inside CPU (Register has set/enable lines set=save, enable=read) All on CPU BUS.
ECC = ECC - Error correction code (Corrects bad bits in memory)

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki Memory Controller


http://en.wikipedia.org/wiki/Memory_controller

2.3 Peripheral Buses


Peripheral Devices and Interconnection Standards can often go hand-in-hand since every peripheral device requires a standard connection bus

Processor I/O Items


Transmission Medium
= Wireless, Wired Physical item that communications are routed on
Communication Port
= What the Transmission Medium connects to; In wireless the item that receives the signal
Communication Interface
= Encoding/Decoding Communication Standards between the Master Processor and I/O devices or controllers
Controller
= Slave Processor that manages the I/O device
Bus
= Connection between board I/O and Master Processor
Master Processor Integrated I/O

( 2.3 SYSTEM CIRCUITS :: Peripheral Buses :: Peripheral Buses ) Page -9-

Processor I/O Peripheral Buses Categories


Networking and Communications I/O
Input
Graphics and Output I/O
Storage I/O
Debugging I/O
Real-Time & Miscellaneous I/O
1. Terms
a) DDIO
b) LVDS
c) GSPS
d) TLP

= Physical Layer of OSI-Model


= Keyboard, Mouse, Remote Control, Voice, Sensors, etc...
= Touch Screen, CRT, Printers, LEDs, etc..
= CD, Magnetic Disk and Tape Controllers
BDM, JTAG, Serial Port, Parallel Port, etc...
Timers/Counters, Analog-to-Digital Converter (ADC), Digital-to-Analog Converter (DAC), switches, etc...

Double data rate I/O


Low Voltage Differential Signal
Giga Samples per Second.
Transaction Layer Packets (PCIe)

= Data is transferred at both the rising and falling edges of a master clock
= Logic signals 1 and 0 are transferred using a difference between 2-line voltages

2. How to Find Hardware Interface / Protocol Standards


a) ISO
b) ISO/IEC
c) JEDEC
d) AEC

+ International Standards Organization


+ International Electra-technical Commission
+ Joint Electron Device Engineering Council
+ Automotive Electronics Council

http://en.wikipedia.org/wiki/International_Organization_for_Standardization
Technical Management Board members is responsible for over 250 technical Committees.)
Is a Technical Committee of ISO. ( http://www.iec.ch/ )
Global standards for the microelectronics industry http://www.jedec.org/
http://www.aecouncil.com/

e) The organization's headquarters were in Arlington, Virginia. The EIA divided its activities into the following sectors:
ECA
Electronic Components, Assemblies, Equipment & Supplies Association
JEDEC
JEDEC Solid State Technology Association, former Joint Electron Devices Engineering Councils
GEIA
(now part of TechAmerica), Government Electronics and Information Technology Association
TIA
Telecommunications Industry Association
CEA
Consumer Electronics Association

3. List of Common Peripherals


a) Discrete IO
GPIO
- General Purpose Input/Output
PIO
- Parallel Input/Output
SSD
- 7-Segment Display
b) Debugging
JTAG
- IEEE standard interface for chip ID activation and for testing/programming.
ISP
ICSP
BDM Port
BITP
DP9 Port
c) SCI
+ Serial Communication Interfaces
RS-232
RS-422
RS-485 and etc...
d) SSCI
I2C
SPI
SSC
ESSI

- Synchronous Serial Communication Interfaces


- Serial Peripheral Interface
- Enhanced Synchronous Serial Interface

e) USB

- Universal Serial Bus

f) Multi Media Cards


SD Cards
Compact Flash
g) Networks
MAC/PHY
Ethernet
LonWorks

- Ethernet Interface

h) Fieldbus
CAN-Bus
LIN-Bus
PROFIBUS
i) Timers
PLL
Capture/Compare
Time Processing Units

- Phase Lock Loop

j) Analog-to-Digital (ADC) / Digital-to-Analog (DAC)

( 2.3 SYSTEM CIRCUITS :: Peripheral Buses :: Peripheral Buses ) Page -10-

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------List of common External and Internal Bus Standards


http://en.wikipedia.org/wiki/Bus_%28computing%29#Examples_of_internal_computer_buses
http://www.xilinx.com/ise/embedded/edk_ip.htm
http://www.bottomupcs.com/peripherals.html
Bandwidth of Common Peripheral Buses
http://en.wikipedia.org/wiki/List_of_device_bandwidths
Wiki Peripheral
http://en.wikipedia.org/wiki/Peripheral

2.3.1 Overview
Serial Interfaces
Terms
SCC
SMC
FIFO
Bandwidth

+ Serial Communication Controller


+ Serial Management Controller
+ First In / First Out Buffer Memory
= The amount of data that can be carried in a serial link (data-bits per second)

Capabilities
Simplex
Half Duplex
Full Duplex

= Either Sends OR Receives Permanently


= Sends OR Receives at one direction at a time
= Sends AND Receives at the same time (e.g. Twisted Pair)

Synchronization
Synchronous
Asynchronous

Continuous stream at regular intervals (clocked)


Intermittent at random intervals (Includes a START/STOP bit signal)

2.3.2 I2C
Signals
START = SDA line transitions from HIGH->LOW while SCLK is HIGH
STOP = SDA line transitions from LOW->HIGH while SCLK is HIGH
Rules
SDA must never change while SCLK is HIGH (Unless marking a Condition change)
8-bits is always transfered at once (followed by 9th bit a read-back ACKnowledge)
1st 8-bits are the SHIP Address or CHIP ID address which is actually 7-bit with 8th bit indicating Read/Write
SDA/SCL in an idle state are required to be pulled high to VDD_IO level. This can be done with either 1K pull-up resistors on the probe-card or using the tester to hold the levels
high.
CHIP_ID |
11-1111-1111-22222
0123-4567-|-8901-2345-6789-01234
-------------------------------------|CHIPID|
|-16BIT REG ADDR -|
1st - 0010-0000-L-0000-0000-0000-0000
2nd - 0010-0001-L-VVVV-VVVV-VVVV-VVVV
|
| ^ACK
|
^Read=1,Write=0
^t_i2c_st
I2C CLK can run at typically 100KHz (standard) or 400KHz (high-speed)

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------I2C Spec Sheet


http://www.i2c-bus.org/fileadmin/ftp/i2c_bus_specification_1995.pdf
Wiki I2C
http://en.wikipedia.org/wiki/I%C2%B2C
Nice I2C Tutorial
http://www.esacademy.com/en/library/technical-articles-and-documents/miscellaneous/i2c-bus.html

2.3.3 Industry Standard Architecture (ISA)


2.3.4 General Purpose I/O (GPIO)
2.3.5 Serial Peripheral Interface (SPI)
Full-Duplex, Master(Initiates data frame)/Slave(Multiple w/Chip Select), 4-wire Serial Bus, often called SSI

Synchronous Transmission

( 2.3.5 SYSTEM CIRCUITS :: Peripheral Buses :: Serial Peripheral Interface (SPI) ) Page -11-

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus (by Motorola)


Full-Duplex, Master(Initiates data frame)/Slave(Multiple w/Chip Select), 4-wire Serial Bus, often called SSI

2.3.6 Joint Test Action Group (JTAG)


IEEE 1149.1 Standard Test Access Port and Boundary-Scan ie: Scan Chain STUCK_AT
Pins
TDI (Test Data In)
TDO (Test Data Out)
TCK (Test Clock)
TMS (Test Mode Select)
TRST (Test Reset) optional.

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki JTAG


http://en.wikipedia.org/wiki/JTAG

2.3.7 Peripheral Component Interconnect (PCI / PCIe)


--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------PCI Bus
http://www.techfest.com/hardware/bus/pci.htm
PCIe v3.0 Specification document
http://komposter.com.ua/documents/PCI_Express_Base_Specification_Revision_3.0.pdf

2.3.8 Serial Communication Interfaces (SCI / RS-XXX)


1. SCI

= Serial Communication Interfaces (RS-232, RS-422, RS-485)

2.3.9 Serializer/Deserializer (SERDES)


SERDES
PISO
SIPO

A Pair of functional blocks that convert between serial & parallel in both directions
Parallel In Serial Out
Serial In Parallel Out

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Wiki SerDes


http://en.wikipedia.org/wiki/SerDes

2.3.10 Universal Async Receiver/Transmitter (UART)


UART = Universal Asynchronous Receiver/Transmitter) Translates parallel to serial and vice versa
Asynchronous Transfer
Full Duplex
Based on the 8251 UART Controller
Pins
TXDx
Transmit Pins
RXDx
Recieve Pins
CDx
Carrier Detect Pins
CTSx
Clear To Send
RTS
Request To Send Pins

( 2.3.11 SYSTEM CIRCUITS :: Peripheral Buses :: Universal Serial Bus (USB) ) Page -12-

2.3.11 Universal Serial Bus (USB)


Versions
USB

Speed (Name)

Host Controller

_ 1.0 Low-Speed(1.5Mbit/s) / Full-Speed(12Mbit/s)


_ 1.1 Same speeds as 1.0 with added functionality

UHCI = Universal Host Controller Interface by Intel


OHCI = Open Host Controller Interface by Others

_ 2.0 High-Speed(480Mbit/s)

EHCI = Enhanced Host Controller Interface

_ 3.0 Super-Speed(5Gbit/s) has more connectors

XHCI = eXtensible Host Controller Interface

USB 1.0 was released in 1996


USB 1.1 was released in 1998 containing clarification & improvements over USB 1.0 only
DC
+ Device Controller
OTG
+ On-The-Go
= Supplement protocol allowing a switch-in USB Host controller in a USB device (ie: non-PC USB Host)
Typically for products like cell-phones and mobile devices that often need to preform as both a Device and a Host for other devices.

A. Abstraction Layers
Functional Layer (Software)
View-point that abstracts (removes) logical & physical layer details

[ Client Software ] >> Pipes >> [ Device Function Interfaces ]


* Pipe = Virtual Communication Channels
a) Control Pipes = Bi-directional (Default Control Pipe)
b) Data Pipes = Uni-directional one-way
Each device can contain multiple pipes through which the host may
communicate with the device.

Logical Layer (Controllers)


View-point that abstracts (removes) functional & physical layer details.
[ Host ] [ Pipes ] [ Device::endpoint(#) ]
Client SW (USBD) System SW (HCD) Device::endpoint(#)
* USBD
* HCD
* Enumeration
* Endpoint

= USB Driver
= Host Controller Driver
= USB Device initialization
= Addressable buffer ( holder for to/fro host data )

Physical Layer ( Wire/Bus )


View-point of electrical wire/signal connections removing logical & functional.
Host (typically a PC containing a host controller & host/root hub)
- Initiates all communication and polls devices for receivable data.
- Communication between host / devices is preformed via data Packets.
a) OUT transfer = Host Device
b) IN transfer = Device Host
* SIE = Serial Interface Engine - used to parse incoming traffic.
Compound/Composite Devices have multiple interfaces (e.g. fax, scan, print)

B. Functional Layer
Communication duties
Host controls all communications
System SW maintains ownership of the Default Control Pipe (ie: Endpoint(0))
Client SW requests data transfer via I/O Request Packets (IRP) to a pipe.
IRP details are part of the hosts operating system (OS)
Enumeration Process (ie: Device Initialization / Introduction)
1. USB device is connected to a host and drives (D+) or (D-) high
2. Host sends device a Reset (ie: D+/D- held low for 3-ticks 'SE0')
3. Host requests USB device descriptors using the Default Control Pipe (ie: Device(00h)::Endpoint(0h))
4. Device Responds with it's descriptor information.
5. Host assigns the device a 7-bit address
6. Host uses the newly assigned device address to request device descriptors a 2 nd time. (ie: Device(#)::Endpoint(0h))
7. Device Responds with it's descriptor information.
8. Host locates the device drivers by reading (.INF) file for driver location and loading driver (.SYS)
9. Host selects the appropriate configuration for the device and device is set to a 'configured' state.
Device Descriptors
Device Descriptor ( Only 1 per device )
Offset
0
1
2
4

5
6
7
8
10
12
14

Field
bLength
bDescriptorType
bcdUSB
bDeviceClass

bDeviceSubClass
bDeviceProtocol
bMaxPacketSize
idVendor
idProduct
bcdDevice
iManufacturer

Bytes
1
1
2
1

1
1
1
2
2
2
1

Value
Number
Constant
BCD
Class

SubClass
Protocol
Number
ID
ID
BCD
Index

Description
Size of the Descriptor in Bytes (18 bytes)
Device Descriptor (0x01)
USB Specification Number which device complies too.
Class Code (Assigned by USB Org)
If equal to Zero, each interface specifies its own class code
If equal to 0xFF, the class code is vendor specified.
Otherwise field is valid Class Code.
Subclass Code (Assigned by USB Org)
Protocol Code (Assigned by USB Org)
Maximum Packet Size for Zero Endpoint. Valid Sizes are 8, 16, 32, 64
Vendor ID (Assigned by USB Org)
Product ID (Assigned by Manufacturer)
Device Release Number
Index of Manufacturer String Descriptor

( 2.3.11 SYSTEM CIRCUITS :: Peripheral Buses :: Universal Serial Bus (USB) ) Page -1315
16
17

iProduct
iSerialNumber
bNumConfigurations

1
1
1

Index
Index
Integer

Index of Product String Descriptor


Index of Serial Number String Descriptor
Number of Possible Configurations

Configuration Descriptor (Only one active at a time user / driver selects the configuration typically there is only one)
Offset
0
1
2
4
5
6
7

Field
bLength
bDescriptorType
wTotalLength
bNumInterfaces
bConfigurationValue
iConfiguration
bmAttributes

bMaxPower

Bytes
1
1
2
1
1
1
1

Value
Number
Constant
Number
Number
Number
Index
Bitmap

mA

Description
Size of Descriptor in Bytes
Configuration Descriptor (0x02)
Total length in bytes of data returned
Number of Interfaces
Value to use as an argument to select this configuration
Index of String Descriptor describing this configuration
D7 Reserved, set to 1. (USB 1.0 Bus Powered)
D6 Self Powered
D5 Remote Wakeup
D4..0 Reserved, set to 0.
Maximum Power Consumption in 2mA units

Interface Descriptors (Function Interfaces Multiples allowed in a Compound/Composite devices (e.g. fax, scan, print))
Each Interface can have alternate settings (ie: Various switchable blocks of endpoint settings)
Offset
0
1
2
3
4
5
6
7
8

Field
bLength
bDescriptorType
bInterfaceNumber
bAlternateSetting
bNumEndpoints
bInterfaceClass
bInterfaceSubClass
bInterfaceProtocol
iInterface

Bytes
1
1
1
1
1
1
1
1
1

Value
Number
Constant
Number
Number
Number
Class
SubClass
Protocol
Index

Field
bLength
bDescriptorType
bEndpointAddress

Bytes
1
1
1

Value
Number
Constant
Endpoint

Description
Size of Descriptor in Bytes (9 Bytes)
Interface Descriptor (0x04)
Number of Interface
Value used to select alternative setting
Number of Endpoints used for this interface
Class Code (Assigned by USB Org)
Subclass Code (Assigned by USB Org)
Protocol Code (Assigned by USB Org)
Index of String Descriptor Describing this interface

Endpoint Descriptors
Offset
0
1
2

bmAttributes

Bitmap

4
6

wMaxPacketSize
bInterval

2
1

Number
Number

Description
Size of Descriptor in Bytes (7 bytes)
Endpoint Descriptor (0x05)
Endpoint Address
Bits 0..3b Endpoint Number.
Bits 4..6b Reserved. Set to Zero
Bits 7 Direction 0 = Out, 1 = In (Ignored for Control Endpoints)
Bits 0..1 Transfer Type
00 = Control
01 = Isochronous
10 = Bulk
11 = Interrupt
Bits 2..7 are reserved. If Isochronous endpoint,
Bits 3..2 = Synchronisation Type (Iso Mode)
00 = No Synchonisation
01 = Asynchronous
10 = Adaptive
11 = Synchronous
Bits 5..4 = Usage Type (Iso Mode)
00 = Data Endpoint
01 = Feedback Endpoint
10 = Explicit Feedback Data Endpoint
11 = Reserved
Maximum Packet Size this endpoint is capable of sending or receiving
Interval for polling endpoint data transfers. Value in frame counts. Ignored for Bulk & Control Endpoints.
Isochronous must equal 1 and field may range from 1 to 255 for interrupt endpoints.

Device Class Codes


= Predefined standard USB device/driver collections that allows standard OS drivers to handle typical devices
* Class codes are set in the Device Descriptor byte-4 and Interface descriptor byte-6
* Bluetooth also uses the USB device classes
HID
+ Human Interface Devices
MSD + Mass Storage Devices
CDC + Communication Device Class
Vendor Specific No standard USB driver; A custom vendor specific driver needs to be created.
There are two levels of APIs related to USB HID: the USB level and the operating system level. At the USB level, there is a protocol for devices to announce their capabilities
and the operating system to parse the data it gets. The operating system then offers a higher-level view to applications, which do not need to include support for
individual devices but for classes of devices. This abstraction layer allows a game to work with any USB controller, for example, even ones created after the game.

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------USB Device classes


http://en.wikipedia.org/wiki/USB#Device_classes
Microsoft USB-Viewer (Part of WDK Windows Driver Kit)
C. Logical Layer
Endpoint = A communication pipe ending created during device design (ie: Part of the USB devices architecture)
Endpoints other than Endpoint(0) must be configured by the host before data transfer can occur on them.
Endpoints are defined and explained to the host using endpoint descriptors (see above in Functional Layer)
Endpoints are addressed using the [ Device-ID | Endpoint # | Data Direction ] combination.
Each Device can support up to 15-IN and 15-OUT endpoints as a Full-Speed device.
Endpoint(0) = (ie: The default control pipe ending) that must be implemented on ALL USB devices for device enumeration

( 2.3.11 SYSTEM CIRCUITS :: Peripheral Buses :: Universal Serial Bus (USB) ) Page -14 Pipes

= Representation of data movement between host software (via Memory Buffers) and endpoints on devices

Transfer-Type

Pipe Mode

Description

Transaction Packets

Control

Message
Control Pipe

Device initialization and pipe control; Bi-directional simple commands / status

Endpoint(0) = Default Control Pipe

Bulk

Stream
Data Pipe

Large payloads, uni-directional per endpoint (file transfers)

Interrupt

Stream
Data Pipe

Timely and reliable, uni-directional (guaranteed pick-up response rates)

Isochronous

Stream
Data Pipe

Pre-negotiated bandwidth (streaming real time transfers) guaranteed data rate (audio / video)

Transfer-Type specifies and typically consists of multiple packets


Data format imposed by the USB
Direction of communication flow
Packet size constraints
Bus access constraints
Latency constraints
Required data sequences
Error Handling
Example Low-Speed Interrupt pipe OUT packets are:
[PRE] [Token] [PRE] [Data] [Handshake]
Pipe Modes
Message Pipes
= Bi-Directional to endpoints (ie: Allows IN/OUT Token packets) as defined by Control Transfer in the USB specification document.
Stream Pipes = Uni-Directional to endpoints; Data stream (FIFO) through data-packet portion of bus transactions; No USB required structure.
Framing (Each Transfer-Type defines what transactions are allowed within a frame) for an endpoint.
Full/Low-Speed devices
1-Frame = 1mS
High-Speed devices
1-Frame = 125uS
(Also called a micro-frame)
Host Controller Polls Devices by sending them a Start-Of-Frame(SOF) Packet.

D. Physical Layer
1. Device Introduction ( ie: Device is plugged physically into a USB port )
a) SE0 State - Single-Ended '0' = Both data-lines are at GND indicating a reset-device or no-device connected state.
b) J-State
- Idle State
= Device pulls a data line high (D+(full speed) /D- (low-speed)) over-ridding the hosts SE0 initial state and setting / defining the J-State.
c) K-State
- Opposite J-State = The differential data-lines pair implement NRZI line coding data representation.
d) NRZI line coding = Non Return to Zero Inverted
'0' = D+/D- compliment (ie: Inverse) previous voltage levels (ie: J K or K J)
'1' = No-change on D+/D- through a data cycle.
e) Reset / Data Polling
USB 2.0
= Host controller polls the bus for traffic (throughput is the slower one of either host / device )
USB Reset
= A Prolonged (10 to 20 mS) of the SE0-State
Low-Speed USB = Requires a Keep-Alive signal (An EOP) every 1 ms to keep device from entering suspended mode.
2. Packet Communications

(8)bit bytes least significant bit (NOTE: not byte) first (LSb)

a) Sync = Initiates communication and synchronizes / defines the data cycle speed (ie: Clock) All packets begin with a 'Sync'
Host drives 'Sync' signals on the data lines that determines the data cycle speed and signals the start of a packet communication.
USB Low/Full Speed Length: 1-byte (ie: 8-bits)
USB High-Speed Length:
4-bytes (ie: 32-bits)
Contains:
'0000_0001' (ie: KJKJKJKK states) same KJ repeat for 32-bit ending with a double KK which signals ( end-of-sync start-of-PID)
b) PID = Packet ID The Packet Type being communicated (e.g. Token, Data, Handshake, Special)
Length:
1-byte (ie: 8-bits)
Contains: [ 4-bit PID Value | 4-bit Inverted PID Value ]

Type
Reserved
Token
Special

Handshake

PID value
Transmitted byte
(msb(lsb-first)
first)

Name

Description

0000

0000 1111

1000

0001 1110

SPLIT

High-bandwidth (USB 2.0) split transaction. Sends data at high-bandwidth to a high-bandwidth HUB where it
will be transferred to a full/low bandwidth to slower devices.

0100

0010 1101

PING

Check if endpoint can accept data (USB 2.0) after getting a 'NYET'

PRE

Low-Speed packet preamble for HUB (USB 2.0 devices ignore this packet)

ERR

Split transaction error from a HUB (USB 2.0 devices ignore this packet)

1100

0011 1100

0010

0100 1011

ACK

Data packet accepted (ONLY Handshake the Host can produce)

1010

0101 1010

NAK

Data packet not accepted; please re-transmit

0110

0110 1001

NYET

Data not ready yet; Device isn't ready to receive another packet yet (USB 2.0 ONLY)

1110

0111 1000

STALL

Transfer impossible; do error recovery

( 2.3.11 SYSTEM CIRCUITS :: Peripheral Buses :: Universal Serial Bus (USB) ) Page -15-

0001

1000 0111

OUT

Contents: [Sync |PID (OUT)


|7-bit Device ADDR
|4-bit ENDP #
|5-bit CRC
|EOP ]
Purpose: (Host Device) Precedes data from host to device transfers.
Followed by Host driven DATAx frame. Device response (ACK, NAK, NYET or STALL)

1001

1001 0110

IN

Contents: [Sync |PID (IN)


|7-bit Device ADDR
Purpose: (Device Host) Request device sends data
Response: Expects a response from the device. (NAK,
Or DATAx Frame which would be followed by

0101

1010 0101

SOF

Contents: [Sync |PID (SOF)


|11-bit Frame #
|5-bit CRC
|EOP ]
Purpose: Start of frame marker (sent each ms) with incremented Frame number(revolving) in place of device
address. For isochronous and interrupt data transfers. (2.0 @ 125uS)

1101

1011 0100

SETUP

Contents: [Sync |PID (SETUP) |7-bit Device ADDR


|4-bit ENDP #
|5-bit CRC
|EOP ]
Purpose: Address for host-to-device control transfer; Follows an 8-byte DATA0 frame

Token

|4-bit ENDP #
to host
STALL)
a Host-ACK.

|5-bit CRC

|EOP ]

Data Transfers includes: [IN/OUT/SETUP Token] [Data Packet] [ACK Handshake Packet]
Payload Size Limits: HS 1024-bytes, FS 64-bytes, LS 8-bytes ( 2-packet type provides 1-bit seq number req by Stop-and-Wait ARQ.)

Data

0011

1100 0011

DATA0

Contents: [Sync |PID (DATA0) |Payload


|16-bit CRC |EOP ]
Purpose: Even-numbered data packet (Data toggles between DATA0/DATA1 for each successful packet transfer)
Response: 'ACK' is expected from either host/device (depending on IN or OUT Token)

1011

1101 0010

DATA1

Contents: [Sync |PID (DATA1) |Payload


|16-bit CRC |EOP ]
Purpose: Odd-numbered data packet (Data toggles between DATA0/DATA1 for each successful packet transfer
Response: 'ACK' is expected from either host/device (depending on IN or OUT Token)

0111

1110 0001

DATA2

Contents: [Sync |PID (DATA2) |Payload


|16-bit CRC |EOP ]
Purpose: Data packet for high-bandwidth isochronous transfer (USB 2.0)
Response: 'ACK' is expected from either host/device (depending on IN or OUT Token)

1111

1111 0000

MDATA

Contents: [Sync |PID (MDATA) |Payload


|16-bit CRC |EOP ]
Purpose: Data packet for high-bandwidth isochronous transfer (USB 2.0)
Response: 'ACK' is expected from either host/device (depending on IN or OUT Token)

ADDR::ENDP = Target device::endpoint the packet will be received by


Default:x00 is the ADDR::ENDP during device enumeration.
Low-Speed functions are limited to 2-optional endpoints beyond the 2 required at endpoint(0)
Full-Speed devices can have 15 IN & OUT endpoints
SOF = Start of Frame(#); Frame Time Markers (keep in-sync with host) full/high-speed ONLY.
Frames are a single or a collection of packets that can fit within a Frame-Time
Each Frame amount of Time must start with a SOF packet.
SOF must be sent every 3 mS to keep device from entering suspend mode.
High-Speed devices send SOF packet every 125uS but frame increments at 1mS
EOP
= End of Packet
Signaled by 2-bit times of SE0 (Single ended zero / both D+ and D- @ GND) then 1-cycle of J-State and held in the J-State (idle)
Data Communications:
[ IN/OUT Token ] [ Data Packet ] [ Handshake ] Reciever Transmitter ]
Data Packets always follow an IN/OUT/SETUP Token
PID toggles between DATA0 and DATA1 for each successful data packet transfer.
NOTE: USB has a bit stuffing rule whereas any six consecutive '1' bits must be followed with a '0' bit. **

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------USB Packet Sniffer Free Device Monitoring Studio


http://www.hhdsoftware.com/Downloads/device-monitoring-studio
Windows USB View Hardware debug application
http://code.msdn.microsoft.com/windowshardware/USBView-sample-application-e3241039
Creates C structures from USB HID Report Descriptors
http://sourceforge.net/projects/hidrdd/
Cypress Introduction to USB AN57294
http://www.cypress.com/?docID=33237
USB 2.0 Specification Documents and USB Vendor ID (for $5000) http://www.usb.org/
USB Specification Website
http://www.beyondlogic.org/usbnutshell/usb1.shtml
Altera DE2 FPGA dev board as a USB Device (No Nios) VHDL code http://mzakharo.github.io/usb-de2-fpga/

2.3.12 VGA Interface Spec


RGB Signals are Analog (Nominal Voltage 0.7Vdc)
Monitor sinks 75-Ohms on each signal.
Horizontal Sync (HS) and Vertical Sync (VS) are digital signals = these are active low
Picture is generated left-to-right(line-by-line), top-to-bottom
HS signals a new line
VS signals top of screen (top-line)
640 x 480 = 60Hz(VS) and 31.5kHz(HS)

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------http://www.fpga4fun.com/PongGame.html


http://martin.hinner.info/vga/

3. CIRCUIT THEORY
Circuit Purpose Groups
Processors
Digital Logic
Frequency
Period = 1 / Frequency
Frequency = 1 / Period
= 0.500
1/3 = 0.333

= Circuits that execute code (Typically in IC form)


= Circuits that an upper-voltage level to represent binary '1' and typically no/little voltage to represent binary '0'
= number of occurrences per unit time

Per (<>1)
mS = Hz

(=1)
kHz(k)

( 3. CIRCUIT THEORY :: CIRCUIT THEORY :: CIRCUIT THEORY ) Page -16 = 0.250


1/5 = 0.200
1/6 = 0.166
1/7 = 0.142
1/8 = 0.125
1/9 = 0.111
1/10 = 0.100
x
Basic Electric

uS = kHz
nS = MHz

Mega(M)
Giga(G)

Convert from Period <=> Frequency ask what is 1/x


Then switch the Eng Notation as listed above.
Ex.
2nS
= 0.5 500MHz (0-0s = 2-0s)
Ex.
20nS
= 0.5 50MHz (1-0s = 1-0s)
Ex.
200nS = 0.5 5MHz
(2-0s = None)

1 0 1:1 else inverse count

--[ References ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Symbols, Circuit examples


http://commons.wikimedia.org/wiki/Category:Electronic_circuits
http://en.wikibooks.org/wiki/Subject:Electrical_engineering
Quick and Simple
http://www.tutorialspoint.com/computer_logical_organization/index.htm
http://www.allaboutcircuits.com/

3.1 Analog
1. Power / Ohms Law
a) Power(Watts) = Current(I-Amps) * Voltage(V-Volts)
b) Ohms Law:
.
/\
Picturing the diagram; Cover the Letter for the item you want to find. (V=Volts, I=Amps, R=Ohms)
.
/V\
Find V (cover V whats left?) V = I * R
.
/-----\
Find I (cover I whats left?) I = V / R
.
/I |R\
R=V/I
.
^^^^^^^
Power = V * I; So we can replace any item in the power equation for derived equations
.
Ex. Power = (I*R) * I = I^2 * R
2. OpAmp
3. Transformer

= Signal amplifier that implements a differential amplifier circuit.


= A group of inductors (ie: Coils) that transforms the level of AC Voltage and Current (ie: step-up or step-down voltage level)

3.1.1 Analysis
http://coen.boisestate.edu/bobhay/ece210/
Chapter 1 Current, Voltage, and Resistance
Charge Quantity of electricity
1 C (Coulomb) = 6.24 x 1018 electrons
Current [I or i] rate of charge flow
Charge to Current equation
I[A] = dq/dt [coulombs/second]
Current to Charge equation
Q[C] = I[A] dt + q(0)[C]
Q(0) is charge at t=0
Voltage The energy(work) required to move electricity
V = dw/dq = (w)energy[Joules]/(q)charge[Coulombs]
Power rate of energy absorption/expension
P[W] = VI = dw/dq * dq/dt ->then = dw/dt (Watts)
Or w[J] = p dt + w(0)[J]
1 Joule = 1Watt/Sec
1 KJ = 1 KW/s
1 KWH = 3600KJ

Prefix
yotta
zetta
exa
peta
tera
giga
mega
kilo
hecto
deca

Symbol
Y
Z
E
P
T
G
M
k
h
da

deci
centi
milli
micro
nano
pico
femto
atto
zepto
yocto

d
c
m

n
p
f
a
z
y

10n
1024
1021
1018
1015
1012
109
106
103
102
101
100
101
102
103
106
109
1012
1015
1018
1021
1024

Chapter 2 Circuit Elements


Superposition states the voltage increments linear with current increments
Homogeneity doubling input causes output to double
Linear element Elements that satisfies both superposition and homogeneity
Resistance in a wire (R)=pL/A, L=length, A=Area, p=Resistivity of element
Ohms Law V=iR
Independent Sources Battery or current source with definite value of V or I
Dependant Sources The source value (right-diamond) depends on the Control
Rectangle Element) where g = gain or multiplier..
Note: You cant use KVL on current sources or KCL on voltages sources

Value (ie: Vc or Ic,

( 3.1.1 CIRCUIT THEORY :: Analog :: Analysis ) Page -17-

Nodal analysis
Current out of node (+)
Node V far side V
Thevinens
Rth = Voc/Isc

3.1.2 Transistors
a) NMOS
b) PMOS

A. CE Amp (DC Analysis)

DC analysis - Dual Stage Bi-Polar NPN PNP Common Emitter Amplifier

Circuit Analysis
Fist step is to find the DC voltage Ratings.
From here we can find Ve because of the 0.7V drop from base to emitter of the NPN Transistor
Now we can find the current through the emitter by ohms law on the emitter resitor
Because of a very small base current we can assume that the collector current through Q1 is approximately the same as the emitter current in Q1, therefore we
can find the voltage drop across the collector resistor by using ohms law.
Then we can find the collector voltage on Q1 by subtracting Vr9 from Vcc
Then we can find voltage from collector to emitter by subtraction.
(For normal operation should be Vcc)
We then do the same process for the second part of the dual stage amplifier to get:

B. Dual Stage NPN PNP Amplifier (AC Analysis)


From Transistor Spec (B=100)
The only DC value we need for AC analysis is Ic or Ie, we then find the re value of the last amplifier. re is the AC resistance the transistor adds to the circuit
from Vb to Ve.
(Where 25mV is a general constant)
We can then find the Gain Av of the second amplifier stage by the equation Av=rc/re. As we can see that by the fact that AC will flow directly through the
capacitor C3, the AC resistance of the collector will be R5||RL (or in parallel with), were the AC resistance of the emitter is re+R6 because capacitor C4 allows
AC current to bypass R11 and return directly to ground through Vcc. This design of amplifier where one capacitor bypasses one emitter resistor but leaves a
smaller resistor at the emitter for some resistance is know as a Swamped Amplifier.
Then we can find the input impedance of the second amplifier stage. (Input Resistance)
Notice that the resistance at the base of the transistor Q2 is the emitter resistance times Beta. Once we know the resistance at the base of transistor we can
see it is in parallel with R7 and R8.
Now we can find the values of the first stage the same as the second stage and we get:
We must be careful when calculating Gain of first stage to include the Input resistance of stage 2 in the collector AC resistance as shown below.
Now that we have both gains in both stages we can find the total amplification by:

Before
We

we can apply gain we must find the actual input AC voltage though at the base. Notice:
can draw the Thevenins equivalent circuit as shown to the left. By this we mean that the source AC goes
through R5 but is also dropped to ground through R1||R3||Zin (Zin of the base of Q1). The total Zin was found
previously to be 403 Ohms. Therefore, the actual input AC is equal to the value in the center of two series
resistors, the first being R2 and the seconds is the resistance from the base to ground of the transistor.

So the
actual AC input voltage is:
(The actual input AC voltage)
With this input voltage we can then find the approximate output voltage by Total Gain:

Different Approach
A different approach to analyzing the above circuit would to find amplifier stage gains without including the load. For example, instead of including Zin of the
next stage, find gain without a load at the output of each amplifier stage. Then one could Thevenize the circuit into three different circuits as shown below:

In the first schematic, we show how we came up with input voltage of 889uV as shown above. The unloaded voltage gain of the first amplifier will be found by:
Then 889uV x 9.59 = 8.53mV
The unloaded gain of the second stage is done exactly the same way. Gain=32 unloaded
After solving the second schematic we find the input voltage into the load with a gain of 32 is 126.4mV.. Finally the output must be divided by the collector
resistor ground and the Load resistance to ground giving us a final Vout of 63.2mV which is approximately the same answer as doing things the other way.

3.1.3 Inductors/Coils
A. Series RL AC Circuits - Low Pass Filtering

Frequency Cutoff
(Frequency cut off is when Inductive Reactance (XL) equals Resistance)
(Rearranged equation from above when Xl=6.28LF)
(This is a slow curved process, cutoff is just a standard)
Cutoff with Inductive reactance passes low frequencies and filters high frequencies.
As shown by the oscilloscope, current leads the voltage or voltage lags the current.
Inductive Reactance
(Where L=Inductor (Henrys) and F=Frequency (Hertz))
(Inductive Reactance always 90degrees)
Inductive Impedance

On the HP48G+ enter polar mode by right shift (MTH), then enter polar numbers in (xx) with<
This can also be found by graphing or Trigonometry as shown below:
As shown by the graph, for solving Z one can use the hypotenuse equation:
Hypotenuse equation

The angle can be found using Trigonometry functions like:

4.
5. Diode
6. Capacitor
7. Inductor (ie: coil)
8. Resistor

3.2 Digital
Combinational Logic Circuits
Sequential Logic
Synchronous Sequential
Asynchronous Sequential

= directly responds to input change


= Remembers present state and combines with input changes to create a new state
= Inputs are only evaluated at master-clock signal change
= Responds to inputs at speeds determined by the devices themselves rather than a master-clock.

VSS LOW '0'


VCC VDD HIGH = '1'
Digital circuit logic can be 'positive logic' where high-voltage = 1 or 'negative logic' where low-voltage = 1
Vdd - is Maximum voltage (~5 to 1Vdc)
V1,min --- * Between V0,max and V1,min is 'undefined'
V0,max --- * No assumed value except in transitional phase.
Vss - is Minimum Voltage (GND)

3.2.1 Sequential Logic (RTL)


RTL = Register Transfer Level
Describes how data sequentially moves through the system
NOTICE; In EDA circuit design; the generally accepted meaning of RTL is any HDL code that can be synthesized. (omitting simulation/debug)
System level digital circuits are categorized by how they handle timing.
RTL design determines Timing-Sequence & Synchronization of data movement (Transfer-Spec) within digital systems.
RTL is Sequential Behavior because data transferred without a sequence is a direct connection
RTL design typically implements algorithmic Boolean equations to move data through the system.
Gate Delay = Time required for valid input-levels to be reflected on the output pin (ie: Also known as Propagation Delay)
TIME handling makes sure logic-element-1 has completely evaluated BEFORE its output is fed into logic-element-2.
Terms
Output register = (ie: latch) Holds output-level until the next clock cycle (ie: Evaluation point-in-time)
Register outputs re-route to register inputs after a fashion
Synchronous (In-Sync)
1. Output state of all logic only changes at the master clock signal (ie: Output register is activated by clock)
a) All evaluation states are synchronized or stepped which allows the required time for logic-transistors/gates to evaluate the inputs.
b) master clock signal - It takes X-clock cycles for output to reflect active inputs.
Asynchronous (Transparent)
1. Asynchronous circuits are commonly referred to as Transparent
2. Elements in an asynchronous circuit are out-of-sync from each other.
3. State changes with changes on the input pins
a) Asynchronous = Output can change at any time (No Master Sync-Clock)
b) Typically use 'complete' signals known as 'data transfer protocols'
logic-element-1 signals 'complete' on a special pin to instruct logic-element-2 to "go"
'Req' uest
'Ack' nowledge
c) Asynchronous sequential circuits may be regarded as Combinational circuits with feedback
d) State changes with changes on the input pins
Finite State Machine (FSM)
1. FSM is a finite (ie: Pre-Defined ) list of states (ie: think to-do list but uses nouns) that iterates from one state to the next state.
a) Moore FSM Typically is just a counter that steps from one state to the next w/o regard to any other inputs besides the "stored" present state.
b) Mealy FSM A state machine that is not a Moore FSM(ie: Non Just A-Counter). Next state depends on both current inputs and present state.
[ASM] Algorithmic State Machine
Sequential logic is used heavily in Finite State Machines (FSM)
Pipe-Lining
= Speed enhancement for sequential logical circuits
Synchronous Pipe-lining = breaking down complex circuits to small blocks so each can have their own synchronous clock
Pipe-lining in RISC Processor architecture is popular
Asynchronous Pipe-lining = output registers are clocked asynchronous
Typically use the REQ(request) / ACK(acknowledge) data transfer protocol

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Finite_state_machine


http://en.wikipedia.org/wiki/Pipeline_%28computing%29
http://en.wikipedia.org/wiki/Asynchronous_logic
http://en.wikipedia.org/wiki/Sequential_logic
http://en.wikipedia.org/wiki/Register-transfer_level
http://en.wikipedia.org/wiki/Propagation_delay

3.2.2 Combinational Logic


Combinational Logic - (ie: 'Transparent') Discrete non-clocked blocks - No memory
NOT identified by Synchronous or Asynchronous but fits into the Asynchronous group.
Said as 'output' is a 'pure function' of the PRESENT input.
Boolean algebra, half/full adders, half/full subtractors, multiplexer, demultiplexer, encoders and decoders.
Combinational = Output is a pure function only representing the present input (ALU is Combinational)
{ http://en.wikipedia.org/wiki/Combinational_logic }

A. Algorithmic Circuits
Algorithmic
Sub-Level Blocks / Sub-Circuits For Logic / Math / Memory
Functionality defined by operation (No hardware implementation details), ALU, RAM, CU
Algorithm level;
much like c-code with if, case, loop statements
Example; 'Z=X+Y' for 32-bit adder

B. Arithmetic Circuits
Arithmetic Circuits (for numeric functions) are Combinational Circuits
Number representation (Encoders/Decoders)

BCD - Binary-coded Decimal; 4-bit groups determine each decimal digit.


Gray-Code - Obsolete; Only changes 1-bit per increment (in past used with shaft position sensors)
B.1 Negative numbers (0x7F)
Negative Numbers are represented by 2s-Compliment
With Negative numbers the range of numbers represented by binary are cut in half for + and -.
4-Bits
(Nibble)
Any value over 0x7 is a negative number
8-Bits
(1-Bytes)
Any value over 0x7F is a negative number
16-Bits (2-Bytes)
Any value over 0x7FFF is a negative number
32-Bits (4-Bytes)
Any value over 0x7FFFFFFF is a negative number
Left-Most bit can be used as a negative bit-flag (1=negative)
1s Compliment; has a sign bit-flag also but inverts every bit in the number (ie: Subtracting it's positive equivalent)
2s Compliment; 2^n - PosNum; (-5 = 10000 - 0101 = 1011)
Easier method; copy all bits that are 0 and first-bit; then compliment all other bits.
Radix-Complement Scheme

B.2 Adder
Math Circuits ( Subtraction is done by changing negative number to 2s Compliment and then adding )
Half-Adder(HA) - 2-binary bit (b1, b2) addition circuit with 'carry' and 'sum' bits.
Full-Adder(FA) - 2-binary bit (b1, b2) addition circuit with a 'carry-in' bit for extra bit addition (Created from 2 Half-Adder circuits and an OR
gate).
Ripple Carry Adder (RCA)
http://en.wikipedia.org/wiki/Adder_%28electronics%29
B.3 Boolean Algebra
Mathematics sector used to represent Logical-Circuits and reduce them to simplest terms.
1. Gate Representation (In precedence order of operations)
a) ' (!~) - NOT - L(x,y) = x' + y';
NOT(X) OR NOT(Y) also line above; cant make on PC
b) * (^) - AND - L(x,y) = xy;
X AND Y; Intersection of X & Y "product"
c) + (v) - OR - L(x,y) = x + y;
X OR Y;
Union of X & Y
"sum"
2. Axioms
a)
b)
c)
d)
e)
3.

AND
0*0=0
1*1=1
0*1=1*0=0
If x=0 {x'=1}

Theorems
a)
AND
b)
x*0=0
c)
x*1=x
d)
xx=x
e)
x!x=0
f)
!!x=x

OR
1+1=1
0+0=0
1+0=0+1=1
If x=1 {x'=0}

OR
x+1=1
x+0=x
x+x=x
x+x'=1

// Huntington's Basic Postulate

// Huntington's Basic Postulate

4. Principle of Duality - An equations dual is obtained by replacing all + with * and 0s with 1s or visa versa. (as shown above)
a) If x,y,z are variables in B(equation) then the following properties hold true.
b)
AND
OR
c)
x*y = y*x
x+y=y+x
// Commutative
// Huntington's Basic Postulate
d)
x*(y*z)=(x*y)*z
x+(y+z)=(x+y)+z
// Associative

e)
f)
g)
h)
i)
j)

x*(y+z)=x*y+x*z
x+y*z=(x+y)*(x+z)
// Distributive
// Huntington's Basic Postulate
x+x*y=x
x*(x+y)=x
// Absorption
xy + xy! = x
(x+y)(x+y!)=x
// Combining
!(xy)=!x+!y
!(x+Y)=!x!y
// DeMorgan's theorem
x+!xy=x+y
x(!x+y)=xy
xy+yz+!xz=xy+!xz
(x+y)(y+z)(!x+z)=(x+y)(!x+z)// Consensus
All other theorems and properties can be derived from the 'Huntingtons Basic Postulates'
These are fundamental concepts of the Synthesis process in CAD::EDA design tools

k) Venn diagram - A pictorial representation in which "sets" are represented by circles or other shapes.

3.2.3 Gates/Flip-Flops(FF)
Logic Gates
switch

= standard / common switch-circuit designs created specifically for handling basic digital logic.
= transistors used for digital purposes
Only on=1 / off=0 states are relevant

Buffers
Separate Drive from Pin
Tri-State (ie: Transmission Gate) buffers allow pins to be either output-driven or 'Z' dis-connected; thus tri-state 1,0,Z
Short-Circuit Prevention when two device outputs share a common wire (One drives while the other in 'Z' high impedance / disconnected )
Register = Collection of Asynchronous Flip-Flops (ie: Latch)
16-bit register ~ 16 latches
Flip-Flops(FF)
Flip-Flop
D

= Common logic-gate circuit design that can retain logic levels through time (e.g. memory)
Q = Output
Description
D=Q

D sets Q @ rising edge of CLK

&

SR

Set / Reset

JK

J=Set,
K=Reset

~&

Latch

D=Q

Logic Gates
Logic Gates
NOT
AND
OR
NAND
NOR
XOR
XNOR

D sets Q @ Enable High (Technically not a FF)

Inverse
All-Input-AND
All-Input-OR
NOT AND
NOT OR
Exclusive OR
Exlusive NOT OR

Verilog
~
&
|
~&
~|
^
~^

Input Output
1 0 / 0 1
1,1,1(all) 1 ELSE 0
0,0,0(all) 0 ELSE 1
NOT(AND)
NOT(OR)
0,1,0(1-1) 1 ELSE 0
NOT(XOR)

Drawing 1: Logic Gate Schematic Symbols

Drawing 2: Gates of a D-Flip-Flop

Propagation delay (ie: Gate Delay) = The time it takes for a digital logic gate to register a result
7400 IC Gates typically have a gate delay of around 10 2 nanoseconds; thus can only operate at 100 500MHz frequency correctly
Inside modern CPU's with speeds of up to 3.5GHz requires gates that respond with a delay of around 280pS (picoseconds)

3.2.4 Market
A. 7400-Series ICs
Labeling Notations
'L' = TTL (74LS00)
'H' = CMOS (74HC00)
Notes
7400-Series buffers are about the only 7400 chips still in use today (74244);
7400-Series SSI-Small Scale Integration technology to make the ICs.
162244 (SOIC-Package, much smaller & more devices)

http://en.wikipedia.org/wiki/7400_series

3.3 Mixed-Signal ( Analog & Digital )


Root Components
ADC + Analog to Digital Converter
DAC + Digital to Analog Converter

= Converts an Analog Input to a Digital Number (ie: Voltage level Digital Number )
= Converts a Digital Number to an Analog Output (ie: Digital Number Voltage Level )

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Electronic_circuits


http://en.wikipedia.org/wiki/Finite_impulse_response FIR Filter

4. CIRCUIT DESIGN STEPS


1. Plan
2. Entry
3. Synthesis
4. Validate
5. Layout

- Containing IP-Blocks/ System Buses / IO (Peripheral Buses)


- Enter the circuit design into EDA software ( Schematics and/or HDL entry )
(ie: Compile) the circuit design to a lower-level NetList
Through simulation that the design meets planned specification and operation
Prepare design for Target Hardware (ie: Floor Planning )

Entry Categories
Behavioral
- How the circuit behaves (e.g. What a house does)
Structural
- How the circuit is connected (e.g. House blue-prints)
Entry Abstraction Layers ( Most abstract to least abstract )
Architectural
- Design in terms of functional blocks (IP-Cores)
Algorithmic
- Design in terms of math function (behavioral)
Register Transfer Level (RTL)
- Design in terms of logic and storage devices
Gate level
- Design in terms of logic comparison gate components
Switch level
- Design in terms of transistor switches or discrete devices

Circuit design tool chain


Each step in an EDA design flow typically has independent software-tools
Companies tend to package a set of tools into an integrated design suite
Integrated Design Suites are often referred to as EDA Software Packages
Best-practices
little code test little more code test (not write a bunch and run)
Concept Partition(Divide & Conquer) Block1, Block2, etc...

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki Design Flow


- http://en.wikipedia.org/wiki/Design_flow_%28EDA%29

4.1 Planning

Purpose/Goal
Specifications
Block Diagram
I/O Interfaces
Interconnects
Feasibility

= Document the system circuits purpose / goal


= Document the specification the system must meet.
= Draw a block diagram of the designs function blocks
= Define I/O Interfaces and standards that might be implemented
= Specify any internal interconnect architecture (ie: Standard Bus's)
= Financial Feasibility and Market

Illustration 1: Example Planning Block Diagram for an IC.

4.1.1 System Buses


System Buses
= Common interconnect standards between various components of a system circuit.
AMBA
by ARM; Advanced Microcontroller Bus Architecture (AMBA)
Wishbone bus by OpenCores; Free and open bus architecture (formerly from Silicore)
CoreConnect
by IBM; bus technology from PowerPC Architecture and Xilinx MicroBlaze
IDT IPBus
Avalon
by Altera; Proprietary bus system for Altera's Nios II SoCs
OCP
= Open Core Protocol
Hyper Transport
by AMD
Quick Path
by Intel
Determine Clock Domains
Decide How the team will divide responsibilities.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------AMBA


http://en.wikipedia.org/wiki/Advanced_Microcontroller_Bus_Architecture
Altera Nios-II SOPC System Bus Standard Avalon Switch Fabric
http://en.wikipedia.org/wiki/Nios_II#Avalon_switch_fabric_interface

4.1.2 IP-Cores (Re-Use)


IP-Core
IP-Block
SIP

+ Intellectual Property - Core


+ Intellectual Property Block
+ Semiconductor Intellectual Property

= A common-use circuit design containing ownership rights (ie: Copyrighted)


= An Alias to an IP-Core
= An Alias to an IP-Core

IP-Cores typically have Interconnection Standards (ie: System Buses) that need to be considered.
List of places to get IP-Cores
http://www.opencores.org/
http://www.geocities.com/SiliconValley/Pines/6639/ip/memory_cores.html
- Free Memory Cores
http://www.estec.esa.nl/wsmwww/erc32/ - An ERC32 (radiation-tolerant SPARC V7) processor developed for space applications.
http://www.cmosexod.com/freeip.htm
- 12bit DSP core / peripherals, 8bit CISC processor, frequency counter, SDRAM Controller
http://young-engineering.com/intellectual_property.html
http://www.freerangefactory.org/cores/
Companies that sell IP-Cores
http://www.smart-dv.com/
http://www.wipro.com/
http://www.hcl.com/

4.1.3 Design For Testability (DFT)


Detail how the design will be tested and what functionality needs to be tested.
Basic Input Self Test (BIST)
= logic circuit that tests the circuit internally

JTAG Boundary Scan

4.2 Schematic Entry


Schematic entry is usually only used at the top-level of a system design to interconnect sub-circuits / cores / blocks.

4.3 HDL Entry


HDL + Hardware Description Language
Standard
VHDL
Verilog
SystemVerilog

(.vhd) file extension


(.v) file extension
- (.sv) file extension

Variations / Extensions
Actel HDL (AHDL)
Altera HDL (AHDL)
SystemC
Verilog-A
BlueSpec Verilog

= VHSIC(Very High Speed Integrated Circuit) HDL


= Rights Recently purchased by Cadence
= Newer version of Verilog by Cadence to cover its system level shortcomings.

= Is a C++ library (TLM - Transaction Level Modeling) much higher-level than RTL
= Analog design extension for Verilog
= Atom System Verilog (Guarded atomic actions); Is a Verilog Simulation extension package.

Historical
ABEL
From 1981
PALASM PAL HDL from 1980s

see http://en.wikipedia.org/wiki/Advanced_Boolean_Expression_Language
see http://en.wikipedia.org/wiki/PALASM

HDL Modeling - HDL is a Mixed-level circuit description language


Synthesis - circuit behavior
Synthesizable Code

= Process of; Abstract desired circuit behavior (RTL) Circuit design


= Code that is synthesized for circuit implementation; Commonly referred to as RTL

Behavioral Code = Verb Emphasis ( Sequential / Procedural ); describes IO responses; what it does or how it behaves.
Algorithm level code
Register Transfer level(RTL) code
Structural Code

Much like c-code with if, case, loop statements


Example; 'Z=X+Y' for 32-bit adder
Determine how data moves / progresses through the system by controlling output registers.

= Noun Emphasis (Concurrent); Tying together gate/transistor level components (verbal wiring w/o storage)

Gate level code (Alias 'Dataflow')


Switch level code
Simulation Code

Boolean expression interconnects AND, NOR, and etc..


ie: transistor level; the MOS transistors inside the gates

Example; 'Z <= X AND Y'

HDL code that is used only for simulation and verification purposes

HDL Terms
Sub-Circuits are sometimes called macro-functions, mega-functions or IP-Cores
Technology Dependent Macro-function
= circuit design for a specific type of chip
Technology Independent Macro-function
= circuit design that can be implemented in any type of chip.
LPM + Library of Parameterized Modules = Circuit Library that is technology independent. 'lpm_add_sub'
Coding Practices ( Typically Job specific no real standard )
Use

For

Postfix

For

addr Address

_n

Active Low

clk

Clock

_r

Register

rst

Reset

_#r

Pipeline #

arst Async Reset _i


rw

Use For

Internal signal

read-write

Physical IO maybe should be all-caps (Aptina)


in / out port labeling is discouraged

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------HDL examples including I/O Hardware Interfaces and descriptions http://www.fpga4fun.com/
HDL Coding Styles
http://www.maia-eda.net/index.php?option=com_content&task=view&id=121&Itemid=258
VHDL Primer
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061348
MIT-Press Circuit Design with VHDL
http://profs.basu.ac.ir/abdoli/upload_file/722.file_ref.1121.1422.pdf
Online HDL Simulator
http://www.edaplayground.com

4.3.1 Verilog
See Also
http://www.doe.carleton.ca/~jknight/97.478/97.478_02F/PetervrlQ.pdf

// synthesis VERILOG_INPUT_VERSION SYSTEMVERILOG_2005


/**<HDL-Basics>
Hardware Description Language - a textual representation of an electronic circuit.
1. HDL Abstraction Levels Switch Level
- Transistor switching (MOS)
Gate Level
- Logic gate level (Either Combinational or Combinational/Register)
Register Level
Algorithm Level
3. Verilog is case-sensitive (commands are typically lower-case)
*******************************************************************************************************************************************/ //
</Basics>

A. Module
// Module = A named sub-circuit with an external interface
module learnbasic(input wire
ClkIn,
RstIn,
ReqIn,
// Port = External connection. (type
input [7:0] AddTo7,
HalfIn,
ShifLft,
//
- 'input' (type wire only)
inout [7:0] DataLine, Trans1,
Trans2,
//
- 'inout' (type wire only)
output wire
ClkLight, RstLight, ReqLight,
//
- 'output' (any net type)
output reg
BcdOut1, BcdOut2, BcdOut3, OddIn7,
output [7:0] Sum7,
HalfOut, Shift,
output [15:0] HWord1,
HWord2,
HWord3,
output [31:0] Word1,
Word2,
Word3); // [msb:lsb] bundle/bus

is optional and 'wire' by default)


An input for a module or task
Tr i-State (input and output)
Output - driven signal

// ** Verilog93 - separated port naming and port declarations **


// STRUCTURAL - Combinational Logic Circuit design ( Concurrent Operation )

B. Parameter
parameter WIDTH = 5;
// assign/drive net-connectors only once ELSE U-get "Error 10028 Can't resolve multiple constant drivers for net "?"."

C. Connectors

line

//--Internal connectors--//
wire [7:0]Sum,DivOut = 0;
wand [7:0]Active;
wor a;
tri b;

////
// // // // -

supply0 Gnd;
supply1 Vcc;
reg [7:0]OperReg = 0;
wire Enable,EnableN;

//
//
//
//

4-Assignable states ('0','1','X','Z'); Can be assigned an initial value.


wire
(basic connector)
General purpose wire
wand
(Wired AND)
0-Dominates;
All connections to the wire are AND'ed together
wor
(Wired OR)
1-Dominates;
All connections to the wire are OR'ed together
tri
(Wired tri-state)
Single-Driver; triand, trior, tri0, tri1; all must be z except one driver

- supply0 (Wired Ground)


Tied directly to power-level(0)
- supply1 (Wired Power)
Tied directly to power-level(1)
- reg
(Wired-Register)
Reflects a variable value.
Multiple items seperated by ','

D. Bit-Literals
//--[ Drive-Line
assign
Word2 =
assign
Word3 =
reg [7:0]Div2 =
reg [7:0]Seven =
assign
W8C
=

]--//
123;
32'd123;
8'b0000_0010;
8'h7;
8'o377;

//// Bit-literal assignments


(%bit-size'%base%%value%)
// (default)
32-bit decimal
// 'd' = decimal
Exactly the same as above
// 'b' = binary
'_' are ignored
// 'h' = hexidicamal
// 'o' = octal

E. Logic Gates
//--[ Logic Gates ]--//
not(Active[0],RstIn);
buf U1(DataLine,A8);
assign EnableN = ~Enable;
assign Enable = ClkIn & RstIn;
notif0(Trans1,DataIn1,EnableN);
bufif1(Trans2,DataIn2,Enable);

//// Primitives
+--------------------------------------------------------------// Gate-Syntax
| not(o,i)
= '~'
notif(o,i)
notif0()
notif1()
// Named 'U1'
| buf(o,i)
bufif(o,i,e)
bufif0()
bufif1()
// BitWise-Syntax
| and(o,i..) = '&'
or() = '|'
xor() = '^'
//
| nand(o,i..) = '~&'
nor() = '~|'
xnor() = '~^'
// Not-gate with a Tri-state output and an active-low('if0') enable.
// Buffer with a Tri-state output and an active-high('if1') enable.

F. Algorithmic
//--[ Algorithmic ]--//
assign
Sum7
= AddTo7 + Seven;
assign
HalfOut = HalfIn / Div2;
assign
Shift
= HalfOut << 1;
assign
HWord1 = {1'b0,Sum7[6:0],Shift};
assign
Word1
= {2{HWord1}};
Sum7 <= Sum7 << 1;

//// Operator Components


// '+' Addition
'-'
Subtraction/Negative
'*' multiplica
// '/' divide
'%'
modulus
'**' exponent
// '>>' shift right
'>>>' arithmetic right shift
// And opposite for left-shift
// '{}' concatenate - Combine "0,Sum7[6:0],Shift" to make 'HWord1'
// Replicate 'HWord1' twice to produce a twice as large connector bus 'Word1'
// Left bit shift by 1

G. Abstraction (Generate, Sub, etc)


//--[ Generate ]--//
generate
genvar i;
for( i = 0; i <= 3; i = i + 1)
begin:Auto
not(HWord2[i],Seven[i]);
end
endgenerate
//--[ Function ]--//

//// Pre-compiler auto-line generator


//// Example produces the equivalent of 4-stand lines:
// not Auto[0](HWord2[0],Seven[0]);
// not Auto[1](HWord2[1],Seven[1]);
// not Auto[2](HWord2[2],Seven[2]);
// not Auto[3](HWord2[3],Seven[3]);

function MyFunc( input n );


assign MyFunc = 1;
endfunction
//--[ Sub-Circuit Initialization ]--// //// Use a Sub-Circuit within this circuit
SubCircuit Sub (.one(a), .two(b));
// IN[0] connects to macro IN (.a) and etc..

H. Compiler Directives
'timescale 1 ns/ 1 ps
'define name code;
'include filename.v;

// Include the contents of a file at this point in the current file

I. Behavioral (Always@)
// BEHAVIORAL - Sequential/Procedural logic (RTL-Modelling) ( Cannot assign net-connectors; only registers and variables )
always @(posedge ClkIn) begin

// Triggers - @(posedge, %net), @(negedge %net), or @(%net) //both edges

reg m; // local

//--[ Comparitors ] - Plexers Coders

I.1 If Else
BcdOut1 = (RstIn == 1) ? 0: 1;
// '?:' IF...THEN
if(ClkIn == 1 && RstIn != 1) BcdOut2 = 1;
// '=='
EQUALS
Not Equal
else if (RstIn == !ReqIn || ClkIn == 0) BcdOut3 = 1; // '!'
NOT

Active[1] = (Comparison) ? TrueValue : FalseValue;


'>=' Greater/Equal
'&<=' Less/Equal
'!='
'&&' AND

'||'

OR

I.2 Case
if(ClkIn == 1) begin
case(AddTo7)
8'b0 : OddIn7 <=
8'b1 : OddIn7 <=
8'd3 : OddIn7 <=
default : OddIn7
endcase
end

1;
1;
1;
<= 0;

// casex() to allow 'X', casez() to allow 'Z' and wild-card '?' but not 'X'
// '<=' is for Synchronous logic where RHS is evaluated but only assigned on next trigger.

end
// SIMULATION - Testbench
initial begin
// Executed once at very beginning of simulation
end

J. Task
task DoSomething;
$display("Hi");
endtask
time z;
//{SO}
//{SO}
//{SO}
//{SO}
//{SO}

initial
wait(%condition)
#5 a = 20
c = #5 a;
fork...join

// Record current Sim time


Initialize simulation execution block (Executes once at start of simulation)
delay execution till condition is true.
a = 20 after 5 time units. Evaluate statement only after the delay in time units.
c = a after 5 time units.
'a' is evaluated immediately then after delay it is assigned to 'c'.
Concurrent execute statements within

endmodule
module SubCircuit#(parameter PassedParam = 5)(input one, output two);
assign two = ~one;
endmodule

4.3.2 VHDL Syntax


A. Include (LIBRARY / USE)
--====================================================================================================================
-- INCLUDE LIBRARIES (ie: Directories) to find Re-usable code
--====================================================================================================================
library work;
-- Examples; 'ieee', 'textio', 'standard', ['std' & 'work' are always included by default]
library std;
-- Include "\altera\13.0sp1\quartus\libraries\vhdl\std"
library ieee;
-- Include "\altera\13.0sp1\quartus\libraries\vhdl\ieee"
-- Import Library.Package.Parts
use std.standard.all;
-- Include the 'std.standard' package
//Types 'BIT' 'BOOLEAN' 'INTEGER' 'REAL' data-types.
use ieee.std_logic_1164.all; -- Include the 'std_logic_1164' package //Values 'Z'=Disconnect 'L'=Weak0 'H'=Weak1 'X'=Unknown '-'=DontCare
'W'=WeakUnknown
use ieee.numeric_std.all;
-- Include the 'numeric_std' package
//Allows arithmetic(+,-,/,*) on 'std_logic_1164' values.

B. External I/O (ENTITY...GENERIC/PORT)


GENERIC default class is CONSTANT
CONSTANT ADD_BITS: .. is the same as just ADD_BITS: .
PORT default class is SIGNAL
SIGNAL mux_out: OUT .. is the same as just mux_out: OUT .
FUNCTIONS & PROCEDURE can also be declared at the end of an ENTITY but not the COMPONENT declaration.
--====================================================================================================================
ENTITY EntityName IS -- External I/O
--====================================================================================================================

GENERIC ( -- Constructor / Instance Arguments -ADD_BITS : INTEGER


:= 4;
-- Bit count for 'add'
CLK_DIV : INTEGER
:= 15);
-- Clock Divider by
PORT ( -- External Connectors --ID
: Mode
DataType
debounce_on
: IN
STD_LOGIC
debounce_off
: IN
STD_LOGIC
debounce_out
: BUFFER STD_LOGIC
debounce_out_n
: OUT
STD_LOGIC
mux_in1
mux_in2
mux_sel
mux_out

:
:
:
:

dmux_in
dmux_sel
dmux_out

: IN
: IN
: OUT

STD_LOGIC
:= '0';
STD_LOGIC
:= '0';
STD_LOGIC_VECTOR ( 1 DOWNTO 0) := "00"; -- Initial Value on both wires is '0'

add_in1
add_in2
add_sum
add_carry

:
:
:
:

STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";


STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";
STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";
STD_LOGIC);

clk_in
clk_out

: IN
STD_LOGIC
: BUFFER STD_LOGIC

SegDisplay
END EntityName;

IN
IN
IN
OUT

IN
IN
OUT
OUT

: OUT

STD_LOGIC
STD_LOGIC
STD_LOGIC
STD_LOGIC

:=Initial Value
:= '0';
:= '0'; -- SR Latch debounce requires double-throw switches (on/off)
:= '0'; -- Buffers allow output to be wired to other internal circuits
:= '0'; -- Inverted 'debounce_out'
:=
:=
:=
:=

'0';
'0';
'0';
'0';

:= '0';
:= '0';

STD_LOGIC_VECTOR (6 DOWNTO 0));

-- 7 Segment Display

C. ARCHITECTURE (Declarations)
SIGNAL / CONSTANTS / TYPE / SUBTYPE definition area local to the Architecture
FUNCTION / PROCEDURE / COMPONENT declarations are generally declared here.
--====================================================================================================================
ARCHITECTURE ArchitectureName OF EntityName IS
--====================================================================================================================
--[ Inter-Architecture ]----------------------------------------------------------------------SIGNAL ABitIs1
: BIT;
SIGNAL Bit1
: BIT;
-- BIT is a basic data type
SIGNAL Bit2
: BIT;
SIGNAL Bits
: BIT_VECTOR(1 DOWNTO 0);
SIGNAL Bits_n
: BIT_VECTOR(1 DOWNTO 0);
SIGNAL Bits_0
: BIT_VECTOR(3 DOWNTO 0);
SIGNAL Bits_1
: BIT_VECTOR(3 DOWNTO 0);
SIGNAL add_sum_full
SIGNAL debounce_tmp

: STD_LOGIC_VECTOR (ADD_BITS DOWNTO 0); -- +1 bit for full add sum of other 2.
: STD_LOGIC;

SIGNAL StateClk
: STD_LOGIC;
SUBTYPE TwoBits
: STD_LOGIC_VECTOR(1 DOWNTO 0);
TYPE States IS ( Display1, Display2, Display3, Display4 );
TYPE SegMem IS ARRAY ( 1 TO 4 ) OF STD_LOGIC_VECTOR(6 DOWNTO 0);
CONSTANT SegROM

: SegMem := (x"F",
x"FF",
x"FF",
x"A");

-----

-----

Clock that increments the state machine


Parse out any STD_LOGIC_VECTOR to only 2-bits.
Each State is enumerated (User-Defined-Type)
Build ROM for Segment Display of each number.

index(1);
index(2);
index(3);
index(4);

Bits
Bits
Bits
Bits

on
on
on
on

7
7
7
7

Segment
Segment
Segment
Segment

display
display
display
display

to
to
to
to

show
show
show
show

a
a
a
a

'1'
'2'
'3'
'4'

C.1 COMPONENT
--[ Declare ]---( Re-Use )------------------------------------------------------------------------COMPONENT mitDFF
GENERIC( RisingEdge
: BOOLEAN
:= TRUE );
PORT(
d: IN STD_LOGIC;
clk: IN STD_LOGIC;
rst: IN STD_LOGIC;
q: OUT STD_LOGIC);
END COMPONENT;

C.2 CONFIGURATION
When VHDL comes across a COMPONENT declaration how does it know the COMPONENT class is associated to the ENTITY? Answer: They both have
the same name.
Actually every COMPONENT declaration has a configuration and the configuration that says use the same-named ENTITY is the VHDL default
configuration.
The CONFIGURATION block allows the designer to specifically assign a COMPONENT Instance to an associated ENTITY.
-- Select a given architecture for your component instance
CONFIGURATION AnyConfigName OF
--(The Entity ----> Architecture ----> Instance
: OfComponent) will point to (Library.Entity(Architecture))
MyEntity IS FOR MyArchitecture FOR MyInstance : OfComponentName USE ENTITY LibraryName.EntityName(ArchitectureName);
end for; end for;
END CONFIGURATION;

Typically the CONFIGURATION block will be in a Tree structure which will allow multiple assignments to parent level FOR
-- Why are two 'for' statements are nested? All 'for Instance'(s) under the main 'for Architecture'
acrchitecture' designated.
CONFIGURATION ForMyEntity OF MyEntity IS
FOR MyArchitecture
FOR MyFirstInstance
: OfComponentName use entity work.ComponentOne(Synchronous_Arch); END
FOR MySecondInstance : OfComponentName use entity work.ComponentOne(Asynchronous_Arch); END
FOR OTHERS
: OfComponentName use entity work.ComponentOne(MixedSignal_Arch); END
END FOR;
END CONFIGURATION;

apply within the parent 'for

FOR;
FOR;
FOR;

CONFIGURATION blocks are typically defined at the end of the VHDL code which uses the COMPONENT definition.

D. BEGIN (Structural Design)


---------------------------------------------------------------------------------------------------------------------BEGIN
-- Circuit design
----------------------------------------------------------------------------------------------------------------------

D.1 <= and => (SIGNAL Assignment)


--[ '<=' & '=>' (Structrual) ]-----------------------------------------------------------------ABitIs1
Bits_n
Bits
Bits_0

<=
<=
<=
<=

'1';
( 0 => NOT Bit1, 1 => NOT Bit2 );
(
Bit1,
Bit2 );
( OTHERS => '0' );

-----

'<=' assign;
'=>' Named connection;
Positional connection;
'OTHERS' keyword;

'ABitIs1' = '1'
connect Bits_n(0) to 'NOT Bit1' etc...
connect Bits(0) to 'Bit1' etc...
connect all other un-assigned bits to '0'

D.2 Logic Gates


--[ Gates (Structural) ]------------------------------------------------------------------------debounce_tmp
debounce_out
debounce_out_n

<= debounce_off
<= debounce_on
<=

NAND
NAND
NOT

debounce_out;
debounce_tmp;
debounce_out;

-- Support-for: NOT AND OR NAND NOR XOR XNOR


-- Cross wired NAND gates (order doesn't matter in structural)
-- Inverted output

D.3 GENERATE
--[ GENERATE (Structural) ]--------------------------------------------------------------------G1: FOR i IN Bits_1'RANGE GENERATE
Bits_1(i) <= '1';
END GENERATE;

-- Auto Generate assignment statements (must have a 'label:' pre-fix)

D.4 WHEN...ELSE
--[ WHEN...ELSE (Structural) ]-----------------------------------------------------------------dmux_out <= '0' & dmux_in
dmux_in & '0'
"ZZ"
"--";

WHEN (mux_sel = '0') ELSE


-- When 'mux_sel' =
WHEN (mux_sel = '1') ELSE
-- When 'mux_sel' =
WHEN (mux_sel = 'U' OR mux_sel = 'Z') ELSE -- When 'mux_sel' =
-- ELSE; 'dmux_out'

0; 'dmux_out' = Concatenate '0' & 'dmux_in'


1; 'dmux_out' = Concatenate 'dmux_in' & '0'
'Z' or 'U'; 'dmux_out' = "ZZ" (disconnect)
= "--"(don't care)

D.5 WITH...SELECT
--[ WITH...SELECT (Structural) ]----------------------------------------------------------------WITH (mux_sel) SELECT
mux_out <=
mux_in1
mux_in2
UNAFFECTED

WHEN '0',
WHEN '1',
WHEN OTHERS;

-- Connect 'mux_out' to 'mux_in1' when 'mux_sel' = 0


-- Connect 'mux_out' to 'mux_in2' when 'mux_sel' = 1
-- ELSE; Don't change anything

D.6 Arithmetic & Casting


--[ '+' & Casting (Structural) ]-----------------------------------------------------------------add_sum_full <= std_logic_vector(unsigned('0' & add_in1) + unsigned('0' & add_in2));
add_sum
<= add_sum_full((ADD_BITS - 1) DOWNTO 0);
-- sum
add_carry
<= add_sum_full(ADD_BITS);
-- +1 bit carry
-- STD_LOGIC_VECTOR doesn't support math functions because signed/unsigned binary isn't defined by it.
-- Therefore; cast STD_LOGIC_VECTOR 'add_in1' & add_in2' to data type 'unsigned' for the '+' operation.
----------------------------------------------------------------------------------------------------------------------- BEHAVIORAL
----------------------------------------------------------------------------------------------------------------------

E. PROCESS (Sequential Design)


PROCESSes are Sequential blocks of code that begin execution only when activated by nodes that change state in it's sensitivity list.
Sequential Code Blocks
PROCESS
FUNCTION
PROCEDURE
E.1 VARIABLE
A VARIABLE is assigned using :=
A SIGNAL assignment uses <=
An Equals Comparison uses =

E.2 IF...THEN
IF <condition> THEN <assign>; ELSIF <condition> THEN <assign>; ELSE <assign>; END IF;
--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
PROCESS(rising_edge(clk_in))
VARIABLE clkcnt : INTEGER := 0;
BEGIN SYNCHRONOUS
--[ IF...THEN (Sequential) ]------------IF clkcnt = CLK_DIV THEN
clkcnt := 0;
-- Reset 'clkcnt'
clk_out <= NOT clk_out;
-- Toggle 'clk_out'
ELSIF clkcnt < 0 THEN
clkcnt := 0;
ELSE
clkcnt := clkcnt + 1;
END IF;
END PROCESS;

E.3 WAIT
WAIT Command is typically used only for Testbench Code; See Simulation
WAIT FOR <signal condition>;
WAIT ON <signals>;
WAIT UNTIL <time>;
E.4 CASE...WHEN
--[ CASE...WHEN (Sequential) ]------------CASE State IS
WHEN Display1 =>
StateAsInt := 1;
NextState := Display2;
WHEN Display2 =>
StateAsInt := 2;
NextState := Display3;
WHEN Display3 =>
StateAsInt := 3;
NextState := Display4;
WHEN OTHERS =>
NextState := Display1;
StateAsInt := 4;
END CASE;

E.5 FOR...LOOP
--[ FOR...LOOP (Sequential) ]--------------FOR i IN SegROM'LOW TO SegROM'HIGH
LOOP
IF ( i = StateAsInt ) THEN
-- Find the 'SegROM(index)' for the State.
SegDisplay <= SegROM(i); -- Drive the 'SegROM(i)' to the display to show the 'State' number.
EXIT;
-- Break out-of-loop
ELSE
NEXT;
-- Example of continuing loop w/o finish.
END IF;
END LOOP;

E.6 WHILE...LOOP
--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
PROCESS
-- No sensitivity list when using 'WAIT'
VARIABLE State
: States
:= Display1; -- Data Type 'States' is User-Defined.
VARIABLE NextState
: States
:= Display1;
VARIABLE StateAsInt
: INTEGER
:= 0;
BEGIN -- SYNCHRONOUS
WAIT ON StateClk;
-- 'WAIT ON' is same as 'PROCESS (StateClk)' must be first line after BEGIN
--[ CASE...WHEN (Sequential) ]------------CASE State IS
WHEN Display1 =>
StateAsInt := 1;
NextState := Display2;
WHEN Display2 =>
StateAsInt := 2;
NextState := Display3;
WHEN Display3 =>
StateAsInt := 3;
NextState := Display4;
WHEN OTHERS =>
NextState := Display1;
StateAsInt := 4;
END CASE;
--[ FOR...LOOP (Sequential) ]--------------FOR i IN SegROM'LOW TO SegROM'HIGH
LOOP
IF ( i = StateAsInt ) THEN
-- Find the 'SegROM(index)' for the State.

SegDisplay <= SegROM(i);


EXIT;
ELSE

NEXT;
END IF;
END LOOP;
------

LOOP

-- Drive the 'SegROM(i)' to the display to show the 'State' number.


-- Break out-of-loop
-- Example of continuing loop w/o finish.

--[ WHILE...LOOP (Sequential) ]------------WHILE (count = '1')

END LOOP;

END PROCESS;
END ArchitectureName;

F. PACKAGE
-===============================================================================================================================================
====
-- PACKAGING
( Creating Custom Libraries )
-===============================================================================================================================================
====
--[ PACKAGE ]--- packages COMPONENTS, FUNCTIONS, and PROCEDURES into a "library"
-- Abstraction in a Package has a declaration (.header) and architecture (PACKAGE BODY).
-- (.header) can exist by itself when only TYPE/CONSTANTS are being declared.
PACKAGE BasicTraining IS
-- Define an ENTITY as a COMPONENT for Re-Use (Definition is a copy of the ENTITY w/o the ARCHITECTURE)
COMPONENT EntityName IS
GENERIC ( -- Constructor / Instance Arguments -ADD_BITS : INTEGER
:= 4;
-- Bit count for 'add'
CLK_DIV : INTEGER
:= 15);
-- Clock Divider by
PORT ( -- External Connectors --ID
: Mode
DataType
debounce_on
: IN
STD_LOGIC
debounce_off
: IN
STD_LOGIC
debounce_out
: BUFFER STD_LOGIC
debounce_out_n
: OUT
STD_LOGIC
mux_in1
mux_in2
mux_sel
mux_out

:
:
:
:

dmux_in
dmux_sel
dmux_out

: IN
: IN
: OUT

STD_LOGIC
:= '0';
STD_LOGIC
:= '0';
STD_LOGIC_VECTOR ( 1 DOWNTO 0) := "00"; -- Initial Value on both wires is '0'

add_in1
add_in2
add_sum
add_carry

:
:
:
:

STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";


STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";
STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";
STD_LOGIC
:= '0';

clk_in
clk_out

: IN
STD_LOGIC
: BUFFER STD_LOGIC

SegDisplay
END COMPONENT;

IN
IN
IN
OUT

IN
IN
OUT
OUT

: OUT

STD_LOGIC
STD_LOGIC
STD_LOGIC
STD_LOGIC

:=Initial Value
:= '0';
:= '0'; -- SR Latch debounce requires double-throw switches (on/off)
:= '0'; -- Buffers allow output to be wired to other internal circuits
:= '0'; -- Inverted 'debounce_out'
:=
:=
:=
:=

'0';
'0';
'0';
'0';

:= '0';
:= '0';

STD_LOGIC_VECTOR (6 DOWNTO 0));

-- 7 Segment Display

FUNCTION DoSomething (VARIABLE a, b : INTEGER) RETURN boolean;


-- PROCEDURE
-- TYPE
-- CONSTANT
END PACKAGE BasicTraining;
-------------------------------------------------------------------------------------------------------------------------------------------------PACKAGE BODY BasicTraining IS -- A Package body is only necessary when a FUNCTION or PROCEDURE needs defined.
FUNCTION DoSomething (VARIABLE a, b : INTEGER) RETURN boolean;
BEGIN
-- PACKAGE COMPONENT EXAMPLES
--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
--[ WAIT...UNTIL (Sequential)]
PROCESS
-- No sense list when using 'WAIT'
BEGIN
WAIT UNTIL rising_edge(clk); -- Must be first statement after BEGIN
WAIT FOR 500 ns;
END PROCESS;
--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
--[ WAIT...ON (Sequential)]
PROCESS
-- No sense list when using 'WAIT'
BEGIN
WAIT ON clk, rst;
-- Must be first statement after BEGIN
END PROCESS;

--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
END FUNCTION DoSomething;
END PACKAGE BODY BasicTraining;

4.3.3 VHDL Usage


A. Simulation (TestBench)
-===============================================================================================================================================
====
-- SIMULATION
( VHDL Features that are NOT-Synthesizable are used for circuit simulation purposes )
-===============================================================================================================================================
====
ARCHITECTURE TestBench OF EntityName IS
BEGIN
----

WAIT UNTIL clk'EVENT;


WAIT ON clk;
WAIT FOR 30 ns;

-- ASSERT("Hi");
END TestBench;

-- PROCESS cannot have sensitivity list when using WAIT; Not part of sensitivity list
-- WAIT must be first statement in a No %sensitivy_list PROCESSS; WAIT ON clk is same as PROCESS(clk);
-- (Simulation Only)

-- Manually display compiling errors and stuff.

entity test_counter is
PORT ( count : BUFFER bit_vector(8 downto 1));
end;
architecture only of test_counter is
COMPONENT counter
PORT ( count : BUFFER bit_vector(8 downto 1);
clk
: IN bit;
reset : IN bit);
END COMPONENT ;
SIGNAL clk
: bit := '0';
SIGNAL reset : bit := '0';
begin
dut : counter
PORT MAP (
count => count,
clk => clk,
reset => reset );
clock : PROCESS
begin
wait for 10 ns; clk
end PROCESS clock;
stimulus : PROCESS
begin
wait for 5 ns; reset
wait for 4 ns; reset
wait;
end PROCESS stimulus;

<= not clk;

<= '1';
<= '0';

end only;

B. ClockDiv Circuit
------------------------------------------------------------------------------------------------------------------------------------------------ ClockDiv Circuit Design
----------------------------------------------------------------------------------------------------------------------------------------------library ieee;
use ieee.std_logic_1164.all;
entity ClockDiv is
generic ( div: integer :=15 );
port ( clkin: in std_logic; clkout: out std_logic);
end ClockDiv;
architecture ClockDiv of ClockDiv is
begin
process(clkin)
variable output : std_logic;
variable clkcnt : integer := 0;
begin
if rising_edge(clkin) THEN
clkcnt := clkcnt + 1;
if clkcnt = div then
clkcnt := 0;
output := NOT output;
else
NULL;
end if;

else

NULL;
end if;
clkout <= output;
end process;
end ClockDiv;

C. Package Example
------------------------------------------------ work.AnEntity with multiple architectures
----------------------------------------------LIBRARY ieee;
USE ieee.std_logic_1164.all;
ENTITY AnEntity IS
GENERIC (PropTime : TIME := 5 ns);
PORT
(OutPin : OUT STD_LOGIC);
END AnEntity;
ARCHITECTURE FirstArch OF AnEntity IS BEGIN
OutPin <= '1' after PropTime;
END FirstArch;
ARCHITECTURE SecondArch OF AnEntity IS BEGIN
OutPin <= '0' after PropTime;
END SecondArch;
ARCHITECTURE AnyOthers OF AnEntity IS BEGIN
OutPin <= 'Z' after PropTime;
END AnyOthers;
--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
------------------------------------------------ MyEntity that will configure various
-- architectures of component 'AnEntity'.
LIBRARY ieee;
USE ieee.std_logic_1164.all;
----------------------------------------------ENTITY MyEntity IS
GENERIC
(EntityArg : TIME := 5 ns);
PORT
(PINS : OUT STD_LOGIC_VECTOR(2 DOWNTO 0) );
END MyEntity;
----------------------------------------------ARCHITECTURE MyEntity OF MyEntity IS
COMPONENT UseConfiguration IS
GENERIC (TimeNS : TIME);
PORT (Output : OUT STD_LOGIC);
END COMPONENT;
BEGIN
MyFirstInstance : UseConfiguration GENERIC MAP (10 ns) PORT MAP (PINS(0));
MySecondInstance : UseConfiguration GENERIC MAP (5 ns) PORT MAP (PINS(1));
SomeOtherInstance : UseConfiguration GENERIC MAP (1 ns) PORT MAP (PINS(2));
END MyEntity;
----------------------------------------------CONFIGURATION OfMyEntity OF MyEntity IS
FOR MyEntity
FOR MyFirstInstance
: UseConfiguration use entity work.AnEntity(FirstArch)
-- Resolve pin mismatches between 'AnEntity' => 'UseConfiguration' COMPONENT
-- GENERIC MAP and PORT MAP are NOT-NEEDED if the Pin Names in COMPONENT declare
-- are the same as the 'AnEntity' ENTITY.
GENERIC MAP (PropTime => TimeNS) PORT MAP (OutPin => Output); END FOR;
FOR MySecondInstance : UseConfiguration use entity work.AnEntity(SecondArch)
GENERIC MAP (PropTime => TimeNS) PORT MAP (OutPin => Output); END FOR;
FOR OTHERS
: UseConfiguration use entity work.AnEntity(AnyOthers)
GENERIC MAP (PropTime => TimeNS) PORT MAP (OutPin => Output); END FOR;
END FOR;
END CONFIGURATION;
----------------------------------------------LIBRARY ieee;
USE ieee.std_logic_1164.all;
ENTITY TestBench IS END TestBench;
ARCHITECTURE TestBench OF TestBench IS
SIGNAL CheckPins : STD_LOGIC_VECTOR(2 DOWNTO 0);
COMPONENT MyEntity IS
GENERIC
(EntityArg : TIME := 5 ns);
PORT
(PINS : OUT STD_LOGIC_VECTOR(2 DOWNTO 0) );
END COMPONENT;
BEGIN
U1 : MyEntity PORT MAP (PINS => CheckPins);
END TestBench;

D. Common Errors
VHDL Common Error Messages and Fixes
Signal does not hold value after clock edge - Only one item can be defined either at rising edge or falling edge but not both.
Multiply driven
- Same as above
clock not locally stable
- clk'EVENT cannot determine if rising/falling edge; no clk='1'
ignored unnecessary pin clk
- means PROCESS(clk) is ignored because 'clk' wasn't used in the code

4.4 Synthesis ( Decoding / Compiling )


Synthesis tools read HDL (ie: RTL) code and generates lower-level Synthesized Net-list files to describe the circuit.
Synthesis
= the process of transforming and optimizing (ie: Compiling) design entry into lower-level / simplest terms or elements (ie: NetList)
NetList
= Text list of component networks
Details all the connections of blocks I/O lines and component specification.
Net-list standards
EDIF + Electronic Design Interchange Format
= Input files (.edf)
Net-lists can be used to
Produce Layout for a photo-mask used in ASIC Wafer Fabrication (ie: IC Fabrication)
FPGA / PLD circuit programming (ie: Laying-out/Fitting/Place N Route) circuit into the FPGA.
Silicon Virtual Prototype Simulators (SVP) that simulate circuits as they would be on a silicon wafer.
Validate and Simulate Circuit Behavior
Synthesis tools can be configured to
Optimization for speed
Optimization for size
Simulation Only outputting a simulation model
Flat Compilation = All design is compiled and analyzed together into one flat net-list. (slow compilation times turn on Rapid Recompile to only compile
changes and speed up.)
Incremental Compilation = Partitioning large designs (even allow UN-finished partitions) by way of separate net-list files that get put together by incremental
compilation.
VHDL keywords / constructs that can be Ignored by most Synthesis Tools (For Simulation only)
after, (transportand inertial)
wait forxx ns
Fileoperations
generic parameters must have default values
All dynamically elaborated data structures
Floating point data types, e.g. Real
Initial values of signals and variables
Multiple drivers for a signal (unless tristated)
The process sensitivity list is ignored
Configurations
Division (/) is only supported if the right operand is a constant power of
Assert
Report
Severity

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/EDIF


http://en.wikipedia.org/wiki/Netlist

4.5 Verification
Terms / Acronyms
PVT
+ Process, Voltage and Temperature Analysis
= How operation varies with varying PVT conditions.
MTBF
+ Mean Time Before Failures
=How long before design failures appear (Higher is better)
IBIS
+ Input Output Buffer Information Specifications
VCD
+ Value Change Dump (Waveform standard)
= A VCD viewer plots a wave form based on VCD-Values.
PLI
+ Programming Language Interface
= Invoking C functions from Verilog (ie: System Call)
HVL
+ Hardware Verification Langauge
= Language specifically designed for HDL verification / testbench
PSL
+ Property Specification Language
= http://www.eda.org/vfv/docs/PSL-v1.1.pdf
VIP
+ Verification IP
URM
+ Universal Reuse Methodology
= https://verificationacademy.com/topics/verification-methodolgy
UVM
+ Universal Verification Methodology
= SystemVerilog Validation - http://www.accellera.org/community/uvm/
OVM
+ Open Verification Methodology
= Documented methodology with a building block library for verification

4.5.1 Simulation ( SPICE / NetList )


HDL Simulation Levels
Functional / RTL Simulation
Gate-level Simulation

No Timing considerations
Includes Timing Analysis (Requires Post-Synthesis NetList)

HDL Simulation Applications


ModelSim
http://www.mentor.com/products/fv/modelsim/

Maia Simulation
Wiki List of HDL Simulators

http://www.maia-eda.net/index.php?option=com_content&task=view&id=13&Itemid=47
http://en.wikipedia.org/wiki/List_of_HDL_simulators

Simulation Implementation
Forced Input
WaveForm
TestBench
Test Vectors
SPICE Simulation = Simulation Program with Integrated Circuit Emphasis ( SPICE Simulation often uses Schematic Entry to simulate circuit designs. )
Common SPICE Applications
NI MultiSim by National Instruments
(Previously ElectronicWorkbench)
Altium CircuitMaker
LTSpice is for transistor level model-ling.
Matlab
Details of SPICE
Synopsis owns HSPICE
Cadence owns PSPICE OrCad contains PSPICE simulation.
ADICE Analog Devices
LTSPICE Linear Technology

Mica Freescale Semiconductor


TISPICE Texas Instruments

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/SPICE


http://en.wikipedia.org/wiki/Category:Electronic_circuit_simulators
http://en.wikipedia.org/wiki/List_of_free_electronics_circuit_simulators
Get CircuitMaker Free; EOL product http://techdocs.altium.com/display/ALEG/Legacy+Downloads
http://en.wikipedia.org/wiki/LTspice
UVM/OVM https://verificationacademy.com/topics/verification-methodology

4.6 Target Hardware ( Fitting / Layout )


Circuit Designs can be implemented in various target hardware
IC
+ Integrated Circuit
PCA
+ Printed Circuit Assembly
Programmable IC(s)

= Single electronic chip package containing an electronic circuit


= Physically interconnected electronic components on a Printed Circuit Board (PCB)
= IC(s) with programmable interconnects that allow a circuit design to be programmed into the IC.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Contains full details about categories, scale integration, fabricating & packaging, and families http://en.wikipedia.org/wiki/Integrated_circuit
ASIC is used to describe custom Integrated Circuits (IC) http://en.wikipedia.org/wiki/Application-specific_integrated_circuit
A PCB with attached components is called a PCA
http://en.wikipedia.org/wiki/Printed_circuit_board

4.6.1 Integrated Circuits (IC)


ASIC + Application Specific Integrated Circuit
Integrated Circuit(s) designed to preform a specific task.
Widely used generic electronic circuits are often packaged in an IC.

Categories
MSI
LSI
VLSI

+ Medium-scale Integration
+ Large-scale Integration
+ Very Large-scale Integration

Manufacturing Steps
Circuit Design
Data-Base Release (DBR)
Wafer Fabrication
Wafer Sort
Dice/Wire-Bond
Packaging

= Chips with 10 to 100 gates


= More than 100 gates up to 1980s
= After 1980s all complex chips were considered VLSI

= Circuit is designed on computers using EDA software which typically stores circuit designs in a database
= Design is released (ie: committed) for IC/ASIC manufacturing
= Circuit design is implemented on a silicon wafers at the FAB using photo-lithography technology.
= Automatic Test Equipment (ATE) tests each Integrated Circuit(IC) on the wafer using wafer probe
= Wafers are cut (ie: Diced), put on a substrate where nodes are wire-bonded for external pins
= Substrates are then put into plastic Chip-Packages

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Semiconductor_device_fabrication

A. Data-Base Release (DBR)


Data-Base Release is the process step at which the circuit design is frozen for IC manufacturing.
Tape-Out
- Process of creating Photo-masks from circuit design files used in IC Fabrication.
[ Circuit Design Files ] [ Chip-Layout / place-n-route / fitting artwork files ] [ Mask Shop ] [ Photo-Masks ]
Reticle

- A single IC-mask on a multi-part Photo-Mask

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Photomask


http://en.wikipedia.org/wiki/Tape-out
http://en.wikipedia.org/wiki/Photolithography
B. Wafer Fabrication (FAB)
1. Silicon Wafer (ie: Slice / substrate )

- Blank silicon plate on which many Integrated Circuit (IC) chips are created

a) Sea-of-Gates Template Wafers


Specially created wafers with an array of gates fabricated in them; Further fab-ing in the interconnects will produce the IC.

2. Fabrication
a) Photo-Masks are used to implant/etch/grow the N and P semiconductor regions into the Silicon Wafer
b) DIE
= One IC (ie: Chip) on a wafer
c) LOT
= Case of 25-Wafers for transport
d) Wafer Traveler
e) Process Integration (PI)

= A list of process-steps at the fabrication facility (ie: FAB) required to create the circuitry of the design
= Handles the fab processing of wafers ( ie: Traveler Steps )

Illustration 3: A "LOT" of Wafers

Illustration 2: Wafer's Die Cut from Wafer

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Wafer_%28electronics%29


C. Wafer Sort (Probe)
Probe Test ( ie: Wafer-Level Testing )
1st Silicon = A common term used when a new design reaches probe test for the first time (ie: The 1 st wafer of the design)
ATE
= Automated Test Equipment
Wafer Cleaning wafers are often cleaned with machines (see: Semi-tool)
Probe Testers
the chips on a wafer are tested by probing contact points ( see manufacturers such as Teradyne )
Laser(ESI-9820) Often laser tools burn in Permanent IC settings/memory ( Otherwise One-Time Programmable Memory (OTPM) is used )
Items like part number, origin factory, programmable repairs and default settings (TRIMS) are marked/set inside the chip itself. Repairs offer the
capability to fix/adjust some of the defects after the sensor has been fabricated.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Wafer_testing

D. Dice & Packaging


Dicing = The process of cutting each DIE from a wafer
Each DIE is then packaged into casings
SIP
single in line package
DIP
dual in line package
2-Side through hole pins
PLCC plastic lead chip carrier
4-Side wrap around chip pins to fit in square socket
QFP quad flat pack
4-Side surface-mount pins
PGA pin grid array
Bottom-side pins (ie: like plug-in CPUs)
BGA ball grid array
PGA without pins just solder balls

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Integrated_circuit_packaging


http://en.wikipedia.org/wiki/List_of_integrated_circuit_packaging_types
E. Final / Back-End Test
After the IC is packaged; a final test or functional test is preformed to guarantee a working IC for the customer.

4.6.2 Programmable IC(s)


Common Programmable IC(s)
FPGA
+ Field Programmable Gate Array
= Design is loaded into SRAM blocks (volatile); defining interconnects and logic.
FPAA
+ Field Programmable Analog Array = An FPGA that allows for Mixed-Signal (Analog/Digital) circuit design
PLD
+ Programmable Logic Device
PLA
+ Programmable Logic Array
PAL
+ Programmable Array Logic
GAL
+ Generic Array Logic

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/FPGA


http://en.wikipedia.org/wiki/FPGA_prototyping
http://en.wikipedia.org/wiki/Programmable_logic
A. Field Programmable Gate Array (FPGA)
FPGA = A Blank Integrated Circuit (IC) Chip in which circuit designs can be programmed into them.
FPGA Architecture varies by vendor/model; below is example architectures of Altera and Xilinx
FPGA Vendors
http://www.xilinx.com/
http://www.altera.com/
http://www.latticesemi.com/
http://www.microsemi.com/
http://www.achronix.com/
http://www.tabula.com/
www.microsemi.com/products/fpga-soc
Purchasing
Xilinx Dev Boards

= Virtex, Spartan, Kintex, Artix, Zynq(ARM)


= Stratix, Arria, Cyclone(ARM)
= ECP5
= Previously ACTEL
= Hand-held niche; Not general use FPGA(s)
= 3-D High Speed FPGA(s)
= MicroSemi

CPLD: CoolRunner, 9500Series

- http://www.digilentinc.com/index.cfm

FPGA Development Boards ( Design Prototyping )


Altera
List of Altera Dev-Boards
Popular provider (Terasic)

Xilinx
Xilinx sells Dev-Boards directly
Popular provider (AVNET)
XTEX FPGA Boards
Mojo (Open-Hardware)
Papilio (Open-Hardware)

@ http://www.altera.com/products/devkits/kit-dev_platforms.jsp
@ http://www.terasic.com.tw/en/

@ http://www.xilinx.com/products/boards-and-kits/
@ http://www.avnet.com/en-us/Pages/default.aspx
@ http://www.ztex.de/
@ http://embeddedmicro.com/
@ http://papilio.cc/

Altera Architecture
FPGA
LAB
LE
LUT

+ Field Programmable Gate Array


+ Logic Array Block
+ Logic Element
+ Look Up Table

Depending on model contain 'x' number of LABs


Each LAB contains (16)LEs.
Each LE contains (4)LUTs.
An electronic truth table to implement a variety of logical gates.

Xilinx Architecture
FPGA
CLB
Slice
LC
LUT

+ Field Programmable Gate Array


+ Configurable Logic Block
+ No Accrymn
+ Logic Cell
+ Look Up Table

Depending on model contains 'x' number of CLBs


Each CLB contains (4)Slices
Each Slice contains (2)LCs
- Each logic cell contains (2)3-input LUT a Full-Adder(FA) and an output register (DFF D Flip Flop)
An electronic truth table to implement a variety of logical gates.

FPGA Architecture (In General)


[LUT/ALM] - Each LE/LC typically includes a 4-input "Look-Up Table" instead of gates; like a truth-table.
ALM(adaptive logic module) - is a type of LUT that includes a [FA]full adder and [FF]flip-flop.
The 4-Input LUT standard is maintained in ALM for compatibility.
Typically there are 4 or 5 LUTs per LE making 16 or 32 possible row truth table (old was 3-LUT or 8-bit)
[Macro-Cell/Resource-Blocks] LE; High-Level functionality blocks - Some LE's are hard-wired functions; IP(Intellectual Property Cores)
PLL phase-lock loop; DLL delay lock loops (Dynamically phase-shift strobes for memory interfaces / temperature change adaptability)
IO Bank; pad slew rate and drive strength (programmable)
SRAM memory
HS-Transceivers
FPGAs has IO control (IO elements) slew control, LVDS, pull-up, clamps, and etc.. Bi-directional has OE (output-enable)
[IOB]Input/Output Block
Also have dedicated resource blocks (memory blocks, FIFO, MLABs memory labs, math operations)
SRAM cells ( stores how the LABs logic and PLL clocks will work ) gates input come form the SRAM cell.
Because of SRAM cells the FPGA must be programmed on power-up (SRAM is volatile)

// Register packing - refers to the use of the LUT and FF in a logic element(LE)

PI - Matrix of "Programmable interconnects" in a Row/Column layout


Clock signals and other high-fan-out signals(ie: global buffers) are routed independently of logic interconnects.
PI's can contain both local-networks for adjacent LE's or Row/Col for entire grid.
FPGAs have dedicated clock pins and clock control blocks
Terms
Device Atoms A LUT of DFF or FA within the FPGA architecture is called a device atom.

Programming a FPGA/PLD

IC-Programming-Unit
In-System-Programming (ISP)

Older PLD's with PROM, EPROM or Fuse-Memory required a physical tool to program the chip.
Circuit board has a JTAG header plug-in for programming chips within the circuit.

B. Programmable Logic Devices (PLD)


PLD / GAL are the root/parent technology that led into FPGA technology
SPLD
+ Simple Programmable Logic Devices
PLA
- Programmable Logic Array
= Programmable interconnects on AND & OR gates
PAL
- Programmable Array Logic
= Device (AND programmable / OR hard-wired
CPLD
+ Combinational / Complex Logic Device
Architecture
Contain multiple PLD/PAL logic arrays in one
Macro-cell = Term used to signify the logic capability count
Equivalent-Gates = term used to describe the count of NAND gates required to implement a design
Each Macro-cell uses 20-gates so an 8-macrocell PLD can have 160-gates and a CPLD with 500-macrocells supports 10,000 gates.

4.6.3 Printed Circuit Assemblies (PCA)


Printed Circuit Assembly (PCA) = Printed Circuit Board (PCB) with components attached
1. PCB Etching
etchant chemical.

- Copper Traces/Routes are created on fiberglass boards typically using a photo-plotter and copper

2. Part Placement
a) Through-hole Technology (THT)
CNC Milling Machine
Wave Soldering machine

- Component leads are inserted through holes in the PCB board.


- Holes in the PCB board are created using automated drilling machines
- Component leads are soldered to the PCB board using a machine that creates waves of molten solder

b) Surface Mount Technology (SMT)


SMT metal stencil
Re-flow Oven

c) Pick N Place
automatic equipment
Tape Reel

- Components are placed on pads on the PCB board.


- A metal template/stensil used to apply solder paste to component pin locations on a PCB board.
- A programmable oven used to melt the solder paste on a PCB.
- Components for the circuit design are picked and placed onto the circuit board typically by Pick N Place
- Spool of electronic components used by Pick N Place machines.

3. PCA Testing
a) ICT
+ In-Circuit-Test = A test instrument with a bed of nails (ie: Connectors) for measure and test the PCA
b) Flying-Probe
= Flying-Probes can also be used for a cheaper and not as thorough In-Circuit-Test
4. Functional Testing

= Finally the circuit board is powered up under normal operating circumstances and tested for sale-quality functionality.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------SMT


http://en.wikipedia.org/wiki/SMT_placement_equipment
ICT
http://en.wikipedia.org/wiki/In-circuit_test
Flying Probe http://en.wikipedia.org/wiki/Flying_probe

5. CIRCUIT DESIGN SOFTWARE (EDA / ECAD)


EDA
ECAD
CAE

+ Electronic Design Automation


+ Electronic Computer Aided Drafting
+ Computer Aided Engineering

= PC-Software specifically for System Circuit Designing (ie: Electronic Engineering )


= Another term for EDA; Software tools are a sector of the Computer Aided Design (CAD)
= Yet another term for Computer Aided Design (CAD)

Overview
EDA Tools were originally created on Linux OS Shells.
TCL + Tool Command Language
= Linux scripting language used heavily in EDA tool integration
EDA Tools typically contain a slew of <command>.exe files inside the tools sub-directory
commands can be invoked entirely from the OS command line.
Graphical User Interfaces (GUI) s are usually just helper tools that auto-launch commands)
SDL + Specification and Description Language
EDA Vendors (Listed by assumed popularity)
Synopsis
Synplify
FPGA design solution by Synplicity (Acquired by Synopsis in 2008)

Mentor Graphics
Leonardo Spectrum
Precision RTL
ModelSim
Cadence
Virtuoso
Allegro SPB
Spectre
OrCad
Allegro Design Entry CIS
SimVision

= CPLD, FPGA or ASIC Synthesis

= Schematic editor
http://www.cadence.com/products/rf/schematic_editor/pages/default.aspx
= Design Tool Suite
= Mixed signal (chip level) Simulation
= PCB design
- Free size limited download
http://www.orcad.com/
= Component Information System
also known as OrCAD Capture CIS
= Unified graphical debugging environment (Waveform simulation)

Xilinx (FPGA/CPLD)
Vivado
Altera (FPGA/CPLD)
Quartus-II
Qsys

= Previously SOPC-Builder

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki List of EDA Software


http://en.wikipedia.org/wiki/Category:Electronic_design_automation_companies
Comparison of EDA Software
http://en.wikipedia.org/wiki/Comparison_of_EDA_Software
http://en.wikipedia.org/wiki/Synopsys
http://www.synopsys.com/home.aspx
http://en.wikipedia.org/wiki/Mentor_Graphics
http://www.mentor.com/products/fpga/synthesis/
http://en.wikipedia.org/wiki/Cadence_Design_Systems
http://www.cadence.com/en/default.aspx
http://en.wikipedia.org/wiki/Altium
http://www.altium.com/
http://en.wikipedia.org/wiki/GEDA
http://www.geda-project.org/
http://en.wikipedia.org/wiki/KiCAD
http://www.kicad-pcb.org/display/KICAD/KiCad+EDA+Software+Suite
http://en.wikipedia.org/wiki/Electronic_design_automation
EDA Software

Commercial
Commercial
Commercial
Commercial
OpenSource
OpenSource

5.1 Altera Quartus-II


File extensions
bdf
+ Block Design File
= Schematic
bsf
+ Block Symbol File
= Schematic block symbols
edf
+ Electronic Design File
= Vendor neutral schematic / design file in Electronic design interchange format (EDIF)
lmf
= ASCII files used to map EDIF(.edf) and Verilog Quartus mapping files (.vqm) (Other Vendor HDL Quartus Logic)
mif
+ Memory Initialization File
ncf
= Altera Monitor Program [NiosII] Project File
pof
+ Program Object File = Compiled project file to upload to FPGA's FLASH for Active-Serial mode (see also .sof)
ppf
+ Pin Planner File
qar
+ Quartus Achive Repository
= Quartus Project Archive Project / Restore archived project
qip
+ Quartus IP-Core
qpf
+ Quartus project file
qsf
+ Quartus Settings File
= Can add PIN-Assignments here - set_location_assignment PIN_N25 -to x1
qsys
- Hardware contents of a Qsys System
sdc
+ Synopsys Design Constraints = Component Simulation parameters text file (Create manually or TimeQuest)
smf
+ State Machine File
sof
+ SRAM Object File
= Compiled file to upload to FPGA
sopcinfo - Description details of the associated 'Qsys' file in XML (For generating the BSP - the build software tools)
sym
- Symbol file
tdf
+ Text Design File
= Design in Altera hardware description language (AHDL)
vho
Simulation structural NetList
vht
ModelSim generated VHDL test-bench files
vqm
+ Verilog Quartus Mapping
= node-level or atom net-list text file
vwf
- Simulation waveform to set node levels at simulation time.
Projects
Project File
Project Settings
Set Default Projects Folder
Import/Export Pin Assignments
Pin Driving (Including UN-Used)
Auto-settings by specification
Project Revisions (Diff settings)
Compare Revisions
Select Revision for Synthesis
Copy Project
Specify timing constraints (SDC)

= <ProjectName>(.qpf); a revisions text file that points to <ProjectNameRevision>(.qsf)


= (.qsf) projects contents and settings text file stores settings made in Quartus Assignments menu
= Menu Tools Options General Default File Location (@Bottom)
= Menu Assignments Import (Retrieve Pin Assignments) or Export (Save Pin Assignments)
= Menu Assignments Device Device and Pin Options (max I/O @ 240mA)
= Menu Tools Laungh Design Space Explorer (Uses SDC timing constraints file with TimeQuest to meet goals)
= Menu Project Revisions (ie: Compilation Settings Revisions not Source File Revisions :: Creates new .qsf file)
= Menu Projects Revisions Compare
= Project Navigator Revisions Right-Click and select Set Current Revision
= Menu Projects Copy Project
Ideal way to create a new project based on existing one
= Menu Tools TimeQuest Timing Analyzer Analyzes timing constraints on compiled design

Quartus Database for teams

= Menu Projects Import/Export Database and Clean Project

Quartus Folders
Error Message Details
= Menu Help Message List
<Install-Path>/quartus/common/help/webhelp/
Altera Device List
= Menu Help Devices and Adapters
<Install-Path>/quartus/common/help/webhelp/
EDA Interfaces (Other Tools)
= Menu Help EDA Interfaces
<Install-Path>/quartus/common/help/webhelp/
Getting Started Tutorial
= Menu Help Getting Started Tutorial
<Install-Path>/quartus/common/help/tutorial/qtutorial.htm
Altera supplied IP-Cores
= Menu Tools IP Catalog (MegaWizard)
<Install-Path>/ip/altera/<IP-Core>
Generate Tcl Project Script
= Menu Projects Generate Tcl file for project
** Add <Install-Path>/quartus/bin64 to Command Line PATH to use 'quartus_sh -qhelp'
Validation Tools
Auto device selected by Fitter
Device Migration
PowerPlay Power Analyzer
Simultaneous Switching Noise (SSN)
Design Assistant

= feature that will pick a suitable Altera FPGA upon design compilation.
= tools that allow designs to move between different FGPA IC-Chips
= Estimates power usage for the Circuit implemented on a PCB board.
= Analyzes / checks for noise /distortion voltage across I/O traces.
= Checks design for adherence to Altera guidelines (Can also use a lint tool for coding style checks)

Early Pin planning


= PCB layout is determined before hand where pin locations must be verified by FPGA fitter to avoid board changes.
The pin planner interfaces with the IP-Core parameter editor and pin-outs created in top-level design file then Start I/O assignment analysis
Then to a board-aware analysis = Enable Advanced I/O Timing Options
TimeQuest Analyzer
= Thorough circuit timing analysis tool
tsu
+ Input setup time
th
+ Input hold time
tco
+ clock to out delays
tpd
+ Propagation delay
pin to pin delays
Fmax
+ Maximum clocking frequency
Clock Period = tco + data delay + setup time clock skew

= tco + B + tsu (E -C)


Fmax = 1/Clock Period

5.1.1 Qsys Designer (SOPC)


Qsys = Embedded System Design Tool ( FYI: Previously named SOPC-Builder )
Systems are constructed by adding (ie: picking N choosing) Qsys Components (ie: IP-Blocks / Cores with common system bus)
Qsys auto-generates
HDL files
Boot-loader
_hw.tcl
SOPCinfo

- Circuit design files


- HEX-Code for the system start-up
- Hardware Components Description File
- Specification file for the Board Support Package (BSP)

Implementation
Component names
System is synthesized

- (ie: IP-Block Names) in Qsys are used by firmware to access the hardware
- [SOF] [FPGA] [HAL] [BSP](system.h) Applicaion(?.elf)

FIFO(s) are used to connect FPGA IO-Pins to the processor.


IN-FIFO & OUT-FIFO both connected to the data bus
( In exports In-Bus / Out exports out bus )
HAL Hardware abstraction layer (library) FPGA

HAL
Altera SBT (The NiosII SBT (System Build Tools) Generates HAL Board Support Package (BSP))
SBT
+ System Build Tools = For Eclipse; Takes the sopcinfo file data and generates HAL -> Component Drivers
system.h
Defines symbols for referencing hardware in the system (BSP) part of the board support package
boot-loader (Intel HEX)
Initialization information for on-chip memories (initializes contents)
.a = Single user library project ( doesn't contain main() )
HAL + Hardware Abstraction Layer
newlib
Device drivers
Eclipse (C/C++) with the NiosII build chain
Compiles to ?.elf file
the executable for embedded processor
elf = Executable and Linking File
format is result of compiled C/C++ application
ELF
- Executable and Likable Format
= Binary File Format (Flexible file format for binary code)

NiosII SBT Command Line


Optional Libraries
NicheStack TCP/IP Stack
Read-only ZIP file system
Host File System (Refer to HAL)

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Software Dev for Nios II System


http://www.altera.com/literature/hb/nios2/n2sw_nii52017.pdf
Altera Tutorial Nios II Hardware Development Tutorial
Altera
http://www.altera.com/support/examples/design-entry-tools/qsys/qsys.html
University Courses w/Qsys
http://myweb.wit.edu/johnsont/

5.1.2 Soft Core Processors


NiosII ( Master of Avalon Interconnect Fabric )
/e
/s Standard Edition
/f
NiosII w/MMU = NiosII for Linux; no System Build Tools (SBT) support

Registers ( Memory Mapping I/O )


Register offsets are assigned within Qsys
Avalon-MM ( Master / Slave type architecture )
Control Registers
Status Registers
Qsys sets up separate command / response networks to IP-Block
2x-throughput
Instruction Cache Memory
Ports
data_master = The processors data bus
Avalon-ST = Streaming interconnect fabric
instruction_master = retrieves instructions
instruction_master jtag_debug_module ( connection to processor for debug/firmware download)
Interconnect Fabric
Connection Fabric = A "Standard" that allows internal connections between Processor and peripherals (A Standard Control, Data, and Address
Bus connectors)
Connection fabric also named NoC(Network-on-chip) Architecture; The arbiter for IP Packet transform to various IP components
The Nios II HAL(Hardware abstraction layer) interprets low IRQ values as higher priority.
HAL - Hardware abstraction layer and peripheral drivers (Software that generates C headers for Custom Nios)
Examples;
ALTERA; Avalon Fabric including Avalon-MM(Memory-Mapped I/O) and Avalon-ST(Streaming) as well as ARM Structure and AIX4
Configure
Reset Vector Offset = 1st Address
(boot-loader / image / custom )
Exception Vector
= Act of responding to an exception and then returning to pre-exception state.
NiosII.Processor.Reference page 3-31
http://www.johnloomis.org/NiosII/interrupts/exception2.html
Pipe-lining Support for up to 4-pipelines
Base Address - Nios II processor cores can address a 31-bit address span.
You must assign base address between 0x00000000 and 0x7FFFFFFF (Over is a negative number)

SOPC-Peripherals
SysID to match firmware with processor core
Generating Systems with Qsys
Simulation
DMA direct memory access controller
DMA - Direct memory access "controller"; DMA is nothing more than a way to bypass the CPU to get to system memory and/or I/O.
http://www.ganssle.com/articles/adma.htm
Bus Request" (AKA "Hold" on Intel CPUs) is an input that, when asserted by some external device, causes the CPU to tri-state it's pins at the
completion of the next instruction.
Bus Grant" (AKA "Bus Acknowledge" or "Hold Acknowledge") signals that the processor is indeed tri-stated. This means any other device can put
addresses, data, and control signals on the bus. The idea is that a DMA controller can cause the CPU to yield control, at which point the
controller takes over the bus and initiates bus cycles. Obviously, the DMA controller must be pretty intelligent to properly handle the timing
and to drive external devices through the bus
What peripherals will Nios connect to (add/remove PIO, VGA, etc..)

--[ References ]----------------------------------------------------------------------------------------------------------------------------------------------------

5.1.3 IP-Cores
Mega-Functions

= Altera Quartus installs off-the-shelf configurable IP cores optimized for Altera devices (OpenCore Plus IP)

Quartus Tools IP Catalog


(Previously MegaWizard Plug-In Manager)
Basic Function IP
DSP Function IP
Interface Protocol IP
Memory Interfaces and Controller IP
Processor and Peripherals IP ( Covered in Qsys Section Above )
Licensed IP's can be used locally as
Untethered = run for a limited time
Tethered = indefinite usage but only when connected to host PC
(.qip) and (.qsys) files can be added directly to a project
Project Navigator Files Right-Click Add/Remove files.
IP-Cores
Include Design Libraries
= Quartus Assignments Settings Libraries
Project library setup in (.qsf)
Global library setup (quartus2.ini)
Via SEARCH_PATH setting
When searching for IP-Cores the project directory takes precedence over all others.
IP-Cores can be instantiated in HDL code
By Name with parameters (In VHDL you must include the associated libraries)
Verilog Altera IP-Core Instance
altfp_mult inst1 (.dataa(wire_dataa), .datab(datab), .clock(clock), .result(result));
defparam
inst1.pipeline = 11,
inst1.width_exp = 8,
inst1.width_man = 23,
inst1.exception_handling = "no";

VHDL Alter IP-Core Instance


library altera_mf;
use altera_mf.altera_mf_components.all;

inst1 : altfp_mult
generic map (
pipeline => 11,
width_exp => 8,
width_man => 23,
exception_handling => "no")
port map (
dataa => wire_dataa,
datab => datab,
clock => clock,
result => result);

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------DSP Solution Center


http://www.altera.com/technology/dsp/dsp-index.jsp
Altera IP literature
http://www.altera.com/literature/lit-ip.jsp

5.1.4 Schematic & HDL Editors


Altera's University Program Training Resources at ftp://ftp.altera.com/up/pub/Altera_Material/13.0/Tutorials/ or { ftp://ftp.altera.com/ }
Steps of the flow can be set just below the project browser
Chip Planner draws the FPGA/LAB/LE used on the chip

RTL simulation?

Simulating a Circuit
File > New > VWF; Edit > Insert > Node or Bus > Node Finder > List > Select and Add > OK > Drag area and click to apply levels
Click "Run a Functional Simulation Button"
Click "Run a Timing Simulation" (Full Compilation required)

Programming the FPGA


JTAG - when switch position is in "Run" during programming
AS (Active Serial) - Design is loaded into on-board flash; switch in "Prog" during programming
Backup DE2 FPGA Flash
Open Programmer
Set Mode to "Active Serial" and set board switch to "Prog"
"Add Device" and choose "EPCS16" (the flash unit)
Select "Examine" then "Start" to load the flash contents
Click "Save" to save the contents to a .pof file.
Templates Quartus Edit Insert Template (Drops template code in the open HDL file.)

--[ References ]----------------------------------------------------------------------------------------------------------------------------------------------------

5.1.5 Design Simulation ( Debug / Performance )


A. Simulation
1. Altera comes with 2-Simulation Tools that can do either RTL or Gate Simulation
a) Qsim
By Altera
b) ModelSim
By Mentor Graphics
2. Simplest way to do this is File > new (University Program VWF; add nodes adjust wave-forms; save)

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki List of Simulators


http://en.wikipedia.org/wiki/List_of_HDL_simulators
B. TimeQuest Timing Analyzer
Executable is 'quartus_sta.exe'
Auto generate SDC Template = Quartus TimeQuest Analyzer Constraints Write SDC File

C. ELA Embedded Logic Analyzer


ELA
HPS

+ Embedded Logic Analyzer


+ Hard Processor System

= An FPGA design/plug-in that exports internal circuit logic for analysis and debug
= (ie: SOC); FPGA is much slower than HPS.

NI Labview - National Instruments Labview is a high-level system design tool that converts graphical block diagrams into digital hardware circuits
NetList - is a circuit connection text file (typically fed into a SPICE simulator to generate XY-plot analysis using Differential non-linear and
calculus/engineering equations.
IBIS + Input/Output Buffer Information Specification

= Hides SPICE model by assigning IO specifications of the device for board level simulation

- Companies involved in FPGA design


- Aldec Active HDL Simulator
- Synopsys Design Analyzer
- Synopsys Design compiler

5.1.6 Bugs / Gotchas


Eclipse Nios errors
0 [main] bash 312 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer. Please report this problem to
the public mailing list cygwin@cygwin.com
{ http://www.alteraforum.com/forum/showthread.php?t=44672&s=1dc3d4440ab489c8969dbfcca15baffe&p=189487#post189487 }
{ http://www.alteraforum.com/forum/showthread.php?t=43526&GSA_pos=2&WT.oss_r=1&WT.oss=Couldn%27t%20compute%20FAST_CWD%20pointer }
Download / Install most recent Cygwin w/Perl for both x86 and x86_64.

I Renamed original folders C:\altera\13.0sp1\quartus\bin\cygwin to \cygwin_original


C:\altera\13.0sp1\quartus\bin64\cygwin to \cygwin_original
Created new empty ....\cygwin folders
Copy paste recent Cygwin into their respective directories C:\altera\13.0sp1\quartus\bin\cygwin (x86) and C:\altera\13.0sp1\quartus\bin64\cygwin (x86_64)
directories respectively.

ModelSim won't simulate the NiosII/s soft-core


NiosII/s proprietary = Remove ModelSim-Altera setting on project start-up

Qsys - "Failed to query available BSP types"


Have to take a different route
error dialog shown below ("Failed to query available BSP types
I filed a service request and received the following reply:
"There is a bug in the GUI for the bsp creation page for Nios II Software Build Tools for Eclipse in ACDS 13.0. The bug is currently planned to be fixed in 13.1.
We are sorry for any inconvenience caused due to this bug.
As a workaround for this issue, instead of choosing New->Nios II Board Support Package, choose the option New -> Nios II Application and BSP from
Template. Select the template Hello World if you would like to have Altera HAL as the Operation System, else select Hello MicroC/OS-II if you would like to
include the MicroC/OS-II RTOS. Please note that you should not click "Next", so that you won't be directed to the bsp page which has bug. Click finish after
you have filled in the required information. The bsp project created will be automatically named as %application project name you specify%_bsp. You may
delete the application project later if it is not needed."

Using command line options in Windows


Add <Install-Path>/quartus/bin64 to environment variable PATH to use 'quartus_sh -qhelp'

**LEAVE OpenCore Plus Status Pop-Up box open else ELF will fail to download. (This message notifies that one of the IP-Cores used requires licensing for inproduction use)

5.2 Xilinx ISE / Vivado


A. System-Level Tools
1. Xilinx Soft-Core Processors
a) MicroBlaze
b) PicoBlaze

B. Circuit-Level Tools
2. IP-Integrator (Previously ISE)

5.3 ModelSim
Features
Altera Quartus-II Installer includes ModelSim-Altera Starter edition
ModelSim has a Transcript command prompt which is actually a TCL shell prompt with necessary imports.
GUI providing tools to create and/or simulate design projects
Menu File New Project
Altera Quartus builds a ModelSim include file at C:\altera\13.0sp1\modelsim_ase\modelsim.ini
Includes Libraries such as: C:\altera\13.0sp1\modelsim_ase\altera\vhdl\altera_mf
Folder $MODELSIM_TECH = C:\altera\13.0sp1\modelsim_ase\win32aloem\

Paths
Program File
Working Directory
.\altera\
.\docs\
.\examples\
.\modelsim.ini
.\ieee\
.\win32aloem\

= C:\altera\13.0sp1\modelsim_ase\win32aloem\modelsim.exe
= C:\altera\13.0sp1\modelsim_ase
= Altera Mega-function simulation files.
= Documents and tutorial guides (as well as a Tcl help guide)
= ModelSim Help/Tutorial example files
= Text file that will include all the locations of Altera Mega-function simulation code
= simulation code for the 'IEEE' library
= The ModelSim Executable directory

File Associations
(.mpf)
ModelSim project file
= Text file containing all files and settings for a simulation project (App; ModelSim.exe)
(.wlf) Simulated Waveform
= Mentor graphics proprietary waveform (App; ModelSim.exe)
See Also
http://en.wikipedia.org/wiki/Waveform_viewer

Usage
Work Directory
- Choosing the directory that ModelSim will work out of
1) Menu File Change Directory
2) The Directory chosen will need a work sub-folder (ie: Library) and can only be properly created by using
ModelSim> vlib work
Right-Click in the Library browser and select 'new' 'library' 'a new library' and give the new sub-folder / library a name.
Compiling
- The Design Files (Verilog / VHDL) or Testbench files
ModelSim> vcom -reportprogress 300 -work work D:/Electronics/CAD/_Projects/MyDFF2/MyDFF2.vhd
Menu Compile Compile and choose File
Once Compiled the output files will be stored in the 'work' library / folder. (Files .dat, .dbs, .prw, .psm )
Simulate
- Load / launch the simulator
ModelSim> vsim -gui work.mydff2
Menu Simulate 'Start Simulation' and pick the Verilog / VHDL file to simulate

6. SYSTEM SOFTWARE
Common System Software
Bootloaders
BSP
OS

+ Board Support Package


+ Operating System

= Bare-Metal programs loaded sequentially to initiate basic usage


= Collection of Device Drivers to expand hardware control
= A set of software libraries used to manage hardware & isolate software from the hardware.

System Software Configurations


Simple Structure (ie: No Operating System)
OS [Contains Middleware & Device Drivers] Hardware
OS Device Drivers Hardware
OS BSP w/Drivers Hardware

= An Operating System is optional in Embedded Systems


= OS Manages device drivers through system level calls
= An OS developed on-top of static device drivers (Platform specific OS)
= An OS developed on-top of a BSP which contains device drivers.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Abstraction Layers


http://en.wikipedia.org/wiki/Abstraction_layer
Hardware Abstractions http://en.wikipedia.org/wiki/Hardware_abstraction

6.1 Bootloaders
Types
Bootstrap Loader
Boot Loader

= Initial Boot loader


= Any other Boot loaders

System Start-Up Sequence


Assert Reset
De-Assert Reset
Set Instruction Pointer
Initialize Registers
Start Interrupt Service Routines (ISR)

= On power-up the reset circuit asserts the reset signal


= Reset is de-asserted when clocks reach running speeds and voltages stabilize
= The processors instruction pointer is set to the 'Reset Vector' for 1 st instruction
= Interrupts are disabled; Clears and sets register values such as the stack pointer and flags
= Launch boot-loaders (ie: device drivers) in the form of Interrupt Service Routines

Boot-loaders can jump to main() functions of C-Code for libraries that matches interface of routines and data structures
Chain-loading
= Process of LOADING multistage boot-loaders one after the other with increasing complexity and functionality
Bootstrap Loader
= Initial instructions that starts the loading of the boot-loaders; Execution begins at the 'reset vector' in ROM
BIOS
- Basic Input/Output System
= A boot-loader for basic I/O functionality (e.g. keyboard/mouse/display)
MBR
- Master Boot Record
= A boot-loader at the very beginning (boot sector) of a secondary memory device
2nd Stage Bootloaders
- Generic Bootloaders
= Further booting device drivers used to expand functionality of the system
Kernel

- Runtime Engine of the OS

Common Bootloaders
BIOS
EFI
UEFI
GNU
GRUB
BOOTMGR
Syslinux
NTLDR
BootX
LILO
CFE
U-Boot

+ Basic Input/Output System


+ Extensible Firmware Interface
+ Unified Extensible Firmware Interface

= Introduced by Intel [1975]


= By Intel; deprecated in 2005 to UEFI
= By Unified EFI Forum

http://www.uefi.org/

+ Grand Unified Boot-loader


+ Boot Manager

= A common Linux boot-loader system


= A MS-Windows Boot-loader

+ Linux Loader
+ Common Firmware Environment
= An open source BIOS boot-loader

= A common Linux boot-loader system


= A boot-loader system and console by Broadcom

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wikipedia Booting (boot-loader loading) http://en.wikipedia.org/wiki/Booting


Wikipedia List of Boot-loaders http://en.wikipedia.org/wiki/Comparison_of_boot_loaders
Wikipedia UEFI http://en.wikipedia.org/wiki/Unified_EFI_Forum
How computers boot up http://duartes.org/gustavo/blog/post/how-computers-boot-up/
http://en.wikipedia.org/wiki/Firmware
Links to ROM imaging and boot-loaders
Wiki ELF File http://en.wikipedia.org/wiki/Executable_and_Linkable_Format
http://www.bottomupcs.com/elf.html

6.2 Board Support Package (BSP/HAL)


BIOS
ASP
FSP

+ Basic Input/Output System


+ Architecture Support Package
+ Firmware Support Package

= BSP that manages basic peripheral device I/O


= Another term for BSP device driver package collection
= Another term for BSP device driver package collection

Notes
The reality is that hobbyist embedded programming doesn't allow time for implementing all the ISRs and the boot-loader code.
Many people use standard software frameworks available for specific processors.
EDA System Design Software typically contains applications that automatically create all the required boot-loaders and device drivers
Terms
HAL
BSP
ESD
SBT
EDS
HID

+ Hardware Abstraction Layer


+ Board Support Package
+ Embedded Software Development
+ Software Building Tools
+ Embedded Design Suite
+ Human Interface Device

= The program layer that joins the hardware software


= Library of boot-loaders and device drivers for hardware software support
= http://www.altera.com/devices/processor/nios2/tools/ni2-development_tools.html
= A library for system-specific support code. (Run-time environment for NiosII)

How firmware connects to the metal (static tables)


** List of Common HAL/BIOS Specifications **
HAL = Isolates platform-specific hardware from Operating System (allows any motherboard)
New platform only requires new driver compilation; because drivers rely on the HAL code.
ACPI
+ Advanced Configuration & Power Interface = Introduced in 1996; http://www.acpi.info/
APM
+ Advanced Power Management
= BIOS Code for Application Programming Interfaces
PNP-BIOS + Plug And Play BIOS
= BIOS Code for Application Programming Interfaces
MPS
+ Multiprocessor Specification
= BIOS code

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------HAL options after XP or Server 2003


http://support2.microsoft.com/kb/309283

6.3 Operating Systems (OS)


OS = Provides a Common (ie: Standard) Operation and Organization (ie: Management) of Hardware & Software Resources.
Manages
Process Management

= Provides basic means of multitasking by dividing and splitting instructions / duties.

Memory Management
Kernel Mode
User Mode

= Controls Virtual Memory tables; dividing memory into two distinct access levels
= Full Access to all resources (ie: Supervisor Mode)
= Limited Access to resources (e.g. Applications cannot corrupt kernel-level code)

I/O Management

= Operates and Organizes Input/Output Devices (e.g. Drivers & File Systems)

Provides
IPC
+ Inter-process Communication
= Facilities/Mechanisms for component communications
HAL
+ Hardware Abstraction Layer
= Base hardware abstraction (e.g. Motherboard Isolation)
SCI
+ System Call Interface
= OS Subsystems provide a Hardware Software Isolation SCI
Windows API + Application Program Interface
= Microsoft Windows SCI

Kernel Architectures
Monolithic
Micro
Hybrid

= Entire OS works in Kernel Mode; Providing a high-level virtual interface over hardware.
= Only fundamental parts of the OS are working in Kernel Mode.
= OS Operation is divided between Kernel and User Mode.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki Abstraction


http://en.wikipedia.org/wiki/Abstraction_%28computer_science%29
Wiki Abstraction Layer
http://en.wikipedia.org/wiki/Abstraction_layer
How to write an OS in Assembly Language
http://wiki.osdev.org/Main_Page
Hobby OS Development
http://en.wikipedia.org/wiki/Hobbyist_operating_system_development
Wiki Operating Systems
http://en.wikipedia.org/wiki/Operating_system
OS Tutorial K-State
http://faculty.salina.k-state.edu/tim/ossg/index.html
Deeper into Windows Architecture
http://blogs.msdn.com/b/hanybarakat/archive/2007/02/25/deeper-into-windows-architecture.aspx
Wiki
Kernel
http://en.wikipedia.org/wiki/Kernel_%28operating_system%29
Monolithic-Kernel
http://en.wikipedia.org/wiki/Monolithic_kernel
Micro-Kernel
http://en.wikipedia.org/wiki/Microkernel
Protection Ring
http://en.wikipedia.org/wiki/Protection_ring

6.3.1 Market
OS Types
Generic
RTOS
+ Real Time OS
= An OS for embedded systems typically with an Real-Time Clock (RTC)
RTOS for Altera NiosII Soft-Core processors
Micrium (MicroC/OS)
http://micrium.com/
http://en.wikipedia.org/wiki/MicroC/OS-II

VxWorks
Embedded Systems
Windows CE
Minix 3

OS Characteristics
Tasking (Single or Multi)
User ( Single or Multi )
Distributed
Templated
Embedded
Real-Time (RTOS)

Microsoft
DOSDOS - Disk Operating System
= OS Shell/Disk Operating System(DOS)
Windows Client Editions
Windows 7 Home Basic
Windows 7 Home Premium
Windows 7 Professional
Windows 7 Ultimate
Windows 7 Enterprise
Windows 7 Starter
Windows Server Editions
Windows Server 2008 R2 Foundation
Windows Server 2008 R2 Standard
= Hyper-V
Windows Server 2008 R2 Enterprise
= Hyper-V
Windows Server 2008 R2 Datacenter
= Hyper-V
Windows Web Server 2008 R2
Windows HPC Server 2008 R2
Windows Server 2008 R2 for Itanium-Based Systems

Invokes OS commands

Linux/Unix
BSD
OS-X
Google Chromium
RedHat
Suse

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------List of RTOS


http://en.wikipedia.org/wiki/List_of_real-time_operating_systems
Popular RTOS
http://en.wikipedia.org/wiki/RTOS#Examples
Sun Micro-Systems Software
http://en.wikipedia.org/wiki/Category:Sun_Microsystems_software

6.3.2 Windows
User-Mode Processes
User Applications
Fixed/Hardwired System Support
Service
Environment subsystems

Kernel-Mode Processes
Executive and Kernel
Device Drivers
HAL
Windowing and Graphics System

= See List of types


= (ie: Hardwired) Logon process, Session Manager; No started by the service control manager)
= Task Scheduler, Print Spooler. Run independent of user log-on
= All User-Mode applications work through subsystem personality & programmer interfaces.

= Hardware (translates user I/O functions calls into specific hardware I/O requests)
= Layer of code that isolates the kernel & device drivers & executive from platform-specific hardware
= Implements Windows GUI functions (ie: Windows USER & GDI functions)

C:\Windows\System32\

Mode

Description

Hal.dll

Kernel

Hardware Abstraction Layer (Hardware Specific)

Ntoskrnl.exe

Kernel

Windows Executive and Kernel

Ntkrnlpa.exe

Kernel (32-bit)

Executive and Kernel w/Physical Address Extension (PAE).

Allows 64GB RAM Access.

Architecture Specific is isolated in HAL & KERNEL above (e.g. Motherboard)


Ntdll.dll

System Support

System service dispatch stubs to executive functions

Win32k.sys

Kernel

Windows Subsystem

Kernel32.dll

Kernel

Windows32 Subsystem

Advapi32.dll

Kernel

API Subsystem

User32.dll

Kernel

User Subsystem

Gdi32.dll

Kernel

Graphics Device Interface (GDI) Subsystem

A. Executive and Kernel (Ntoskrnl.exe)


Executive = The Upper-Layer of Ntoskrnl.exe
Major Components
Configuration Manager
Process Manager
Security Reference Monitor
I/O Manager
Plug and Play (PnP) Manager
Power Manager
Windows Driver Model Windows Management Instrumentation routines
Cache Manager
Memory Manager
Logical Prefetcher and Superfetch
Support Functions (Used by the Executive Components)
Object Manager
ALPC
- Advanced Local Procedure Call
Run-Time library Functions
Executive Support routines
= System Memory allocation (paged & nonpaged pool), interlock access, synchronization objects resources, fast
mutexes, and pushlocks
Base OS Services
Memory
Process and thread management

Security
I/O
Networking
IPC
Functions
ALPC
NtQueryInformationProcess, NtCreatePagingFile Undocumented System Services (not part of ntdll.dll exports)
Supplies a general interface (Calls between user Kernel Mode for device drivers not associated with read/write)
WDK Kernel Functions
Hidden
WDK Undocumented Kernel Functions Starts with Inbv)
Iop = Internal I/O manager support functions
Mi = Internal memory management support functions

Kernel = The Lower-Layer of Ntoskrnl.exe


Low-Level OS Support
Thread scheduling
= Kernel Dispatcher objects; sync capabilities
Interrupt and exception dispatching
Multiprocessor synchronization
Provides API to the Windows Executive for higher-level constructs
Functions
WDK provides some documentation of the kernel functions; they start with 'Ke'

B. Inter-process Communications (IPC Ntdll.dll)


Windows

Ntdll
Ldr
- Image Loader
Csr
- Heap Manager / Windows subsystem process communications
Rtl
- General run-time library routines
DbgUi - User Mode debug functions
Etw - Event Tracing functions
APC - Asynchronous Procedure Call
= Dispatcher and exception dispatcher
CRT - C Run-Time routines
= Contains only a small sub-set of functions
Exports system services from the Executive (Ntoskrnl.exe)
Contains the 'Image Loader' for loading and communicating DLL files.

C. Environmental Subsystems
MS-Windows Subsystems
Windows Subsystem
POSIX
OS/2
SUA

- C:\Windows\System32\Win32k.sys
= Kernel-mode part of the Windows Subsystem
- Last shipped with Windows 2000
- Last shipped with Windows 2000
- Subsystem for Unix-based Applications = An Enhanced POSIX subsystem

Windows Subsystem
- Files; Kernel32.dll, Advapi32.dll, User32.dll and Gdi32.dll
= Windows API
SUA Subsystem
- Files; Psxdll.dll
= SUA API Functions
Allows running UNIX-based applications; Supported on Windows Server / Enterprise / Ultimate editions.
C.1 Windows API (SCI)

Categories
Base Services
Windows API Functions
- Documented (e.g. Create Process, CreateFile, GetMessage)
System Calls
- (ie: Native System Services) Undocumented, underlying user-mode callable (e.g. NtCreateUserProcess)
Routines
- (ie: Kernel Support Functions)
= Only callable from Kernel-mode (e.g. ExAllocatePoolWithTag for drivers)
Windows Services - User Level services like the Task Scheduler
DLL - Dynamic-link Libraries
=
Terminology
Fibers
User-Mode Scheduling (UMS)
Component Services

User Interface Services


Graphics and Multimedia Services
Messaging and Collaboration
Networking
Web Services

Details
SMSS
+ Session Manager Subsystem
= Launches Environmental Subsystems
Windows Registry @ HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems
CSRSS
+ Client/Server Run-Time Subsystem
GDI
+ Graphics Device Interface
= Library for graphics output devices (ie: drawing)
USER32 [Window Manager] (Windows / Buttons) GDI Graphics device driver / Video miniport driver Hardware

6.3.3 Memory Management


Memory Management = Component that associates [ virtual address spaces physical memory ]
Memory Addresses are routed from virtual address to physical addresses by memory manager.
Paged Pool
= Memory that can be paged out to the hard drive
Non-paged Pool = Always resident in memory
1-Memory Page = 4kilobytes
Memory Manager takes care of pushing over-loads to disk Pool memory space.
Virtual Memory

= Memory split or allocated between

Systems usually handle addresses through a Memory Management Unit (MMU)


This allows Virtual Address Physical Address management
In Windows User-Mode Processes are assigned their own virtual address space to operate in

Virtual Memory Spaces


Kernel
User

= (ie: Kernel Space or System Space) Kernel Architecture of the OS determines software in the Kernel Space
= Kernel Architecture of the OS determines software in the User Space

Windows Memory spaces


User Space
- Virtual Memory
System Space
- Shared memory
User Space
System Space

= Each process is virtually allocated the full bit-length of bit-wise address spaces
= All processes share the same virtual address space

= 0x 0000 0000 0x 7FFF FFFF (32-bit / 8-digit HEX) Virtually allocates to only half the physical address space
= 0x 0800 0000 0x FFFF FFFF (32-bit / 8-digit HEX) Statically linked to half the physical address space

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Explains Virtual Memory/Space


https://msdn.microsoft.com/en-us/library/windows/hardware/hh439648%28v=vs.85%29.aspx
Wiki User Space
http://en.wikipedia.org/wiki/User_space

6.3.4 Process Management


A. Multiprocessor Platforms
Hardware Types
Multicore
Hyper-Threading
NUMA

= Multiple physical processor cores on one IC Package


= Two logical processors for each physical core (see; thread scheduling)
= Each Node contains a processor and memory. Nodes are interconnected by a cache-coherent bus.

Support Mechanisms
SMP
ASMP

+ Symmetric MultiProcessing
+ Asymmetric MultiProcessing

= Threads split between processors (there is no master processor)


= A master processor runs the kernel; other processors run user code.

MS-Windows Features
SMP Multiprocessor support
Multicore, Hyper-Threading, and NUMA Platform support
Windows Architecture knowledge for device drivers
spin locks
wait locks
Threads and Processes fully re-entrant, MP safe

Processor modes Ring0 and Ring3 in x86


Memory Management User vs Kernel Mode and demand paged virtual memory
Multiple nested interrupt levels
Difference between IO port and memory space
Device registers and why/when devices interrupt
DMA and basic difference between DMA and programmed IO relevant to a driver
Race / Deadlock control
Synchronization = Using synchronization objects to protect shared data
Serialization
= Stack / queue requests for one at a time access to shared data

Need to look-up and document


Semaphores
Mutex
Heap

B. Scheduling

Windows Implementations
Kernel Scheduler
Fibers
UMS
- User-mode Scheduling

= (ie: Light-weight threads) Manual Scheduling; Use ConvertThreadToFiber()


= 64-bit Windows support; See Direct Context Switch

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki Scheduling


http://en.wikipedia.org/wiki/Scheduling_%28computing%29

6.3.5 Inter-Process Communication (IPC)


Types
File
Signal
Messaging
Pipe
Semaphore
Shared Memory
Memory-Mapped

Interface Categories
ABI
API

+ Application Binary Interface


+ Application Programming Interface

= Interface between program components at the machine code level (e.g. OS level)
= Interfaces between program components at the source code level

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki


Inter-process Communication
http://en.wikipedia.org/wiki/Inter-process_communication
Inter-process Communication Categories
http://en.wikipedia.org/wiki/Category:Inter-process_communication
Local Procedure Call
http://en.wikipedia.org/wiki/Local_Procedure_Call
Windows communication and services
http://en.wikipedia.org/wiki/Category:Windows_communication_and_services
Unix Doors
http://en.wikipedia.org/wiki/Doors_%28computing%29
A. General IPC (CORBA/ORB)
OS Libary
Windows is part of

Ntdll.dll library

Technologies
Dynamic Linker
Dynamically Loaded Library
DLL- Dynamic Link Library
IPC - Inter-Process Communication

= Microsoft's implementation of Shared Libraries through shared memory space.


= Using communication protocols to message

Component Re-Use
Late / Dynamic binding

= Method being called on an object is looked up by name at runtime.

Early / Static binding


= Compilation fixes data-types in the virtual method table (v-table)
Dynamic Loading / Binding
Static Linking
- (ie: Static Dispatch /
Dynamic Linking
Dynamic
Static

Methods of Library Loading


Path
Name
- OS finds the library via Registry
- Dependency Hell ( DLL Hell ) - UID Unique ID were invented to prevent DLL hell
Windows checks the registry to determine the place of dynamic libraries that implement the COM objects.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki Library


http://en.wikipedia.org/wiki/Library_%28computing%29
Wiki Dynamic Link Library
http://en.wikipedia.org/wiki/Dynamic-link_library
Wiki Dynamic Loading
http://en.wikipedia.org/wiki/Dynamic_loading

Dynamic Linker
- Late Binding
= The part of an OS that loads and links shared libraries at run-time.
This is done by copying the library contents to RAM and filling jump tables and pointers
Late Linking
http://en.wikipedia.org/wiki/Late_binding
Dynamic Dispatch
Name Binding
http://en.wikipedia.org/wiki/Name_binding
Dynamic Loading
http://en.wikipedia.org/wiki/Dynamic_loading
3-mechanisms by which a program can use other software
dynamic loading
static linking
dynamic linking

Market
CORBA- Common Object Request Broker Architecture
ACE
- Adaptive Communication Environment
TAO
- The ACE ORB (Object Request Broker)
http://en.wikipedia.org/wiki/Adaptive_Communication_Environment
LPC
ALPC
RPC

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Inter-Process Communication


http://en.wikipedia.org/wiki/Inter-process_communication
Inter-Process Communication Categories
http://en.wikipedia.org/wiki/Category:Inter-process_communication
Windows Communication and Services
http://en.wikipedia.org/wiki/Category:Windows_communication_and_services
Dynamic Loading
Static Linking
Dynamic Linker
Dynamic Dispatch
VTable
Application Virtualization Software
Foreign Function Interface
Language Binding

http://en.wikipedia.org/wiki/Dynamic_loading
http://en.wikipedia.org/wiki/Static_library
http://en.wikipedia.org/wiki/Dynamic_linker
http://en.wikipedia.org/wiki/Dynamic_dispatch
http://en.wikipedia.org/wiki/Virtual_method_table
http://en.wikipedia.org/wiki/Comparison_of_application_virtualization_software
http://en.wikipedia.org/wiki/Foreign_function_interface
http://en.wikipedia.org/wiki/Language_binding

CBSE
- Component-Based Software Engineering
http://en.wikipedia.org/wiki/Component-based_software_engineering
CBD
- Component-Based Development
TI IPC Users Guide
http://processors.wiki.ti.com/index.php/IPC_Users_Guide/Use_Cases_for_IPC
Wiki IPC Categories http://en.wikipedia.org/wiki/Category:Inter-process_communication
Wiki Synchronization http://en.wikipedia.org/wiki/Synchronization_%28computer_science%29
OS MicroKernel http://en.wikipedia.org/wiki/Microkernel
Software Layers http://accu.org/index.php/journals/460
OS Technology
http://en.wikipedia.org/wiki/Category:Operating_system_technology
http://en.wikipedia.org/wiki/Loader_%28computing%29
B. Microsoft IPC (LPC/COM/IDL)
LPC

+ Local Procedure Call

= Requires the 'Image Loader'

DDE
+ Dynamic Data Exchange
NetDDE
+ Windows for Workgroups DDE
COM
+ Component Object Model
COM
+ Common Object Model
DCOM
+ Distributed COM
MTS
+ Microsoft Transaction Server
COM+
OLE
+ Object Linking and Embedding
OLE Automation Active X

= [1987] MS-Windows or OS/2 protocol for inter-process communications.


= An expanded DDE protocol to work between networked systems.
= [1993] Base Standard ABI Component enabling inter-process communication.
= Specification & API(s) with system-level run-time libraries for marshaling
= COM ABI with features for network communicating components / calls.
= MTS Implemented DCOM
= IOleObject interface; Creating a control extension (OCX)
= IDispatch interface;
= [1996] Expanded COM technology to support ActiveX objects for WWW.

C++ COM Models


ATL
MFC

+ Active Template Library


+ Microsoft Foundation Classes

= Set of template-based C++ classes to assist in COM objects.

DLL - Dynamic Link Library


= A collection (ie: Library) of program components with a dynamic interface specification.
MS-Windows registry picks the DLL file to use (See steps below)
Reference to 'C:\Lib.DLL'
Windows will read the GUID on 'C:\Lib.DLL'
Looks up the GUID in the windows registry
Registry GUID path DLL is used (ie: If a new DLL with the same GUID has been registered then windows will use the \new\ one even if directly
referenced to C:\Lib.DLL
IDL + Interface Definition Language
Terminology
DCE
Marshalling

+ Distributed Computing Environment


= Originally by Open Software Foundations origins of COM/OLE/ActiveX
= Calling external methods (e.g. External methods is called Marshalling an external method calls arguments.)

COM Type Libraries Are components that can describe themselves to the COM engine
Registry records a UID for each COM component known as HKEY_CLASSES_ROOT hive
Registry REVERSE look-up to UID is stored in HKEY_CLASSES_ROOT\CLSID sub-folder
Standardizes the instantiation (ie: Creation) process of COM objects by requiring the use of 'Class Factories'
Standard requires two items to exist
Type Library Contains
CLSID of a component
IID(s) of the interfaces the component implements
Descriptions of each of the methods of those interfaces.
Type Libraries are typically used by Rapid Application Development (RAD) environments such as Delphi, VB, VS to assist developers of client
applications.
RegFree COM
- Registration-Free COM
= A technology introduced with Windows-XP that allows COM compo
Allows COM components to store activation metadata and Class ID (CLSID) for the component w/o using the registry.
Metadata
- Instead, Metadata and CLSID(s) of the classes are implmented in the compontent and declared in an assmebly manifest
(described using XML), sotred either as a resource in the executable OR as a seperate file installed with the component. This allows multiple
versions of the same component to be installed in different directories; described by their own manifests as well as XCOPY deployment. This
technology has limited support for EXE and COM servers and cannot be used for system-wide components such as MDAC, MSXML, DirectX
or Internet Explorer.
Composed of
IDL
+ Interface definition language
= (Has Interfaces and Type Libraries) each having a GUID (Global Unique Identifier)
Enums and Data-Types can be defined in IDL
IID
- Interface ID(s) another common term for GUID(s)
LIBID(s)
- Type Library ID(s) a more specific term
CLSID
- Class ID(s)
COM Components contain:
Interface
= Does NOT carry any implementations of the methods (JUST method declarations)
Interface is the only way a client can access the services of the COM component
Two Types of Interfaces
Standard- Interfaces provided by the COM library. (e.g. Iunknown, Idispatch, IclassFactory, Iole, IdataObject, Istream, IStorage)
Custom
- Programmer interfaces
CoClass
- Component Class
= COM Class Definition (The 'class' identifier in IDL)
Types
In-Process
DLL Libraries that run in the same memory space as the client application using it. If DLL crashes App does too.
Out-Process
EXE Runs in separate memory space as the client App calling it. If EXE crashes App remains active and EXE is reloaded.
Remote
Just like any other component but runs from a seperate location via network; Implemented with DCOM (Distributed COM)
technology.
.NET has its own COM run-time tool known as WinRT

Windows Loader
#1 Application loads
#2 Windows searches for the manifest;
If preset, the loader adds information from it to the activation context
#3 When the COM class factory tries to instantiate a class
The activation context is first checked to see if an emplementation for the CLSID can
be found ONLY IF THE LOOKUP FAILS is the registry scanned.
Windows DNA
ActiveX
DHTML
COM

- Windows Distributed interNet Applications Architecture

= Collection of MS Techonology for Windows / Internet

Component Object Model (COM) is a binary-interface standard for software componentry introduced by Microsoft in 1993. It is used to enable interprocess
communication and dynamic object creation in a large range of programming languages. The term COM is often used in the Microsoft software development
industry as an umbrella term that encompasses the OLE, OLE Automation, ActiveX, COM+ and DCOM technologies.
Different component types are identified by class IDs (CLSIDs), which are Globally Unique Identifiers (GUIDs). Each COM component exposes its functionality
through one or more interfaces. The different interfaces supported by a component are distinguished from each other using interface IDs (IIDs), which are GUIDs
too.
COM interfaces have bindings in several languages, such as C, C++, Visual Basic, Delphi, and several of the scripting languages implemented on the Windows
platform. All access to components is done through the methods of the interfaces. This allows techniques such as inter-process, or even inter-computer
programming (the latter using the support of DCOM).
Interfaces
All COM components must (at the very least) implement the standard

IUnknown interface, and thus all COM interfaces are derived from IUnknown.

The IUnknown interface consists of three methods: AddRef() and Release() (which implement reference counting and control the lifetime of
interfaces) and QueryInterface(), which by specifying an IID allows a caller to retrieve references to the different interfaces the component
implements. The effect of QueryInterface() is similar to dynamic_cast<> in C++ or casts in Java and C#.

Notes from : http://www.youtube.com/watch?v=3ciT2uOz1kM


NIC Network interface card
Grids Computers across the internet CORBA over IP
Cluster Server rack or multiple racks all in one room
Theme Has one Dispatcher and a lot of Workers
SETI@Home, BOINC, Render farms, Google clusters

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Component_Object_Model


C++ and the COM Interface http://na.support.keysight.com/pna/help/latest/Programming/Learning_about_COM/c++_and_the_com_interface.htm
C++ as an IDL http://g.oswego.edu/dl/mood/C++AsIDL.html
Wiki Windows DNA http://en.wikipedia.org/wiki/Windows_DNA
MSDN Inter-process Communications https://msdn.microsoft.com/en-us/library/aa365574%28VS.85%29.aspx
Wiki Windows Registry http://en.wikipedia.org/wiki/Windows_Registry
C. Remote Procedure Call (RPC)
RPC
- Remote Procedure Call
= Sun Systems ABI standard for inter-process communications.
POSIX
See Also
Unix IPC Guide
http://beej.us/guide/bgipc/
DTrace Monitoring Tool
http://en.wikipedia.org/wiki/DTrace

http://www.devarticles.com/c/a/COM/COM-101-A-Quick-Primer/1/#ZmD8mreIzVrKXBbA.99
Understanding Exported Code (DLLs, IDL, etc..) for VB6
http://whathesaid.ca/what-he-wrote/tame-visual-basic-with-idl/

Visual Basic Data Type


Boolean
Byte
Collection
Currency
Date
Double
Integer
Long

IDL Data Type


VARIANT_BOOL
unsigned char
_Collection*
CURRENCY
DATE
double
short
long

Object
Recordset
Single
String
Variant
no parameters
Figure 2: Visual Basic data types and their corresponding data types in IDL

IDispatch*
_Recordset*
float
BSTR
VARIANT
void

Other than unsigned char (Byte), keep in mind that VB can only implement signed types. Parameters marked as [in] use the IDL representation as in
figure 1. These correspond to ByVal parameters in VB. Parameters marked as [in, out] add a single indirection operator (*). These correspond to VBs ByRef
parameters. For example:
HRESULT Method1(
// ByVal As Integer
[in] short intInParm,
// ByVal As Object
[in] IDispatch* objInParm,
// ByRef As Integer
[in, out] short* intInOutParm,
// ByRef As Object
[in, out] IDispatch** objInOutParm
);

6.4 I/O Management


A. Plug and Play Devices (PnP)

Illustration 4: ACPI HAL System Device Tree


PnP Device Tree
= The Windows kernel Plug and Play Manager collects all-peripheral devices into a device tree.
Device Node
= Physical Device, Software component, or Function of a Composite Device in the PnP Device Tree
Device Object(DO) = Each Node is represented by an instance of the DEVICE_OBJECT data structure.
Driver Stack
= The path of drivers through the device tree to a specific target device the device's driver stack

Driver Types
Root
Software
Class

= Entry point driver to the device tree (ACPI in the diagram)


= No hardware just used for Kernel-Mode access and/or User Mode drivers
= Applies to all devices within a given windows-defined device class

Function (FDO) = Primary bus/device driver that handles read/write/control (ie: Also called Mini-Port driver)
FDO
- Function Device Object = Parent device object
PDO
- Physical Device Object
= Child device object within a parent FDO

CDO

- Control Device Object

= Non-PnP driver for legacy devices (handles its own create/destroy)

Filter (Filter DO) = Extension (ie: In-between driver) component for specialized protocols or bug-fixes
Upper-level filter driver
Processes IRP data before the Function Driver
Lower-level filter driver
Processes IRP data after the Function Driver
At start-up
The Windows kernel PnP-Manager requests that each parent driver enumerate all connected child nodes(PDO Child-list).
Each Child PDO then has at least 1-FDO or 1+ Filter DO
For Example: Every USB device is a PDO of the USB Host FDO But each USB device also has a local Function Driver (FDO)
OS Class Drivers

= OS's comes pre-packaged with general purpose standard device drivers for a particular class of devices

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Device Nodes and Stacks @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff554721%28v=vs.85%29.aspx


Windows Device Classes @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff557557%28v=vs.85%29.aspx

6.5 Unix/Linux

7. SOFTWARE DEVELOPMENT
User Applications
Windows 32-bit or 64-bit
Windows 3.1 (16-bit)
MS-DOS (16-bit)
POSIX 32-bit or 64-bit
Note: 16-bit applications can only run on 32-bit Windows

7.1 Overview
Programming
WAT
AOT

= Process of writing source code that is converted (ie: Compiled/Interpreted) to a target machine language (ie: Processor Instructions)

+ Way Ahead Of Time = The program is compiled to target processor machine code (ie: Compiler IS system processor specific)
+ Ahead Of Time
= A common alias to WAT

Initial Compilation
System Specific
JIT

Converts all source code to target Machine Language all at once during the compilation process
The compiler is system hardware/processor specific

+ Just-In-Time Compilation = AOT Compiler item is NOT system processor specific / The JIT Compiler/Interpreter IS processor specific
Source Code AOT Compiler Intermediate Language
Intermediate Language JIT Compiler Machine Language
Intermediate Language Interpreter Machine Language

Original Source code is converted to an intermediate language code standard


Parts of the code are compiled once and executed multiple times
Other parts must remain interpreted and converted every time during execution

JIT-Compiler is also sometimes referred to as translators or dynamic adaptive compilation (DAC)


Interpreters
No Compilation

Source Code is NOT system processor specific; The Interpreter Engine IS system processor specific
Converts source code to machine language on-the-fly line per line every-time the code is executed.

Virtual Machine (VM)

Machine-Level converter from one system platform (Itself) to a target system platform.

Language Terminology
Late-Binding
Scripting Language
JavaScript, Vb-script)
Program Paradigm

Allocates data type resolution on-the-fly rather than at compile time


All scripting languages are interpreted but not all Interpreted languages are scripting languages

- Fundamental Style

(e.g. HTML,

- See http://en.wikipedia.org/wiki/Programming_paradigm

Usually is written so the data is dynamic while the functionality is static


Learn to use libraries and code bases that have already been written
Organization
Around its code (what is happening)
Structured / Functional (Code acting on data)
Around its data (who is being affected) Object Oriented (Data controlling access to code)(Define the routines allowed to act on the data type)
Structured Programming (Mid-Level)
FORTRAN [1950]
COBOL [1959]
BASIC [1964]
Pascal [1970]
ANSI C [1972]

High-Order Languages (HOL); Stand-alone subroutines; Procedural Languages

Object Oriented Programming (OOP)


Very High Level Languages (VHLL)
LISP [1960]
Simula [1967]
SmallTalk [1972]
Java, C++, SQL, Delphi [1990s]
** OOP techniques became widely accepted in all languages except C. **
Natural Languages (AI Artificial Intelligence)
Still in development stages (Programming similar to conversational languages)
Mechanism
What capabilities are to be provided (drivers should not entail policy; deal with making the hardware available leaving how to use
up to the application)
Policy
How those capabilities can be used.
Programming
Bare-Metal Programming (Low-Level) Programming without an OS (ie: NOTHING between the program and the processor instructions)
Machine Language
Processor specific binary (ie: '1s' or '0s') that represent data and/or a processor commands
Assembly Language [1949]
Processor specific symbolic text representation of worded binary (ie: Machine Language)

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki Operating System


http://en.wikipedia.org/wiki/Operating_system
Language comparison
http://en.wikipedia.org/wiki/Comparison_of_programming_languages
Functional Language comparison
http://en.wikipedia.org/wiki/Comparison_of_functional_programming_languages
Language list
http://en.wikipedia.org/wiki/List_of_programming_languages
Keywords Compared in Different Languages
http://msdn.microsoft.com/en-us/library/zwkz3536%28v=vs.71%29.aspx
List of Compilers
http://en.wikipedia.org/wiki/List_of_compilers
Online ISOCPP(ie: C++) compilers https://isocpp.org/blog/2013/01/online-c-compilers also see https://isocpp.org/get-started
Capable of representing a kernel binary as easily as an executable or system library
Cross Compilation (Different Target Systems)
http://airs.com/ian/configure/configure_5.html
Embedded System Programming
http://www.bogotobogo.com/cplusplus/embeddedSystemsProgramming_gnu_toolchain_ARM_cross_compiler.php
Cmake Cross Compilation
http://www.vtk.org/Wiki/CMake_Cross_Compiling
Wiki AOT Compilers
http://en.wikipedia.org/wiki/Ahead-of-time_compilation
Wiki Program Execution
http://en.wikipedia.org/wiki/Execution_%28computing%29

7.1.1 Compilers/Interpreters
Compiler Types
Assembler
Cross-compilers

= (ie: Assembly Language compiler) Converts assembly language to machine language; Typically both are processor specific
= Compilers located on a development PC but compiled for an embedded systems hardware platform

Compiling Tool-chain
Pre-processor
Compiler
Linker
Libraries
Executable

= Adjusts (ie: Adds, Deletes, Substitutes) source code fragments based on Pre-processor variables before compilation.
= Converts all source code Target language (ie: Machine Code or Byte Code) at one time.

Final file after linking the object file with system libraries file is ready to be transferred to the embedded systems memory

7.1.2 Common Notations


1. Naming

Event
Boolean

= 'On' like OnProgramStarted or OnButtonClicked()


= 'Is' like IsOkay or IsPathSet()

7.1.3 File Extensions


1. Object files
(.o) = Compiled source file (If you have several source files in your application, you will also have several object files.)
2. Libraries (Package of object files)
(.a ) Linux / (.lib) Windows
(.so) Linux / (.dll) Windows

= Static Library
Linked during compilation and become part of the executable
= Dynamic Library Loaded only when program is running and library is called.

7.1.4 Object Oriented Programming (OOP)

1. General Components
Data Storage - Noun
Variable
A named memory spot for holding data (Name Value)
Compound Contains both code and data (e.g. Objects)
Discrete
Only contains data
Static
All objects share one memory location (ie: variable)
Field
Alias for a public variable within a 'class' in OOP languages.
Property
Wrapper for a field in OOP languages.
Data Manipulation Verb ( Any data manipulation code generally takes on any of the below names technicality isn't maintained )
Function
= In Data Process Out Data
Method
= Alias for Function in OOP Languages.
Sub-routine = A function that does not directly return data
Function Types
Delegate

= Call Wrapper

Function that receives a pointer to some other function (e.g. DelagateCaller(InData, PtrToFunction))

2. Encapsulation = Data and function encapsulation within Classes and Structures ('struct')
class
= A defined and named block of code including variables(ie: Properties) and functions(ie: Methods)
Classes bind together functions and data
e.g. Class Circle { VARIABLES: 'radius', 'color', FUNCTIONS: getRadius(), getColor(), getArea() }
struct

= A class typically used for a data structure (User-defined Data Type (UDT)); where the variables within are public by default
e.g. struct milk { brand, amount, grade }
TYPE keyword is used instead of 'struct' in VB6, VHDL and various other languages

object

= An isolated copy of the class code that maintains it's own variable values (ie: Instance of a class)
C1 = A named copy of 'circle class' code thus 'C1' can have it's own radius and color settings.
C2 = A named copy of 'circle class' code thus 'C2' can have it's own radius and color settings.
C3 = A named copy of 'circle class' code thus 'C3' can have it's own radius and color settings.
NEW keyword typically instantiates the object from a class design

** Above isn't actually how classes/objects work; but it represents the effect **
** OOP languages use vtables behind the scenes to link-in the correct values for each object's variable values **
Ex. One can drive Object1 car without driving Object2 & Object3 cars even though they all derive from the same class (ie: design)
Class Types
Concrete Classes = Classes defined for object creation
Abstract Classes = Classes that never become objects but are strictly used for inheritance
C++ - Abstract classes contain at least one pure virtual function (to prevent objectifying it)
Example: Dog inherits Animal whereas just a plain 'Animal' object will never exist (Abstract is the common-ground of sub-classes)
Interface = A particular type of abstract class that contains ONLY empty PUBLIC members that must be implemented (ie: Over-ridden)
Interface abstract classes do not contain any information or functionality; just a public interface

C++ does not have a keyword 'interface'; Typically, a class with ONLY pure virtual(ie: =0) functions is considered an 'Interface'
Java does have keyword 'interface'; In Java, classes can inherit multiple interfaces but only one other class
Data Hiding
Public
Access allowed anywhere
Protected
Access allowed within the inheritance tree; keyword FRIEND is used in VB
Friend
In C++ a Friend Function can be defined as part of a class definition which allows that function access to private/protected class
variables.
Private
Access allowed within the class
3. Inheritance

= Method used to expand class functionality with finer details Models a hierarchical classification

e.g. food (base class) fruit (inherits 'food' class) apple (inherits 'fruit' class)
Classes that inherit a parent/base class are called derived classes
Other Terminology identifying inheritance
base derived class
parent child class
super sub class
Overloading = Same named functions with more than one implementation/functionality
Function Overloading = Two same-named functions with different arguments ( The caller argument count/type will determine which function
implementation is used)
Operator Overloading = Overloading operators like <,>,=,+, and etc.. (e.g. iostream overloads '<<' and '>>' operators for 'cin' and 'cout')
Overriding = One function implementation over-rides the previous version (Both having identical call names and arguments)
When an interface or abstract class is inherited and function bodies are defined in the derived class they actually override the empty body.
4. Polymorphism = Using the base class interface to access derived class objects
Using class inheritance a pointer to a derived class is compatible with a pointer to its base class
Polymorphism is the ability to access an object via it's base class inherited interface as its base class type
Base Class Animal; Func Walk
Derived class Dog
Derived class Cat
Animal DogPointer = &Dog
Animal CatPointer = &Cat
DogPointer->Walk()
We can call a base call using a pointer of base type even though Dog is of the derived dog class.

7.1.5 Toolkits / Libraries


A. Microsoft .NET
Visual Studio
VS2012 and VS2013 do not have C++ GUI developers (by default but can still be brought up)
VS2010 C++ doesn't have intellisense
Windows Form Types
Win32 = DLL or Win32 Applications (Using bare WinAPI)
ATL
=
MFC
= Microsoft Foundation Classes
Higher-level wrappers for Windows API for form design (unmanaged C++, native C++)
CLR/CLI
= Common Language Runtime/Interface Brings .NET framework (multi-language) to C++
ATL

= Active Template Library

(C++ classes to simplify programming COM objects)

Runtime Library = Core functions and engine needed by a programming language compiler
Visual Basic Runtime = VBRUN60.DLL
Required for any compiled Visual Basic v6.0 compiled program to execute.
Microsoft .NET Framework [2003]
residing at the system software layer

Microsoft combined languages J#, C# and VB to execute on a Common Language JIT-Compiler

.NET Programming Language = Is any language that meets the Microsoft Common Language Specification Standard (e.g. C#, J#, VB-2003+, JavaScript)
.NET Framework

Must be installed on the target processor system in order to execute a .NET application

.NET Source Code initial compiler Microsoft Intermediate Language (MSIL)


MSIL Common Language Runtime (CLR) Machine Language
CLR Runtime contains:
MSIL Execution Engine w/JIT-Compiler

Class Loader
Platform Extension Libraries
Garbage Collector (GC)

Platform libraries are withing the Base Class Library (BCL)

B. C++
Core language (variables, data types, literals)
C++ Standard Library (files, strings)'stdlib' Functions for manipulating files and strings
StdLib is != the STL library; but it is a common mistake to refer to the StdLib as STL; StdLib derived parts of the original STL library
Standard Template Library (STL) (std::)
methods for manipulating data structures (2.9+ may contain Boost libraries)
Boost
Typically considered the 'StdLib' sandbox; a library of pre-standard libraries
Cocoa (Mac)
GUI Designers (Cross-Platform User Interface Toolkits)
Linux (MinGW)
Qt(KDE default DUI engine) / GTK(GIMP engine) / wxWidgets (MFC copy-cat in Dev-C++) / SDL
Windows
Blend / MFC / CLR

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------GUI/Widget Toolkits


http://en.wikipedia.org/wiki/List_of_widget_toolkits (Often contain their own rendering engine)
Wiki C++ Standard Library http://en.wikipedia.org/wiki/C%2B%2B_Standard_Library
Wiki Standard Template Library (STL) http://en.wikipedia.org/wiki/Standard_Template_Library
Graphics Rendering Engines OpenGL, OpenVG, EGL, SDL

7.1.6 Language Comparisons


Java JVM

Keywords

7.1.7 Data Models (Serialization)


XML
Frankly, if you aren't having to describe/discover the data's type, XML is overkill.
JSON
YAML - All JSON is a valid YAML
See http://en.wikipedia.org/wiki/Serialization
The process of serializing (encoding) an object is also called "marshalling" an object.
de-coding is "unmarshalling"

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://en.wikipedia.org/wiki/Serialization

7.2 OS Shells
7.2.1 MS-DOS
A. >path
Display Environment PATH
Add to the Environment PATH

>PATH
>PATH=<NewPath>;%PATH%

Edit PATH through windows


Computer Right Click Properties Advanced System Settings Advanced Tab Environment Variables
Windows 8 DOS commands are located at:

C:

7.3 Device Driver Development


Types
Architecture-specific
Generic

- Manages master processor integrated hardware/components (e.g. MMU Drivers, Floating Point Drivers)
- Manages board devices

Hardware Driver Functions


Interface to OS - Each function has code to interact directly with hardware
Start-up
- Initialize hardware upon power-on/reset
Shutdown
- Configures hardware into its power-off state
Disable
- Allows other software to disable hardware on-the-fly
Enable
- Allows other software to enable hardware on-the-fly
Acquire
- Allows other software to gain LOCK access to the hardware
Release
- Allows other software to FREE/UNLOCK the hardware
Read
- Allows other software to READ data from the hardware
Write
- Allows other software to WRITE data to the hardware
Install
- Allows other software to install new hardware on-the-fly
Uninstall
- Allows other software to remove installed hardware on-the-fly

Generic Hardware States


Inactive
Busy
Finished

(IDLE)

- Disconnected; needs installed w/Power OR Disabled; needs enabled


- Actively being used
- Allows acquisition READ/WRITE requests

Communications
Application OS
OS Drivers
Drivers HAL
HAL Device

Applications calls OS-API functions that send/receive hardware I/O requests


OS generates I/O Request Packet (IRP) objects and notifies the driver by calling driver Call-back functions
Drivers (like OS-Plug-ins) work with OS-Architecture to communicate with the Hardware Abstraction Layer (HAL)
HAL (Abstracting OS from hardware) takes standard calls and converts them to electrical signals

Communication Terms
IRP
WMI
DMA
IRQ
ISR
DPC

+ I/O Request Packet


= OS Kernel data structure used to transfer data packets at the driver level
+ Windows Management Instrumentation= Microsoft's IT Distributed Management infrastructure
+ Direct Memory Access
= Address space to hardware (Typically for high data devices like disks, networks or displays)
+ Interrupt ReQuest
= Hardware initiated communication requiring reception by software/driver
+ Interrupt service routine
= Function to handle a device interrupts (Each event = 1 interrupt)
+ Deferred Procedure Call
= Handles software interrupts and/or time-consuming interrupts

IRQL
- Interrupt ReQuest Level
= Interrupts contain priority levels DIRQL, DISPATCH, PASSIVE
DIRQL
- Most critical
= ISR(s) use interrupt spin lock (non-paged memory)
DISPATCH
- Highest software
= Spin lock process synchronization (non-paged memory)
PASSIVE - Application level
= Fast mutex / resource objects (built from dispatcher object-events)
Port-IO

= OS Initiated communication (MS-Windows uses 'IN' and 'OUT' Port access instead of Address Mapped I/O)

Debugging
Symbols
HLK

= Allows module debugging; Viewing the specific construct throwing an error on compiled code (PDB file)
+ Hardware Lab Kit
= Microsofts all-purpose device/driver tests for windows. (Device Driver Qualification)

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki IRQ


http://en.wikipedia.org/wiki/Interrupt_request
Wiki Debug Symbols
https://en.wikipedia.org/wiki/Debug_symbol

7.3.1 Driver Development Kits (DDK)


Windows Driver Kits (WDK)
TSR
VDD
WDM
WDF

Microsoft's different driver kits through time

+ Terminate and Stay Resident


+ Virtual Device Drivers
+ Windows Driver Model
+ Windows Driver Foundation

[MS-DOS]
[Windows 3.x, 95, 98, Me drivers]
[Windows NT/XP/2000 till 2005]
Windows Vista, 7, 8 (2005+)

Real-Mode drivers (written in Assembly)


Managed resource drivers (written in Assembly)
Full managed drivers (calls OS-system service routines )
Helpful Abstraction layer framework to the WDM

File Extensions
SYS
DLL
INF

= Driver based on the Kernel-Mode device Driver Framework (KMDF)


= Driver based on the User-Mode device Driver Framework (UMDF)
= Driver Installer file
Used by Add/Remove hardware; records in the windows registry which files are function/filter drivers

WDF Terms
DDI- Device Driver Interface
SDV - Static Driver Verifier
PREfast
Checked Build OS
Free Build OS
WDF Versioning
Permanent Object
Transient Object

= Abstract OS-kernel supplied driver interfaces that drivers need to implement (ie: Driver Model)
= Debugging / Verifying tool packaged in the WDK

= Debugging / Verifying tool packaged in the WDK


= MS-Windows OS distribution that contains debug-related code/symbols specifically for driver debugging
= Normal/Released MS-Windows OS distribution
= Drivers are compiled with WDF framework version # so OS can choose correct framework for a driver
= Programming object that remains present through the life of a plugged-in device
= Programming object created and destroyed per-event

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------MSDN


WDF Reference
@ http://msdn.microsoft.com/en-us/library/windows/hardware/dn265590%28v=vs.85%29.aspx
WDF Reference as a CHM File @ http://download.microsoft.com/download/3/3/C/33CFEF4D-21DA-4229-BC17-3EAC7A7EABE1/WDKDocs_12112009.chm
Windows Driver Development Kit Solutions (DDK) @ http://support2.microsoft.com/ph/7229
Windows WDK
@ http://msdn.microsoft.com/en-us/windows/hardware/default.aspx
Windows API
@ http://msdn.microsoft.com/en-US/windows/desktop/aa904962.aspx
Bus and Port Drivers
@ http://msdn.microsoft.com/en-us/library/windows/hardware/ff557547%28v=vs.85%29.aspx
Windows Checked Builds
@ http://msdn.microsoft.com/en-us/library/windows/hardware/ff543457%28v=vs.85%29.aspx
Wiki
TSR
http://en.wikipedia.org/wiki/Terminate_and_stay_resident_program
Device Drivers
http://en.wikipedia.org/wiki/Device_driver
WDF
http://en.wikipedia.org/wiki/Windows_Driver_Foundation
OSR Online
What exactly is a Driver
@ http://www.osronline.com/article.cfm?article=233

7.3.2 Kernel-Mode Driver Framework (KMDF)


Overview
Written in 'C' using libraries 'ntoskrnl.exe' and 'hal.dll' for native API and executive services that support DMA and handle IRQ(s)
Interacts through handles (ie: Pointers to framework objects) and registered-callback functions (e.g. framework calls a custom driver function when
an event occurs)
IOCTRL(s)
= I/O Requests(IRP) that are for controlling the device instead of data transfer

KMDF Object Attributes


ContextSizeOverride
ContextTypeInfo
- Pointer to type information for the object context area
EvtCleanupCallback - Pointer to Callback routine invoked to cleanup the object before its deleted (before all references destroyed)
EvtDestroyCallback - Pointer to callback routine invoked when reference count is zero during an object destroy (later than cleanup)
ExecutionLevel
- Sets the IRQL for KMDF callbacks
ParentObject
- Handle to the parent object
Size
- Objects size
SynchronizationScope
- How callbacks are synchronized (applies to driver, device and file-object)
KMDF Objects (defined in \inc\wdf\Wdfstatus.h or Ntstatus.h)
Child-List
Collection
Device
DMA
Buffer
Enabler
Transactions

WdfChildList
WdfCollection
WdfDevice

WdfCommonBuffer
WdfDMAEnabler
WdfDMATransaction

- List of child devices for a bus-driver


- Similar objects container
- Driver contains one device object for each device it controls

- Buffer that connects device and driver


- Enables a DMA channel with a device
- One DMA Transaction (like an IRP for DMA)

DPC
Driver

WdfDPC
WdfDriver

- Deferred Procedure Call


- Top-level Driver Object

File
Application ]

WdfFileObject

- File object for application and external driver access to the driver [ Device DMA Driver File

The native File Object represents a single, specific, open instance of a device (or a file on a device)
File object for application and external driver access to the driver [ Device DMA Driver File Application ]
Unique open instance of a WDF Device Object
Note that we are provided a WDF Device Object handle, which represents the WDF File Objects target device. We are also provided a WDF
Request Object handle, which is the WDF abstraction of the native I/O operation representing the creation of the File Object.
WDF Device Object handle, which represents the WDF File Objects target device
As an aside that we will revisit later, this WDF Request Object is unique in KMDF in that it is not queue presented, meaning that it has no parent
WDF Queue Object.
Register via FileObject for Create, Close, and Cleanup Callbacks of IRP(s)
General
I/O
Queue
Request (IRP)
Target

WdfObject

WdfQueue
WdfRequest
WdfIoTarget

Driver Context object or object for any driver usage requirements

- Any I/O Queue


- Stack to which the driver is forwarding IRP(s)

Interrupt
Look-Aside List
Memory
Registry-Keys

WdfInterrupt
WdfLookAside
WdfMemory
WdfKey

Resources
List
Range-List
Requirements
String

WdfCmResList
WdfIoResList
WdfIoResReqList
WdfString

Synchronization
SpinLock
WaitLock
Timer

WdfSpinLock
WdfWaitLock
WdfTimer

USB
Device
Interface
Pipe
WMI
Work-Items

WdfUsbDevice
WdfUsbInterface
WdfUsbPipe
WdfWMIInstance
WdfWorkItem

- One device Interrupt Request(IRQ) -or- message-signaled interrupt(MSI)


- Dynamically sized list of identical buffers allocated from paged -or- nonpaged pool
- I/O memory buffer for the driver to store an IRP
- Represents one windows registry key

- Devices list of resources


- Configuration for a device
- Set of I/O resources list and their configurations (Each element is a WdfIoResList)
- Unicode string

- Spin lock synchronization for DISPATCH_LEVEL data


- Wait lock synchronization for PASSIVE_LEVEL data
- Object for timed callback routine execution

- One USB device


- Interface for a USB device
- Pipe for a USB device
- Windows Management Instrumentation
- PASSIVE_LEVEL system thread item

KMDF Standard Syntax


WdfObjectOperation
WdfObject{Set/Get}Data
WdfObject{Assign/Retrieve}Data

KMDF Method naming notation


KMDF No-Status Property naming notation
KMDF Status Property naming notation (ie: Return is NTSTATUS)

Getting Started
All Drivers contain
(1) DriverEntry()
Gets called when driver gets loaded and creates the Top-Level (ie: Root) Driver Object
(1+)EvtDriverDeviceAdd() Gets called when device gets connected and creates Device Object(s) (1-FDO and 1+PDO for PnP Devices)
Creates Device Objects
Filter DO
= Filter Device Object
- Filters / Modifies IRP(s) for a device
FDO
= Functional Device Object
- Primary device driver for a PnP device tree
PDO
= Physical Device Object
- A Bus drivers child device enumerator for the PnP device tree
Control DO = Control Device Object
- Non-PnP device or control interface ( Operation independent of PnP Device stack
Queue )
Sets Device Attributes
Registers Required Callback Functions ( Not related to kernel-dispatcher events )
EvtDeviceEject
EvtIo*
Callback functions that handle specific types of IRP(s) from a particular IRP-Queue
PnP Manager Codes
IRP_MN_EJECT
Only drivers for physical devices with an eject require handling the request

/
***********************************************************************************************************************************************
*****
* Kernel Mode Device Driver based on:
*
Kernel Mode Driver Framework (KMDF) - A sub-division of the Windows Driver Foundation's (WDF) Windows Driver Kit (WDK) written in C
*
_In_ & _Out_ are Function parameter annotations; see http://msdn.microsoft.com/en-us/library/hh916382.aspx
*
*
DRIVER_OBJECT see http://msdn.microsoft.com/en-us/library/windows/hardware/ff544174%28v=vs.85%29.aspx
*
*
This version shows how to register for PNP and Power events, handle create & close file requests, handle WMI set and query events, fire WMI
*
notification events.
*
***********************************************************************************************************************************************
*****/
#include <ntddk.h>
// #include the Windows-NT Device Driver Kit (DDK)
#include <wdf.h>
// #include the Windows Driver Foundation (WDF) Framework

A. DriverEntry()
Driver Object Reference
Call-Back

@ http://msdn.microsoft.com/en-us/library/windows/hardware/dn265636%28v=vs.85%29.aspx
Methods

Structures/Enums

Initialization Functions

EvtDriverDeviceAdd
EvtDriverUnload

WdfDriverCreate
WdfDriverGetRegistryPath
WdfDriverIsVersionAvailable
WdfDriverMiniportUnload
WdfDriverOpenParametersRegistryKey

WDF_DRIVER_CONFIG
WDF_DRIVER_INIT_FLAGS
WDF_DRIVER_VERSION_AVAILABLE_PARAMS

WDF_DRIVER_CONFIG_INIT
WDF_DRIVER_VERSION_ABAILABLE_PARAMS_IN

/**********************************************************************************************************************
* DriverEntry()
*
IN:
DriverObject
*
IN:
RegistryPath
*
DESC:
*
- First routine called by the OS-PnP Manager when driver gets loaded.
*
- Creates the Driver Object and Registers 'EvtDriverDeviceAdd' and 'EvtDriverUnload' functions.
*
- Export standard set of entry points using the OS data-structure DRIVER_OBJECT
*
- OS looks at the data-structure of function pointers to call when a request is targeted to a device described by DEVICE_OBJECT
*
Function dispatch table = contains a function pointer for each major function code the OS system supports
*
28-functions can be supported but usually only 8 are: IRP_MJ_CREATE, CLOSE, READ, WRITE, PNP, POWER, DEVICE_CONTROL, and SYSTEM_CONTROL
*
by default all these functions point to a routine which indicates that major function is NOT supported.
* Parameters:
*
DriverObject = represents the instance of the function driver that is loaded
*
into memory. DriverEntry must initialize members of DriverObject before it
*
returns to the caller. DriverObject is allocated by the system before the
*
driver is loaded, and it is released by the system after the system unloads
*
the function driver from memory.
*
*
RegistryPath = represents the driver specific path in the Registry.
*
The function driver can use the path to store driver related data between
*
reboots. The path does not store hardware instance specific data.
* Duties:
*
1) Create
a PDDRIVER_OBJECT Instance by calling WdfDriverCreate()
*
2) Configure the DriverObject Instance using WDF_DRIVER_CONFIG_INIT(WDF_DRIVER_CONFIG)
/*********************************************************************************************************************/
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) {
NTSTATUS
WDF_DRIVER_CONFIG

status = STATUS_SUCCESS;
config;

KdPrint(("WDF DriverEntry() Function Driver Sample - Featured version\n"));


KdPrint(("Built %s %s\n", __DATE__, __TIME__));
// Initialize driver config settings structure and register AddDevice()
WDF_DRIVER_CONFIG_INIT( &config, MyEvtDeviceAdd );
// Create the Driver Object
status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);

if (!NT_SUCCESS(status)) { KdPrint( ("WdfDriverCreate failed with status 0x%x\n", status));}


return status;

B. EvtDeviceAdd()
Device Object Reference

@ http://msdn.microsoft.com/en-us/library/windows/hardware/dn265631%28v=vs.85%29.aspx

Device
Prefix

Call (Verb)

Item (Noun)

Structure

Create

WdfDevice

CreateDevice

Interface

Create Interface

WdfDevice

RetrieveDevice

InterfaceString

Retrieves symbolic link name

WdfDevice

SetDevice

InterfaceState

EvtDevice

Process

QueryInterfaceRequest

WdfDevice

Add

QueryInterface

WdfDevice

WDFDEVICE_INIT

Structure Initializer

WdfDevice

Device Initializer

Enables/Disables Interface
WDF_QUERY_INTERFACE_CONFIG

WDF_QUERY_INTERFACE_CONFIG_INIT

Interface{Der/R}eferenceNoOp

WdfDevice
WdfDevice

SetDevice

State

WdfDevice

Create

SymbolicLink

WdfDevice

WDF_DEVICE_STATE

MiniportCreate

Creates device for miniport driver

WdfDevice

InitAssign
/RetrieveDevice

Name

WDFDEVICE_INIT

WdfDevice

InitAssign

SDDLString

WDFDEVICE_INIT

WdfDevice

Init

Free

WdfDevice

DeviceGet/InitSet/Set

Characteristics

WdfDevice

InitSetDevice

Class

WdfDevice

InitSetDevice

Type

WdfDevice

InitSet

Exclusive

WdfDevice

Assign

MofResourceName

WdfDevice

Set

Failed

WdfDevice

WdmGet

DeviceObject

WdfDevice

WdmGet

PhysicalDevice

Security Setting
De-allocate WDFDEVICE_INIT

WDF_DEVICE_FAILED_ACTION

Notify framework of Failure


WDM-model device object

WdfWdmDevice GetWdf

DeviceHandle

Device Object for WDM device

WdfDevice

OpenRegistryKey

Access Windows Registry

/WdfFdoInit
WdfFdo

InitSet

DefaultChildListConfig

WdfFdo

InitSet

EventCallbacks

EvtDevice

Filter{Add/Remove}

ResourceRequirements

FDO

EvtDevice

RemoveAdded

Resources

FDO

WdfFdo

InitSet

Filter

WdfFdo

InitWdmGet

PhysicalDevice

WdfFdo

Add

StaticChild

WdfFdo

Get

DefaultChildList

WdfFdo

{Lock/Unlock}

StaticChildListForIteration

WdfFdo

QueryFor

Interface

WdfFdo

Retrieve

NextStaticChild

WdfPdo

Init

AddCompatibleID

WdfPdo

InitAdd

DeviceText

WdfPdo

InitAdd

HardwareID

WdfPdo

Init

Allocate

WdfPdo

InitAllow

ForwardingRequestToParent

WdfPdo

InitAssign

ContainerID

WdfPdo

InitAssign

DeviceID

WdfPdo

InitAssign

InstanceID

WdfPdo

InitAssign

RawDevice

WdfPdo

InitSet

DefaultLocale

WdfPdo

InitSet

EventCallbacks

EvtChildList

WDF_FDO_EVENT_CALLBACKS

WDF_FDO_EVENT_CALLBACKS_INIT

WDF_CHILD_LIST_CONFIG

WDF_PDO_EVENT_CALLBACKS

WDF_PDO_EVENT_CALLBACKS_INIT

CreateDevice

WdfChildList

Get

Device

WdfChildList

Retrieve

AddressDescription

WdfChildList

Retrieve

Pdo

EvtChildList

AddressDescription

Cleanup

EvtChildList

AddressDescription

Copy

EvtChildList

AddressDescription

Duplicate

EvtChildList

IdentificationDescription

Cleanup

EvtChildList

IdentificationDescription

Compare

EvtChildList

IdentificationDescription

Copy

EvtChildList

IdentificationDescription

Duplicate

WDF_CHILD_ADDRESS_DESCRIPTION_HEADER WDF_CHILD_ADDRESS_DESCRIPTION_HEADER_INI
T

EvtChildList

EvtChildList

WDF_CHILD_IDENTIFICATION_DESCRIPTION_
HEADER

DeviceReenumerated

EvtChildList

ScanForChildren

WdfChildList

AddOrUpdate/UpdateAll ChildDescriptionAsPresent

WdfChildList

Update

ChildDescriptionAsMissing

WdfChildList

{Begin/End}

Iteration

WdfChildList

{Begin/End}

Scan

WdfChildList

Create

WdfChildList

Request

ChildEject

WdfPdo

Add/Remove

EjectionRelationsPhysicalDevice

WdfPdo

Clear

EjectionRelationsDevices

WdfChildList

Retrieve

NextDevice

WdfChildList

Device Dependencies
PreFix

Call

Item

Structure

Structure Initializer

WdfDevice

Add/Remove

DependentUsageDeviceObject

Dependent driver

WdfDevice

Add/Remove

RemovalRelationsPhysicalDevice

Dependent driver/remove

WdfDevice

Clear

RemovalRelationsDevices

Remove all-drivers/dependence

WdfDevice

WdmGet

AttachedDevice

Gets next-lower device

WdfPdo

Get

Parent

WdfPdo

MarkMissing

WdfPdo

Request

Eject

WdfPdo

Retrieve/Update

AddressDescription

WdfPdo

Retrieve

IdentificationDescription

File
PreFix

Call

Item

WdfDevice

InitSet

FileObjectConfig

WdfDevice

Get

FileObject

Evt

File

Cleanup

Structure

Structure Initializer

WDF_FILEOBJECT_CONFIG

WDF_FILEOBJECT_CONFIG_INIT

EvtDeviceFileCreate HANDLE

Close access to device

WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEAD
ER_INIT

Evt

File

Close

EvtDeviceFileCreate HANDLE

Close access to device

WdfDevice

Set

SpecialFileSupport

WDF_SPECIAL_FILE_TYPE

Enable/Disable support for special files

Access / File (Application I/O)


PreFix

Call

Item

Structure

Structure Initializer

WdfDevice

InitSet

IoInCallerContextCallback

Register EvtIoInCallerContext function

WdfDevice

InitSet

IoType

Register function for IO buffers for special device

WdfDevice
/WdfFdoInit

AllocAndQueryProperty

WdfDevice
/WdfFdoInit

QueryProperty

WdfDevice

{Set/Get}

AlignmentRequirement

WdfDevice

Get

Driver

WdfDevice

Get

IoTarget

WdfDevice

Set

BusInformationForChildren

EvtDevice

Prepare

Hardware

EvtDevice

SelfManaged

IoCleanup

EvtDevice

SelfManaged

IoFlush

EvtDevice

SelfManaged

IoInit

EvtDevice

SelfManaged

IoRestart

EvtDevice

SelfManaged

IoSuspend

Access device properties


Devices address for memory transfer
Pointer to Function that handles I/O
PNP_BUS_INFORMATION

EvtDevice

UsageNotification

WDF_SPECIAL_FILE_TYPE

EvtDeviceWdm

IrpPreprocess

IRP Structure

EvtDeviceWdm

DispatchPreprocessedIrp

Evt

IoInCallerContext

Information about a bus

Receives IRP before framework


Returns Preprocessed IRP to the framework

Device Object, IRP Object

I/O Request before I/O queue

DEVICE_OBJECT
Called when a new device is plugged-in
Registers the Functions that the Driver will Support

http://msdn.microsoft.com/en-us/library/windows/hardware/dn265631%28v=vs.85%29.aspx

Bus Driver
= KMDF drivers indicate a Bus Driver by calling PDO initialization methods before creating it s Device Object in EvtAddDevice().
Static Model
For PDO devices that are statically attached (ie: USB Host controller on the Motherboard)
Dynamic
For PDO devices that are hot-swappable (Plug n Play)
/**************************************************************************************************
* EvtDeviceAdd()
*
IN:
Driver
= Handle to a framework driver object created in DriverEntry
*
IN:
DeviceInit
= Pointer to a framework-allocated WDFDEVICE_INIT structure.
*
DESC:
Is called by the framework in response to AddDevice call from the PnP manager.
/*************************************************************************************************/
NTSTATUS MyEvtDeviceAdd(IN WDFDRIVER Driver, IN PWDFDEVICE_INIT DeviceInit) {
// Initialize settings structures
NTSTATUS
status = STATUS_SUCCESS;
WDF_PNPPOWER_EVENT_CALLBACKS
pnpPowerCallbacks;
WDF_OBJECT_ATTRIBUTES
fdoAttributes;
WDFDEVICE
device;
WDF_FILEOBJECT_CONFIG
fileConfig;
WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings;
WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS wakeSettings;
WDF_POWER_POLICY_EVENT_CALLBACKS
powerPolicyCallbacks;
WDF_IO_QUEUE_CONFIG
queueConfig;
//PFDO_DATA
fdoData;
WDFQUEUE
queue;
WDF_DEVICE_FAILED_ACTION
*one;
UNREFERENCED_PARAMETER(Driver);
PAGED_CODE();
KdPrint(("EventDeviceAdd called\n"));
one = new WDF_DEVICE_FAILED_ACTION;
one->WdfDeviceFailedUndefined = 1;
one.WdfDeviceFailedAttemptRestart;
WdfDeviceSetFailed(&device, one);

B.1 Plug and Play (PnP)

WDF Framework handles PnP and Power Management via a State Machine (Applies to both KMDF and UMDF)
Driver can implement particular states callback functions that it needs to handle specifically while leaving others for the WDF default implementations
The WDF Default implementation can handle other parts of the framework so proper behavior occurs when a state transition occurs
Example: The I/O queue can stop dispatching requests when device is in a low-power state

PnP Operations
PreFix

Call

Item

Structure

Structure Initializer

WdfDevice

Set

PnpCapabilities

WDF_DEVICE_PNP_CAPABILITIES

WDF_DEVICE_PNP_CAPABILITIES_INIT

WdfDevice

InitSet

PnpPowerEventCallbacks

WDF_PNPPOWER_EVENT_CALLBACKS

WDF_PNPPOWER_EVENT_CALLBACKS_INIT

WdfDevice

GetDevice

PnpState

WDF_DEVICE_PNP_STATE

EvtDevice

PnpStateChange

WDF_DEVICE_PNP_NOTIFICATION_DATA

EvtDevice

ReleaseHardware

When drive is no longer accessible

EvtDevice

SurpriseRemoval

When device is hot-removed/failed

EvtDevice

SelfManaged

IoCleanup

EvtDevice

SelfManaged

IoInit

WDF_DEVICE_PNP_CAPABILITIES_INIT

//-- [ PnP Power ] --//


// WdfDeviceInitSetPnpPowerEventCallbacks() @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546135%28v=vs.85%29.aspx
// IN:
&WDFDEVICE_INIT
// IN:
Initialized Structure -- WDF_PNPPOWER_EVENT_CALLBACKS_INIT( WDF_PNPPOWER_EVENT_CALLBACKS )
// DESC:
Initialize the pnpPowerCallbacks for PNP and Power events
//
-Or- use framework defaults which depend on DeviceInit being FDO, PDO or Filter DO.
WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks);
pnpPowerCallbacks.EvtDevicePrepareHardware
= EventDevicePrepareHardware;
// PnP
pnpPowerCallbacks.EvtDeviceReleaseHardware
= EventDeviceReleaseHardware;
// PnP
pnpPowerCallbacks.EvtDeviceSelfManagedIoInit
= EventDeviceSelfManagedIoInit;
// PnP
pnpPowerCallbacks.EvtDeviceD0Entry
= EventDeviceD0Entry;
// Power - Default/Empty?
pnpPowerCallbacks.EvtDeviceD0Exit
= EventDeviceD0Exit;
// Power
WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpPowerCallbacks);

B.2 Power Management

Power States
Sx = System Power States (Where 'x' is 0 to 5)
S0 = Working State
Dx= Device Power States (Where 'x' is 0 to 3) higher uses less power and longest wake-up latency
D0 = Working State

Power
PreFix

Call

Item

Structure

Structure Initializer

WdfDevice Set

PowerCapabilities

WDF_DEVICE_POWER_CAPABILITIES

WDF_DEVICE_POWER_CAPABILITIES_INIT

WdfDevice InitSet

PowerPolicyEventCallbacks

WDF_POWER_POLICY_EVENT_CALLBACKS

WDF_POWER_POLICY_EVENT_CALLBACKS_INIT

WdfDevice InitRegister

PowerPolicyStateChangeCallback

WdfDevice InitSet

PowerPolicyOwnership

EvtDevice

PowerPolicyStateChange

WdfDevice GetDevice

PowerPolicyState

WdfDevice GetDevice

PowerState

WDF_DEVICE_POWER_POLICY_NOTIFICATION_DATA
WDF_DEVICE_POWER_STATE (Returns)

WdfDevice InitRegister

PowerStateChangeCallback

EvtDevice

PowerStateChange

WdfDevice InitSet

PowerInrush

WdfDevice InitSetPower{Not}

Pageable

WdfDevice {Set/Get}Device

State

WdfDevice Get

SystemPowerAction

WdfDevice Assign

S0IdleSettings

WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS

WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT

WdfDevice Assign

SxWakeSettings

WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS

WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT

WdfDevice Indicate

WakeStatus

WDF_DEVICE_POWER_NOTIFICATION_DATA
Device requires inrush current @ start-up
Driver accepts pageable data during sleep or not
WDF_DEVICE_STATE (Returns)

WDF_DEVICE_STATE_INIT
Current system power action if any

Device has awoke

WdfDevice {Stop/Resume}Idle

Not in use; ok for idle state

WdfDevice Set

StaticStopRemove

EvtDevice

{Arm/Disarm}

WakeFromS0

WDF_DEVICE_PNP_CAPABILITIES

WDF_DEVICE_PNP_CAPABILITIES_INIT

EvtDevice

{Arm/Disarm}

WakeFromSx

WDF_PNPPOWER_EVENT_CALLBACKS

WDF_PNPPOWER_EVENT_CALLBACKS_INIT

EvtDevice

Arm

WakeFromSxWithReason

EvtDevice

Whether device can be removed

WakeFromS0Triggered

EvtDevice

WakeFromSxTriggered

EvtDevice

D0{Entry/Exit}

EvtDevice

D0Entry

PostInterruptsEnabled

WDF_POWER_DEVICE_STATE

EvtDevice

D0Exit

PreInterruptsDisabled

WDF_POWER_DEVICE_STATE

WdfDev

StateIsNP

WdfDev

StateNormalize

State machine states as index

WakeAtBus

PDO

EvtDevice

Eject

PDO

EvtDevice

ResourceRequirementsQuery

EvtDevice

Disable/Enable

EvtDevice
EvtDevice

WDF_DEVICE_POWER_STATE

Is Non-Pageable

ResourcesQuery
Set

EvtDevice

Lock
ShutdownNotification

Wdf

ControlDeviceInit

Wdf

ControlDeviceInitSet ShutdownNotification

Wdf

Control

FinishInitializing

Po

Register/Unregisted

PowerSettingCallback

WDF_DEVICE_SHUTDOWN_FLAGS

Allocate

//-- [ Power Policy ] --//


// WdfDeviceInitSetPowerPolicyEventCallbacks() @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546774%28v=vs.85%29.aspx
// IN:
&WDFDEVICE_INIT
// IN:
Initialized Structure -- WDF_POWER_POLICY_EVENT_CALLBACKS_INIT( WDF_POWER_POLICY_EVENT_CALLBACKS )
// DESC:
Register Power-Policy callbacks to handle arm/disarm ing the hardware ( wait-wake when wake event is triggered by device)
//
WdfDeviceInit | SetPowerPolicy | EventCallbacks() @
WDF_POWER_POLICY_EVENT_CALLBACKS_INIT(&powerPolicyCallbacks);
powerPolicyCallbacks.EvtDeviceArmWakeFromS0 = EventDeviceArmWakeFromS0;
powerPolicyCallbacks.EvtDeviceDisarmWakeFromS0 = EventDeviceDisarmWakeFromS0;
powerPolicyCallbacks.EvtDeviceWakeFromS0Triggered = EventDeviceWakeFromS0Triggered;
powerPolicyCallbacks.EvtDeviceArmWakeFromSx = EventDeviceArmWakeFromSx;
powerPolicyCallbacks.EvtDeviceDisarmWakeFromSx = EventDeviceDisarmWakeFromSx;
powerPolicyCallbacks.EvtDeviceWakeFromSxTriggered = EventDeviceWakeFromSxTriggered;
WdfDeviceInitSetPowerPolicyEventCallbacks(DeviceInit, &powerPolicyCallbacks);
//
// Register the power policy callbacks.
//
WdfDeviceInitSetPowerPolicyEventCallbacks(DeviceInit, &powerPolicyCallbacks);
//-- [ Dx Power ] Callbacks --//
// Set the idle power policy to put the device to Dx if the device is not used for the specified IdleTimeout time.
// Since this is a virtual device we tell the framework that we cannot wake ourself if we sleep in S0.
// Only way the device can be brought to D0 is if the device recieves an I/O from the system.
WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&idleSettings, IdleCannotWakeFromS0);
idleSettings.IdleTimeout = 60000; // 60 secs idle timeout
status = WdfDeviceAssignS0IdleSettings(device, &idleSettings);
if (!NT_SUCCESS(status)) {
KdPrint( ("WdfDeviceAssignS0IdleSettings failed 0x%x\n", status));
return status;}
//-- [ Wait-wake policy ] --//
WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT(&wakeSettings);
status = WdfDeviceAssignSxWakeSettings(device, &wakeSettings);
if (!NT_SUCCESS(status)) {
// We are probably enumerated on a bus that doesn't support Sx-wake.
// Let us not fail the device add just because we aren't able to support
// wait-wake. I will let the user of this sample decide how important it's

// to support wait-wake for their hardware and return appropriate status.


KdPrint( ("WdfDeviceAssignSxWakeSettings failed 0x%x\n", status));
status = STATUS_SUCCESS;}

B.3

File / Context

//-- [ File Object ] --//


// For Immediate IRP(s) -> Non-Queue
// WdfDeviceInitSetFileObjectConfig() @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546107%28v=vs.85%29.aspx
// IN:
Struct to tell the
// DESC:
Handle Create, Close and Cleanup requests for other IRP(s).
WDF_FILEOBJECT_CONFIG_INIT(&fileConfig, EventDeviceFileCreate, EventFileClose, WDF_NO_EVENT_CALLBACK);
WdfDeviceInitSetFileObjectConfig(DeviceInit, &fileConfig, WDF_NO_OBJECT_ATTRIBUTES);
//-- [ Register context cleanup ] --//
// This cleanup will be called in the context of pnp remove-device when the framework deletes the device object.
fdoAttributes.EvtCleanupCallback = EventDeviceContextCleanup;

B.4 Device
//-- [ Create Device ] --//
// DeviceInit is completely initialized so create the device and attach it to the lower stack
status = WdfDeviceCreate(&DeviceInit, &fdoAttributes, &device);
if (!NT_SUCCESS(status)) {
KdPrint( ("WdfDeviceCreate failed with Status code 0x%x\n", status));
return status;}

B.5 Interface
//-- [ Create Interface ] --//
// Tell the Framework that this device will need an interface so that applications can find our device and talk to it.
status = WdfDeviceCreateDeviceInterface(device, (LPGUID) &GUID_DEVINTERFACE_TOASTER, NULL);
if (!NT_SUCCESS (status)) {
KdPrint( ("WdfDeviceCreateDeviceInterface failed 0x%x\n", status));
return status;}

B.6 I/O Handling


1. KMDF packages device I/O into IRP(s) (ie:.. WdfRequest Object) @ the I/O-Request Handler and Queues or Directly transfers I/O.
2. Determines if the driver has a configured a I/O- Queue for the request and queues the request
3. Checks the PnP power state for D0 operational state and turns-on device if necessary
4. ELSE the request fails
WDF Framework manages the flow of I/O requests by creating a queue object and configuration it
Dispatching Type
Queues are configured by the type of dispatching
IRP Type
Queues are configured by the type of I/O request
WDF Framework adds requests to the queue and dispatches according to drivers specification
Specification Types of IRP queue handling (PnP / Power-Managment handle the three differently)
Parallel
- Queue pushes requests to the driver as soon as they arrive
Sequential
- Queue pushes requests to the driver synchronously
Manual
- Driver pulls requests from the queue as needed
PnP / Power Management events on the queue
Driver specifies what happens on queue during start, stop and resume events
Windows I/O is inherently Asynchronous so drivers must cope with race conditions and locks if not using the default cancellation system in the
WDF framwork.
Drivers must synchronize access to shared data (Windows is multi-threaded; default WDF is to lock/hold requests and synchronization scope )
UMDF calls this the locking constraint and applies only to device objects default; Device Scope
Objects synchronization scope tells WDF if it can invoke multiple callbacks on the object concurrently
Can be specified for drivers, device, and file objects
Synchronization Scopes
Device = Don't call certain I/O event callbacks concurrently for a single device object or any file object or queue objects that are its
children
Queue = Per Queue basis do not call IRP callbacks concurrently
None
= WDF can call any callbacks concurrently (default setting)
IRP Major Function Codes @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff550710%28v=vs.85%29.aspx
Required Dispatch Routines @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff561060%28v=vs.85%29.aspx
How Requests are dispatched from the queue
IO Target Device (WDF framework object that represents a driver)
IO Target is default the next driver in the driver stack

Communications
I/O Request Packet (IRP) = All windows I/O requests are carried by an IRP which is a kernel data structure.
Write IRP Packet
= Data to be written to the device
- WriteFile()

Read IRP Packet


= Pass buffer to driver to be filled with data from the device - ReadFile()
I/O Control Packet
= Other than read/write purpose (e.g. Type, Status)
- DeviceIoControl()
PnP Manager Packet
Power Manager Packet
Device Status
Device Queries
IoCallDriver()
= Sends an IRP to a driver
Pointer to a DRIVER_OBJECT
Pointer to the IRP instance
If the target driver is the next on the driver stack the IRP is called a local I/O Target else it is called a remote I/O Target

IRP - I/O Transfer Types


Buffered
Direct
Neither

= IRP has a pointer to Kernel buffer space (ie: METHOD_BUFFERED)


= A Memory Descriptor List (MDL) is passed to the driver (ie: METHOD_DIRECT)
= Buffer size and address in client space is passed to the driver (ie: METHOD_NEITHER)

Interrupt Request's (IRQ)


EvtIoRead
How Power Management events affect the queue
WDF integrates PnP / Power Management with the I/O Queue by canceling the queue requests during power-save states.
Handling IRP(s) @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff546847%28v=vs.85%29.aspx
Writing Dispatch Routines to handle IRP(s) @ http://msdn.microsoft.com/en-us/library/windows/hardware/ff566407%28v=vs.85%29.aspx

IRP
PreFix
WdfDevice

Call

Item

InitAssign WdmIrpPreprocessCallback

WdfRequest Allocate

Timer

WdfRequest Cancel

SentRequest

WdfRequest Change

Target

WdfRequest

Complete

WdfRequest

CompleteWithInformation

WdfRequest

CompleteWithPriorityBoost

WdfRequest

Create

WdfRequest

CreateFromIrp

WdfRequest Format

RequestUsingCurrentType

WdfRequest

ForwardToIoQueue

WdfRequest

ForwardToParentDeviceIoQueue

WdfRequest Get

CompletionParams

WdfRequest Get

FileObject

Get

Information

Get

IoQueue

Get

Parameters

Get

RequestorMode

Structure

Structure Initializer
IRP Major Code handler

Query
PreFix

Call

Structure

Structure Initializer

WdfDevice

InitSetRequestAttributes

Apply to IRP(s) attributes at Queue

WdfDevice

ConfigureRequestDispatching

Assigns IRP to specific queue

WdfDevice

DeviceEnqueueRequest

IRP Type Framework

WdfDevice

GetDefaultQueue

Devices default queue handle

EvtDevice

QueryRemove

EvtDevice

QueryStop

EvtDevice

RelationsQuery

EvtIo

AllocateRequestResources

EvtIo

AllocateResourcesForReservedRequest

EvtIo

CanceledOnQueue

EvtIo

Default

EvtIo

DeviceControl

EvtIoWdm

IrpForForwardProgress

WDF_IO_FORWARD_PROGRESS_ACTION

WdfIoQueue

AssignForwardProgressPolicy

WDF_IO_QUEUE_FORWARD_PROGRESS_POLICY

EvtIo

InternalDeviceControl

EvtIo

QueueState

WdfIoQueue

Start

EvtIo

Read

EvtIo

Resume

WdfIoQueue/EvtIo Stop
WdfIoQueue

StopSynchronously

EvtIo

Write

WdfIoQueue

Create

WdfIoQueue

Drain

WdfIoQueue

DrainSynchronously

WdfIoQueue

FindRequest

WdfIoQueue

GetDevice

WdfIoQueue

GetState

WdfIoQueue

Purge

WdfIoQueue

PurgeSynchronously

WdfIoQueue

ReadyNotify

WdfIoQueue

RetrieveFoundRequest

WdfIoQueue

RetrieveNextRequest

WdfIoQueue

RetrieveRequestByFileObject

WDF_IO_QUEUE_CONFIG

WDF_IO_QUEUE_CONFIG_INIT
WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE

//-- [ I/O Queue ] --//


// Register I/O IRP_MJ_READ, IRP_MJ_WRITE, and IRP_MJ_DEVICE_CONTROL callbacks
// IRP(s) go to: Registered, default EvtIoDefault handler, or fails to STATUS_INVALID_DEVICE_REQUEST.
// Create default queue - gets all the requests that are not configure-fowarded using WdfDeviceConfigureRequestDispatching.
// Dispatch Types (WdfIoQueueDispatch)
// Sequential
= IRP(s) -> EvtIo(Read/Write/{Internal}DeviceControl/Default) request handlers -> WdfRequestComplete (one at a time)
// Parallel = Handle I/O request simultaneously (must protect simultaneously accessed data).
// Manual
=
WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, WdfIoQueueDispatchParallel); // EvtIoCancel
queueConfig.EvtIoRead = EventIoRead;
queueConfig.EvtIoWrite = EventIoWrite;
queueConfig.EvtIoDeviceControl = EventIoDeviceControl;
__analysis_assume(queueConfig.EvtIoStop != 0); // EvtIoStop to prevent SDV warning
status = WdfIoQueueCreate(device,
&queueConfig,
WDF_NO_OBJECT_ATTRIBUTES,
&queue
);
__analysis_assume(queueConfig.EvtIoStop == 0);
if (!NT_SUCCESS (status)) {
KdPrint( ("WdfIoQueueCreate failed 0x%x\n", status));
return status;}

//--[ Finally register all our WMI datablocks with WMI subsystem. ]--//
status = ToasterWmiRegistration(device);
return status;

//--[
// Set the idle power policy to put the device to Dx if the device is not used
// for the specified IdleTimeout time. Since this is a virtual device we
// tell the framework that we cannot wake ourself if we sleep in S0. Only
// way the device can be brought to D0 is if the device recieves an I/O from
// the system.
//
WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT(&idleSettings, IdleCannotWakeFromS0);
idleSettings.IdleTimeout = 60000; // 60 secs idle timeout
status = WdfDeviceAssignS0IdleSettings(device, &idleSettings);
if (!NT_SUCCESS(status)) {
KdPrint( ("WdfDeviceAssignS0IdleSettings failed 0x%x\n", status));
return status;
}
//
// Set the wait-wake policy.
//
WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INIT(&wakeSettings);
status = WdfDeviceAssignSxWakeSettings(device, &wakeSettings);
if (!NT_SUCCESS(status)) {
//
// We are probably enumerated on a bus that doesn't support Sx-wake.
// Let us not fail the device add just because we aren't able to support
// wait-wake. I will let the user of this sample decide how important it's
// to support wait-wake for their hardware and return appropriate status.
//
KdPrint( ("WdfDeviceAssignSxWakeSettings failed 0x%x\n", status));
status = STATUS_SUCCESS;
}
//
// Finally register all our WMI datablocks with WMI subsystem.

//
status = ToasterWmiRegistration(device);
//
//
//
//
//
//
//

Please note that if this event fails or eventually device gets removed
the framework will automatically take care of deregistering with
WMI, detaching and deleting the deviceobject and cleaning up other
resources. Framework does most of the resource cleanup during device
remove and driver unload.

return status;
}

C. Callback Functions
/************************************************************************************************************
* EventDevicePrepareHardware()
*
IN:
Device - Handle to a framework device object.
*
IN:
ResourcesRaw - Handle to a collection of framework resource objects.
*
This collection identifies the raw (bus-relative) hardware
*
resources that have been assigned to the device.
*
IN:
ResourcesTranslated - Handle to a collection of framework resource objects.
*
This collection identifies the translated (system-physical)
*
hardware resources that have been assigned to the device.
*
The resources appear from the CPU's point of view.
*
Use this list of resources to map I/O space and
*
device-accessible memory into virtual address space
*
DESC:
*
When PnP manager sends IRP_MN_START_DEVICE; EvtDevicePrepareHardware() can:
*
- map resources
*
- Get USB device descriptors, config, and select configs.
*
- Download firmware to the device if firmware is reatained during D0 -> D3 states else use EvtDeviceD0Entry
*************************************************************************************************************/
NTSTATUS EventDevicePrepareHardware(WDFDEVICE Device, WDFCMRESLIST ResourcesRaw, WDFCMRESLIST ResourcesTranslated) {
//PFDO_DATA
fdoData;
NTSTATUS status = STATUS_SUCCESS;
ULONG i;
PCM_PARTIAL_RESOURCE_DESCRIPTOR descriptor;
//fdoData = ToasterFdoGetData(Device);
UNREFERENCED_PARAMETER(Device);
UNREFERENCED_PARAMETER(ResourcesRaw);
KdPrint(("EventDevicePrepareHardware called\n"));
PAGED_CODE();
// Get the number of items that are currently in the Resources collection
for (i=0; i < WdfCmResourceListGetCount(ResourcesTranslated); i++) {
// iterate thru as many times to get more information about the each items
descriptor = WdfCmResourceListGetDescriptor(ResourcesTranslated, i);
switch(descriptor->Type) {
case CmResourceTypePort:
KdPrint(("I/O Port: (%x) Length: (%d)\n",
descriptor->u.Port.Start.LowPart,
descriptor->u.Port.Length));
break;
case CmResourceTypeMemory:
KdPrint(("Memory: (%x) Length: (%d)\n",
descriptor->u.Memory.Start.LowPart,
descriptor->u.Memory.Length));
break;
case CmResourceTypeInterrupt:
KdPrint(("Interrupt level: 0x%0x, Vector: 0x%0x, Affinity: 0x%0Ix\n",
descriptor->u.Interrupt.Level,
descriptor->u.Interrupt.Vector,
descriptor->u.Interrupt.Affinity));
break;
default:
break;
}

}
// Fire device arrival event.
ToasterFireArrivalEvent(Device);
return status;

/************************************************************************************************************
* EventDeviceReleaseHardware()
*
IN:
Device - Handle to a framework device object.
*
IN:
ResourcesTranslated - Handle to a collection of framework resource objects.
*
This collection identifies the translated (system-physical)
*
hardware resources that have been assigned to the device.
*
The resources appear from the CPU's point of view.
*
Use this list of resources to map I/O space and
*
device-accessible memory into virtual address space
*
DESC:

*
EvtDeviceReleaseHardware is called by the framework whenever the PnP manager
*
is revoking ownership of our resources. This may be in response to either
*
IRP_MN_STOP_DEVICE or IRP_MN_REMOVE_DEVICE. The callback is made before
*
passing down the IRP to the lower driver.
*
*
In this callback, do anything necessary to free those resources.
*************************************************************************************************************/
NTSTATUS EventDeviceReleaseHardware(IN WDFDEVICE Device, IN WDFCMRESLIST ResourcesTranslated) {
//PFDO_DATA
fdoData;
UNREFERENCED_PARAMETER(Device);
UNREFERENCED_PARAMETER(ResourcesTranslated);
KdPrint(("EventDeviceReleaseHardware called\n"));
PAGED_CODE();

//fdoData = ToasterFdoGetData(Device);
// Unmap any I/O ports, registers that you mapped in PrepareHardware.
// Disconnecting from the interrupt will be done automatically by the framework.
return STATUS_SUCCESS;

/************************************************************************************************************
* EventDeviceSelfManagedIoInit()
*
IN:
Device - Handle to a framework device object.
*
DESC:
*
EvtDeviceSelfManagedIoInit is called it once for each device,
*
after the framework has called the driver's EvtDeviceD0Entry
*
callback function for the first time. The framework does not
*
call the EvtDeviceSelfManagedIoInit callback function again for
*
that device, unless the device is removed and reconnected, or
*
the drivers are reloaded.
*
*
The EvtDeviceSelfManagedIoInit callback function must initialize
*
the self-managed I/O operations that the driver will handle
*
for the device.
*
*
This function is not marked pageable because this function is in the
*
device power up path. When a function is marked pagable and the code
*
section is paged out, it will generate a page fault which could impact
*
the fast resume behavior because the client driver will have to wait
*
until the system drivers can service this page fault.
*
*
In this callback, do anything necessary to free those resources.
*************************************************************************************************************/
NTSTATUS EventDeviceSelfManagedIoInit(IN WDFDEVICE Device) {
NTSTATUS
PFDO_DATA

status;
fdoData;

KdPrint(("EventDeviceSelfManagedIoInit called\n"));
fdoData = ToasterFdoGetData(Device);
// We will provide an example on how to get a bus-specific direct
// call interface from a bus driver.
status = WdfFdoQueryForInterface(Device,
&GUID_TOASTER_INTERFACE_STANDARD,
(PINTERFACE) &fdoData->BusInterface,
sizeof(TOASTER_INTERFACE_STANDARD),
1,
NULL);// InterfaceSpecific Data
if(NT_SUCCESS(status))
{
UCHAR powerlevel;
// Call the direct callback functions to get the property or
// configuration information of the device.
(*fdoData->BusInterface.GetCrispinessLevel)(fdoData->BusInterface.InterfaceHeader.Context,
&powerlevel);
(*fdoData->BusInterface.SetCrispinessLevel)(fdoData->BusInterface.InterfaceHeader.Context, 8);
(*fdoData->BusInterface.IsSafetyLockEnabled)(fdoData->BusInterface.InterfaceHeader.Context);
// Provider of this interface may have taken a reference on it.
// So we must release the interface as soon as we are done using it.
(*fdoData->BusInterface.InterfaceHeader.InterfaceDereference)
((PVOID)fdoData->BusInterface.InterfaceHeader.Context);

} else {
// In this sample, we don't want to fail start just because we weren't
// able to get the direct-call interface. If this driver is loaded on top
// of a bus other than toaster, ToasterGetStandardInterface will return
// an error.
status = STATUS_SUCCESS;
}
return status;

/************************************************************************************************************
* EventDeviceContextCleanup()
*
IN:
Device - Handle to a framework device object.
*
DESC:
EvtDeviceContextCleanup event callback must perform any operations that are
necessary before the specified device is removed. The framework calls
the driver's EvtDeviceContextCleanup callback when the device is deleted in response

to IRP_MN_REMOVE_DEVICE request.
In this callback, do anything necessary to free those resources.
*************************************************************************************************************/
VOID EventDeviceContextCleanup(IN WDFOBJECT Device) {
//PFDO_DATA
fdoData;
UNREFERENCED_PARAMETER(Device);
KdPrint( ("EventDeviceContextCleanup called\n"));
PAGED_CODE();

//fdoData = ToasterFdoGetData((WDFDEVICE)Device);
return;

/************************************************************************************************************
* EventDeviceFileCreate()
*
IN:
Device - Handle to a framework device object.
*
IN:
FileObject - Pointer to fileobject that represents the open handle.
*
IN:
CreateParams - Parameters for create
*
DESC:
The framework calls a driver's EvtDeviceFileCreate callback
when the framework receives an IRP_MJ_CREATE request.
The system sends this request when a user application opens the
device to perform an I/O operation, such as reading or writing to a device.
This callback is called in the context of the thread
that created the IRP_MJ_CREATE request.
In this callback, do anything necessary to free those resources.
*************************************************************************************************************/
VOID EventDeviceFileCreate (IN WDFDEVICE Device, IN WDFREQUEST Request, IN WDFFILEOBJECT FileObject) {
//PFDO_DATA
fdoData;
UNREFERENCED_PARAMETER(FileObject);
UNREFERENCED_PARAMETER(Device);
KdPrint( ("EventDeviceFileCreate %p\n", Device));
PAGED_CODE ();
// Get the device context given the device handle.
//fdoData = ToasterFdoGetData(Device);
WdfRequestComplete(Request, STATUS_SUCCESS);
return;
}
/************************************************************************************************************
* EventFileClose()
*
IN:
FileObject - Pointer to fileobject that represents the open handle.
*
DESC:
EvtFileClose is called when all the handles represented by the FileObject
is closed and all the references to FileObject is removed. This callback
may get called in an arbitrary thread context instead of the thread that
called CloseHandle. If you want to delete any per FileObject context that
must be done in the context of the user thread that made the Create call,
you should do that in the EvtDeviceCleanp callback.
In this callback, do anything necessary to free those resources.
*************************************************************************************************************/
VOID EventFileClose (IN WDFFILEOBJECT FileObject) {

//PFDO_DATA
fdoData;
UNREFERENCED_PARAMETER(FileObject);
PAGED_CODE ();
//fdoData = ToasterFdoGetData(WdfFileObjectGetDevice(FileObject));
KdPrint( ("EventFileClose\n"));
return;

/************************************************************************************************************
* EventIoRead()
*
IN:
Queue - Handle to the framework queue object that is associated with the I/O request.
*
IN:
Request - Handle to a framework request object.
*
IN:
Lenght - Length of the data buffer associated with the request.
The default property of the queue is to not dispatch
zero lenght read & write requests to the driver and
complete is with status success. So we will never get
a zero length request.
*
DESC:
Performs read to the toaster device. This event is called when the
framework receives IRP_MJ_READ requests.
*************************************************************************************************************/
VOID EventIoRead (WDFQUEUE Queue, WDFREQUEST Request, size_t Length) {
NTSTATUS
ULONG_PTR
WDFMEMORY

status;
bytesCopied =0;
memory;

UNREFERENCED_PARAMETER(Length);
UNREFERENCED_PARAMETER(Queue);
PAGED_CODE();
KdPrint(("EventIoRead: Request: 0x%p, Queue: 0x%p\n",
Request, Queue));
// Get the request memory and perform read operation here
status = WdfRequestRetrieveOutputMemory(Request, &memory);

if(NT_SUCCESS(status) ) {
// Copy data into the memory buffer using WdfMemoryCopyFromBuffer
}
WdfRequestCompleteWithInformation(Request, status, bytesCopied);
}
/************************************************************************************************************
* EventIoWrite()
*
Queue
- Handle to the framework queue object that is associated with the I/O request.
*
Request - Handle to a framework request object.
*
Lenght - Length of the data buffer associated with the request. (0-lenght buffers aren't passed)
*
The default property of the queue is to not dispatch
*
zero lenght read & write requests to the driver and
*
complete is with status success. So we will never get
*
a zero length request.
*
DESC: Performs write to the toaster device. This event is called when the framework receives IRP_MJ_WRITE requests.
*************************************************************************************************************/
VOID EventIoWrite (WDFQUEUE Queue, WDFREQUEST Request, size_t Length) {
NTSTATUS
status;
WDFMEMORY memory;
UNREFERENCED_PARAMETER(Queue);
KdPrint(("EventIoWrite. Request: 0x%p, Queue: 0x%p\n", Request, Queue));
PAGED_CODE();
// Get the request buffer and perform write operation here
status = WdfRequestRetrieveInputMemory(Request, &memory);
if(NT_SUCCESS(status) ) {
// 1) Use WdfMemoryCopyToBuffer to copy data from the request
// to driver buffer.
// 2) Or get the buffer pointer from the request by calling
// WdfRequestRetrieveInputBuffer to transfer data to the hw
// 3) Or you can get the buffer pointer from the memory handle
// by calling WdfMemoryGetBuffer to transfer data to the hw.
}
WdfRequestCompleteWithInformation(Request, status, Length);
}
/************************************************************************************************************
* EventIoDeviceControl()
*
Queue
- Handle to the framework queue object that is associated with the I/O request.
*
Request
- Handle to a framework request object.
*
OutputBufferLength
- length of the request's output buffer, if an output buffer is available.
*
InputBufferLength - length of the request's input buffer, if an input buffer is available.
*
IoControlCode
- the driver-defined or system-defined I/O control code (IOCTL) that is associated with the request.
*
DESC:
This event is called when the framework receives IRP_MJ_DEVICE_CONTROL requests from the system.
*************************************************************************************************************/
VOID EventIoDeviceControl(IN WDFQUEUE Queue,IN WDFREQUEST Request,IN size_t OutputBufferLength,
IN size_t InputBufferLength, IN ULONG IoControlCode) {
NTSTATUS
WDF_DEVICE_STATE
WDFDEVICE

status= STATUS_SUCCESS;
deviceState;
hDevice = WdfIoQueueGetDevice(Queue);

UNREFERENCED_PARAMETER(OutputBufferLength);
UNREFERENCED_PARAMETER(InputBufferLength);
KdPrint(("EventIoDeviceControl called\n"));
PAGED_CODE();
switch (IoControlCode) {
case IOCTL_TOASTER_DONT_DISPLAY_IN_UI_DEVICE:
// This is just an example on how to hide your device in the
// device manager. Please remove this code when you adapt
// this sample for your hardware.
WDF_DEVICE_STATE_INIT(&deviceState);
deviceState.DontDisplayInUI = WdfTrue;
WdfDeviceSetDeviceState(
hDevice,
&deviceState
);
break;
default:
status = STATUS_INVALID_DEVICE_REQUEST;

}
// Complete the Request.
WdfRequestCompleteWithInformation(Request, status, (ULONG_PTR) 0);
}

/
***********************************************************************************************************************************************
*****
* Device Driver based on
*
Kernel Mode Driver Framework (KMDF) - A sub-division of the Windows Driver Foundation's (WDF) Windows Driver Kit (WDK)
*
_In_ & _Out_ are Function parameter annotations; see http://msdn.microsoft.com/en-us/library/hh916382.aspx
*
Drivers export a standard set of entry point in its DriverEntry() by filling in a data-structure created by the OS called DRIVER_OBJECT
*
OS looks at the data-structure of function pointers to call when a request is targeted to a device described by DEVICE_OBJECT
*
Function dispatch table = contains a function pointer for each major function code the OS system supports
*
28-functions can be supported but usually only 8 are: IRP_MJ_CREATE, CLOSE, READ, WRITE, PNP, POWER, DEVICE_CONTROL, and SYSTEM_CONTROL
*
by default all these functions point to a routine which indicates that major function is NOT supported.

***********************************************************************************************************************************************
*****/

DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_DEVICE_ADD KmdfEvtDeviceAdd;
// All global variables must be defined in 'DeviceEntry' File ; This File
// All Device Drivers START at DriverEntry() which creates the DriverObject when the driver is loaded
NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
NTSTATUS status;
WDF_DRIVER_CONFIG config;
//--- sends a string to the kernel debugger --//
KdPrintEx(( DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: DriverEntry\n" ));
/*ULONG KdPrintEx(
ULONG ComponentId,
ULONG Level,
PCSTR Format,
... arguments);*/
//-- Initializes WDF_DRIVER_CONFIG object; a driver's config structure --//
WDF_DRIVER_CONFIG_INIT(&config, KmdfEvtDeviceAdd);
/* WDF_DRIVER_CONFIG_INIT(
PWDF_DRIVER_CONFIG
Config,
PFN_WDF_DRIVER_DEVICE_ADD EvtDriverDeviceAdd );*/
//-- Creates a framework driver object for the calling driver --//
status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);
/*NTSTATUS WdfDriverCreate(
PDRIVER_OBJECT
DriverObject,
PCUNICODE_STRING
RegistryPath,
PWDF_OBJECT_ATTRIBUTES
DriverAttributes,
PWDF_DRIVER_CONFIG
DriverConfig,
WDFDRIVER
*Driver);*/
return status;
}
//-- Each Device gets added --//
NTSTATUS KmdfEvtDeviceAdd(_In_ WDFDRIVER Driver, _Inout_ PWDFDEVICE_INIT DeviceInit)
{
NTSTATUS status;
WDFDEVICE hDevice;
UNREFERENCED_PARAMETER(Driver);
KdPrintEx(( DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: KmdfHelloWorldEvtDeviceAdd\n" ));
status = WdfDeviceCreate(&DeviceInit, WDF_NO_OBJECT_ATTRIBUTES, &hDevice);
return status;
}

*/

7.3.3 User-Mode Driver Framework (UMDF)


UMDF cannot directly access the hardware (ie: DMA, IRQ or WMI)
User-Mode
= HRESULT (SUCCEED or FAILED; A type of the COM model)
UMDF = User-Mode Driver Framework
Written in C++ (V1 is difficult and being deprecated / V2 is only supported on Windows 8.1 platforms)
Each process runs in a specific virtually addressed user space
Uses Libraries kernel32.dll, user32.dll, wingdi.dll, msvcrt.dll
Crash recovery without reboot
Debugging on same PC
Uses the Active Template Library (ATL); a C++ template library designed for COM objects
See http://msdn.microsoft.com/en-us/library/windows/hardware/dn265594%28v=vs.85%29.aspx

UMDF Object Interfaces (ie: Abstract base classes) to inherit


IWDFObject
Base WDF object type
IWDFDriver
Driver object
IWDFDevice
Device object
IWDFFile
File Object
IWDFIoQueue Queue of I/O requests
IWDFIoRequest Describes and I/O Request Packet
IWDFIoTarget Driver that is the target of an I/O Request Packet
IWDFMemory Access to an area of memory

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki-books Device Driver Introduction @ http://en.wikibooks.org/wiki/Windows_Programming/Device_Driver_Introduction


Windows driver development

WDK Kit
Differences between WDM and WDF
Device Driver Classes/Models

http://msdn.microsoft.com/en-US/windows/hardware/gg454513
http://msdn.microsoft.com/en-us/library/windows/hardware/gg583838%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/Library/Windows/Hardware/ff557557%28v=vs.85%29.aspx

Windows WDK kit @


Windows driver development
http://msdn.microsoft.com/en-us/windows/hardware/ff960953
Sample Drivers
http://code.msdn.microsoft.com/windowshardware
OSR Online Everything windows driver development @ http://www.osronline.com/
OSR Online - Writing Windows Drivers http://www.osronline.com/article.cfm?article=20
CPU Architectures
http://www.youtube.com/watch?v=H4Z0S9ZbC0g&index=5&list=PLNLBZ0YJh9Y_ShtMzUUaD321ess_idQlR
USB Open Source
Install USB drivers - Libwdi @ https://github.com/pbatard/libwdi/wiki
libusbx
libusb-win32
libusbK

7.3.4 Linux
A. Overview
Linux device drivers have 3-sides
Kernel Communications
driver registers functions that will respond to events (open file, page fault, plug and play)
talk through initialization function, register_chrdev, hooking into timer interrupt
Hardware Communications
User Communications

User driver interface via device files (character / block device files) e.g. /dev/klife device file

B. Code
'init' is called on driver initialization and 'exit' is called when driver is removed
init() will register hooks that will call driver code when an event occurs
Driver registers chardev tied to a given major number
Static int __init klife_module_init(void) {
int ret;
pr_debug(klife module init called\n);
if (( ret = register_chrdev(KLIFE_MAJOR_NUM, klife, &klife_fops) ) < 0 )
printk(KERN_ERR register_chrdev: %d\n, ret);
return ret;
}

Registering Chardev hooks (ie: Event Calls Function Name)


struct file_operations klife_fops = {
.owner = THIS_MODULE,
.open = klife_open,
.release = klife_release,
.read = klife_read,
.write = klife_write,
.mmap = klife_mmap,
.ioctl = klife_ioctl
};

User Space access to major number


# mknod /dev/klife c 250 0

//
//
//
//
//
//

for allocating resources


releasing resources
generating and reading states of the device
start-up settings
faster but more complex direct access to device
querying device and enabling/disabling timer interrupts

// creates file

Use File
if ((kdf = open(/dev/klife, O_RDWR)) < 0 ) {
perror(open /dev/klife);
exit(EXIT_FAILURE);
}

7.4 Assembly Language (ASM)


Terms
uOps - Micro-operations

= (ie: Macro-instructions) Detailed low-level instructions to implement complex instructions

Common Processor Registers


EAX = Function return
EBX = Base pointer to the data section
ECX = Counter for string/loop operators
EDX = IO pointer

ESI = Source pointer for string


EDI = Destination pointer for string
ESP = Stack Pointer
EBP = Stack frame base pointer (here's where the function starts)
EIP = Pointer to next instruction (instruction pointer) read-only access via 'JUMP' or 'CALL'
X Registers
AH ( High Byte ) AL ( Low Byte )
AXE, BXE, CXE For 32-bit storage
AX, BX, CX For 16-bit storage
Broken into AH(
I/P can only be accessed at the 16-bit level
Register Conventions (Prevent register access conflicts)
Caller-Save Registers (EAX, EDX, ECX) Parent is responsible for saving registers to the stack and restoring them before calling another function that
may destroy them.
Callee-Save Registers (EBP, EBX, ESI, EDI) called function will never use/smash or is responsible for store/restore original values if required to be used.
Stomping Prevention
= Saved at the beginning and restored at the end (looks pointless but very important for stomping)
EFLAGS Register (32-bit of FLAGS) bit flagging (Boolean operations T/F Compare; set after each instruction)
ZF (Zero Flag) = 1 if result is 0
SF (Signed Flag) = MSB but last number (2s Compliment) 0x7FFFF is used because 0x80000 = (-) negative numbers (Compiler handles negative
numbers)
x86 Instructions
NOP = No operation (exchanges EAX -> EAX)
- The Stack (RAM) up to OS where to put it (Reserves some chunk of RAM for FIFO) - Stack sequences from biggest address to little address

- Data is pushed on and popped off (ESP always points at the first of the stack)

- Keeps track of parent function while going into called function (Just like Higher-Level-Language stacks)
- PUSH = Push value (Constants/Register Address's Value) onto stack (Not EIP; caller/jump handles that)
- POP = Gets top stack value puts into a register
- Calling Conventions

- cdecl(C declaration), stdcall (how to pass function arguments)

- cdecl = args are pushed onto stack from right to left

- take frame pointer (create new stack area)

- parent is responsible to clear passed parameters from stack

- stdcall - callee is responsible to clear received parameters from stack

- CALL = Set EIP

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki http://en.wikipedia.org/wiki/Comparison_of_assemblers


Wiki http://en.wikipedia.org/wiki/Assembly_Language

7.5 C & C++


1. C++ contains
Text Editor
Compiler
(.h & .cpp) (.o)
Includes a Pre-processor / Pre-Compiler that translates # items)
Linker
Links object code to missing functions (libraries)
Standard Library
Class Libraries
Debugger

2. Libraries
StdLib
STL
Boost

= C++ Standard Library


= Standard Template Library
= Pre StdLib libraries

3. Standards = Committees have been organized to produce standard programming language specifications that compiler writers are encouraged to follow
ANSI
Developed the ANSI C standard
ISO/IEC
Developed the C++ Standard
https://isocpp.org/std/the-committee

Reserved ID naming
'__' and '_[A-Z]'
- double underscore and underscore + capitol letter are reserved naming notations
'_*'
- prefixed underscore is reserved at the global namespace; class and local naming is okay
is[a-z]* , mem[a-z]* , str[a-z]* , to[a-z]* , wcs[a-z]* are all reserved naming conventions and should not be used
E[A-Z]*, LC_[A-Z]* , SIG[A-Z]*, SIG_[A-Z]*
are all reserved macro naming conventions and should not be used
C++ keywords are reserved
and

new

private

signed

template typeid

and_eq case

break const

const_cast dynamic_cast false

double

extern if
inline

not

protected

sizeof

this

typename volatile

asm

catch

continue

else

float

int

not_eq

public

static

throw

union

auto

char

default

enum

for

long

operator register

bitand

class

delete

explicit

friend mutable

bitor

compl do

export

goto

or

namespace or_eq

static_cast TRUE

void
wchar_t

unsigned while

reintepret_cast struct

try

using

xor

return

typedef

virtual

xor_eq

switch

bool

Literals
= integer, float, boolean, char or string constant
Notation = dec, oct, hex

7.5.1 Compilers (GCC/MSVC)


GCC vs MSVC
= GNU Compiler Collection (GCC) vs Microsoft Visual C++(MSVC)
keyword 'abstract' is MS only
properties in C++ are MS only
Pointer Unswizzling - is DE-referencing object pointers in memory before saving.
C++ Standard Library http://en.cppreference.com/w/cpp/header
GCC

+ GNU Compiler Collection = An Integrated Compiler supporting multiple languages. (The abbreviation formerly stood for GNU C Compiler).

Current language support


GCC can compile programs written in any of these languages
C
>gcc GNU C Compiler - Compiles (.c)(.cpp) as C and C++ respectively
gcc compiling ANSI C files contains less predefined macros.
G++
>g++ GNU C++ Compiler Compiles (.c)(.cpp) both will be treated as C++
Compiles straight to object code no ANSI C code will exist
Automatically include the 'std' C++ libraries (gcc does not do this)
Objective-C C++ compiler for OSX and iOS (Apple) with the Cocoa Library; also adds messaging to the C language (.mm source code file
extension)
Ada
>GNAT
Described in separate manual
Fortran
Described in separate manual
Java
Described in separate manual
Treelang
Described in separate manual

Expanded language support


Mercury
Pascal

Front-ends to GCC are installers that expand language support

7.5.2 C++
Standard Variables
Data Types
Name
char

OPERATORS
Description
Character or small integer.

Size*
1byte

Range*
signed: -128 to 127
unsigned: 0 to 255

addition

subtraction
signed: -2147483648 to 2147483647 *
multiplication
unsigned: 0 to 4294967295
/
division
bool
Boolean value. (values: true or false)
1byte
true or false
%
modulo
short int (short)
Short Integer.
2bytes
signed: -32768 to 32767
unsigned: 0 to 65535
long int (long)
Long integer.
4bytes
signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
CONDITIONAL
float
Floating point number.
4bytes
+/- 3.4e +/- 38 (~7 digits)
double
Double precision floating point number. 8bytes
+/- 1.7e +/- 308 (~15 digits)
== Equal to
long double
Long double precision floating point.
8bytes
+/- 1.7e +/- 308 (~15 digits)
!=
Not equal to
wchar_t
Wide character.
2 or 4 bytes
1 wide character
>
Greater than
operators which can appear in C++. From greatest to lowest priority, the priority order is as follows:
<
Less than
Level
Operator
Description
Grouping
>= Greater than or equal to
1
::
scope
Left-to-right
<= Less than or equal to
2
() [] . -> ++
postfix
Left-to-right
&& AND
dynamic_cast
static_cast
reinterpret_cast
const_cast
typeid
3
++ -- ~ ! sizeof new delete
unary (prefix)
Right-to-left
||
OR
*&
indirection and reference (pointers)
?:
Condition ? True : False
+unary sign operator
ESCAPE CHARACTERS
4
(type)
type casting
Right-to-left
\n
newline
5
.* ->*
pointer-to-member
Left-to-right
\r
carriage return
6
*/%
multiplicative
Left-to-right
\t
tab
7
+additive
Left-to-right
\v
vertical tab
8
<< >>
shift
Left-to-right
\b
backspace
9
< > <= >=
relational
Left-to-right
\f
form feed (page feed)
10
== !=
equality
Left-to-right
\a
alert (beep)
11
&
bitwise AND
Left-to-right
\'
single quote (')
12
^
bitwise XOR
Left-to-right
\"
double quote (")
13
|
bitwise OR
Left-to-right
\?
question mark (?)
14
&&
logical AND
Left-to-right
\\
backslash (\)
15
||
logical OR
Left-to-right
16
?:
conditional
Right-to-left
17
= *= /= %= += -= >>= <<= &= ^= |= assignment
Right-to-left
18
,
comma
Left-to-right
COMPOUND OPERATORS
BITWISE OPERATORS
expression
is equivalent to
&
AND Bitwise AND
value += increase; value = value + increase;
|
OR Bitwise Inclusive OR
a -= 5;
a = a - 5;
^
XOR Bitwise Exclusive OR
a /= b;
a = a / b;
~
NOT Unary complement (bit inversion)
price *= units + 1; price = price * (units + 1);
<<
SHL Shift Left
>>
SHR Shift Right
int

Integer.

4bytes

A. Header File
// C++ source code is typically broken out into 2-text files (.h/.cpp)
/***********************************************************************************************************
* (.h) Header files = Define the Interface ( Classes / Prototypes / Structure )
*
- #includes
Inherited classes that are required
*
- structure declares
Struct, class, union
*
- global prototypes
Global (non-member) function signatures, constants and variables
*
- see also: http://embeddedgurus.com/barr-code/2010/11/what-belongs-in-a-c-h-header-file/
************************************************************************************************************/

A.1 #Pre-processor directives


#ifndef MYHEADER_H
#define MYHEADER_H

// PRE-PROCESSOR directives = Source code manipuation before compilation(ie: code -> executable)
// 'MYHEADER_H' = If pre-processor variable is not defined THEN
//
Set MYHEADER_H as defined and include code block (#if->#endif)

A.2 #Include/Using
<iostream> C++ standard library 'std' namespace = <stdio.h> in C
New style #include doesn't necessarily represent a file-name (why .h was removed) the actual file is decoded by the compiler.
New header files
= Includes with no (.h) and prefix of 'c' (e.g. <cstring>) and all 'c' prefixes are part of the 'std' namespace.
(prevents name collisions)

using namespace std


#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

- puts the 'std' name-space into the global name-space for default non-name-space identified calls.

<stdafx.h>
<iostream>
<string>
<array>
<vector>
<list>
<set>
<map>
<stack>
<queue>

// #INCLUDE = Reference outside library code


//
//
// Standard Library(StdLib) Containers
//
//
//
//
//
//

using namespace System;


//------------------ SCOPE / TYPEDEF
-------------------------------------------------------------------using namespace std;
// using
= Default namespace scope; Find commands in this namesapce if not specifically
specified
typedef unsigned long ulong;
// typedef
= Name for existing type; typedef struct udt{...} is acceptable (e.g. ulong =
"unsigned long")
int inline InlineAdd(int a, int b) {
// inline
= Pre-Processor function declaration to be expanded to command-list where called
return a + b; }

A.3 Namespace/Class/Struct/Union
namespace myspace {
//------------------ BLOCK STRUCTURES
------------------------------------------------------------------// namespace
= Named block of top-level code (typically one namespace per project)
// class
= Named design containing data and/or function code (all members are 'private' by
default)
class Arrays;
// struct
= Named class typically for data structures only
(all members are 'public' by
default)
union aunion;
// union
= Named single storage compartment having various data types associated with it
(protocol usage)
// --- Class Types --class AbstractABC;
// ABC
= Abstract base class cannot be initialized / objectified
(1+ pure-virtual
members)
template<class T> class Concrete;
// Concrete
= a class that allows object instances
(No pure-virtual
members)
class Interface {
// Interface
= An abstract-base-class(ABC) never having any functionality (All pure-virtual
members)
public:
virtual void Input(int) = 0; // virtual
= allows the function to be over-ridden in a derived classes
virtual int Output() = 0;
// pure-virtual = a member "func() =0" which makes the class abstract(ABC)
};
struct Fundamental_Data_Types {
//--------------------- DATA TYPES
---------------------------------------------------------------------bool Abool;
// Boolean
= true/false
1-byte
short AShort;
// Short
= 32,767(+/-)
2-byte
int AnInt;
// Integer
= 2,147,483,648(+/-)
4-byte
long ALong;
// Long
= 2,147,483,648(+/-)
4-byte
float Afloat;
// Float
= E+/-38 ~7 digits
4-byte
double Adouble;
// Double
= precision ~15 digits
8-byte
char AChar;
// character
= (1)ASCII character 1-byte
others: char16_t, char32_t, wchar_t(2/4-byte)
wchar_t AWChar;
char Charray[5][5];
// arrays
- Any data type can be a single[index] or multi[5][5] dimensional array.
ulong ultype;
// user-defined = typedef name (See 'typedef' above)
} FData;
// ** Optionally ** classes, struct, and union can initiate objects(CSV) right away (e.g. 'FData'
object)
struct STL_Containers {
std::string name;
std::vector<int> vect;
std::list<int> linklist;
std::set<int> aset;
std::map<string,int> amap;
std::stack<string> astack;
std::queue<string> aqueue;
} STLCon;

//
//
//
//
//
//
//

Multi-character strings
Dynamic array type
Link list
Data Sets
Dictionary - Hash Table
Stack
Queue

}
//#endif

B. Source File
/***********************************************************************************************************
* (.cpp) C++ source code "body" file
*
- File where header(.h) declaration are defined (over-riding the empty declarations)
*
************************************************************************************************************/
// #include <ThisFile.h>
using namespace myspace;
class myspace::AbstractABC {
//---------------------------- MEMBERS
-----------------------------------------------------------------private:
// private
= members that are visible/accessible in-class
protected: string thewords;
// protected
= members that are visible/accessible in-class and derived-classes
public:
int LetterCount;
virtual void Words(string in) {
this->thewords = in;}
virtual string Words() {
function to use)
return this->thewords;}

//
//
//
//
//

public
Field
Property(Set)
this
Property(Get)

// return

=
=
=
=
=

members that are visible/accessible everywhere


public data member
C++ doesn't natively support properties; use over-loading instead
pointer to the object instance currently being executed
OVER-LOADS function 'Words' (callers argument count/type determine which

= value returned by the call

('void'= no return value; 'string' in this case

is type returned)
virtual void Display() = 0;
};

// Function()

= pure virtual function

template<class T>
// template<T>
= Identifies 'data type' used in the class; set by the initializing
caller
class myspace::Concrete :
// [:]
= Inherits
public Interface,
// ***** NOTE: Variables cannot be initialized in the original class definitions *****
public AbstractABC {
//
private: T iIn;
// typename T
= is the received template argument passed to this class @ initialization
public:
//
Concrete(int a) { iIn = a;}
// Constructor
= Gets called automatically when an object of this class is created
(ie: 'new')
~Concrete() { iIn = 0;}
// Destructor
= Gets called automatically when an object of this class is destroyed
(ie: 'delete')
void Input(T In) { this->iIn = In;}
// Implement code-bodies for the Interface members
T Output() { return this->iIn; }
//
void Display() {
// Implement code-bodies for the AbstractABC class - Only Display() is still a pure-virtual
std::cout << "Input = " << Output()<< "\n";
std::cout << "Words = " << Words() << "\n";
printf("Protected 'thewords' = %s\n",this->thewords);
}
};
int main()
---------------------------------------{

//--------------------------------- Main() Start-up Function

//---------------------------- Storage Specifiers


--------------------------------------------------auto Hi = "Hi there";
// auto
= Initializing value automatically determine data type
//extern Ext;
// extern
= object with external **linkage** defined in a different source file
//mutable ConstChange;
// mutable
= data member that can be modified even if the containing object is const
volatile int HrdwIO;
// volatile
= a variable tied to a hardware register (changes w/o being set by code)
static int iAllObjects;
// static
= One variable for all object instances
const int CONST = 3;
// const
= Read only (can be applied to data types or classes)
char hello[] = "Hello";
// Initial Bounds
= array bounds are auto-set by initializing value.
//int iarray[];
// Bound-less
= Initialize a bound-less array
decltype(Hi) Bye;
// decltype
= obtain data type for variable 'Hi'
//---------------------------- Value Assignments
---------------------------------------------------FData.ALong
= 1L;
// (Pre)(Suf)fix = Assignment values can have type identifiers
FData.ALong
= 07L;
// 0 = Octal
L = Long
FData.ALong
= 0x1UL;
// 0x = Hex
U = Unsigned
FData.Afloat = 1.1E-24F;
// E = ExponentF = FLOAT
FData.AChar
= L'a';
// L = wchar_t
FData.AChar
= '\07';
// Char Octal 7
FData.AChar
= '\xFF';
// Char Hex "FF"
FData.AWChar = '\u00C0';
// Char Unicode ASCII character 0x03C0*/
FData.Charray[0][0] = 'A';
//
FData.Adouble= (double)3;
//----------------------------- Type Casting
-------------------------------------------------------FData.Abool
= bool(1);
//
//FData.Afloat
= const_cast<int>(&3);
// Type must be pointer, reference or pointer to member of an object
//FData.ALong
= dynamic_cast;
// Must be pointer or reference to a complete class type
//FData.AShort
= reinterpret_cast;
//
FData.AnInt
= static_cast<int>(3.3); //
Console::WriteLine(L"Main()");
int IntVal = 50;
------------------------------------------int *AddrPtr;
printf(" IntVal = %d\n", IntVal);
printf("&IntVal = %x\n", &IntVal);
AddrPtr = &IntVal;
printf(" AddrPtr = %x\n", AddrPtr);
printf("*AddrPtr = %d\n\n", *AddrPtr);
Concrete<int> myobj(111);
Concrete<int> *ObjPointer;
ObjPointer = new Concrete<int>(3);
myobj.Display();
ObjPointer->Display();

// Believe 'Console' is Windows Only


//----------------------------- NAME & POINTER addressing
//
//
//
//
//
//
//
//
//
//
//

type [*]
printf
[&]
[=]

=
=
=
=

declare pointer variables


ANSI C print to standard output (e.g. print the named variable 'IntVal')
AddressOf
Assign
(e.g. AddrPtr = AddressOf(IntVal))

[*]
type 'name'

= Dereference pointer (ie: Return Value@Address)


= will auto-initiate a named object

new
[.]
[->]

= Initiate an un-named object at 'ObjPointer' address


= call a named object member
= call a un-named pointer object member

STLCon.name = "Hello";
std::cout << InlineAdd(2,3);
//----------------------------- Flow Control
-------------------------------------------------------for(int i = 0; i < 5; i++) {
// for-loop
= for(variable; loop again condition; per loop command) { commands }
if (i == 1)
// if
STLCon.name = "One\n";
else if (i == 2)
// else if
continue;
// continue
= immediate next-iteration
ie: skip the rest of the loop
else if (i == 4)
break;
// break
= immediate exit
ie: Exit the loop without finishing
else
// else
=
if (i != 0)
STLCon.name = "Empty\n";
try {
// try
= Error Handling routine
std::cout << STLCon.name;
// cout
= C++ send to standard output (e.g. standard output(console) receives
STLCon.name)
throw exception("My Exception");
// throw
= Raise a runtime error

} catch (...) {
std::cerr << "Something";
}

}
for(char c : STLCon.name) {
std::cout << "[" << c << "]";}
while (IntVal > 0 ) {
std::cout << IntVal << "\n";
IntVal--;}
do {
std::cout << IntVal++ << "\n";
} while (IntVal <= 5);
switch (IntVal) {
case 1:
std::cout << "One";
break;
case 2:
std::cout << "Two";
break;
default:
std::cout << "Not One or Two";
}
return 0;

// catch
// cerr

= Catch a runtime error;


(...) = Catch 'ALL' exception errors
= Send to startard output 'err' pipe

// for :
//
// while

= for each item in region

// do-while
// switch-case
// case
// if 'break' is missing both 'case 1' block and 'default' block would execute when IntVal = 1
//
// default

= no 'break' were incountered (ie: no cases were satisfied)

// main return

= '0' to the Operating System(OS) indicating a successful run

B.1 Details
int main() in C++ = int main(void) in C
('void' isn't required in C++)
'<<' (output operator) in C++ shifts something into 'cout' the screen - C uses printf() to print on screen (C++ supports printf also)
'>>' (input operator) in C++ 'cin' = standard input device
Single value initial assignments
Type X(99); is the same as Type X = 99;
char me[] = "String Literal"; //Which is a character array with terminator \0
void* - Any data type but must be defined before *
NULL = 0 or pointer that goes no-where
Lambda functions are code blocks (ie: Like a function w/o a name)
auto is like template T but determines type automatically (need to look into this one a little more)
Struct, Class, Union
struct A UDT or Class generally used to declared plain data structures, can also be used to declare classes that have member functions, with the
same syntax as with keyword class. The only difference between both is that members of classes declared with the keyword struct have public
access by default, while members of classes declared with the keyword class have private access by default. For all other purposes both keywords
are equivalent in this context.
Unions - is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are
also classes and can thus also hold member functions. The default access in union classes is public.
Only base classes are allowed 'pure-virtual' members
C++ Dynamic Link Library (DLL)
Has a main entry point DllMain() that gets called by each connecting application
DLL defines its own interface which is exported as a (.LIB) file that applications link to

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------CplusPlus Tutorial


http://www.cplusplus.com/doc/tutorial/
Standard C++ Library Reference
http://www.cplusplus.com/reference/
C. Qt
Use CONFIG -= QT to omit all Qt libraries form the Qt Creator
Had to un-install VS 6.0 to get to work; don't know why or how to get around it.
Add CONFIG += c++11 to your Qt .pro file for C11++ support.

D. Makefile
Variables
NAME = VALUE
Special
$@ = Name of the file to be made
$? = Names of the changed dependents
MS editions of Make is Nmake
Research also

Visual Studio uses MSBuild


Nant scripts to automate build and test units (build server)
'devenv.exe' = make
commands
'.vcproj' = Makefile
'.sln' = $(Make)
ie: Root directory makefile will find recursively other makefiles whereas .sln has list of projects and dependancies
'cl.exe' = 'g++'
Compilers
about linux makefile

Line types:
-File dependancies
-shell commands
-variable assignments
-include statements
-conditional (loops & comments)
Extenting a line via \
Visual Studio
Command

devenv.exe

Compile and Link options .vcproj

make Utility
make
Makefile

Dependency

.sln has list of projects and dependencies The root directory Makefile will recursively find other makefiles via the command $(MAKE)

Compiler

cl.exe

gcc, g++, c++ (or any other compiler, even cl.exe)

Linker

link.exe

ld (or any other linker)

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://cognitivewaves.wordpress.com/makefiles/

7.6 Java
Java Source Compiler Java Byte-Code (object file) Java Virtual Machine (Interpreter) Machine Language
Java Incorporates both compiling and interpreting machine code generation methods
Compilation Java Byte Code (Platform Independant)
Java Byte Code Java Virtual Machine (JVM) Machine Code
JVM can be installed at the hardware (Java Processor), system software (JVM) or application layer (JVM)
Contains 2-Components; JVM Classes / (Compiled Libraries) / Java APIs & Execution Engine
See http://www.oracle.com/technetwork/java/embedded/javame/embed-me/documentation/javame-embedded-apis-2181154.html

Java Technologies
See https://www.oracle.com/java/technologies/solutions.html
Java Card
Java Cloud Service
Java EE
- Enterprise Edition with HTML5
Java Embedded
Java ME Embedded Client
- Micro Edition for small embedded devices.
Java ME SDK
Java SE
- Standard Edition
Java SE Advanced and Suite
Java SE Embedded
Java SE Support

Java TV
Java Wireless Client
Jrockit

- Jave SE + JVM + Profiling, Monitoring and diagnostic tools

Java Virtual Machines (Besides Oracle)


http://www.skelmir.com/products
Java Engine
Contains algorithms that either compiles or Interprets Byte-Code (Platform independent byte-code Platform dependent machine
code)
Interpretation
Interprets source machine code on each instruction line everytime its executed
WAT/AOT
Way Ahead of Time / Ahead Of Time Compilation

JIT
Just In Time Compilation ( Interprets source once and stores the native form; allowing redundant code to be executed w/o
reinterpreting )
Variations on the JIT compiler are referred to as translators or dynamic adaptive compilation (DAC)
Compilation to an Intermediate Language (.NET Common Intermediate Language (CIL))
See http://connect.smithmicro.com/insignia-device-management

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------References


Java JIT-Compiler
http://connect.smithmicro.com/insignia-device-management
A Java AOT-Compiler
http://www.atego.com/

7.7 C#
Features of C#
Versioning
Generics
Delegates
Data Types
Value Types variables that directly contain a value (copies the contained value ie: a=b)
Reference Types variables that contain a pointer to an object but not the object itself.

7.8 VB6 & VBA


VB6
Visual Basic version 6.0
Visual Basic version 6.0 and previous versions did not include a full-featured object-oriented programming nor the .NET framework
VBA
Visual Basic for Applications
Visual Basic for Applications; Typically for MS-Office applications Access by using alt-F11 from Word, Access or Excel

To write/read a file:
iFileHandler = FreeFile
Open <filename> For Output As #iFileHandler
Write #iFileHandler <string>
Close #iFileHandler

Late Binding:
Public Me as Object
Me = CreateObject(<Class(name)>)
Set Me = ObejctFromSomewhere that is type identified.

Early Binding:
Public Me as New <ClassName>

Programming Tips & Debug:


DLL will crash Excel w/o debugger if a String() is attempted to be cast to a variant
Always check 0/? In match to prevent crashes, IIF(lTopNum <> 0, lTopNum/lBotNum,0) doesn't work since IIF evaluates both True/False spots.
Determining if the IDE or VBA is being used.
A trick to determining if the code is running in a compiled project or within an IDE is by using the Debug.Print command which is ignored when
compiled.
Example:
On Error Resume Next
Debug.Print 1/0
If Err = 0 then
msgbox running in a compiled project.
Else
msgbox running in debugger or vba
End if

Handy Windows API


Private Declare Sub Sleep Lib "kernel32" (ByVal lMilliseconds As Long)

7.8.1 VB(6&A) Learned Items


Dealing with VB6 Data Types
ENUM - in classes CAN be shared from a dll to Office Applications
TYPE you can share a type structure defined in VB6 but you CANNOT pass a Type structure variable from the DLL to VBA.
The only way to pass a variable of Type is to change it to variant->VBA->back to Type Structure.
ARRAYS
Arrays cannot be an optional argument Use CSV or variant type to pass an optional array.

To check if an array is initialized use If ((Not Array) = -1) Returns -1 if NOT initialized
Above notation only works on base variable types, UDT (User-Defined Type Arrays will not work)
If an empty string array is cast into a variant the above will not flag correctly;
Use LenB(Join(VariantArrayName)) = 0 to determine if a String() that is passed as a variant has been initialized.

Variants received as Non-Array Cannot be Cast to Array (Ex: variant = split(variant)) DOESNT WORK.
For this a second Variable Dim VariantArray() as ?? need to be setup and only If Then structure will work
Example; If IsArray(Variant) Then VariantArray = Split(Variant) Else VariantArray = Variant
Compiled vs Debugging VB6 ( Unexpected differences between)
Util.Average Throws a Expression Too Complex during DLL debugging, but works OK when not debugging.
If a Function returns a String() then a For Each <Variant> will cause a compiled DLLs to Crash Excel but not during VB6 debugging.
Never Use On Error Resume Next during a Open FILE operation because EOF() is never reached (endless-loop) with a compiled DLL but works with
VB6 debugger.
Conditional Compilation Arguments
Pre-Compilation Options (ie: #IF something THEN) can be set either locally or project globally.
Local - Use #Const something = <Integer> will apply only to the class/Module.
Be careful since local #Const something = Can be a string BUT global ones can only be integers. (+/- are supported)
Global - Use VB6 or VBA Menu item Project Properties Conditional Compilation Arguments (Under Make Tab in VB6).
Example; See UseEmulator setting below which will set all #If UseEmulator = 1 Then Statements in all modules and classes.
Multiple items can be assigned by separating them with a (:)

Modifying at run time and Importing VBA Code automatically


The CodeModule of a VBComponent allows a lot of Source Code Control and Code changing.
Example Item(5) = a module which is found by looping all the vbcomponents .Name property
ThisWorkbook.VBProject.VBComponents.Item(5).CodeModule.CountOfLines

ThisWorkbook.VBProject.VBComponents.Item(5).CodeModule.Lines(1,10) Dumps lines 1-10 of the module


Importing Source code from an HTTP location into VBA
Public Function Import(ByVal sModuleName As String)
Dim oHTTP As Object, sFirstLine As String, sImportedModName As String, lCnt As Long, bExists As Boolean
Dim oNewComponent As VBComponent, sLine As String, sLines() As String, lLineCnt As Long, bInBEGIN As Boolean
If LCase$(Left$(sModuleName, 7)) = "http://" Then
Set oHTTP = CreateObject("MSXML2.ServerXMLHTTP")
Call oHTTP.Open("GET", sModuleName, , "testdevRpt", "p3T)zpko")
Call oHTTP.send("")
sLines = Split(oHTTP.responseText, vbLf)
For lLineCnt = 0 To IIf(UBound(sLines) > 30, 30, UBound(sLines))
If Left$(sLines(lLineCnt), 9) = "Attribute" Then '//If Attribute Line check for Module Name
If InStr(1, sLines(lLineCnt), "Attribute VB_Name =") > 0 Then sImportedModName = Trim(Replace(Replace(Replace$
(sLines(lLineCnt), "Attribute VB_Name = ", ""), """", ""), Chr(13), ""))
sLines(lLineCnt) = "" '//Blank out Attribute lines
End If
If Left$(sLines(lLineCnt), 7) = "VERSION" Then sLines(lLineCnt) = ""
If Left$(sLines(lLineCnt), 5) = "BEGIN" Then bInBEGIN = True
If bInBEGIN And Left$(sLines(lLineCnt), 3) = "END" Then: bInBEGIN = False: sLines(lLineCnt) = ""
If Left$(sLines(lLineCnt), 1) = "'" Then Exit For
If bInBEGIN Then sLines(lLineCnt) = ""
Next
With ThisWorkbook.VBProject.VBComponents
For lCnt = 1 To .count
If LCase$(Trim(.Item(lCnt).name)) = LCase$(sImportedModName) Then
MsgBox "Module '" & sImportedModName & "' already exists in this job."
bExists = True
End If
Next
If Not bExists Then
Set oNewComponent = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule)
oNewComponent.name = sImportedModName
oNewComponent.name = "Datalog"
oNewComponent.CodeModule.AddFromString Join(sLines, vbLf)
End If
End With
End If
Set oHTTP = Nothing
End Function

Grabbing object from Excel VBA into VB6 automatically (TheHdw & TheExec) without passing the object.
Note: The VBA call function that returns the object must be a function (ie: It cannot be a property get)
If TheHdw Is Nothing Or TheExec Is Nothing Then
'vvv[ Get TheHdw & TheExec Objects from Excel ]vvvvvvvvvv
Dim ExApp As Excel.Application
Set ExApp = GetObject(, "Excel.Application")
Set TheHdw = ExApp.Run("tl_tm_GetTheHdw")
Set TheExec = ExApp.Run("tl_tm_GetTheExec")
Set ExApp = Nothing
'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
End If

Excel crashes when VB6 DLL Module has global names conflict with VBA names
Its always a good idea to make VB6 modules Private to the VB6 Project.
Option Explicit
Option Private Module '//Prevent module clashes with Excel VBA - Keeps Module private to this Project.
Notes about VB6 Events (ie: Private WithEvents OBJ as CLS & Public Event Something())
Events CANNOT be handled in a Module (Must be contained in classes)
Object that trigger or handles Events must be put into a class.
Objects must be early-binded (late-binding doesn't cause events to trigger)
The class containing the Handling object Public WithEvents OBJ as CLS must also contain all Event handlers
An object with events cannot be passed into a class that handles the events
All object variables must reside in the same class with the event handling subs.
Event handler subs can objects CAN be Private
Any object variable WithEvents cannot be assigned within a TYPE structure.
When events don't work (something is out of place) there is no error trapping/messages available that I know of.

8. INDUSTRIAL CONTROL SYSTEMS (ICS)


Types
SCADA
DCS
PLC
RTU

+ Supervisory control and data acquisition


+ Distributed control system
+ Programmable Logic Controller
+ Remote Terminal Unit

Mostly composed of remote terminal units (RTU) across larger areas geographically
Generally includes a network of PLC controllers
Micro-controller device for industrial use
Device control with an interface to DCS or SCADA systems

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki ICS


http://en.wikipedia.org/wiki/Industrial_Control_System
Wiki PLC
http://en.wikipedia.org/wiki/Programmable_logic_controller
Wiki RTU
http://en.wikipedia.org/wiki/Remote_Terminal_Unit
Vendors
http://www.directindustry.com/cat/automation-A.html

8.1 Allen-Bradley PLC


A Rockwell Automation company http://www.ab.com/en/epub/catalogs/12762/2181376/Table-of-Contents.html
PLC-5 System
http://ab.rockwellautomation.com/Programmable-Controllers/PLC-5
Programming Software = Rockwell RSLogix5

SLC-500 System
http://ab.rockwellautomation.com/Programmable-Controllers/SLC-500
Programming Software = Rockwell RSLogix500

FlexLogix / MicroLogix System (Considered Programmable Automation Controller (PAC))


http://ab.rockwellautomation.com/Programmable-Controllers/MicroLogix-Systems
Programming Software = Rockwell RSLogix5000

Illustration 5: AB MicroLogix System


Illustration 6: Allen-Bradley Flex I/O (Distributed I/O Solution)
Distributed I/O = Flex I/O
ControlLogix System (Considered Programmable Automation Controller (PAC))
Programming Software = Rockwell RSLogix5000

Illustration 7: AB ControlLogix PLC


CompactLogix System
Programming Software = Rockwell RSLogix5000

Illustration 8: AB CompactLogix PLC


SoftLogix System
PC Host Controller Software
Distributed I/O = PLC controls I/O modules in another panel located elsewhere.
Flex I/O ( believe PLC Remote Adapter woks on DeviceNet Communication)

Point I/O
CompactBlock LDX

Communications
EtherNet/IP
ControlNet
DeviceNet
Universal Remote I/O
DH+, DH-486 (RS-232)

Software (Rockwell Automation)


RSLogix
= Ladder-Logic editor
RSLinx
= Connects RSLogix Programming software to the PLC-Controller
RSView
= Creates operator interfaces / human machine interface (HMI)
RSNetWorx ???

Other Software of Interest


HMI Human Machine Interface (ie: Operator interfaces)
Various Solutions
@ http://discover.rockwellautomation.com/IS_EN_Performance_Performance_Visibility.aspx
RSView
@ http://www.rockwellautomation.com/rockwellsoftware/performance/view32/overview.page
Wonderware InTouch @ http://software.invensys.com/wonderware/

8.2 Siemens
STEP 7
CONFIGURATOR

SIMATIC PLC Series


Appears to be related to sharing bits with HMI Software

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------http://www.pcschematic.com/en/electrical-cad-design-drawing-software/siemens-simatic-plc-et200s-electrical-cad/simatic-et200-plc-configurator.htm

8.3 Omron
Syswin
CX-Programmer
WINNT

(.swp extension files) Legacy Software


CX-One (demo?)
(.cxt or .cxp extension files)
Console connection program

For C-Series Omron PLCs

8.4 Ladder-Logic on PLC


PLC is programmed using Ladder-Logic which closely resembles the wiring of relays

Ladder-Logic components
Rungs (horizontal lines span edge-to-edge)
Nodes (Internal Input / Output Points bits)
Inputs ( I:1.0 would be found on the PLC-Controller as ??? )
Outputs ( O:2.0 would be ??? on the PLC I/O Rack )
Vendor Specific Software is Used to Program ladder-logic
Allen-Bradley RSLOGIX
Omron
CXP, SYSWIN
(Believe NTWIN is come kind of Omron Table)
Siemens
STEP 7

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Diagrams here include Ladder-Diagrams and how they relate to Gate Logic Circuits http://www.allaboutcircuits.com/

8.5 Human Machine Interface (HMI)


HMI(s) could also be called an Operator's Interface Panel
Typically PLC(s) are programmed using Ladder-Logic and often User-Based control knobs/settings is offered through a Human Machine Interface (HMI)
Allen-Bradley (Rockwell Software)
PanelBuilder
Is design software used to program a special embedded system by Allen-Bradley called the Panel
RSView
Is HMI design software that executes on a standard PC
Invensys Wonderware
IAS
InTouch

A Company specifically for HMI Interfaces that supports various PLC Manufacturers out there.
Industrial Application Server (by ArchestrA)
HMI development software

Wonderware FactorySuite
Wonderware System Platform
Appliation Server
Historian
Information Server
Device Integration Products

OS specifically for wonderware


Executes InTouch Applications (Like Java Engine) Called StandAlone InTouch

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------https://wonderwarepacwest.com/


http://software.invensys.com/wonderware/
https://www.youtube.com/watch?v=pGtB7E4jBRc
Invensys Wonderware - System Platform for Beginners

8.6 Instrumentation
Motor Control
Starter
Contactor
Drives
VFD
Encoder
Meger

Safe starts a large-load motor and protects against under-voltage overload protection
Heavy current relay
Sometimes short for VFD or to describe large scale VFD.
= Variable Frequency Drives
Adjusts AC frequency and voltage to produce motor speed control
Measures motor rotations / speed
Hand-Held test equipment to measure wire insulation (Commonly used to find a faulty motor)

Valves
Solenoid Valves
I/P Transducer
Butter Fly Valve
Angle Seat Valve

= Commonly used device the PLC activates to turn on/off air pressure to devices like pneumatic vales / cylinders (rams) and etc.
= Converts electrical current/voltage to output pressure (I/P= Current Pneumatic Pressure)
= 90-degree angle pipe valve
= Common Pneumatic actuated tank outlet valve

Illustration 9: I/P Transducer

Illustration 10: Solenoid Valves

Sensors ( Transducers )
Condition
Temperature
RTD = Resistance temperature detectors
Thermo-couples
Thermisters
Pressure
Level
Flow
Speed
HVAC
pH Sensor
Proximity
Capacitive( Non-metal detection )
Inductive ( Metal object detection )
Photoelectric (Beam or Reflective)
Ultrasonic ( Reflective Sound Level of water in tank )
Switches
Limit Switches
Safety Interlock switches
Flow
EMF Electromagnetic Flow Meter (ie: MagMeter)
UFM = Ultrasonic Flow Meter

Acronyms
CIP = Cleaning In Place
An equipment cleaning process that doesn't require tear-down or removal (Flush/Clean pipes with chemicals)
SIP = Sterilization In Place

Illustration 11: PLC Panel with ControlLogix PLC(Top), VFDs(Center) and Starters(Bottom)

9. NETWORKING
IEEE Committees
802.3
802.11 / 802.16 / 802.20
Cellular

= Ethernet
= Wireless Local Area Networks (WLAN)

9.1 IT Distributed Management (DMTF)

DMTF
DMI
MIB
SNMP

= Distributed Management Task Force (IT Enterprise Infrastructure Technology for containing routers, printers, and etc... on a common network)
= Desktop Management Interface
= Management Information Base/Database
= Simple Network Management Protocol

The DMTF DMI MIB provides the framework for accessing DMI instrumented information and receiving Desktop Management Interface (DMI) indications
through an SNMP/DMI Mapping Agent.

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Wiki DMTF @ http://en.wikipedia.org/wiki/Distributed_Management_Task_Force


Wiki MIB @ http://en.wikipedia.org/wiki/Management_information_base
OID Tree @ https://support.ipmonitor.com/mibs_byoidtree.aspx

9.2 Cellular Networking


1G Networks (1st Generation Networks)
AMPS
+ Advanced Mobile Phone Service
2G Networks (Mostly TDMA based)
TDMA
+ Time Division Multiplexing
DAMPS
= Digital AMPS
also known as TDMA and can also use first-generation AMPS Service

CDMA IS-95 = by Qualcomm


GSM
= Global System for Mobile Communications standard; The most popular 2G network standard.
802.11 Access points are Towers
2.5G Networks (Mostly TDMA based)
TDMA (Time-division) Multiplexing
Enhanced networks and handsets (GPRS Services and Handsets)
Wireless internet applications started (previously text-based)
email, calendar, contact lists, instant messaging, still/moving images, job dispatch, remote LAN, and file sharing
Vehicle positioning applications
3G Networks (Mostly CDMA based)
CDMA Multiplexing
= Code-division multiplexing (All nodes same freq but each has unique chipping sequence Only one device accepts signal)
First attempt at global standard (Third-Generation Partnership Program (3GPP)) Resulted in 3-different standards
CDMA2000
Wide-band CDMA (WCDMA)
Europe used Universal Mobile Telecommunications Systems (UMTS)
Enhanced Data Rates for Global Evolution (EDGE)
International Mobile Telecommunication-2000 (IMT-2000) standard was approved by International Telecommunication Union (ITU)
Features
High (144Kbps), Full (384 Kbps), and Limited (2 Mbps) mobility bandwidth
QoS (IP-based) support from end-to-end

4G Networks
FDMA (Frequency-division) Multiplexing

--[ References ]---------------------------------------------------------------------------------------------------------------------------------------------------Cellular Network Standards @ Wiki http://en.wikipedia.org/wiki/Template:Cellular_network_standards


Links
Bluetooth
www.bluetooth.com
CDMA Development Group (CDG)

www.cdg.org

ETSI, for HIPERLAN/2 specifications

www.etsi.org

IEEE 802.15

www.ieee802.org/15/

IEEE 802.11

www.ieee802.org/11/;
www.standards.ieee.org

Infrared Data Association (IrDA)

www.irda.org

International Mobile Telecommunication-2000 (IMT-2000)

www.imt-2000.org

International Telecommunications Union

www.itu.int/home/index.html

Mobitex Operator Information

www.mobitex.org

QUALCOMM CDMA

www.qualcomm.com/cdma/index.html

Third-Generation Partnership Project (3GPP)

www.3gpp.org

Third-Generation Partnership Project 2 (3GPP2)

www.3gpp2.org

3G Americas

www.3gamericas.com

3G information

www.3g.co.uk

Universal Mobile Telecommunications System (UMTS)

www.umts-forum.org

Wi-Fi Alliance

www.wi-fi.org

9.3 Area Networking (LAN/WAN)


Overview
Network Architectures
Peer-to-peer
No centralized area of control
Client/Server
Centralized control device (Server)
Hybrid
Both Peer-to-peer and Server/Client Architectures
Network Topology Is the physical arrangement of connected devices and connection medium (e.g. Cable, Wireless) and distance between devices
Internetwork
= 2+ Networks (ie: LANs) connected together via a Router and configured to use logical addressing (IPv4 or Ipv6)
Segmentation = Internetworks are divided into network segments (Logically[IP] and Physically[MAC]) for better performance (See IP about network
segmentation)

Service Industry Terminology


SAP / Demarc
CPE
DTE

+ Service Access Point / Demarcation Point


+ Customer Premises equipment
+ Data Terminal Equipment

Service Providers connection point to CPE begins


Leased equipment from service provider at customers site
Customer-Site equipment (e.g. modem, hosts, printers, etc...)

DCE
CSU
DSU

+ Data Communication Equipment


+ Channel Service Unit
+ Data Service Unit

Equipment of the Internetwork (e.g. Routers, Switches, etc...)

M2M
NMS
IoT
CO / POP
Local Loop
Toll Network
MTU

+ Machine to Machine
+ Network management stations
+ Internet of Things
+ Central Office / Point of Presence
- Closest CO Demarc
= Trunk line in providers network
+ Maximum Transmission Unit

Domain
AS
ES
IS

Customer network to providers network

= Collection of networks under common administration and sharing a common routing strategy
+ Autonomous System (ie: Domain)
+ End System
Does not preform routing or forwarding (e.g. Printers, Workstations, Servers)

+ Intermediate System Preforms routing or forwarding (e.g. Routers and Switches)


Intradomain IS
= Communicates only within the domain
Interdomain IS
= Communicates within and between domains

Illustration 12: Internetwork - Various networks connected together

Network Category Naming


LAN + Local Area Network
Ethernet
Token Ring

= typically Owned by a company / person

WAN + Wide Area Networks


= typically Leased networks by a service provider
Frame Relay
High-Speed Serial Interface
Integrated Services Digital Network
Point-to-Point Protocol
Switched Multimegabit Data Service
Synchronous Data Link Control and Derivatives
X.25
Digital Subscriber Line (DSL)
WPAN + Wireless Personal Area Network

IrDA (Infrared Data Association)


Bluetooth
IEEE 802.15
WLAN + Wireless Local Area Networks
WiFI= IEEE 802.11 Wireless LAN
802.15 (1Mbps)
802.11 a/g (54Mbps)
802.11b (5-11 Mbps)
WWAN
WMAN

+ Wireless Wide Area Network (Mid to Long Range / Cellular Standards (Outdoor Networks))
+ Wireless Metropolitan Area Networks

VPN + Virtual Private Networks


= allows private networking across the Internet medium
Remote Access = Telecommuters access to corporate network
Site-to-Site
= Connection to backbone over public internet instead of using WAN or Frame Relay
Extranet
= B2B (Business to Business) limited access to a corporate network
VLAN + Virtual Local Area Network = Reserving a set of Switch Ports for an entirely independent network segment
Allows switches to break up broadcast domains (Usually done by routers)
A router must be connected between VLAN networks to obtain cross network communication
VTP
= VLAN Trunk Protocol
Ad-hoc

= No Base Router Node to Node connection (e.g. Only a Crossover Cable / Hub )

Network Device Categories


Residential
= Personal/Home
Small Office Home Office (SOHO)
= Routers in this category come equipped with Internal Switch / Firewalls / DHCP / DNS / etc.. services
Enterprise
= Has to work all the time with limited features (Routers are simplistic)

Network Devices

Illustration 13: Network Devices


NIC
= Network Interface Card; Supplies host with network physical plug-in (e.g. Ethernet Card in a PC-Host)
Hub
= (ie: Multiport Repeater) All-Ports on single Collision Domain
All-Ports on single broadcast domain
Gateway
= Access port to external mainframe / network (Broadcast Domain) sometimes used equivalently with Router
Switch
= (ie: Multiport Bridge)
Per-Port Collision Domain
All-Ports on single broadcast domain; Unless VLAN(s) exist
Data-Link Layer-2 Device
Locates and tracks devices per-port using a Physical MAC-Address
Trunk Port (ie: GBIC/Daisy Chain/Uplink Port) If a device isn't on the local switch the trunk port will search an outside-other connected switch for
the device
UN-Managed Switch = No Console; All configurations are done automatically
No QoS/CoS Configuration
Quality/Class of Service Prioritizes packets (e.g. VoIP then Video then File Transfer)
No routing-loop trapping
Where a slave switch is not plugged into the trunk-port causing a endless communication loop
Managed Switch
= Console Configurable / Hard-code settings are possible
Speed (10Mbps, 100Mbps, 1Gbps ) Back-Plane Speed rating is the total cross-talk speed of all ports together (ie: Main-board connecting all
ports)
Duplexing (Half/Full Duplex)
Legacy Half-Duplex supports talk -OR- listen whereas Full-Duplex supports talk -AND- listen at the same
time.
VLAN (Port-Group Networks)
Only available on Managed Switches; Group ports are entirely separated and cannot communicate with
each other
Router

Network Layer-3 Device


Per-Port Broadcast & Collision Domain using logical addressing (Sometimes refereed to as a Layer-3 Switch)
Maps & Connects together
WAN(s) using a serial interface like V.35 physical interface / LAN(s) / VLAN(s) / Sub-nets (Doesn't care about hosts;
Just networks)
Routing Table Map
Network Address Device address in various addressing protocols / Ipv4, Ipv6, IPX, etc...
Interface
Exit interface packet will take when destined for a specific network
Metric
Physical distance to remote network
Routing Table Data Gathering
Static Routing
= Administrator hand-types the routing table
Dynamic Routing= Routers update each other through the network
Preforms
Packet Switching
by means of logical addresses (IPv4 and IPv6)
Packet Filtering
by means of an access list
Internetwork Communication
Path Selection
by means of a routing table ( map of the Internetwork )

Communication Basics
Device Addressing = Scheme used to identify a network device
Logical
Typically; IP-Address (IPv4 or IPv6 )
Physical
Typically; MAC-Address
Collision Domains
= Parallel connected devices all receiving the same line signal; only one device can communicate at a time; Destination NIC filters
the traffic
Hub
All-ports are on the same Collision Domain
Switch
Per-port Collision Domain (Layer-2)
Router
Per-port Collision Domain (Layer-2)
Private Collision Domain = One host per Port (Private within the plug/port)
Broadcast Domains
Network)
Hub
Switch
Router

= Group of devices that all receive the Broadcast signals (ie: Signals sent to IP - ###.###.###.255 or MAC xx:xx:xx:ff on a Class C
All ports are on the same Broadcast Domain
All ports are on the same Broadcast Domain
Per-port Broadcast Domain (Layer-3)

Domain Networks use the Domain Name Service (DNS) to obtain destination MAC address
MS-Windows also allows a generic Data-Link Broadcast (ie: IP - ### . ### . ### . 255 , MAC ff:ff:ff:ff ) for Host Name to MAC address resolution
Source Device Sends:
Src: 192.168.0.2 - Dst: 192.168.0.255(ie: Data-Link Broadcasting Address) - Protocol: NBNS - Info: Name Query
NB<DstHost><00>
Destination Response:
EthernetII,Src:192.168.0.2(00:14:22:be:18:3b),Dst:Broadcast(ff:ff:=ff:ff:ff:ff)
Source Device Sends:
Src: 192.168.0.2 - Dst: 192.168.0.255 - Protocol: ARP - Info: Who has 192.168.0.37 Tell 192.168.0.2
Destination Response:
Src: 192.168.0.3 Dst: 192.168.0.2 Protocol: ARP Info: 192.168.0.3 is at 00: db:db:99:d3:5e
Destination Response:
Src: 192.168.0.3 Dst: 192.168.0.2 Protocol: NBNS Info: Name query response NB 192.168.0.3
Communication Types
Layer-2/Hardware Broadcasts
Layer-3 Broadcasts
Unicast
Multicast

= Using MAC Wild-Card (ff) to address all nodes on a LAN ( Broadcast doesn't go past any routers / LAN only )
= Using IP Wild-Card (255) to signal all nodes on a LAN
= Single destination host (e.g. DHCP)
= Single source many devices on different networks (Subscribed in a group address list )

Reference
Cisco Wiki @ http://docwiki.cisco.com/wiki/Main_Page

9.3.1 OSI Protocol Model


OSI Model
PDU

= Open Systems Interconnection Communications Model (7 layers)


= Protocol Data Unit General term describing a protocol attachment (ie: In the process of wrapping and encapsulation protocols)

Illustration 14: OSI Model

Protocol

= Formal rules of behavior/Standards that define precisely the data communication

methods/rules
Protocol Categories
Interconnection
LAN Protocols
WAN Protocols
Network Protocols

(ie: Router/Switch Protocols) Handle data transfers and routing from point to point

Various upper-level (ie: Application) protocols that exist in a Protocol Suite

Protocol Documentation
IANA
Internet Assigned Numbers Authority Group that carries many of the protocols and standards used on the Internet
IETF
Internet Engineering Task Force
The group that creates Internet protocols and standards published as RFC(s)
RFC Request for Comments
Documentation scheme used to document a technology and/or standards
FYI
= For Your Information
An RFC that is for Information
BCP
= Best Current Practices
An RFC describing a Best practice
STD
= Standards
An RFC Numbered separately and used for describing an Internet Protocol
TS = Technical Specification
A STD RFC that defines the protocol; Progressively staged as 1 st Proposed, 2nd Draft, then 3rd
Internet Standard.
AS = Applicability Statement
A STD RFC Document that describes when the protocol is to be used (e.g. Required,
Recommended, Elective )
Reference
Wiki List of Network Protocols (OSI model ) http://en.wikipedia.org/wiki/List_of_network_protocols_%28OSI_model%29

A. Application Layer-7 (HTTP/POP3)


Software implemented (e.g. Firefox, Outlook, Chrome, etc....)
TCP/UDP Port Numbers that define the application protocol
Virtual Port Numbers
Transport Protocols
Socket
Socket Pair
task
Registered Ports
System Specific

= TCP/UDP:Port# ( 0-1023 reserved ); like virtual mail-boxes for Application protocol specific delivery; Used by the
= IP : Port# (e.g. 192.168.10.20:80) Created for each communication task
= Includes the Socket identifier of both source and destination requiring at least one unique item per communication
At http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
View C:\Windows\System32\Drivers\Etc\SERVICES

Common Ports to Know


21 = FTP (TCP)
23 = Telnet (TCP)
25 = SMTP (TCP)
53 = DNS (TCP/UDP)
69 = TFTP (UDP)
70 = Gopher(TCP/UDP)
79 = Finger (TCP/UDP)
80 = HTTP (TCP)
110 = POP3 (TCP/UDP)
119 = NNTP
161 = SNMP (UDP)
389 = LDAP (TCP/UDP)
443 = HTTPS (TCP)
993 = IMAP4
5353 = MDNS (TCP/UDP)

File Transfer Protocol


Telnet Protocol
Simple Mail Transfer Protocol
Domain Name Service Protocol
Trivial File Transfer Protocol (Allows remote file boot-up / OS )
RFC4146
World Wide Web
Post Office Protocol V3
Network News Transfer Protocol
Simple Network Management Protocol
Lightweight Directory Access Protocol
Secure WWW
Interactive Mail Access Protocol
Multicast DNS Responder IPC (DNS has many flavors)

B. Presentation (Layer-6)
Presentation Layer= Manages a common data representation method between systems for communication data translation (OS-Layer)
Big / Little Endian Negotiates the Byte Order between systems
Encryption
Enables encrypted data to be deciphered at the destination
Compression
Enables data compressed at the source to be DE-compressed at the destination
Text / Data
Negotiates common character sets (ie: US-ASCII, EBCDIC)
Video
Like QuickTime, Motion Picture Experts Group (MPEG)
Graphics
Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG), Tagged Image File Format (TIFF)
Protocols
NVT
= Network Virtual Terminal (Subset of the Telnet Specification)
IBM NetBIOS
XDR
= Sun's External Data Representation
DCE RPC
= Distributed Computing Environment's Remote Procedure Call

C. Session (Layer-5)
Session Layer
= Establishes, Manages, and Terminates Communication Sessions between two systems (ie: Service Requests / Service
Responses) per application
ZIP
= Zone Information Protocol
AppleTalk
= Coordinates the name binding process

SCP
DECnet Phase IV

= Session Control Protocol


= ??

Duplexing Control
Simplex
Half Duplex = Hubs
10Mbps / 10BaseT ; Uses one set of wires ( Send -or- Receive )
Full Duplex
= Switch / Crossover Cable 100Mbps; Uses two sets of wires ( Send -and- Receive ) ; No collisions

D. Transport Layer-4 (TCP/UDP Data Segment)


Provides
= Transport Header + Data (ie: Segment) Network Layer-3
Segmentation
Sequencing
Virtual circuits
Data Integrity
Connection-less Network Service = No flow control, CRC or ACK
Connection-Oriented
= Uses Handshaking, sequencing, acknowledgment and Flow Control
Buffering
Windowing
= A window is the quantity in bytes the transmitter can send without receiving an ACK (TCP/IP allows 1
or 3 bytes per ACK)
Congestion Avoidance
QoS/CoS
= Quality/Class of Service Packet Prioritizing; VoIP/Video first then file transfer
Protocols
User Data-gram Protocol (UDP)
Transmission Control Protocol (TCP)
Resource Reservation Protocol (RSVP)

= No reliability; Used occasionally for a status update broadcast (like printer toner low)
= Uses Sequencing, ACK, and Windowing flow control for reliability

E. Network Layer-3 (IP Packet Data)


Provides Logical (e.g. IP) network device addressing and routing (ie: Routers / Data & Routing Information)

Interconnection Protocols
IP
ICMP
ARP
RARP
Proxy ARP

+ Internet Protocol
+ Internet Control Message Protocol
+ Address Resolution Protocol
+ Reverse Address Resolution Protocol
- Allows Hot swap-able router additions

= Routed Protocol; Logical addressing and physical location for path determination
= Runs on top of IP ( Generated by Routers ); ICMP Echo is commonly named Ping
= IP MAC Address resolution (Doesn't use IP Transport)
= MAC IP Address resolution
= See also Cisco Host Standby Router Protocol (HSRP)

Routing Protocols = Used to build / maintain routing tables


RIP
+ Routing Information Protocol
EIGRP
+ Enhanced Interior Gateway Routing Protocol
OSPF
+ Open Shortest Path First

Other Protocols
IPX
MPLS

= Legacy Novell IP-Technology that causes a lot of chatter


= Multiprotocol Label Switching ( Faster than a routing table )

E.1 Internet Protocol (IP)


IP Octet / Versions
IPv4 = Addresses network devices using 4 octets/bytes ( e.g. 192.168.10.20 )
IPv6 = Addresses network devices using 6 octets/bytes ( e.g. 192.168.30.20.10.1 )

IP-Class Schemes = An IP-Address has various schemes (ie: IP-Class) that is identified by it's first octet range
Class A = 0 127
Prefix 0
Subnets CIDR /8 /15
Class B = 128 191 Prefix 10
Subnets CIDR /16 /23
Class C = 192 223 Prefix 110 Subnets CIDR /24 /30 (2-bits for hosts are required)
Class D = 224 239 Multi-cast
Class E
= 240 255 Scientific
** e.g. 192.168.0.1 is a Class C IP which means its on Network (ie: LAN) 192.168.0 host 1

Wild-Card (0)
0.0.0.0
1.1.1.1
0.0.16.23
1.1.16.23
127.0.0.1

= Typically used to address an entire Network (e.g. Class A: 10.0.0.0, Class B: 172.16.0.0, Class C: 192.168.10.0)
Default route or any network
All 1s Broadcast / Limited broadcast; reacts same as 255.255.255.255
This(0) network where network bytes are (0)
All(1) networks node 16.23
Loop-back (local node)

Wild-Card (255)
255.255.255.255
172.16.255.255

= Wild-card for a Broadcast Signal


Broadcast signal destined for All networks; All nodes
Broadcast signal destined for All Subnets and hosts on network 172.16.<xxx . xxx>

Private IP
= Addresses for local network only ( Not routable )
NAT = Network Address Translation Converts Private IP to a routable one
Static NAT
= One to one mapping between local and global addresses
Dynamic NAT
= Map unregistered IP addresses to registered IP(s)
PAT (ie: NAT Overloading)
= Port Address Translation Most popular; Maps multiple unregistered IP-Addresses to a single
registered IP-Address

Tunneling Protocols for VPN(s)


L2F
+ Layer 2 Forwarding
PPTP
+ Point-to-Point Tunneling Protocol
L2TP
+ Layer 2 Tunneling Protocol
GRE
+ Generic Routing Encapsulation
IPSec
= IP Secure Transfer
require GRE tunnel then IPSec)
AH = Authentication Header
ESP = Encapsulating Security Payload

By Cisco; Used in Virtual Private Dial-Up Networks (VPDN) proceeded by L2TP


By Microsoft; data transfer from remote networks to corporate networks
By Cisco & Microsoft; Replacement of L2F & PPTP (Merging the two)
By Cisco; Create point to point links that allow variety of protocol encapsulation in IP tunnel.
A standard set of protocols for authentication & encryption services (IP-based only; Others
Authentication is part of each data packet
Integrity check on the data packet

All IP-Network Protocols are wrapped within an IP Header


ICMP
=1
Management and Messaging for IP ( Network status messaging including Buffer-full, Hops, Ping, Trace-route (ie: >tracert )
IP in IP
=4
IP Tunneling
TCP
=6
IGRP
=9
UDP
= 17
EIGRP
= 88
OSPF
= 89
Ipv6
= 41
GRE
= 47
L2TP
= 115
Layer 2 Tunneling Protocol

Complete List @ http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml


E.2 Subnet
Subnet is the bit-wise masking of the IP-Address's host portion which divides IP-Addresses into separate LAN(s)
Types
Classful
= All nodes use the same subnet mask
Protocols RIPv1 and IGRP are Classful Only Routing protocols
Classless (VLSM) = Variable Length Subnet Masks
Protocols RIPv2, EIGRP and OSPF contains the subnet mask for each router
interface)
CIDR
= Classless Inter-Domain Routing
Syntax: <IP>/# = Where # is the number of 1s in the IP-Address mask Left Right
Class C Network /25 Example
Mask
1111-1111 . 1111-1111 . 1111-1111 . 1000-0000 . 0000-0000
Dec 255.255.255.128.0
255.255.255.128/25
^-- Subnet bit differentiates the (2) Class C Subnet
Subnet(0)
Start:
192.168.10.1
192.168.126
Broadcast IP: 192.168.127
Subnet(128) Start:
192.168.10.129
192.168.10.254
Broadcast IP: 192.168.10.255
Class C Network /26 Example
Mask
1111-1111 . 1111-1111 . 1111-1111 . 1100-0000 . 0000-0000
Dec 255.255.255.192
255.255.255.192/26
^^-- Subnet Bit differentiates the (4) Class C Subnet
Subnet(0)
Start:
192.168.10.1
192.168.10.62
Broadcast IP: 192.168.10.63
Subnet(64) Start:
192.168.10.65
192.168.10.126
Broadcast IP: 192.168.10.127
Subnet(128) Start:
192.168.10.129
192.168.10.190
Broadcast IP: 192.168.10.191
Subnet(192) Start:
192.168.10.193
192.168.10.254
Broadcast IP: 192.168.10.255
Subnetting /30 is good for WAN that have 2-Gateways since the two will be on their own network

CIDR

CIDR

F. Data-Link Layer-2 (MAC Frame Data)


Data-Link Layer
= Provides Framing and placing data on medium (Switches are Layer-2 Devices)
Physical Addressing MAC Address
Network Topology
Defines how devices are to be physically connected (ie: Bus/Ring topology)
Error Notification
Alerts upper-layer protocols of Data-Link layer errors
Frame Sequencing
Numerically orders frames so they can be reordered correctly
Flow Control
LLC Support services that moderates and keeps in-sync communication between the two devices
Sub-Layers (Divided by IEEE)
LLC
= Logical Link Control
MAC
= Media Access Control

Supports TCP/UDP Port protocols at the data-link layer (see IEEE 802.2 Spec)
Provides protocol access to the physical network medium.

MAC Frame = Bits Bytes Frames


Packets from the Network layer become a MAC Frame with CRC 802.3 frames or Ethernet frames
Ethernet II
Preamble SFD DA
SA
Type
Data FCS
8-bytes
6-bytes 6-bytes 2-bytes ?
4-bytes
802.3 Ethernet Preamble SFD DA
SA
Length Data FCS
8-bytes
6-bytes 6-bytes 2-bytes ?
?

Preamble
SFD/Sync

= Start Frame Delimiter

DA + Destination Address ff:ff:ff:ff:ff:ff:ff address is a Ethernet Broadcast going out to all devices
SA + Source Address
Length (802.3)
= Must be used with a proprietary LAN (e.g. IPX)
Type (Eth II)
= Network layer protocol type (0x800 = IPv4, 0x86DD = IPv6 )
Data
FCS

= Packet data (64 to 1500 bytes)


= Frame Check Sequence (CRC)

Frame Data

= Bits of Data containing all other OSI layers

MAC (ie: Hardware) = Media Access Control address (e.g. F1:F2:F3:|F4:F5:F6| )


bit 47 - I/G = Individual -or- Group
0 = Address is a device MAC address
1 = Address is a broadcast or multicast address
bit 46 - G/L = Global/Universal -or- Local
0 = Globally administered address 1 = Locally governed administered address (DECnet)
45-24 - OUI = Organization Unique Identifier 3-bytes assigned by IEEE
23-0 Device = Lower 24-bits is manufacturer assigned device code locally administered (often the same 6 hex digits are the end of the serial
number)
MAC addresses never go through a router (LAN access only)
MAC Address (Hardware static) = Hardware Address
Name Resolution (Host Name to IP Address resolution)
Domain Name Service (DNS) Resolution
MS-Windows Networking (W/O DNS) Just
Router Connected = IP-Address 192.168.0.255 MAC-Address (Data link layer broadcast) ff:ff:ff:ff:ff:ff
Beginning of MAC Address is Manufacturer and Serial Number on the end.
MAC address spoofing?

Routing Protocols
STP + Spanning Tree Protocol Used to stop network loops from occurring
UN-Managed doesn't have routing loop prevention (When two switches are connected together using non-Trunk ports)
Allows switches to talk to each other and route packet fastest way from A B
Prevents routing loops

WAN Protocols
Serial Interface Protocols
HDLC

+ High-Level Data-Link Control Protocol = ISO-standard encapsulation for data on synchronous serial links (Point-to-Point Protocol)

PPP
+ Point-to-Point Protocol
LCP
+ Link Control Protocol
NCP
+ Network Control Protocol
IPCP
IPXCP

Frame Relay

= Links for carrying HDLC (e.g. Asynchronous (dial-up) / Synchronous (ISDN) serial media)
= Method of establishing, configuring and terminating P2P connections
= Establishing/Configuring multiple network layer protocols (routed protocols) on a P2P

+ Internet Protocol Control Protocol


+ Internetwork Packet Exchange Control Protocol

Data-Link/Physical Protocol; successor to X.25; Provides dynamic bandwidth and congestion control

Classified as a Non-Broadcast Multi-Access (NBMA) Network; Doesn't send any broadcasts like RIP updates
Roots of X.25; It is a Leased-Line network (but not a HDLC/PPP network) TELCO Network
Is a Packet-Switched technology (ie: Splits one communication path into multiple paths / inputs to routers)
CIR
= Committed Information Rate Guaranteed maximum bandwidth
Packet Encapsulation
Cisco
= Used if both devices connected are Cisco devices

IETF = Internet Engineering Task Force


Creates Virtual Circuits
Permanent Virtual Circuits (PVC) = Static mapping
Identified to DTE end devices by Data Link Connection Identifiers (DLCI)
IARP
= Inverse ARP is used to map DLCI to an IP Address in Frame Relay Networks
LMI = Local Management Interface Signaling standard between router and first Frame Relay switch
Switched Virtual Circuits (SVC)
Others
ISDN
LAPB
LAPD
HDLC
PPPoE
Convergence
PoE
VoIP

= Like a phone call only established when data needs transferred (for Private usage)

+ Integrated Services Digital Network


+ Link Access Procedure, Balanced
+ Link Access Procedure, D-Channel
+ High-level Data Link Control
+Point-to-Point Protocol over Ethernet

= Voice + Data over existing phone lines up to T1


= Used with ISDN as D-Channel access
= HDLC is manufacturer proprietary
= Encapsulates PPP frames into Ethernet Frames for ADSL services

= Using Ethernet for irregular purposes ( other than file transfer )


Power over Ethernet ( Device power carried on Ethernet; Standards versions V1, V2, V3 )
Voice over IP

G. Physical Layer-1 (PHY Bit Data)


Medium
= Physical transmission tools used to deliver information or data (ie: Cabling / Voltage / etc...)
FDDI
= Fiber Distributed Data Interface
Ethernet
= [ IEEE 802.3 ]
Token Ring
= [ IEEE 802.5 ]

Protocols
Ethernet Protocol

[ 802.3 ]

Cabling
Networking Cables
RJ45 Connector is used in Twisted pair cables
Straight-Through
= Cable is used for host/device to hub/switch/router
Crossover Cable
= is used for no network device PC to PC networking
Rolled Cable
= Fancy word for an RS-232 Cat5 cable used for Network equipment's Terminal Emulation
SAP
+ Service Access Point
=The cable ending/plug standards
EIA/TIA-232 or TIA-449
V.35
= For CSU/DSU connection points
EIA-530
HSSI
= High Speed Serial Interface
G.1 WAN Physical Layer

Terms
HSSI
CATV

= High Speed Serial Interface


= Cable TV lines; Coaxial Cable; HFC Network

DSL
= Digital Subscribe Line
Symmetrical DSL = Up/Download speeds the same
Asymmetrical DSL = Different Up/Download Speeds
ADSL
= ?? (Carries voice/data together)
HDSL
= High-bit-rate DSL
RADSL
= Rate Adaptive DSL
SDSL
= Synchronous DSL (data only)
IDSL
= ISDN DSL (data only)
VDSL
= Very-high-data-rate DSL (Carries voice/data together)
LRE
= Cisco's Long Range Ethernet (Employs VDSL)
MPLS
ATM
Speeds
64Kbps

= Multiprotocol Label Switching


= Asynchronous Transfer Mode ( Protocol used for DSL )

1.544Mbps(T1)
4.5Mbps(T3)
WLAN + Wireless Local Area Networks
802.11 Wireless specification is like hub Ethernet; Uses Half-Duplex over Radio Frequency (RF)
802.11b ( Released ? - 2.4GHz )
Rate Shifting 1, 2, 5.5 and 11Mbps depending on signal integrity
CSMA/CA
= Carrier Sense Multiple Access w/ Collision Avoidance using Request-To-Send (RTS) and Clear-To-Send (CTS)
CSMA/CD
= Carrier Sense Multiple Access with Collision Detection
Modulation via Direct Sequence Spread Spectrum (DSSS)
802.11g ( Released 2003 2.4GHz , 54 Mbps )
802.11b compatible (DSSS Modulation) but delivers 54Mbps on OFDM Access Points (AP)
Modulation by Orthogonal Frequency Division Multiplexing (OFDM)
802.11h
Adds Multiple Input Multiple Output (MIMO) providing 250Mbps.
802.11a ( Released 1999 5GHz , 54Mbps )
Originally very expensive
Rate Shifts of 6, 9, 12, 18, 24, 36, 48 and 54Mbps
Extended as 802.11h adding Transmit Power Control (TPC) (For battery conservation) and Dynamic Frequency Selection (DFS)
Cisco Unified Wireless Solution
WMAN = Wireless Metropolitan Area Networks
FCC Released Frequencies for Public Use
900MHz Referred to as the Industrial, Scientific, and Medical (ISM Band)
2.4GHz Also Referred to as the Industrial, Scientific, and Medical (ISM Band)
5.7GHz Referred to as the Unlicensed National Information Infrastructure (UNII Band)

802.11b/g/n
802.11a/h

9.4 Reference / Tools


Emulation Software
NetSim @ http://netsimk.com/
Cisco Console @ http://www.ciscoconsole.com/free-cisco-lab-simulators.html
Wikipedia
Overlay Network @ http://en.wikipedia.org/wiki/Overlay_network
Failover = Switching to redundant or standby servers @ http://en.wikipedia.org/wiki/Failover
IANA
= Internet Assigned Numbers Authority @ http://www.iana.org
RFC
= Request For Comments
TCP/UDP Reserved Ports @ http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

9.5 Cisco Systems


Cisco Hierarchy Model
Core Layer
Distribution Layer
Access Layer
IOS
SDM

= No tables just fast switching (FDDI, Fast Ethernet, ATM)


= Routers (ie: Workgroup Layer), Routing, Filtering, WAN Access and Core Bridge
= (ie: Desktop Layer) Switches / Hosts

+ Cisco's Internet-working Operating System = A Cisco OS Kernel for Routers / Switches


+ Cisco's Security Device Manager
=Configuration by web interface (EWI = Embedded Web Interface)

CLI
+ Command Line Interface
= CLI Session also called an EXEC session.
Aux Port
Terminal access via Callable Telephone Modem (ie: out-of-band)
Ethernet
Terminal access via Ethernet (ie: In-band)
Serial Port
Terminal access via a serial RJ45
>ip subnet-zero

Class C you get subnets 0, 64, 128 and 192

10. RESOURCES
1. EDA.org
a)
2. Electronic Circuits
a) Circuit tutorials
b) Circuit exampels (DIY)

http://www.eda.org/
http://www.electronics-circuits.com/index.html

c) EDA Links and Resources


3. Free IP-Cores
a) http://www.freemodelfoundry.com/
b) http://opencores.org/
4. Generic Acronyms & Terminology
a) EMI Electromagnetic interference
b) Legacy Products Processors
1st Microprocessor was the Intel 4004
TI 99/4A was 16-bit; TMS9900 @ 3MHz
Commodore-64 was 8-bit; MOS-Technology 6510 @ 1MHz
TRS-80 Color Computer 2 was 8-bit; Motorola MC6809E @ 1MHz
Tandy 1000TL; was 16-bit 80286 @ 8MHz ( Tandy -> AST -> Samsung )
8086(16-bit) / 8088(Is an 8086 with an 8-bit data bus for reverse compatibility)

10.1 Engineering Models

Big Bang Model


Code & Fix
Waterfall
Spiral
Waterfall).

No planning or processes in place before and during the development of a system


Product requirements are defined by no formal processes are in place before the start of development
Process for developing in steps where the results of one step flow into the next step
Process for developing in steps and throughout various steps feedback is obtained and re-incorporated into the process (Open

Embedded System Design & Development Cycle


Phases
Creating the architecture (Block Diagram of Interacting Elements)
Stages
1 Strong Technical Foundation
Research methodologies and standards in the market segment
2 Understand the Architectural Business Cycle
3 Define Architectural patterns and models
4 Define Architectural structures
5 Document the Architecture
Block Diagrams
Overview of major components
Central Processing Unit (CPU) Blocks
Memory Blocks
Input Device Blocks
Output Device Blocks
Bus Pathways
Showing interconnects for data travel and bus control
Schematics
Circuit components (ie: Symbols) and connections
Wiring Diagrams
Physical Layout of a PCB board showing Buses and connection between components
Logic Diagrams
Depicts logic (AND, OR, NOT, XOR) of a circuit
Timing Diagrams
Timing graphs of I/O signals of a circuit
6 Analyze and review the Architecture
Primary architecture tool
Application Software Layer
System Software Layer
Hardware Layer
implementing the architecture
testing the system
maintaining the system

10.2 Market Segments


Embedded Systems often fall within an Embedded Market Segment
Consumer Electronics
PDAs, TVs, Games, Toys, Home Appliances, Internet Applications
Medical
Devices used to diagnose and treat humans
Industrial Automation and Controls
Sensors, Motion controllers, HMI, Switches
Networking and Communications
Hubs, Gateways, Routers
Cell-Phones, Pagers, ATM Machines
Automotive
Devices used in vehicles
Commercial / Home Office
Printers, Scanners, Monitor, Faxes, Copiers, Bar-code readers
Aerospace and Defense

10.2.1 Market-Specific Standards


Hardware Engineers use IEEE for standards mostly However no single entity exists for firmware / software standards
Consumer Electronics
CEA
Consumer Electronics Association

http://www.ce.org/

JavaTV
DVB
MHP
DAVIC
ATSC
DASE
ATVEF
SMPTE
DTVIA
ARIB-BML
OCAP
OSGi
OpenTV
MicrosoftTV

http://www.oracle.com/technetwork/java/embedded/javame/index.html
Digital Video Broadcasting
Multimedia Home Platform
Digital Audio Visual Council (ISO/IEC 16500)
Advanced Television Standards Committee
Digital TV Applications Software Environment
Advanced Television Enhancement Forum
Society of Motion Picture and Television Engineers (DDE-1)
Digital Television Industrial Alliance of China
Association of Radio Industries and Business of Japan
OpenCable Application Forum
Open Services Gateway Initiative
DVB-Compliant

https://www.dvb.org/standards
http://en.wikipedia.org/wiki/Multimedia_Home_Platform
http://www.davic.org/ http://www.iso.org/iso/home.html
http://www.atsc.org/cms/
http://www.atvef.com/
https://www.smpte.org/

http://www.arib.or.jp/
http://www.cablelabs.com/specs/specification-search/?cat=video
http://www.osgi.org/Main/HomePage
http://www.nagra.com/
http://windows.microsoft.com/en-us/windows/understanding-tv-signals-

tuners#1TC=windows-7
HAVi
Home Audio Video Initiative
Medical Devices
FDA
US Food and Drug Administration
http://www.fda.gov/
Medical Devices Directive
Medical Device Communications
IEEE1073
Industrial Automation and Controls
IEC
International Electrotechnical Commission
http://www.iec.ch/
ISO
International Standards Organization
http://www.iso.org/iso/home.html
DICOM
Digital Imaging and Communications in Medicine `
http://medical.nema.org/
Department of Commerce
http://trade.gov/td/health/
The Machinery Directive
Networking and Communications
Ethernet
Institute of Electronics and Electrical Engineers
IEEE 802.3
http://www.ieee.org/index.html
TCP/IP
Transmission Control Protocol / Internet Protocol - RFC 791(IP) & 793(TCP) http://www.faqs.org/rfcs/
PPP
Point-to-Point Protocol
Cellular
http://www.cdg.org/
http://www.tiaonline.org/
HTTP
Hypertext Transfer Protocol
http://www.w3.org/Protocols/Specs.html
SIG-Bluetooth
Bluetooth Special Interest Group
https://www.bluetooth.org/en-us
HTML
Hyper Text Markup Language
Automotive
OPEL
Engineering Material Specifications
https://www.ihs.com/products/design-industry-standards-organizations-

index.html
FMVSS
Federal Motor Vehicle Safety Standards
http://www.nhtsa.gov/cars/rules/standards/
ISO/TS 16949
The Harmonized Standard for the Automotive Supply Chain
http://www.iaob.org/
GM Global
https://www.ihs.com/products/design-industry-standards-organizations-index.html
Ford Standards
same as above
Aerospace and Defense
SAE
Society of Automotive Engineers
http://www.sae.org/
AIA/NAS
Aerospace Industries Association of America
http://www.aia-aerospace.org/
DOD
Department of Defense
DISA
Defense Information Systems Agency
http://www.disa.mil/
JTA
Joint Technical Architecture
Office
TIP/SI
TechnologyTransport Independent Printer/System Interface
IEEE Std 1284.1 1997 IEEE
Postscript
http://www.adobe.com/
ANSI/AIM
Uniform Symbology Specification for Bar Codes
http://www.aimglobal.org/standards/aimpubs.htm

10.2.2 General Purpose Standards


Programming Languages
pJava
Personal Java
J2ME
Java 2 Micro Edition
.NET
Compact Framework
Security
IETF
Netscape Internet Engineering Task Force
SSL
Secure Socket Layer
SILS
Standards for Inter-operable LAN/MAN Security
QA - Quality Assurance
ISO 9000 International Standards Organization

10.3 Embedded System IDE


Integrated Development Environment (IDE)
Freescale
CodeWarrior Development Studio

http://netscape.aol.com/
http://www.ieee802.org/

Uses Eclipse IDE w/Processor Expert Integrated


ARM Processors (ColdFire, ColdFire+, DSC, Kinetis, MPC5xxx, RS08, S08 and S12Z )
http://en.wikipedia.org/wiki/CodeWarrior
http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=CW-MCU10&tid=vanCWMCU10
Kinetis Design Studio (KDS)
http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=KDS_IDE&tid=vanKDS
IAR Systems
https://www.iar.com/iar-embedded-workbench/
mbeddr http://mbeddr.com/
WindRiver http://www.windriver.com/
Crossworks from Rowley http://www.rowley.co.uk/arm/
Nedit http://en.wikipedia.org/wiki/NEdit
Atollic TrueSTUDIO http://atollic.com/index.php/truestudio
Mentor Graphics CodeSourcery http://www.mentor.com/embedded-software/codesourcery
Keil's MDK uVision IDE http://www.keil.com/arm/mdk.asp
Text Editors for Firmware Development
Notepad++
http://notepad-plus-plus.org/
Sublime Text http://www.sublimetext.com/
Slick Edit
Build Tools http://www.throwtheswitch.org/
Wiki Build Tools http://en.wikipedia.org/wiki/List_of_build_automation_software
Eclipse seems to be the most popular IDE

10.4 Symbols
10.4.1 Timing Diagrams

10.4.2 Schematic Symbols

Você também pode gostar