electronics engineering n2no = process of; abstract desired circuit behavior (rtl) → circuit...

55
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. INTRO .........................................................................................................................................................................................1 2. SYSTEM CIRCUITS ................................................................................................................................................................2 2.1 System on a chip (SOC) .........................................................................................................................................2 2.2 System on Programmable Chip (SOPC) ........................................................................................................3 2.2.1 Field Programmable Gate Array (FPGA) ..............................................................................................3 2.2.2 Programmable Logic Devices (PLD) ......................................................................................................4 2.3 Processors ...................................................................................................................................................................4 2.3.1 Market ..................................................................................................................................................................4 2.3.2 Architectures .....................................................................................................................................................4 A. Control Unit (CU) ..............................................................................................................................................5 B. Algorithmic Logic Unit (ALU) .....................................................................................................................5 C. Memory – Instruction Cache .......................................................................................................................5 D. Bit-Numbering (Endianness) .....................................................................................................................5 E. Registers / Timing ...........................................................................................................................................5 2.4 Memory ........................................................................................................................................................................5 2.5 Peripherals ..................................................................................................................................................................5 2.5.1 I2C ..........................................................................................................................................................................6 2.5.2 ISA ..........................................................................................................................................................................6 2.5.3 General Purpose I/O (GPIO) ......................................................................................................................6 2.5.4 Serial Peripheral Interface (SPI) ..............................................................................................................6 2.5.5 Joint Test Action Group (JTAG) .................................................................................................................6 2.5.6 PCI / PCIe ............................................................................................................................................................6 2.5.7 Transceivers ......................................................................................................................................................7 2.5.8 USB .........................................................................................................................................................................8 A. Abstraction Layers ...........................................................................................................................................8 B. Functional Layer ...............................................................................................................................................8 C. Logical Layer .......................................................................................................................................................9 D. Physical Layer .................................................................................................................................................10 2.5.9 VGA Interface Spec .......................................................................................................................................11 2.6 Wireless / Networking .......................................................................................................................................11 2.7 Logic ............................................................................................................................................................................12 2.7.1 7400-Series ICs .............................................................................................................................................12 3. CIRCUIT THEORY ...............................................................................................................................................................12 3.1 Analog .........................................................................................................................................................................12 3.2 Digital .........................................................................................................................................................................13 3.2.1 Sequential Logic (RTL) ..............................................................................................................................13 A.1 Synchronous (In-Sync) ....................................................................................................................13 A.2 Asynchronous (Transparent) .......................................................................................................13 A.3 Implementation ...................................................................................................................................13 A.3.1 Finite State Machine (FSM) ......................................................................................................13 A.3.2 Pipe-Lining .......................................................................................................................................13 3.2.2 Combinational Logic ...................................................................................................................................13 A. Algorithmic Circuits .....................................................................................................................................13 B. Arithmetic Circuits ........................................................................................................................................13 B.1 Negative numbers (0x7F) ...............................................................................................................14 B.2 Adder ........................................................................................................................................................14 B.3 Boolean Algebra ..................................................................................................................................14 3.2.3 Logic Gates .......................................................................................................................................................14 3.3 Mixed-Signal ( Analog & Digital ) ..................................................................................................................15 4. SYSTEM CIRCUIT DESIGN ..............................................................................................................................................15 4.1 Planning .....................................................................................................................................................................15 4.1.1 Outlining ...........................................................................................................................................................15 4.1.2 Interconnect Standards .............................................................................................................................15 4.1.3 IP-Cores (Re-Use) .........................................................................................................................................15 4.1.4 Design For Testability (DFT) ...................................................................................................................16 4.2 Design Flow .............................................................................................................................................................16 4.2.1 Design Software (EDA / ECAD) .............................................................................................................16 4.2.2 Schematic Entry ............................................................................................................................................16 4.2.3 HDL Entry ........................................................................................................................................................17 A. Verilog .................................................................................................................................................................17 A.1 Circuit → Verilog .................................................................................................................................17 B. VHDL ....................................................................................................................................................................19 B.1 Include (LIBRARY / USE) ................................................................................................................19 B.2 External I/O (ENTITY...GENERIC/PORT) ................................................................................19 B.3 Declarations (Architecture) ...........................................................................................................19 B.3.1 COMPONENT ..................................................................................................................................19 B.4 Architecture (BEGIN) .......................................................................................................................19 B.5 <= and => (SIGNAL Assignment) ................................................................................................19 B.6 Logic Gates .............................................................................................................................................20 B.7 GENERATE .............................................................................................................................................20 B.8 WHEN...ELSE .........................................................................................................................................20 B.9 WITH...SELECT .....................................................................................................................................20 B.10 Arithmetic & Casting ......................................................................................................................20 B.11 PROCESS (Sequential) ...................................................................................................................20 B.11.1 VARIABLE .......................................................................................................................................20 B.11.2 IF...THEN .........................................................................................................................................20 B.11.3 WAIT .................................................................................................................................................20 B.11.4 CASE...WHEN ................................................................................................................................20 B.11.5 FOR...LOOP .....................................................................................................................................20 B.11.6 WHILE...LOOP ...............................................................................................................................20 B.12 CONFIGURATION .............................................................................................................................24 4.2.4 Synthesis ( Decoding / Compiling ) .....................................................................................................24 4.2.5 Verification .....................................................................................................................................................24 A. Simulation ( SPICE / NetList ) .................................................................................................................24 4.2.6 Target Hardware ( Layout ) .....................................................................................................................25 A. FPGA Device Vendors ..................................................................................................................................25 B. IC Circuit Packages ........................................................................................................................................25 5. FIRMWARE ............................................................................................................................................................................26 5.1 Assembly Language (ASM) ...............................................................................................................................26 5.2 Bootloaders and Interfaces ..............................................................................................................................26 5.3 Board Support Package (BSP) ........................................................................................................................27 5.4 Operating Systems (OS) .....................................................................................................................................27 5.4.1 Real Time Operating System (RTOS) ..................................................................................................27 5.4.2 OS Memory Management .........................................................................................................................27 5.4.3 OS Process Management ...........................................................................................................................28 5.5 Device Drivers ........................................................................................................................................................28 5.5.1 Device Tree / Driver Stack .......................................................................................................................28 5.5.2 Driver Development Kits (DDK) ............................................................................................................29 5.5.3 Kernel-Mode Driver Framework (KMDF) ........................................................................................29 A. DriverEntry() ...................................................................................................................................................30 B. EvtDeviceAdd() ..............................................................................................................................................31 B.1 Plug and Play (PnP) ...........................................................................................................................33 B.2 Power Management ..........................................................................................................................33 B.3 File / Context .......................................................................................................................................34 B.4 Device .......................................................................................................................................................34 B.5 Interface ..................................................................................................................................................34 B.6 I/O Handling .........................................................................................................................................34 C. Callback Functions ........................................................................................................................................37 5.5.4 User-Mode Driver Framework (UMDF) .............................................................................................40 A. Reference ...........................................................................................................................................................41 5.5.5 Linux ...................................................................................................................................................................41 A. Overview ...........................................................................................................................................................41 B. Code .....................................................................................................................................................................41 6. Altera Quartus-II ................................................................................................................................................................41 6.1 Qsys Designer (SOPC) .........................................................................................................................................42 6.2 Soft Core Processors ............................................................................................................................................43 6.3 IP-Cores .....................................................................................................................................................................43 6.4 Schematic & HDL Editors ..................................................................................................................................44 6.5 Design Simulation ( Debug / Performance ) ............................................................................................44 A. Simulation .........................................................................................................................................................44 B. TimeQuest Timing Analyzer ....................................................................................................................44 C. ELA – Embedded Logic Analyzer ...........................................................................................................44 6.6 Bugs / Gotchas .......................................................................................................................................................44 7. Xilinx ISE / Vivado .............................................................................................................................................................45 A. System-Level Tools .......................................................................................................................................45 B. Circuit-Level Tools ........................................................................................................................................45 8. ModelSim ...............................................................................................................................................................................46 8.1 Projects ......................................................................................................................................................................46 9. Industrial Control Systems (ICS) ................................................................................................................................47 9.1 Allen-Bradley PLC .................................................................................................................................................47 9.2 PLC – Programmable Logic Controller .......................................................................................................48 9.3 Instrumentation ....................................................................................................................................................48 10. IT Distributed Management (DMTF) .....................................................................................................................49 11. ONLINE RESOURCES .....................................................................................................................................................49 1. INTRO Electronic Devices are very complex circuits that can only be understood by the divide and conquer approach System = A set of interacting independent components forming an integrated whole. Architecture = A model that defines structure, components, behavior and/or view of a system. Circuit = An electrical network of interconnected elements IP-Core = A named circuit (block) for portable re-use in a variety of upper-level circuits. IP = Intellectual Property; (e.g. VGA controller, UART, Processor, Ethernet, etc...)

Upload: hoangnhi

Post on 30-Jun-2019

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

Electronics Engineering N2NONewbie-2-Novice-Outline

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

Table of Contents1. INTRO.........................................................................................................................................................................................12. SYSTEM CIRCUITS................................................................................................................................................................2

2.1 System on a chip (SOC).........................................................................................................................................22.2 System on Programmable Chip (SOPC)........................................................................................................3

2.2.1 Field Programmable Gate Array (FPGA)..............................................................................................32.2.2 Programmable Logic Devices (PLD)......................................................................................................4

2.3 Processors...................................................................................................................................................................42.3.1 Market..................................................................................................................................................................42.3.2 Architectures.....................................................................................................................................................4

A. Control Unit (CU)..............................................................................................................................................5B. Algorithmic Logic Unit (ALU).....................................................................................................................5C. Memory – Instruction Cache.......................................................................................................................5D. Bit-Numbering (Endianness).....................................................................................................................5E. Registers / Timing...........................................................................................................................................5

2.4 Memory........................................................................................................................................................................52.5 Peripherals..................................................................................................................................................................5

2.5.1 I2C..........................................................................................................................................................................62.5.2 ISA..........................................................................................................................................................................62.5.3 General Purpose I/O (GPIO)......................................................................................................................62.5.4 Serial Peripheral Interface (SPI)..............................................................................................................62.5.5 Joint Test Action Group (JTAG).................................................................................................................62.5.6 PCI / PCIe............................................................................................................................................................62.5.7 Transceivers......................................................................................................................................................72.5.8 USB.........................................................................................................................................................................8

A. Abstraction Layers...........................................................................................................................................8B. Functional Layer...............................................................................................................................................8C. Logical Layer.......................................................................................................................................................9D. Physical Layer.................................................................................................................................................10

2.5.9 VGA Interface Spec.......................................................................................................................................112.6 Wireless / Networking.......................................................................................................................................112.7 Logic............................................................................................................................................................................12

2.7.1 7400-Series ICs.............................................................................................................................................123. CIRCUIT THEORY...............................................................................................................................................................12

3.1 Analog.........................................................................................................................................................................123.2 Digital.........................................................................................................................................................................13

3.2.1 Sequential Logic (RTL)..............................................................................................................................13A.1 Synchronous (In-Sync)....................................................................................................................13A.2 Asynchronous (Transparent).......................................................................................................13A.3 Implementation...................................................................................................................................13A.3.1 Finite State Machine (FSM)......................................................................................................13A.3.2 Pipe-Lining.......................................................................................................................................13

3.2.2 Combinational Logic...................................................................................................................................13A. Algorithmic Circuits.....................................................................................................................................13B. Arithmetic Circuits........................................................................................................................................13

B.1 Negative numbers (0x7F)...............................................................................................................14B.2 Adder........................................................................................................................................................14B.3 Boolean Algebra..................................................................................................................................14

3.2.3 Logic Gates.......................................................................................................................................................143.3 Mixed-Signal ( Analog & Digital )..................................................................................................................15

4. SYSTEM CIRCUIT DESIGN..............................................................................................................................................154.1 Planning.....................................................................................................................................................................15

4.1.1 Outlining...........................................................................................................................................................154.1.2 Interconnect Standards.............................................................................................................................154.1.3 IP-Cores (Re-Use).........................................................................................................................................154.1.4 Design For Testability (DFT)...................................................................................................................16

4.2 Design Flow.............................................................................................................................................................164.2.1 Design Software (EDA / ECAD).............................................................................................................164.2.2 Schematic Entry............................................................................................................................................164.2.3 HDL Entry........................................................................................................................................................17

A. Verilog.................................................................................................................................................................17A.1 Circuit → Verilog.................................................................................................................................17

B. VHDL....................................................................................................................................................................19B.1 Include (LIBRARY / USE)................................................................................................................19B.2 External I/O (ENTITY...GENERIC/PORT)................................................................................19B.3 Declarations (Architecture)...........................................................................................................19B.3.1 COMPONENT ..................................................................................................................................19

B.4 Architecture (BEGIN).......................................................................................................................19

B.5 <= and => (SIGNAL Assignment)................................................................................................19B.6 Logic Gates.............................................................................................................................................20B.7 GENERATE.............................................................................................................................................20B.8 WHEN...ELSE.........................................................................................................................................20B.9 WITH...SELECT.....................................................................................................................................20B.10 Arithmetic & Casting......................................................................................................................20B.11 PROCESS (Sequential)...................................................................................................................20B.11.1 VARIABLE.......................................................................................................................................20B.11.2 IF...THEN.........................................................................................................................................20B.11.3 WAIT.................................................................................................................................................20B.11.4 CASE...WHEN................................................................................................................................20B.11.5 FOR...LOOP.....................................................................................................................................20B.11.6 WHILE...LOOP...............................................................................................................................20

B.12 CONFIGURATION.............................................................................................................................244.2.4 Synthesis ( Decoding / Compiling ).....................................................................................................244.2.5 Verification .....................................................................................................................................................24

A. Simulation ( SPICE / NetList ).................................................................................................................244.2.6 Target Hardware ( Layout ).....................................................................................................................25

A. FPGA Device Vendors..................................................................................................................................25B. IC Circuit Packages........................................................................................................................................25

5. FIRMWARE............................................................................................................................................................................265.1 Assembly Language (ASM)...............................................................................................................................265.2 Bootloaders and Interfaces..............................................................................................................................265.3 Board Support Package (BSP)........................................................................................................................275.4 Operating Systems (OS).....................................................................................................................................27

5.4.1 Real Time Operating System (RTOS)..................................................................................................275.4.2 OS Memory Management.........................................................................................................................275.4.3 OS Process Management...........................................................................................................................28

5.5 Device Drivers........................................................................................................................................................285.5.1 Device Tree / Driver Stack.......................................................................................................................285.5.2 Driver Development Kits (DDK)............................................................................................................295.5.3 Kernel-Mode Driver Framework (KMDF)........................................................................................29

A. DriverEntry()...................................................................................................................................................30B. EvtDeviceAdd()..............................................................................................................................................31

B.1 Plug and Play (PnP)...........................................................................................................................33B.2 Power Management..........................................................................................................................33B.3 File / Context.......................................................................................................................................34B.4 Device.......................................................................................................................................................34B.5 Interface..................................................................................................................................................34B.6 I/O Handling.........................................................................................................................................34

C. Callback Functions........................................................................................................................................375.5.4 User-Mode Driver Framework (UMDF).............................................................................................40

A. Reference...........................................................................................................................................................415.5.5 Linux...................................................................................................................................................................41

A. Overview...........................................................................................................................................................41B. Code.....................................................................................................................................................................41

6. Altera Quartus-II................................................................................................................................................................416.1 Qsys Designer (SOPC).........................................................................................................................................426.2 Soft Core Processors............................................................................................................................................436.3 IP-Cores.....................................................................................................................................................................436.4 Schematic & HDL Editors..................................................................................................................................446.5 Design Simulation ( Debug / Performance )............................................................................................44

A. Simulation.........................................................................................................................................................44B. TimeQuest Timing Analyzer....................................................................................................................44C. ELA – Embedded Logic Analyzer...........................................................................................................44

6.6 Bugs / Gotchas.......................................................................................................................................................447. Xilinx ISE / Vivado.............................................................................................................................................................45

A. System-Level Tools.......................................................................................................................................45B. Circuit-Level Tools........................................................................................................................................45

8. ModelSim...............................................................................................................................................................................468.1 Projects......................................................................................................................................................................46

9. Industrial Control Systems (ICS)................................................................................................................................479.1 Allen-Bradley PLC.................................................................................................................................................479.2 PLC – Programmable Logic Controller.......................................................................................................489.3 Instrumentation....................................................................................................................................................48

10. IT Distributed Management (DMTF).....................................................................................................................4911. ONLINE RESOURCES.....................................................................................................................................................49

1. INTRO✔ Electronic Devices are very complex circuits that can only be understood by the divide and conquer approach

◌ System = A set of interacting independent components forming an integrated whole.◌ Architecture = A model that defines structure, components, behavior and/or view of a system.◌ Circuit = An electrical network of interconnected elements◌ IP-Core = A named circuit (block) for portable re-use in a variety of upper-level circuits.

▫ IP = Intellectual Property; (e.g. VGA controller, UART, Processor, Ethernet, etc...)

Page 2: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

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

✔ System Groups◌ Computers (Software) – Preforms a variety of functions by means of loading execution instructions (IE. software)◌ Embedded Systems (Firmware) – Dedicated function by means of “fixed-in-hardware” execution instructions (IE. firmware)◌ Consumer Electronics – Electronic equipment for everyday use

✔ System Architecture typically consists of◌ Hardware Components

▪ Microprocessors – A Processor; memory and peripherals are not part of the processor chip (HPS / SPS = Hard/Soft-Core Processor based)▪ Microcontroller – A System-On-Chip (SOC) containing memory and peripherals (HPS / SPS = Hard/Soft-Core Processor based)▪ Memory▪ Interconnects

▫ IC System Interconnect Fabric▫ PCB Printed Circuit Board traces

▪ Peripherals▫ Transceivers▫ JTAG chain - IEEE standard interface for chip ID activation and for testing/programming.▫ System Interconnect Fabric▫ GPIO - General Purpose Input/Output▫ PIO - Parallel Input/Output▫ MAC/PHY - Ethernet Interface▫ SSD - 7-Segment Display

◌ Execution Instructions▪ Software = Computer execution instructions▪ Firmware = Embedded System Execution instructions

▫ BSP = Board Support Package – Specific support code for a given embedded system / circuit board / IC-Chip.▫ ASP = Architecture Support Package – Code for Processor Instruction-Set▫ FSP = Firmware Support Package – Code for ?▫ Boot-loader – Program in ROM to access memory devices (Example: BIOS)▫ File System▫ Tool-chain – Compilers for making programs for the

embedded system.▫ RTOS =– Real Time Operating Systems for Embedded Systems

▫ RTC = Real Time Computing which contains a RTC ( Real Time Clock )

✔ Circuit Architecture can be described using a variety of approaches and modeling levels.◌ Approach

▪ Behavioral – How the circuit behaves (e.g. What a house does )▪ Structural – How the circuit is connected (e.g. How to build a house )

◌ Model-ling Levels (IE. 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 – Design in terms of logic and storage devices (Behavioral/Structural)▪ Gate level – Design in terms of logic gate components (IE. Standard circuits that perform very basic comparison operations)▪ Switch level – Design in terms of transistors and basic electronic components (Structural) (In digital a transistor is used only as a binary switch ON(1)/OFF(0))

◌ Package Level (Physical Characterizing)▪ PCB = Printed Circuit Board Circuit – Circuit of any complexity existing on a board ( Ex. Motherboard, Daughter-card )▪ IC = Integrated Circuit – Any circuit of any complexity integrated into a single physical package (chip)▪ Discrete – Individual single-purpose electronic part

◌ Purpose Groups▪ Processors – Circuits that execute code (Typically in IC form) ▪ Digital Logic – Circuits that an upper-voltage level to represent binary '1' and typically no/little voltage to represent binary '0'

✔ See◌ http://en.wikipedia.org/wiki/Integrated_circuit Contains full details about categories, scale integration, fabricating & packaging, and families◌ http://en.wikipedia.org/wiki/Computer Covers many details of low/high level programming and Processor architectures◌ http://en.wikipedia.org/wiki/Embedded_system Details including ASIC and FPGA solutions

▪ http://en.wikipedia.org/wiki/Firmware Links to ROM imaging and boot-loaders▪ http://en.wikipedia.org/wiki/Electronic_control_unit Automotive Engine Controller▪ http://en.wikipedia.org/wiki/RTOS#Examples Quick list of popular RTOS

◌ http://commons.wikimedia.org/wiki/Category:Electronic_circuits Symbols, Circuit examples◌ http://en.wikibooks.org/wiki/Subject:Electrical_engineering

2. SYSTEM CIRCUITS

2.1 System on a chip (SOC) ✔ SOC = Microprocessor + Peripherals all integrated on a single chip✔ Microprocessor = Processor is a discrete device physically separate from memory.✔ Microcontroller = Typically any Processor + Memory integrated circuit (IC) centered at controlling interfaces or devices.

◌ Microprocessor SOC Development Boards ( Microprocessor System Design Prototyping )▪ http://en.wikipedia.org/wiki/Microprocessor_development_board▪ http://en.wikipedia.org/wiki/Single-board_computer▪ MS Windows compatible development boards - http://msdn.microsoft.com/en-US/windows/hardware/dn770216

Name Processor Software Links

Galileo Intel Quark SoC X1000 http://www.intel.com/content/www/us/en/do-it-yourself/galileo-maker-quark-board.html

Intel Shark Cove Intel Atom MS-VS http://www.sharkscove.org/ (Dev Board recommended by MS for driver design)

Page 3: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

◌ Microcontroller Development board ( Microcontroller System Design Prototyping )▪ Wiki http://en.wikipedia.org/wiki/Microcontroller

Name Micro-controller Software Links

Arduino AVR / ARM http://www.arduino.cc/ http://en.wikipedia.org/wiki/Arduinohttp://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems

Atmel Atmega8 / Atmega32 / ARM / 8051 / AVR http://en.wikipedia.org/wiki/Atmel

MicroChip PIC / dsPIC MPLAB http://www.microchip.com/

Parallax http://www.parallax.com/

Rasberry Pi ARM processor by Broadcom http://www.raspberrypi.org/

Texas Instruments MSP430 https://estore.ti.com/

2.2 System on Programmable Chip (SOPC) ✔ SOPC = System on a Programmable Chip – Houses a Soft-Core Processor + Peripherals inside a programmable chip✔ FPGA = Chip for implementing custom logic circuits – Design is loaded into SRAM blocks (volatile) creating needed interconnects and logic. http://en.wikipedia.org/wiki/FPGA✔ FPAA = Field Programmable Analog Array – An FPGA that allows for Mixed-Signal (Analog/Digital) programmable circuit design✔ Soft-Core Processor – A Microprocessor implemented into a programmable chip

2.2.1 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

1. FPGA Vendors a) http://www.xilinx.com/ Virtex, Spartan, Kintex, Artix, Zynq(ARM) CPLD: CoolRunner, 9500Series b) http://www.altera.com/ Stratix, Arria, Cyclone(ARM) c) http://www.latticesemi.com/ ECP5 d) http://www.microsemi.com/ Previously ACTEL e) http://www.achronix.com/ Hand-held niche; no general use FPGAs f) http://www.tabula.com/ 3-D High Speed FPGAs

2. FPGA Development Boards ( Design Prototyping ) a) Altera

• List of Altera Dev-Boards @ http://www.altera.com/products/devkits/kit-dev_platforms.jsp• Popular provider (Terasic) @ http://www.terasic.com.tw/en/

b) Xilinx• Xilinx sells Dev-Boards directly @ http://www.xilinx.com/products/boards-and-kits/ • Popular provider (AVNET) @ http://www.avnet.com/en-us/Pages/default.aspx• XTEX FPGA Boards @ http://www.ztex.de/• Mojo (Open-Hardware) @ http://embeddedmicro.com/• Papilio (Open-Hardware) @ http://papilio.cc/

3. Altera Architecture a) FPGA = Field Programmable Gate Array – Depending on model contain 'x' number of LABs b) LAB = Logic Array Block – Each LAB contains (16)LEs. c) LE = Logic Element – Each LE contains (4)LUTs. d) LUT = Look Up Table – An electronic truth table to implement a variety of logical gates.

4. Xilinx Architecture a) FPGA = Field Programmable Gate Array – Depending on model contains 'x' number of CLBs b) CLB = Configurable Logic Block – Each CLB contains (4)Slices c) Slice = No Accrymn – Each Slice contains (2)LCs d) LC = Logic Cell - Each logic cell contains (2)3-input LUT a Full-Adder(FA) and an output register (DFF – D Flip Flop) e) LUT = Look Up Table – An electronic truth table to implement a variety of logical gates.

5. FPGA Architecture (In General) a) [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)

b) [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)

Page 4: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

• [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)

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

d) 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

e) Terms• “Device Atoms” – A LUT of DFF or FA within the FPGA architecture is called a device atom.

6. Programming a FPGA/PLD✔ IC-Programming-Unit – Older PLD's with PROM, EPROM or Fuse-Memory required a physical tool to program the chip.✔ ISP = In-System-Programming – Circuit board has a JTAG header plug-in for programming chips within the circuit.

2.2.2 Programmable Logic Devices (PLD)✔ PLD / GAL are the root/parent technology that led into FPGA technology✔ http://en.wikipedia.org/wiki/Programmable_logic

1. SPLD = Simple Programmable Logic Devices a) PLA = Programmable Logic Array – Programmable interconnects on AND & OR gates b) PAL = Programmable Array Logic – Device (AND programmable / OR hard-wired c)

2. CPLD = Combinational / Complex Logic Device a) 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.

2.3 Processors 1. Drive Address Bus 2. Activate Enable 3. Fetch Data from Data Bus 4. Control Unit - receives instructions from RAM 5. Interrupt Handling

2.3.1 Market 1. Categories

a) CPU = Central Processing Unit – CPU can infer box, board, or processor chip http://en.wikipedia.org/wiki/Microprocessor b) MCU = Micro-controller Unit – Processor + Memory + IO Control on one chip http://en.wikipedia.org/wiki/Microcontroller c) DSP = Digital Signal Processor d) GPU = Graphics Processing Unit

2. Implementation Hardware a) HPS = Hard-Core Processor System – Processor resides is an integrated circuit chip b) SPS = Soft-Core Processor System – Processor resides in an FPGA or other programmable-circuit device c) SPOC = Soft PrOcessor Core – Acronym for soft core processor IP-Core

3. List of Processor Devices a) Wiki micro-controller list http://en.wikipedia.org/wiki/List_of_common_microcontrollers b) Wiki microprocessor list http://en.wikipedia.org/wiki/Category:Lists_of_microprocessors c) Wiki Soft-Core Processor list http://en.wikipedia.org/wiki/Soft_microprocessor

d) ARM (by Acorn Computers Ltd) - Power optimized (Fab-less design company).• Versatile Express board (Linaro builds)• Load-Store Model (RAM -> Register)• In-line barrel shifter• Memory mapped IO (Peripherals are accessed by memory) - vendor implemented• U-Boot is open source BIOS (boot loader)

e) Legacy Products• 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 8086 with an 8-bit data bus for reverse compatibility)

4. Processor Emulators (Software) a) Wiki list http://en.wikipedia.org/wiki/Comparison_of_platform_virtual_machines b) Bochs – Emulates x86, x86-64 http://en.wikipedia.org/wiki/Bochs a) QEMU Emulator – Emulates x86, ARM, SPARC and Power-PC processors http://en.wikipedia.org/wiki/QEMU

2.3.2 ArchitecturesWiki List http://en.wikipedia.org/wiki/List_of_CPU_architectures

1. Main Micro-Architectures a) Harvard Architectures http://en.wikipedia.org/wiki/Modified_Harvard_architecture

• Separate address spaces for code and working memory b) Von Neumann Architectures http://en.wikipedia.org/wiki/Von_Neumann_architecture

• Need to research some more• Some chips don't have Memory-Mapped I/O (have instruction 'OUT' and 'IN') this route is mostly historical. (x86 has it?)

2. Derived Architectures http://en.wikipedia.org/wiki/List_of_instruction_sets a) ARM – RISC based Instruction Set Architecture (ISA) {by ARM Holdings Co.) b) MIPS – RISC based Instruction Set Architecture (ISA) {by MIPS Technologies} c) AVR – RISC based Instruction Set Architecture (ISA) {by Atmel Technologies}

Page 5: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

d) MCS-51 (8051) – CISC based legacy commonly used for learning e) LEON – Soft-Core; FPGA based on SPARC-V8

✔ 8-bits = 1-byte✔ Word = 16-bits (2-bytes) (0xFFFF)✔ Double Word = 32 – bits (4-bytes) (0xFFFF_FFFF)

A. Control Unit (CU)✔ Instruction Set Architecture (ISA) = The commands a processor can execute ( ISA – is circuit-level / hard-wired ). http://en.wikipedia.org/wiki/Instruction_set

1. CISC (Intel) - Complex Instruction Set http://en.wikipedia.org/wiki/List_of_instruction_sets a) Less registers b) More clocks per complex commands c) Complex commands hardware added for heavy use functions d) Variable length instructions between 1-bit and 16-bit?

2. RISC (PowerPC, ARM, SPARC, MIPS, Nios) a) Reduced Instruction Set Computer b) More registers c) Less clocks per simple command d) Designed for compiler optimization simplification e) Instruction size is typically fixed to processor structure size (16/32/64-bit)

3. Parts of the Control Unit a) Reset Vector Offset = Memory Address the Instruction Pointer goes to on reset de-assert (IE. Power-up)

B. Algorithmic Logic Unit (ALU) 1. Mathematical / Comparison operations

a) (Input A, Input B(temp register to store from bus), Input TYpe of OPeration, COmpare Flags - CU, Output f)

C. Memory – Instruction Cache 1. Instruction Cache 2. RAM Address → Data 3. BUS Registers / Latches

a) Just like RAM but inside CPU (Register has set/enable lines set=save, enable=read) All on CPU BUS. 4. ECC = ECC - Error correction code (Corrects bad bits in memory)

D. Bit-Numbering (Endianness) 1. Endianness = Is a BYTE(8-bits) level order (2-digit HEX Swap)

a) Little-endian = Least significant byte is at byte(0) in Left → Right. b) Big-endian = Most significant byte is at byte(0) in Left → Right.

2. Bit-Significance a) LSB - Least significant bit b) MSB - Most significant bit

3. Timing a) Time handling makes sure logic-element-1 has evaluated before its output is fed into logic-element-2 b) Register = Is a Flip-Flop circuit that holds it's output state (has memory).

4. See also: http://en.wikipedia.org/wiki/Bit_numbering

E. Registers / Timing 1. Control Registers 2. Status Registers 3. General Purpose Registers 4. Instruction Address Pointer Register 5. Accumulation Register 6. See Also:

a) http://en.wikipedia.org/wiki/Processor_register b) http://computer.howstuffworks.com/microprocessor2.htm

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

✔ See Also: Firmware::Assembly Language◌ https://www.youtube.com/watch?v=cNN_tTXABUA◌ http://en.wikipedia.org/wiki/Microarchitecture

2.4 Memory ✔ See http://en.wikipedia.org/wiki/Semiconductor_memory

1. Random Access Memory (RAM) "volatile" a) Dynamic random-access memory (DRAM)

• SDRAM = Synchronous Dynamic RAM – Requires a refresh clock and synchronous clock (storage cells are made of capacitors)• RDRAM• DDR-SDRAM• OTHERS : FPM-DRAM, EDO-DRAM, VRAM, SGRAM, PSRAM

b) Static random-access memory (SRAM): { http://en.wikipedia.org/wiki/Static_random-access_memory }• SRAM is basically a network of Flip-Flops

2. Read Only Memory (ROM) – “non-volatile” (IE. Permanent memory) a) PROM = Programmable ROM b) EPROM = Erasable PROM – ultra-violet light to erase and electronic programming. (Uses FAMOS transistors) c) EEPROM = Electronic EPROM – electronic erase and programming (Uses FLOTOX transistors)

3. Memory Management a) MMU = Memory Management Unit – Digital block handling memory management b) MPU = Memory Protection unit – Digital block handling memory access

2.5 Peripherals ✔ http://www.xilinx.com/ise/embedded/edk_ip.htm✔ Nice Description http://www.bottomupcs.com/peripherals.html✔ Wiki Bandwidth http://en.wikipedia.org/wiki/List_of_device_bandwidths

1. Terms

Page 6: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

a) DDIO – Double data rate I/O b) PLL – Phase Lock Loop c) LVDS – Low Voltage Differential Signal d) GSPS – Giga Samples per Second. e) TLP – Transaction Layer Packets (PCIe)

2. How to Find Hardware Interface / Protocol Standards http://en.wikipedia.org/wiki/International_Organization_for_Standardization a) ISO = International Standards Organization – Technical Management Board members is responsible for over 250 technical Committees.) b) ISO/IEC = International Electra-technical Commission – Is a Technical Committee of ISO for electrical, electronic and related technologies. ( http://www.iec.ch/ ) c) JEDEC = Joint Electron Device Engineering Council – Global standards for the microelectronics industry http://www.jedec.org/ d) AEC = Automotive Electronics Council – 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 a)

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

▪ Conditions▫ 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-00002nd - 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)

2.5.2 ISA

2.5.3 General Purpose I/O (GPIO)

2.5.4 Serial Peripheral Interface (SPI)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.5.5 Joint Test Action Group (JTAG)✔ IEEE 1149.1 Standard Test Access Port and Boundary-Scan ie. Scan Chain STUCK_AT✔ Wiki http://en.wikipedia.org/wiki/JTAG✔ Pins

▪ TDI (Test Data In)▪ TDO (Test Data Out)▪ TCK (Test Clock)▪ TMS (Test Mode Select)▪ TRST (Test Reset) optional.

2.5.6 PCI / PCIe

http://www.techfest.com/hardware/bus/pci.htm Specification document http://komposter.com.ua/documents/PCI_Express_Base_Specification_Revision_3.0.pdf

Page 7: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

2.5.7 TransceiversSerial links are describe in frequency (cycles per second (Hz))Amount of data that can be carried in a Serial Link is called “Bandwidth”Bandwidth is measured in the amount of data-bits per second that the serial channel can carry.

1. SCI = Serial Communication Interfaces (RS-232, RS-422, RS-485) 2. SERDES = Pair of functional blocks that convert between serial & parallel in both directions http://en.wikipedia.org/wiki/SerDes 3. UART = Universal Asynchronous Receiver/Transmitter) Translates parallel to serial and vice versa

Page 8: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

2.5.8 USB

✔ USB Flavors (USB = Universal Serial Bus)

USB Speed (Name) Host Controller

_ 1.0_ 1.1

Low-Speed(1.5Mbit/s) / Full-Speed(12Mbit/s)Same speeds as 1.0 with added functionality

UHCI = Universal Host Controller Interface by IntelOHCI = 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 released in 1996; USB 1.1 released in 1998 (clarification & improvements only over USB 1.0)◌ Device Controller (DC)◌ On-The-Go (OTG)

▪ A supplement protocol specifically for embedded systems that implements 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 = USB Driver* HCD = Host Controller Driver* Enumeration = USB Device initialization* Endpoint = 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 2nd 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 Field Bytes Value Description0 bLength 1 Number Size of the Descriptor in Bytes (18 bytes)1 bDescriptorType 1 Constant Device Descriptor (0x01)2 bcdUSB 2 BCD USB Specification Number which device complies too.4 bDeviceClass 1 Class Class Code (Assigned by USB Org)

If equal to Zero, each interface specifies it’s own class codeIf equal to 0xFF, the class code is vendor specified.Otherwise field is valid Class Code.

5 bDeviceSubClass 1 SubClass Subclass Code (Assigned by USB Org)6 bDeviceProtocol 1 Protocol Protocol Code (Assigned by USB Org)7 bMaxPacketSize 1 Number Maximum Packet Size for Zero Endpoint. Valid Sizes are 8, 16, 32, 648 idVendor 2 ID Vendor ID (Assigned by USB Org)

10 idProduct 2 ID Product ID (Assigned by Manufacturer)12 bcdDevice 2 BCD Device Release Number14 iManufacturer 1 Index Index of Manufacturer String Descriptor15 iProduct 1 Index Index of Product String Descriptor16 iSerialNumber 1 Index Index of Serial Number String Descriptor17 bNumConfigurations 1 Integer Number of Possible Configurations

▪ Configuration Descriptor (Only one active at a time – user / driver selects the configuration – typically there is only one)Offset Field Bytes Value Description

0 bLength 1 Number Size of Descriptor in Bytes

Page 9: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

1 bDescriptorType 1 Constant Configuration Descriptor (0x02)2 wTotalLength 2 Number Total length in bytes of data returned4 bNumInterfaces 1 Number Number of Interfaces5 bConfigurationValue 1 Number Value to use as an argument to select this configuration6 iConfiguration 1 Index Index of String Descriptor describing this configuration7 bmAttributes 1 Bitmap D7 Reserved, set to 1. (USB 1.0 Bus Powered)

D6 Self PoweredD5 Remote WakeupD4..0 Reserved, set to 0.

8 bMaxPower 1 mA 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 Field Bytes Value Description0 bLength 1 Number Size of Descriptor in Bytes (9 Bytes)1 bDescriptorType 1 Constant Interface Descriptor (0x04)2 bInterfaceNumber 1 Number Number of Interface3 bAlternateSetting 1 Number Value used to select alternative setting4 bNumEndpoints 1 Number Number of Endpoints used for this interface5 bInterfaceClass 1 Class Class Code (Assigned by USB Org)6 bInterfaceSubClass 1 SubClass Subclass Code (Assigned by USB Org)7 bInterfaceProtocol 1 Protocol Protocol Code (Assigned by USB Org)8 iInterface 1 Index Index of String Descriptor Describing this interface

▪ Endpoint Descriptors

Offset Field Bytes Value Description0 bLength 1 Number Size of Descriptor in Bytes (7 bytes)1 bDescriptorType 1 Constant Endpoint Descriptor (0x05)2 bEndpointAddress 1 Endpoint Endpoint Address

Bits 0..3b Endpoint Number.Bits 4..6b Reserved. Set to ZeroBits 7 Direction 0 = Out, 1 = In (Ignored for Control Endpoints)

3 bmAttributes 1 Bitmap Bits 0..1 Transfer Type 00 = Control01 = Isochronous10 = Bulk11 = Interrupt

Bits 2..7 are reserved. If Isochronous endpoint, Bits 3..2 = Synchronisation Type (Iso Mode)

00 = No Synchonisation01 = Asynchronous10 = Adaptive11 = Synchronous

Bits 5..4 = Usage Type (Iso Mode) 00 = Data Endpoint01 = Feedback Endpoint10 = Explicit Feedback Data Endpoint11 = Reserved

4 wMaxPacketSize 2 Number Maximum Packet Size this endpoint is capable of sending or receiving6 bInterval 1 Number 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

▪ Human Interface Devices (HID)▪ Mass Storage Devices (MSD)▪ Communication Device Class (CDC)▪ 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 individualdevices 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.

✔ Reference▪ 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

✔ Pipes = Representation of data movement between host software (via Memory Buffers) and endpoints on devicesTransfer-Type Pipe Mode Description Transaction Packets

Control MessageControl Pipe

Device initialization and pipe control; Bi-directional simple commands / status Endpoint(0) = Default Control Pipe

Bulk StreamData Pipe

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

Interrupt StreamData Pipe

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

Isochronous StreamData Pipe

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

▪ Transfer-Type specifies and typically consists of multiple packets▫ Data format imposed by the USB▫ Direction of communication flow▫ Packet size constraints

Page 10: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▫ 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 ]

TypePID value

(msb-first)

Transmitted byte(lsb-first) Name Description

Reserved 0000 0000 1111

Token1000 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'

Special1100 0011 1100

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

Handshake

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

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

Token

0001 1000 0111 OUTContents: [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 |4-bit ENDP # |5-bit CRC |EOP ]Purpose: (Device → Host) Request device sends data to hostResponse: Expects a response from the device. (NAK, STALL) Or DATAx Frame which would be followed by a Host-ACK.

0101 1010 0101 SOFContents: [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

Data

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.)

0011 1100 0011 DATA0Contents: [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 DATA1Contents: [Sync |PID (DATA1) |Payload |16-bit CRC |EOP ]Purpose: Odd-numbered data packet (Data toggles between DATA0/DATA1 for each successful packet transferResponse: 'ACK' is expected from either host/device (depending on IN or OUT Token)

0111 1110 0001 DATA2Contents: [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 MDATAContents: [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)

Page 11: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

• 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. **

✔ Reference◌ 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.5.9 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)

✔ Reference◌ http://www.fpga4fun.com/PongGame.html◌ http://martin.hinner.info/vga/

2.6 Networking ✔ IEEE Committees

◌ 802.3 = Ethernet◌ 802.11 / 802.16 / 802.20 = Wireless Local Area Networks (WLAN)◌ Cellular

2.6.1 Cellular Networking

✔ 1G Networks (1st Generation Networks)◌ Advanced Mobile Phone Service (AMPS)

✔ 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

Page 12: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

✔ Reference◌ 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

2.6.2 Area Networking (LAN/WAN)✔ Overview

◌ Internetwork = 2+ LAN(s) connected together via a Router and configured to use logical addressing (IPv4 or Ipv6)◌ Segmentation = Internetworks are broken-up into network segments (Logically and Physically) for better performance (IE. Less signal congestion )◌ AP = Access Point◌ NMS = Network management stations◌ M2M = Machine to Machine◌ IoT = Internet of Things◌ Ad-hoc = No Base Router – Node to Node connection (e.g. Crossover Cable)◌ DTE = Data Terminal Equipment ( Customer-Site equipment / e.g. modem, hosts, printers, etc... )◌ DCE = Data Communication Equipment ( Equipment of the Internetwork )

▪ CSU – Channel Service Unit▪ DSU – Data Service Unit

◌ Convergence = Using Ethernet for irregular purposes ( other than file transfer )▪ PoE – Power over Ethernet ( Device power carried on Ethernet; Standards versions V1, V2, V3 )▪ VoIP – Voice over IP

◌ QoS/CoS = Quality/Class of Service – Packet Prioritizing; VoIP/Video first then file transfer

◌ Protocol = Set of Standards that define precisely the data communication methods/rules▪ Interconnection protocols – The data transfers from point to point▪ High-end switch protocols – Used by DCE to control the Internetwork communication equipment▪ Documentation

▫ Internet Assigned Numbers Authority▫ Request For Comments (RFC)

✔ Network Categories◌ LAN = Local Area Network – typically Owned by a company / person◌ WAN = Wireless Area Networks – typically Leased networks by a service provider◌ WPAN = Wireless Personal Area Network

▫ IrDA (Infrared Data Association)▫ Bluetooth▫ IEEE 802.15

◌ WLAN = Wireless Local Area Networks▫ IEEE 802.11 Wireless LAN = WiFi▫ 802.15 (1Mbps) 802.11 a/g (54Mbps) 802.11b (5-11 Mbps)

◌ WWAN = Wireless Wide Area Network (Mid to Long Range / Cellular Standards (Outdoor Networks))◌ WMAN = 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▫ 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

✔ 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 = Group of devices that all receive the Broadcast signals (IE. Signals sent to IP - ###.###.###.255 or MAC ff:ff:ff:ff )

Page 13: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▪ Hub – All ports are on the same Broadcast Domain▪ Switch – All ports are on the same Broadcast Domain▪ Router – 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<Host><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

✔ DCE Device Categories◌ Residential = Personal/Home◌ Small Office Home Office (SOHO)= Routers equipped with Internal Switch / Firewalls / DHCP / DNS / etc.. services◌ Enterprise = Has to work all the time with limited features (Routers are simplistic)

✔ Network Devices◌ NIC = Network Interface Card (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 )

A. OSI Model✔ OSI Model = Open Systems Interconnection Communications Model (7 – layers)✔ PDU = Protocol Data Unit – General term describing a protocol attachment (IE. In the process of wrapping and encapsulation of protocol levels)

A.1 Application Layer-7 (HTTP/POP3)✔ Software (Firefox, Outlook, Chrome, etc....)✔ Port Numbers

▪ Virtual Port Numbers = TCP/UDP:Port# ( 0-1023 reserved ); like virtual mail-boxes for protocol specific delivery; Used by the Transport Protocols▫ Socket = IP : Port# (e.g. 192.168.10.20:80) Created for each communication task▫ Socket Pair = Includes the “Socket” identifier of both source and destination requiring at least one unique item per communication task▫ Registered Ports – At http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml▫ System Specific – View C:\Windows\System32\Drivers\Etc\SERVICES

▪ Common Ports to Know▫ 21 = FTP (TCP) – File Transfer Protocol▫ 23 = Telnet (TCP) – Telnet Protocol▫ 25 = SMTP (TCP) – Simple Mail Transfer Protocol▫ 53 = DNS (TCP/UDP) – Domain Name Service Protocol▫ 69 = TFTP (UDP) – Trivial File Transfer Protocol▫ 70 = Gopher(TCP/UDP)▫ 79 = Finger (TCP/UDP) – RFC4146

Page 14: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▫ 80 = HTTP (TCP) – World Wide Web▫ 110 = POP3 (TCP/UDP) – Post Office Protocol V3▫ 119 = NNTP – Network News Transfer Protocol▫ 161 = SNMP (UDP) – Simple Network Management Protocol▫ 389 = LDAP (TCP/UDP) – Lightweight Directory Access Protocol▫ 443 = HTTPS (TCP) – Secure WWW▫ 993 = IMAP4 – Interactive Mail Access Protocol▫ 5353 = MDNS (TCP/UDP) – Multicast DNS Responder IPC (DNS has many flavors)

A.2 Presentation (Layer-6)✔ Data processing like encryption, compression or translation (OS-Layer); Not required but occasionally added.✔ Resolves items such as byte-order (IE. Little/big Endian), Character Sets (IE. US-ASCII, EBCDIC)

▪ 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

A.3 Session (Layer-5)✔ Dialog control (Creates session between the two systems); keeps applications data separate from other applications

▪ 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

A.4 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

✔ Protocols▪ User Data-gram Protocol (UDP) = No reliability; Used occasionally for a status update broadcast (like printer toner low)▪ Transmission Control Protocol (TCP) = Uses Sequencing, ACK, and Windowing flow control for reliability▪ Resource Reservation Protocol (RSVP)

A.5 Network Layer-3 (IP – Packet Data)✔ Provides Logical (e.g. IP) network addressing and routing (IE. Routers / Data & Routing Information)✔ Interconnection Protocols

▫ IP = Internet Protocol – Routed Protocol; Logical addressing and physical location for path determination – IP address▫ ICMP = Internet Control Message Protocol – Runs on top of IP ( Generally generated by Routers; I think ); ICMP Echo is commonly named “Ping”▫ ARP = Address Resolution Protocol – IP → MAC Address resolution (Doesn't use IP Transport)▫ RARP = Reverse Address Resolution Protocol – MAC → IP Address resolution▫ Proxy ARP = Allows Hot swap-able router additions – 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 = Legacy Novell IP-Technology that causes a lot of chatter▫ MPLS = Multiprotocol Label Switching ( Faster than a routing table )

A.5.1 Internet Protocol (IP)✔ All IP-Network Protocols are wrapped with an IP Header✔ Communication

▪ Layer-2/Hardware Broadcasts = Using MAC to address all nodes on a LAN ( Broadcast doesn't go past any routers / LAN only )▪ Layer-3 Broadcasts = All nodes on the network▪ Unicast = Single destination host (e.g. DHCP)▪ Multicast = Single source → many devices on different networks (Subscribed in a group address list )

✔ IP Schemes▪ IP (v4 – octets/bytes, v6 – octets/bytes)▪ Network Addressing (0) = Each network is named using ending 0 (e.g. 10.0.0.0, 172.16.0.0, 192.168.10.0)

▫ 0.0.0.0 = Default route or any network▫ 1.1.1.1 = All 1s Broadcast / Limited broadcast; reacts same as 255.255.255.255

Page 15: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▫ 0.0.16.23 = “This(0)” network where network bytes are (0)▫ 1.1.16.23 = “All(1)” networks node 16.23▫ 127.0.0.1 = Loop-back (local node)

▪ Broadcast Addressing (255) = Wild-card for network broadcasting▫ 255.255.255.255 – All networks; All nodes▫ 172.16.255.255 – All Subnets and hosts on 172.16.xx.xx

▪ IP Network Classes = A network can have various IP addressing schemes; Network → Subnet → Host▫ 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

▪ Private IP = Addresses for local network only ( Not routable )▫ NAT = Network Address Translation – Converts Private IP to 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 – By Cisco; Used in Virtual Private Dial-Up Networks (VPDN) proceeded by L2TP which is compatible with L2F▪ PPTP = Point-to-Point Tunneling Protocol – By Microsoft; data transfer from remote networks to corporate networks▪ L2TP = Layer 2 Tunneling Protocol – By Cisco & Microsoft; Replacement of L2F & PPTP (Merging the two)▪ GRE = Generic Routing Encapsulation – By Cisco; Create point to point links that allow variety of protocol encapsulation in the IP tunnel.▪ IPSec = IP Secure Transfer – A standard set of protocols for authentication & encryption services (IP-based only; Others require GRE tunnel then IPSec)

▫ AH = Authentication Header – Authentication is part of each data packet▫ ESP = Encapsulating Security Payload – Integrity check on the data packet

✔ IP Header▪ Protocol Field

▫ 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

A.5.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.0CIDR 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

CIDR 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 not wasting theother 252-IP addresses

A.6 Data-Link Layer-2 (MAC – Frame Data)✔ Framing and placing data on medium (Includes Switches and Bridges)

▪ 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

Page 16: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

✔ Beginning of MAC Address is Manufacturer and Serial Number on the end.✔ MAC address spoofing?

▪ LLC = Logical Link Control – Packet header with destination MAC address▪ MAC Frame = Bits → Bytes → Frames – Packets from Network layer become a MAC Frame with CRC 802.3 frames or Ethernet frames

Ethernet II Preamble8-bytes

DA6-bytes

SA6-bytes

Type2-bytes

Data?

FCS4-bytes

802.3 Ethernet Preamble8-bytes

DA6-bytes

SA6-bytes

Length2-bytes

Data?

FCS?

▫ 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 = Packet data (64 to 1500 bytes)▫ FCS = Frame Check Sequence (CRC)

✔ Routing Protocols▫ STP = Spanning Tree Protocol – Used to stop network loops from occurring▫ Spanning Tree Protocol – 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▪ Typical Serial Interface Protocols

▫ HDLC = High-Level Data-Link Control Protocol – ISO-standard encapsulation method for data on synchronous serial links (Point-to-Point Protocol)▫ PPP = Sets up point to point links for carrying HDLC – Used on asynchronous (dial-up) or synchronous (ISDN) serial media

✔ LCP = Link Control Protocol – Method of establishing, configuring and terminating P2P connections✔ NCP = Network Control Protocol – Establishing/Configuring multiple network layer protocols (routed protocols) on a P2P connection

∙ IPCP = Internet Protocol Control Protocol∙ IPXCP = Internetwork Packet Exchange Control Protocol

▪ Frame Relay – DataLink/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) = Like a phone call – only established when data needs transferred (for Private usage)

▪ Others▫ ISDN = Integrated Services Digital Network – Voice + Data over existing phone lines up to T1▫ LAPB = Link Access Procedure, Balanced▫ LAPD = Link Access Procedure, D-Channel – Used with ISDN as D-Channel access▫ HDLC = High-level Data Link Control – HDLC is manufacturer proprietary▫ PPPoE = Encapsulates PPP frames into Ethernet Frames for ADSL services

A.7 Physical Layer-1 (Ethernet)✔ Medium = Physical transmission tools used to deliver information or data (IE. Cabling / Voltage / etc...)✔ Protocols

▪ Ethernet Protocol [ 802.3 ]✔ Wired

▪ Cabling▫ 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 RS-232 Cat5 cable for Network equipment Terminal Emulation

A.7.1 WAN Physical Layer✔ Terms

▪ CPE = Customer Premises equipment – Leased equipment from service provider▪ Demarc = Demarcation Point – Where service provider responsibility ends and CPE begins (Typically an RJ-45 plug in a telecommunications closet)

▫ Demarc Cable Ends✔ EIA/TIA-232 or TIA-449✔ V.35 – For CSU/DSU connection point✔ EIA-530✔ HSSI = High Speed Serial Interface

▪ CO / POP = Central Office (CO) – Customer network to providers network▪ Local Loop = Closest CO → Demarc▪ POP = Point of Presence (Alias term for CO)▪ Toll Network = Trunk line in providers network▪ MTU = Maximum Transmission Unit▪ HSSI = High Speed Serial Interface▪ CATV = Cable TV lines; Coaxial Cable; HFC Network

✔ DSL = Digital Subscribe Line▪ Symmetrical DSL = Up/Download speeds the same

Page 17: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▪ 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 = Multiprotocol Label Switching✔ ATM = Asynchronous Transfer Mode ( Protocol used for DSL )

✔ Speeds▪ 64Kbps▪ 1.544Mbps(T1)▪ 4.5Mbps(T3)

✔ Wireless Local Area Networks (WLAN)

▪ 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) – 802.11b/g/n▫ 5.7GHz – Referred to as the Unlicensed National Information Infrastructure (UNII Band) – 802.11a/h

B. 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

C. Cisco Systems✔ Cisco Hierarchy Model

▪ Core Layer = No tables just fast switching (FDDI, Fast Ethernet, ATM)▪ Distribution Layer = Routers (IE. Workgroup Layer), Routing, Filtering, WAN Access and Core Bridge▪ Access Layer = (IE. Desktop Layer) Switches / Hosts

✔ IOS = Cisco's Internetworking Operating System – A Cisco OS Kernel for Routers / Switches✔ SDM= 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-zeroClass C you get subnets 0, 64, 128 and 192

2.7 Logic

2.7.1 7400-Series ICs 1. Labeling Notations

• 'L' = TTL (74LS00)• 'H' = CMOS (74HC00)

2. 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.

3. 162244 (SOIC-Package, much smaller & more devices)✔ http://en.wikipedia.org/wiki/7400_series

3. CIRCUIT THEORY✔ Quick and Simple http://www.tutorialspoint.com/computer_logical_organization/index.htm

Page 18: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

✔ http://www.allaboutcircuits.com/✔ Things to memorize

◌ Period = 1 / Frequency◌ Frequency = 1 / Period

▪ ½ = 0.500 Per (<>1) (=1)▪ 1/3 = 0.333 mS = Hz → kHz(k)▪ ¼ = 0.250 uS = kHz → Mega(M)▪ 1/5 = 0.200 nS = MHz → Giga(G)▪ 1/6 = 0.166▪ 1/7 = 0.142 Convert from Period <=> Frequency ask what is 1/x 1 0 1:1 else inverse count▪ 1/8 = 0.125 Then switch the Eng Notation as listed above.▪ 1/9 = 0.111 Ex. 2nS ½ = 0.5 500MHz (0-0s = 2-0s)▪ 1/10 = 0.100 Ex. 20nS ½ = 0.5 50MHz (1-0s = 1-0s)▪ x Ex. 200nS ½ = 0.5 5MHz (2-0s = None)

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 = Signal amplifier that implements a differential amplifier circuit. 3. Transformer = A group of inductors (IE. Coils) that transforms the level of AC Voltage and Current (IE. step-up or step-down voltage level) 4. Transistors

a) NMOS b) PMOS

5. Diode 6. Capacitor 7. Inductor (IE. coil) 8. Resistor

3.2 Digital Combinational Logic Circuits = directly responds to input changeSequential Logic = remembers present state and combines with input changes to create a new stateSynchronous Sequential = Inputs are only evaluated at master-clock signal changeAsynchronous Sequential = Responds to inputs at speeds determined by the devices themselves rather than a master-clock.

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 code)

✔ 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.

✔ Sequential logic components have output registers (IE. latches) to hold output-level until the next clock cycle (IE. Evaluation point-in-time)◌ Register outputs re-route to register inputs after a fashion

A.1 Synchronous (In-Sync) 1. Output state of all logic only changes at the master clock signal (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.

A.2 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

A.3 Implementation

A.3.1 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)

A.3.2 Pipe-Lining✔ Pipe-Lining is a 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

Page 19: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

✔ 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) AND OR b) 0*0=0 1+1=1 c) 1*1=1 0+0=0 d) 0*1=1*0=0 1+0=0+1=1 e) If x=0 {x'=1} If x=1 {x'=0}

3. Theorems a) AND OR b) x*0=0 x+1=1 // Huntington's Basic Postulate c) x*1=x x+0=x d) xx=x x+x=x e) x!x=0 x+x'=1 // Huntington's Basic Postulate f) !!x=x

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) x*(y+z)=x*y+x*z x+y*z=(x+y)*(x+z) // Distributive // Huntington's Basic Postulate f) x+x*y=x x*(x+y)=x // Absorption g) xy + xy! = x (x+y)(x+y!)=x // Combining h) !(xy)=!x+!y !(x+Y)=!x!y // DeMorgan's theorem i) x+!xy=x+y x(!x+y)=xy j) 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 Logic Gates✔ Logic Gates = standard / common switch-circuit designs created specifically for handling basic digital logic.

◌ switch = transistors used for digital purposes – Only “on=1 / off=0” states are relevant

Page 20: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

◌ 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-flops are a common logic-gate circuit design that can retain logic levels through time (memory)

Flip-Flop Q = Output DescriptionD D = Q D sets Q @ rising edge of CLKT &

SR Set / Reset |JK J=Set, K=Reset ~&

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

◌ Logic Gates – are a common transistor level circuit design. Logic Gates Verilog-Symbol Description (Input → Output)

NOT Inverse ~ 1 → 0 / 0 → 1AND All-Input-AND & 1,1,1(all) → 1 ELSE → 0OR All-Input-OR | 0,0,0(all) → 0 ELSE → 1NAND NOT AND ~& → NOT(AND)NOR NOT OR ~| → NOT(OR)XOR Exclusive OR ^ 0,1,0(1-1) → 1 ELSE → 0XNOR Exlusive NOT OR ~^ → NOT(XOR)

✔ 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.3 Mixed-Signal ( Analog & Digital ) ✔ More @ http://en.wikipedia.org/wiki/Electronic_circuits

✔ ADC = Analog to Digital Circuit – Converts an Analog Input to a Digital Number ( Voltage level → Digital Number )✔ DAC = Digital to Analog Circuit – Converts a Digital Number to an Analog Output ( Digital Number → Voltage Level )✔ http://en.wikipedia.org/wiki/Finite_impulse_response FIR Filter

4. SYSTEM CIRCUIT DESIGN

4.1 Planning

4.1.1 Outlining✔ Create detailed design purpose and specifications for the system / circuit

◌ Document the system circuits purpose / goal◌ Document the specification the system must meet.◌ Draw a block diagram of the designs function blocks◌ Specify Input and Output (I/O) Interfaces and standards that might be implemented◌ Specify any internal interconnect architecture (IE. Standard Bus's)◌ Financial Feasibility and Market

4.1.2 Interconnect Standards◌ 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.

4.1.3 IP-Cores (Re-Use)✔ IP-Cores/Blocks are standard or already designed circuits that can be re-used. (IE. Intellectual Property (IP))

◌ IP-Cores typically have Interconnection Standards that need to be considered.◌ IP-Core = Intellectual Property Circuit Design – A circuit design considered as property (IE. Copyrighted) and intended for re-use in multiple circuit designs.

Drawing 2: Gates of a D-Flip-Flop

Drawing 1: Logic Gate Schematic Symbols

Illustration 1: Example Planning Block Diagram for an IC.

Page 21: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

◌ SIP = Semiconductor IP-Core – An IP-Core for semiconductor integrated circuit (IC) implementation.

✔ List of places to get IP-Cores◌ http://www.free-ip.com/ (Out-Of-Business; Dead-Link)◌ 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 etc.◌ 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.4 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 Design Flow ✔ Circuit design steps

◌ Entry – Enter the circuit design (Includes imported IP-Cores)◌ Synthesis – (IE. Compile) the circuit design to lower-level NetList◌ Validate – that the design meets planned specification◌ Simulate – the circuit to verify operation◌ Layout – Prepare design for target hardware (IE. Floor Planning / Placement and Routing / Fitting )

✔ 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

✔ Circuit design best-practices◌ little code → test → little more code → test (not write a bunch and run)◌ Concept → Partition(Divide & Conquer) → Block1, Block2, etc...

4.2.1 Design Software (EDA / ECAD)✔ EDA = Electronic Design Automation – Category of PC-Software specifically for System Circuit Designing (IE. Electronic Engineering )✔ ECAD = Electronic-Computer Aided Drafting – Another term for EDA. EDA software tools are considered a sector of the Computer Aided Design (ECAD) category✔ CAE = Computer Aided Engineering – Yet another term for CAD

✔ Wiki list of EDA Vendor Software packages http://en.wikipedia.org/wiki/Category:Electronic_design_automation_companies✔ Wiki comparison list of EDA Software packages http://en.wikipedia.org/wiki/Comparison_of_EDA_Software

✔ EDA Tools were originally created on Linux OS Shells.◌ EDA Tools typically contain a slew of “<command>.exe” files inside the tools sub-directory◌ EDA Tool commands typically can be invoked entirely from the OS command line

▪ Graphical User Interfaces (GUI) s are usually just helper tools that auto-launch commands)◌ Tcl = Tool command language – Tcl is a Linux scripting language / shell (windows ported); It is used heavily in EDA tool automation (IE. Tool Integration).

✔ SDL = Specification and Description Language

---[ Sample List of EDA Vendors and tools (based on assumed popularity)]---✔ Synopsis

◌ Synplify – FPGA design solution by Synplicity (Acquired by Synopsis in 2008)

✔ Mentor Graphics◌ Leonardo Spectrum = CPLD, FPGA or ASIC Synthesis◌ Precision RTL◌ ModelSim

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

✔ Xilinx (FPGA/CPLD)◌ Vivado

✔ Altera (FPGA/CPLD)

Page 22: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

◌ Quartus-II◌ Qsys = Previously “SOPC-Builder”

✔ Reference◌ http://en.wikipedia.org/wiki/Synopsys – http://www.synopsys.com/home.aspx – Commercial◌ http://en.wikipedia.org/wiki/Mentor_Graphics – http://www.mentor.com/products/fpga/synthesis/ – Commercial◌ http://en.wikipedia.org/wiki/Cadence_Design_Systems – http://www.cadence.com/en/default.aspx – Commercial◌ http://en.wikipedia.org/wiki/Altium – http://www.altium.com/ – Commercial◌ http://en.wikipedia.org/wiki/GEDA – http://www.geda-project.org/ – OpenSource◌ http://en.wikipedia.org/wiki/KiCAD – http://www.kicad-pcb.org/display/KICAD/KiCad+EDA+Software+Suite – OpenSource

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

◌ SPICE Simulation often uses Schematic Entry to simulate circuit designs.

Page 23: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

4.2.3 HDL EntryHDL Coding Styles http://www.maia-eda.net/index.php?option=com_content&task=view&id=121&Itemid=258✔ HDL Languages

◌ Standard▪ VHDL – (.vhd) file extension – VHSIC(Very High Speed Integrated Circuit) HDL▪ Verilog – (.v) file extension – Rights Recently purchased by Cadence

◌ Variations / Extensions▪ Actel HDL (AHDL)▪ Altera HDL (AHDL)▪ SystemC – Is a C++ libarary (TLM - Transaction Level Modeling) much higher-level than RTL (early

architectural design) ▪ Verilog-A – Analog design extension for Verilog▪ BlueSpec Verilog – Atom System Verilog (Guarded atomic actions); Is a Verilog Simulation extension package.

◌ Historical▪ ABEL – From 1981 see http://en.wikipedia.org/wiki/Advanced_Boolean_Expression_Language▪ PALASM – PAL HDL from 1980s; see http://en.wikipedia.org/wiki/PALASM

✔ HDL Modeling (HDL is a Mixed-level description language)

◌ Synthesizable Code – Code that is synthesized for circuit implementation; Commonly referred to as RTL (Even though RTL's actual meaning is quite different)▪ Algorithm level code – much like c-code with if, case, loop statements Example; 'Z=X+Y' for 32-bit adder▪ Register Transfer level(RTL) code – Registers connected by Boolean equations that determine how data moves / progresses through the system.▪ Gate level code – Boolean expression interconnects AND, NOR, and etc.. Example; 'Z <= X AND Y'▪ Switch level code – IE. transistor level; the MOS transistors inside the gates

◌ Simulation Code – HDL code that is used only for simulation purposes

◌ Code Types▪ Structural; – Noun Emphasis (Concurrent) – Tying together gate-level components (verbal wiring diagram w/o storage); Example assign a = b & c | d & (~c);▪ Behavior/Procedural; – Verb Emphasis (Sequential) – describes IO responses; what it does or how it behaves.

✔ 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'

✔ Favorite learning HDL links◌ 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

✔ Coding Practices◌ 'addr' address; sys_addr, up_addr◌ 'clk' clock; clk_div2, clk_x2◌ 'rst' reset;◌ 'arst' asynchronous reset;◌ 'arst_l' active-low◌ 'rw_l' read-write (write is active-low)◌ %signal_io for bi-directional◌ %signal_l active-low

▪ DONT use IN/OUT because of hierarchical boundaries (in = out)◌ %signal_i (internal signal)

▪ Use %signal_i to count and pass to 'count' port because 'buffer' requires all connecting components to be 'buffer' and 'inout' is bad. (I have it right!)◌ %variable_v◌ Pipe-lining

▪ %signal after pipe-lining▪ %signal_p0, %signal_p1 signals after a pipeline▪ %signal_q0, %signal_q1 signals before a pipeline

◌ Physical IO maybe should be all-caps (Aptina)

✔ Excellent Websites◌ HDL examples including I/O Hardware Interfaces and descriptions http://www.fpga4fun.com/

A. Verilog

A.1 Circuit → Verilog// 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>

// Module = A named sub-circuit with an external interfacemodule learnbasic(input wire ClkIn, RstIn, ReqIn, // Port = External connection. (type is optional and 'wire' by default) input [7:0] AddTo7, HalfIn, ShifLft, // - 'input' (type wire only) An input for a module or task inout [7:0] DataLine, Trans1, Trans2, // - 'inout' (type wire only) Tri-State (input and output) output wire ClkLight, RstLight, ReqLight, // - 'output' (any net type) Output - driven signal output reg BcdOut1, BcdOut2, BcdOut3, OddIn7,

Page 24: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

output [7:0] Sum7, HalfOut, Shift, output [15:0] HWord1, HWord2, HWord3, output [31:0] Word1, Word2, Word3); // [msb:lsb] bundle/bus

// ** Verilog93 - separated port naming and port declarations **// STRUCTURAL - Combinational Logic Circuit design ( Concurrent Operation )

parameter WIDTH = 5; // assign/drive net-connectors only once ELSE U-get "Error 10028 Can't resolve multiple constant drivers for net "?"." //--Internal connectors--// //// 4-Assignable states ('0','1','X','Z'); Can be assigned an initial value. wire [7:0]Sum,DivOut = 0; // - wire (basic connector) General purpose wire wand [7:0]Active; // - wand (Wired AND) 0-Dominates; All connections to the wire are AND'ed together wor a; // - wor (Wired OR) 1-Dominates; All connections to the wire are OR'ed together tri b; // - tri (Wired tri-state) Single-Driver; triand, trior, tri0, tri1; all must be z except one driver line supply0 Gnd; // - supply0 (Wired Ground) Tied directly to power-level(0) supply1 Vcc; // - supply1 (Wired Power) Tied directly to power-level(1) reg [7:0]OperReg = 0; // - reg (Wired-Register) Reflects a variable value. wire Enable,EnableN; //// Multiple items seperated by ',' //--[ Drive-Line ]--// //// Bit-literal assignments (%bit-size'%base%%value%) assign Word2 = 123; // (default) 32-bit decimal assign Word3 = 32'd123; // 'd' = decimal Exactly the same as above reg [7:0]Div2 = 8'b0000_0010; // 'b' = binary '_' are ignored reg [7:0]Seven = 8'h7; // 'h' = hexidicamal assign W8C = 8'o377; // 'o' = octal //--[ Logic Gates ]--// //// Primitives +--------------------------------------------------------------- not(Active[0],RstIn); // Gate-Syntax | not(o,i) = '~' notif(o,i) notif0() notif1() buf U1(DataLine,A8); // Named 'U1' | buf(o,i) bufif(o,i,e) bufif0() bufif1() assign EnableN = ~Enable; // BitWise-Syntax | and(o,i..) = '&' or() = '|' xor() = '^' assign Enable = ClkIn & RstIn; // | nand(o,i..) = '~&' nor() = '~|' xnor() = '~^' notif0(Trans1,DataIn1,EnableN); // Not-gate with a Tri-state output and an active-low('if0') enable. bufif1(Trans2,DataIn2,Enable); // Buffer with a Tri-state output and an active-high('if1') enable. //--[ Algorithmic ]--// //// Operator Components assign Sum7 = AddTo7 + Seven; // '+' Addition '-' Subtraction/Negative '*' multiplica assign HalfOut = HalfIn / Div2; // '/' divide '%' modulus '**' exponent assign Shift = HalfOut << 1; // '>>' shift right '>>>' arithmetic right shift // And opposite for left-shift assign HWord1 = {1'b0,Sum7[6:0],Shift}; // '{}' concatenate - Combine "0,Sum7[6:0],Shift" to make 'HWord1' assign Word1 = {2{HWord1}}; // Replicate 'HWord1' twice to produce a twice as large connector bus 'Word1'

// ABSTRACTION

//--[ Generate ]--// //// Pre-compiler auto-line generator generate //// Example produces the equivalent of 4-stand lines: genvar i; // not Auto[0](HWord2[0],Seven[0]); for( i = 0; i <= 3; i = i + 1) // not Auto[1](HWord2[1],Seven[1]); begin:Auto // not Auto[2](HWord2[2],Seven[2]); not(HWord2[i],Seven[i]); // not Auto[3](HWord2[3],Seven[3]); end endgenerate //--[ Function ]--// 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.. // 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 BcdOut1 = (RstIn == 1) ? 0: 1; // '?:' IF...THEN Active[1] = (Comparison) ? TrueValue : FalseValue; if(ClkIn == 1 && RstIn != 1) BcdOut2 = 1; // '==' EQUALS '>=' Greater/Equal '&<=' Less/Equal '!=' Not Equal else if (RstIn == !ReqIn || ClkIn == 0) BcdOut3 = 1; // '!' NOT '&&' AND '||' OR

if(ClkIn == 1) begin case(AddTo7) // casex() to allow 'X', casez() to allow 'Z' and wild-card '?' but not 'X' 8'b0 : OddIn7 <= 1; // '<=' is for Synchronous logic where RHS is evaluated but only assigned on next trigger. 8'b1 : OddIn7 <= 1; 8'd3 : OddIn7 <= 1; default : OddIn7 <= 0; endcase end end

// SIMULATION - Testbench

initial begin // Executed once at very beginning of simulation end task DoSomething; $display("Hi"); endtask time z; // Record current Sim time

// {SO} initial Initialize simulation execution block (Executes once at start of simulation)//{SO} wait(%condition) delay execution till condition is true.//{SO} #5 a = 20 a = 20 after 5 time units. Evaluate statement only after the delay in time units. //{SO} c = #5 a; c = a after 5 time units. 'a' is evaluated immediately then after delay it is assigned to 'c'.//{SO} fork...join Concurrent execute statements within

endmodule

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

endmodule

Page 25: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

B. VHDL

B.1 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.Partsuse 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'=WeakUnknownuse ieee.numeric_std.all; -- Include the 'numeric_std' package //Allows arithmetic(+,-,/,*) on 'std_logic_1164' values.

B.2 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 :=Initial Valuedebounce_on : IN STD_LOGIC := '0';debounce_off : IN STD_LOGIC := '0'; -- SR Latch debounce requires double-throw switches (on/off)debounce_out : BUFFER STD_LOGIC := '0'; -- Buffers allow output to be wired to other internal circuitsdebounce_out_n : OUT STD_LOGIC := '0'; -- Inverted 'debounce_out'

mux_in1 : IN STD_LOGIC := '0';mux_in2 : IN STD_LOGIC := '0';mux_sel : IN STD_LOGIC := '0';mux_out : OUT STD_LOGIC := '0';

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

add_in1 : IN STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_in2 : IN STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_sum : OUT STD_LOGIC_VECTOR ((ADD_BITS - 1) DOWNTO 0) := "0000";add_carry : OUT STD_LOGIC);

clk_in : IN STD_LOGIC := '0';clk_out : BUFFER STD_LOGIC := '0';

SegDisplay : OUT STD_LOGIC_VECTOR (6 DOWNTO 0)); -- 7 Segment DisplayEND EntityName;

--====================================================================================================================ARCHITECTURE ArchitectureName OF EntityName IS--====================================================================================================================

B.3 Declarations (Architecture)✔ SIGNAL / CONSTANTS / TYPE / SUBTYPE definition area local to the Architecture✔ FUNCTION / PROCEDURE / COMPONENT declarations are generally declared here.--[ Inter-Architecture ]-----------------------------------------------------------------------SIGNAL ABitIs1 : BIT;SIGNAL Bit1 : BIT; -- BIT is a basic data typeSIGNAL 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 : STD_LOGIC_VECTOR (ADD_BITS DOWNTO 0);-- +1 bit for full add sum of other 2.SIGNAL debounce_tmp : STD_LOGIC;

SIGNAL StateClk : STD_LOGIC; -- Clock that increments the state machineSUBTYPE TwoBits : STD_LOGIC_VECTOR(1 DOWNTO 0); -- Parse out any STD_LOGIC_VECTOR to only 2-bits.TYPE States IS ( Display1, Display2, Display3, Display4 ); -- Each State is enumerated (User-Defined-Type)TYPE SegMem IS ARRAY ( 1 TO 4 ) OF STD_LOGIC_VECTOR(6 DOWNTO 0); -- Build ROM for Segment Display of each number.

CONSTANT SegROM : SegMem := (x"F", -- index(1); Bits on 7 Segment display to show a '1'x"FF", -- index(2); Bits on 7 Segment display to show a '2'x"FF", -- index(3); Bits on 7 Segment display to show a '3'x"A"); -- index(4); Bits on 7 Segment display to show a '4'

B.3.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;

B.4 Architecture (BEGIN)----------------------------------------------------------------------------------------------------------------------BEGIN -- Circuit design----------------------------------------------------------------------------------------------------------------------

B.5 <= and => (SIGNAL Assignment)--[ '<=' & '=>' (Structrual) ]------------------------------------------------------------------

ABitIs1 <= '1'; -- '<=' assign; 'ABitIs1' = '1'Bits_n <= ( 0 => NOT Bit1, 1 => NOT Bit2 ); -- '=>' Named connection; connect Bits_n(0) to 'NOT Bit1' etc...

Page 26: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

Bits <= ( Bit1, Bit2 ); -- Positional connection; connect Bits(0) to 'Bit1' etc...Bits_0 <= ( OTHERS => '0' ); -- 'OTHERS' keyword; connect all other un-assigned bits to '0'

B.6 Logic Gates--[ Gates (Structural) ]-------------------------------------------------------------------------

debounce_tmp <= debounce_off NAND debounce_out; -- Support-for: NOT AND OR NAND NOR XOR XNORdebounce_out <= debounce_on NAND debounce_tmp; -- Cross wired NAND gates (order doesn't matter in structural)debounce_out_n <= NOT debounce_out; -- Inverted output

B.7 GENERATE--[ GENERATE (Structural) ]---------------------------------------------------------------------

G1: FOR i IN Bits_1'RANGE GENERATE -- Auto Generate assignment statements (must have a 'label:' pre-fix)Bits_1(i) <= '1';

END GENERATE;

B.8 WHEN...ELSE--[ WHEN...ELSE (Structural) ]------------------------------------------------------------------

dmux_out <= '0' & dmux_in WHEN (mux_sel = '0') ELSE -- When 'mux_sel' = 0; 'dmux_out' = Concatenate '0' & 'dmux_in'dmux_in & '0' WHEN (mux_sel = '1') ELSE -- When 'mux_sel' = 1; 'dmux_out' = Concatenate 'dmux_in' & '0'"ZZ" WHEN (mux_sel = 'U' OR mux_sel = 'Z') ELSE -- When 'mux_sel' = 'Z' or 'U'; 'dmux_out' = "ZZ" (disconnect)"--"; -- ELSE; 'dmux_out' = "--"(don't care)

B.9 WITH...SELECT--[ WITH...SELECT (Structural) ]-----------------------------------------------------------------

WITH (mux_sel) SELECTmux_out <= mux_in1 WHEN '0', -- Connect 'mux_out' to 'mux_in1' when 'mux_sel' = 0

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

B.10 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); -- sumadd_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----------------------------------------------------------------------------------------------------------------------

B.11 PROCESS (Sequential)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

B.11.1 VARIABLE✔ A VARIABLE is assigned using “:=”✔ A SIGNAL assignment uses “<=”✔ An Equals Comparison uses “=”

B.11.2 IF...THEN– IF <condition> THEN <assign>; ELSIF <condition> THEN <assign>; ELSE <assign>; END IF;

--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvPROCESS(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 THENclkcnt := 0;

ELSEclkcnt := clkcnt + 1;

END IF;

END PROCESS;

B.11.3 WAIT✔ WAIT FOR <signal condition>;✔ WAIT ON <signals>;✔ WAIT UNTIL <time>;

B.11.4 CASE...WHEN

B.11.5 FOR...LOOP

B.11.6 WHILE...LOOP--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvPROCESS -- 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 -- SYNCHRONOUSWAIT 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 =>

Page 27: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

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'HIGHLOOP

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

ELSENEXT; -- Example of continuing loop w/o finish.

END IF; END LOOP;

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

END PROCESS;END ArchitectureName;

--===================================================================================================================================================-- VHDL = VHSIC Hardware Design Language - (VHSIC=Very High Speed Integrated Circuit)-- * Not Case-Sensitive-- * No block commenting-- * All EOL(end-of-line) = ';'-- Comments legend:-- '| |' wrappers means OPTIONAL -- '!' Should be read as NOT--===================================================================================================================================================

------------------------------------------------------------------------------------------------------------------------- INCLUDE LIBRARIES (IE. Directories) to find Re-usable codelibrary 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.Partsuse 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'=WeakUnknownuse ieee.numeric_std.all; -- Include the 'numeric_std' package //Allows arithmetic(+,-,/,*) on 'std_logic_1164' values.

ENTITY EntityName IS -- A circuit's external interface definition block uniquely named or U-get "conflicts with primitive name".

GENERIC ( -- Values that can be over-ridden externally (See COMPONENT & COMPONENT Instance). ---------------------------------------------------------------------------------------- --|Class| IDs : DataType |:=InitValue| - Default |Class| = 'CONSTANT' CONSTANT By : INTEGER := 8; tphz, tplz : TIME := 3 ns; GenConst : BIT := '1'; cnt_dir : STRING := "up"); -- CONSTANT datamem : BIT_VECTOR := (('0','0'),('1','1'));

PORT ( -- Entities External “Pin-In/Out” Connectors --|Class| IDs: Mode DataType |:=InitValue| - Default |Class| = 'SIGNAL' SIGNAL P3 : IN BIT; --[ MODES ]-- clk : IN BIT; -- 'IN' indicates that the signal is an input led1 : OUT BIT; -- 'OUT' indicates that the signal is an output(Driven); not readable ( led1 <= not led1 !!ERROR). tri1 : INOUT BIT; -- 'INOUT' the signal can be an input or an output. buf1 : BUFFER BIT; -- 'BUFFER' indicates that the signal is an output but readable by the entity’s architecture SIGNAL P2 : IN BIT; --[ Data Types ]-- OnOff : IN BOOLEAN; -- 'BOOLEAN' can have the value TRUE or FALSE IntIn : IN INTEGER; -- 'INTEGER' can have a range of integer values Float : OUT REAL; -- 'REAL' can have a range of real values Letter : OUT CHARACTER; -- 'CHARACTER' any printing character STime : OUT TIME; -- 'TIME' to indicate time Logic1 : IN STD_LOGIC; -- STD_LOGIC {1,0,X,Z,-,U,H,L,W} from "IEEE.std_logic_1164.All" library ULogic : IN STD_LOGIC := '1'; -- 1/0=Logical An Initially driven connector (1=Logical'1' 0=Logical'0' and etc...) DrivenU : IN STD_LOGIC := 'H'; -- H=Weak High Defaults to '1' when not specifically driven; Like a pull-up resistor. DrivenX : IN STD_LOGIC := 'L'; -- L=Weak Low Defaults to '0' when not specifically driven; Like a pull-down resistor. DrivenX : IN STD_LOGIC := 'Z'; -- Z=High Impedance Disconnects when not specifically driven. DrivenX : IN STD_LOGIC := 'W'; -- W=Weak Typically not set directly DrivenX : IN STD_LOGIC := 'X'; -- X=Unknown Typically not set directly DrivenX : IN STD_LOGIC := 'U'; -- U=Uninitialized Typically not set directly Driven1 : IN STD_LOGIC := '-'; -- -=don't care SIGNAL P1 : IN BIT_VECTOR (0 TO 7); --[ VECTORS ] = Array/Bundle/Bus of indexed connectors VLogic : OUT STD_LOGIC_VECTOR (15 DOWNTO 0); -- Signed STD_LOGIC //'DOWNTO' = MSB(15) - LSB(0) little-endian VULogic : OUT STD_ULOGIC_VECTOR (0 TO 15); -- UnSigned STD_LOGIC //'TO' = MSB(0) - LSB(15) big-endian Seven : OUT STD_LOGIC_VECTOR (3 DOWNTO 0) := "0001"; -- Initially driven STD_LOGIC_VECTOR Reverse : OUT STD_LOGIC_VECTOR (3 DOWNTO 0) := "LLLL");-- Last internal PORT line no ';'

-- ** ABSTRACTION "Function" and "Procedure" (!Component) can be defined here in the ENTITY **

END EntityName;

ARCHITECTURE ArchitectureName OF EntityName IS -- A circuit's internal design - Circuit-design(ARCHITECTURE) OF Circuits-external-interface(ENTITY)

Page 28: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

--{{ Declare Section (HEADER) }}--

--[ Constants ]-- CONSTANT widtha := 3; --[ Connectors ]-- -- SIGNALS do not update till end of process (end of PROCESS block assignment)

SIGNAL local1,local2,w,e,r,t,u: BIT; -- Scalars: BIT, STD_LOGIC, STD_ULOGIC, BOOLEANSIGNAL lLogic: STD_LOGIC_VECTOR (31 DOWNTO 0); -- Vectors: BIT_VECTOR, STD_LOGIC_VECTOR, STD_ULOGIC_VECTOR, INTEGER, SIGNED, UNSIGNED SIGNAL aLogic: STD_LOGIC_VECTOR (31 DOWNTO 0);SIGNAL bLogic: STD_LOGIC_VECTOR (31 DOWNTO 0);SIGNAL cLogic: STD_LOGIC_VECTOR (31 DOWNTO 0);SIGNAL dLogic: STD_LOGIC_VECTOR (31 DOWNTO 0);SIGNAL DblWord: STD_LOGIC_VECTOR (63 DOWNTO 0);SIGNAL Lom: BIT_VECTOR(15 DOWNTO 0);SIGNAL Loo: BIT_VECTOR(15 DOWNTO 0);SIGNAL Q,D: BIT; SIGNAL output : STD_LOGIC;

--[ VARIABLES ]-- (:= assign)(*Within PROCESS block Only [!Concurrent])VARIABLE Onne: NATURAL;VARIABLE Twwo: POSITIVE;VARIABLE Thhe: CHARACTER;VARIABLE Foor: STRING;VARIABLE Fvve: TIME;VARIABLE Siix: REAL;VARIABLE Veas: INTEGER;VARIABLE Seil: INTEGER;VARIABLE x,y,p,temp: INTEGER;

-- [ UDT ]-- ---- (User-Defined-Types; Not allowed in entity but OK in Package) TYPE Color IS (Red, Green, Blue); -- (Enum 0, 1, 2) perspectively; Define a data-structure (Cannot be defined in entity)

TYPE MyInt IS RANGE -255 TO 255; TYPE table IS ARRAY (7 DOWNTO 0) OF STD_LOGIC; -- A one dimensional array of vector identifiers.

TYPE Rec IS RECORD -- TYPE RECORD is for creating structs of different types. day: INTEGER RANGE 1 TO 31; month: CHARACTER; END RECORD; SUBTYPE MyMiniInt IS INTEGER RANGE -32 TO 32; -- A TYPE with constraints. Allows standard operations of it's base type (MyMiniInt can do any operation of INTEGER) -------------------------------------------------------------------------------------------------------------------------------- -- ABSTRACTION; Typically, abstraction blocks are written and tested outside of a package and later pasted/put into a package. ** See PACKAGING section ** -- Abstraction blocks "Function" and "Procedure" can optionally be defined in the ENTITY -------------------------------------------------------------------------------------------------------------------------------- COMPONENT and2 -- Import an ENTITY defined elsewhere into this design for code re-use (Components allows stored data). port (in1, in2: in std_logic; -- "ENTITY and2" must be defined in a file within the project somewhere. out1: out std_logic); -- Define interface of the 'and2' entity (copy of it's port() section) END COMPONENT; FUNCTION EFuncName(CONSTANT z: STD_LOGIC; SIGNAL a, b: BIT) RETURN BOOLEAN IS -- Pre-Defined a PROCESS block BEGIN -- 'VARIABLE' not allowed; Ranges shouldn't be specified. -- ARGS(|CONSTANT| / SIGNAL) RETURN 1-item;

-- Functions initialize data on each call - no stored data -- Doesn't support WAIT RETURN(FALSE); END EFuncName;

PROCEDURE EProcName(a: IN BIT, SIGNAL b, c: IN BIT, SIGNAL x: OUT BIT_VECTOR(7 DOWNTO 0)) IS ATTRIBUTE NumOfInputs: INTEGER; -- declaration EProcName'NumOfInputs -- Declare ( For IN CONSTANT is default; OUT,INOUT default VARIABLE. ) BEGIN --[ PROCEDURE ] = Pre-Defined PROCESS with connectors (IN/INOUT/OUT) -- Procedure body END EprocName;

BEGIN -- Circuit design. The BODY of the architecture

--[ Shift ]--Loo <= Lom SRA 1; -- (Bit-Shift; fill0) SLL = Shift-left SRL = Shift-right fill0 -- (Arithmetic; fill-bit) SLA = Shift-left SRA = Shift-right

-- (Rotate) ROL = Rotate-left ROR = Rotate Right

--[ Structural Directives ]--lLogic(15) <= '1' when (lLogic(0) = '0') else -- WHEN...ELSE - Process/Structural but Case is required in Process.

'Z' when (lLogic(0) /= '0') else '1'; -- Relational Operators '=' Equals '/=' Not-Equal '<' '<=' '>' '>='

--[ Arithmetic ]-- (Package 'numeric_std' required.)aLogic <= std_LOGIC_VECTOR(unsigned(cLogic) + unsigned(dLogic)); -- Casting for type alignment.bLogic <= std_LOGIC_VECTOR(unsigned(cLogic) - unsigned(dLogic)); --| '+'= Add '-' = Subtract/NegativeDblWord <= cLogic & dLogic; --| '&'= Concatenate 'MOD'= ModuluscLogic <= std_LOGIC_VECTOR(unsigned(cLogic) MOD unsigned(dLogic));--| '*'= Multipley '/' = Divide

--[ Generate / Properties ]--MyGen: FOR I IN lLogic'HIGH DOWNTO 0 GENERATE -- Use Property 'HIGH to get Upper-Bounds

lLogic(I) <= '1'; END GENERATE MyGen; MyGen2: FOR I IN aLogic'RANGE GENERATE -- Use Property 'RANGE to iterate EACH

aLogic(I) <= '0';END GENERATE MyGen2;

--[ Block ]-- ---- Custom Code BLOCK for partitioning code; nesting is OK; Block can have a (Guarded) Event line. MyCodeBlock: BLOCK BEGIN -- Can create For...Loop that is Concurrent/Combinational logic (RANGE must be static!) e <= '1'; -- IF can also be used but not 'else' w <= '0';

END BLOCK MyCodeBlock;

MyBlock: BLOCK (Clk'EVENT and Clk = '0') BEGIN -- Driver active when (Guard) is TRUE Q <= guarded D; END BLOCK MyBlock;

-- [ BEHAVIORAL ]-- // Sequential Code PROCESS, FUNCTION, PROCEDURE block-lines are the only ones executed sequentiallyPROCESS (clk) -- Block executes any time an item in the %sensitivity_list changes state; items must be in code or they are ignored.

-- labelname: PROCESS (clk); -- Optionally; a process can be labelled with a name. VARIABLE x, y: INTEGER; -- Local Variable definitions VARIABLE a, b, c: STD_LOGIC;

Page 29: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

VARIABLE sel : STD_LOGIC_VECTOR(1 DOWNTO 0);BEGIN

--[ Variable Assignment ]--Veas := 44; --

-- IF / THEN / ELSEIF (x=y) THEN

x := 0;ELSIF (x=y AND w='0') THEN y := 1;ELSE x := 11;

END IF;

-- CaseCASE sel IS

WHEN "00" => output <= '1';WHEN "01" => output <= '0';WHEN "10" => output <= '0';WHEN "11" => output <= 'Z';WHEN OTHERS => output <= 'X';

END CASE;-- CASE bLogic IS -- CASE / WHEN (Sequential - NULL) whereas WHEN is (Concurrent - UNAFFECTED)---- WHEN "00" => 1 :=x; -- <=b; -- CASE allows multiple settings but WHEN only allows 1.---- WHEN OTHERS => 0 := 0; -- <="ZZZZ"; -- Special instructions NULL and UNAFFECTED-- END CASE;

FOR i IN 0 TO 5 LOOP -- FOR LOOP ('label: FOR...' is optional); range must be static.-- i = i + 1; -- ILLEGAL (Cannot modify the iterator; Iterator-Id doesn't need to be declared)

-- EXIT slabel WHEN (i = 2); -- %condition;-- Break loop -- NEXT -- slabel; -- WHEN %condition; -- Continue loop without finishing

-- WHEN OTHERS => EXIT; END LOOP;

llabel: WHILE (D = '1') LOOP -- WHILE LOOP ('label: WHILE...' is optional) END LOOP llabel;

END PROCESS;

END ArchitectureName;-- +---<C.Configuration>----------------------------------------------------------------------------------------------------------- C) Configuration (Ties the Architecture and Entity together)-- CONFIGURATION %config_name% OF %entity_name% IS-- FOR %architecture_name%-- END FOR;-- END CONFIGURATION %config_name% ;-- </C.Configuration>--===================================================================================================================================================-- PACKAGING ( Creating Custom Libraries )--===================================================================================================================================================

--===================================================================================================================================================-- SIMULATION ( VHDL Features that are NOT-Synthesizable are used for circuit simulation purposes )--===================================================================================================================================================ARCHITECTURE TestBench OF EntityName ISBEGIN

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

-- ASSERT("Hi"); -- Manually display compiling errors and stuff.END TestBench;

-------------------------------------------------------------------------------------------------------------------------------------------------- ClockDiv Circuit Design------------------------------------------------------------------------------------------------------------------------------------------------library ieee;use ieee.std_logic_1164.all;

entity ClockDiv isgeneric ( div: integer :=15 );port ( clkin: in std_logic; clkout: out std_logic);

end ClockDiv;

architecture ClockDiv of ClockDiv isbegin

process(clkin)variable output : std_logic;variable clkcnt : integer := 0;

beginif rising_edge(clkin) THEN

clkcnt := clkcnt + 1;if clkcnt = div then

clkcnt := 0;output := NOT output;

elseNULL;

end if;else

NULL;end if;clkout <= output;

end process;end ClockDiv;

--===================================================================================================================================================-- ERRORS ( VHDL Common Errors / Fixes )--===================================================================================================================================================-- "signal does not hold value after clock edge" - Usually only one item can be defined either at rising edge or falling edge but not both.-- "multiply driven" - also same as above usually.-- "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.

Page 30: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

B.12 CONFIGURATIONWhen 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 instanceCONFIGURATION 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' apply within the parent 'for acrchitecture' designated.CONFIGURATION ForMyEntity OF MyEntity IS

FOR MyArchitectureFOR MyFirstInstance : OfComponentName use entity work.ComponentOne(Synchronous_Arch); END FOR;FOR MySecondInstance : OfComponentName use entity work.ComponentOne(Asynchronous_Arch); END FOR;FOR OTHERS : OfComponentName use entity work.ComponentOne(MixedSignal_Arch); END FOR;

END FOR;END CONFIGURATION;

4.2.4 Synthesis ( Decoding / Compiling )✔ Synthesis tools read HDL (RTL Code) text 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 tri‐stated)◌ – 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◌ http://en.wikipedia.org/wiki/Photolithography

4.2.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); see Metastability and synchronization registers

◌ 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) Ex. Getting HEX images form file, printing text in debug window.◌ HVL = Hardware Verification Langauge – Language specifically designed for HDL verification / testbench (Ex. E-Language, VERA, TestBuilder C++)◌ PSL = Property Specification Language – (by Accellera) http://www.eda.org/vfv/docs/PSL-v1.1.pdf ( Sounds like it's a verification language )

A. Simulation ( SPICE / NetList )✔ HDL Simulation Levels

◌ Functional / RTL Simulation – No Timing considerations◌ Gate-level Simulation – Includes Timing Analysis (Requires Post-Synthesis NetList)

✔ HDL Simulation Applications◌ ModelSim◌ Maia Simulation http://www.maia-eda.net/index.php?option=com_content&task=view&id=13&Itemid=47

Page 31: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

✔ Simulation Implementation◌ Forced Input◌ WaveForm◌ TestBench◌ Test Vectors

✔ SPICE Simulation = Simulation Program with Integrated Circuit Emphasis◌ 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

✔ Reference◌ 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◌ http://techdocs.altium.com/display/ALEG/Legacy+Downloads (Get CircuitMaker Free; EOL product)◌ http://en.wikipedia.org/wiki/LTspice

4.2.6 Target Hardware ( Layout )✔ Layout - Sometimes refereed to as Place-N-Route or Fitting

✔ Typical Target Hardware◌ ASIC = Application Specific Integrated Circuit

▪ Tape-out = The Circuit Design Data-Base is Released (DBR) to generate a Photo-mask.▪ Silicon Fabrication = Circuit design is implemented on a silicon wafers at the “FAB” using photo-lithography technology. (Many IC(S) per wafer)▪ Wafer Sort = Automatic Test Equipment (ATE) tests each Integrated Circuit(IC) on the wafer using “wafer probe” technology.▪ Chip Packaging = Wafers are cut (IE. Diced), put on a substrate where nodes are wire-bonded for external pins and then put into Chip-Packages

◌ FPGA / PLD = Programmable Logic Device / Field Programmable Gate Array▪ Device Programming = PLD and FPGA devices are programmed to implement the designed circuit either by a JTAG plug or physical programming device.

◌ PCB = Printed Circuit Board▪ PCB Etching = Copper Traces/Routes are created on boards (can be multiple layers of traces) typically using a photo-plotter and copper etchant chemical.▪ Solder Paste = A Template is used to apply Solder paste to PCB part pin locations.▪ Pick N Place = Components for the circuit design are picked and placed onto the circuit board (typically by Pick N Place automatic equipment)▪ Re-flow Oven = The Board, Paste and Parts are heated to a point where the solder melts causing solder connections (After which the board is washed of flux)▪ ICT = In-Circuit-Test is a test instrument that has a bed of nails (IE. Connectors) that measure and test the completed circuit board.▪ Flying-Probe = Flying-Probes can also be used for a cheaper and not as thorough In-Circuit-Test measure and device testing.▪ Functional Test = Finally the circuit board is powered up under normal operating circumstances and tested for sale quality functionality.

A. FPGA Device Vendors

◌ Xilinx◌ Altera◌ MicroSemi – http://www.microsemi.com/products/fpga-soc/fpga/igloo2-fpga◌ Buy at:

▪ http://www.digilentinc.com/index.cfm (Xilinx Only)

✔ See Also◌ http://en.wikipedia.org/wiki/Electronic_design_automation◌ http://en.wikipedia.org/wiki/Application-specific_integrated_circuit◌ http://en.wikipedia.org/wiki/FPGA_prototyping◌ http://en.wikipedia.org/wiki/Design_flow_%28EDA%29 ◌ http://en.wikipedia.org/wiki/SMT_placement_equipment◌ http://en.wikipedia.org/wiki/Tapeout

B. IC Circuit Packages✔ IC = Integrated Circuit

◌ ASIC = Application Specific Integrated Circuit▪ ASICS require chip-layout work▪ 'sea-of-gates' technology (gate-array template wafers) and later customizes them by fab-ing in connectors.

◌ Chips with 10 to 100 gates is from MSI; Medium-scale integration technology◌ Anything over MSI up to 1980s was LSI; Large-scale integration technology◌ After 1980s the terms were abandoned and all chips were considered VLSI; Very large scale integration technology

✔ Packaging◌ - 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

Page 32: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

5. FIRMWARE✔ 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

5.1 Assembly Language (ASM) ✔ Wiki http://en.wikipedia.org/wiki/Comparison_of_assemblers✔ Wiki http://en.wikipedia.org/wiki/Assembly_Language

1. Common Processor Registers a) EAX = Function return b) EBX = Base pointer to the data section c) ECX = Counter for string/loop operators d) EDX = IO pointer

e) ESI = Source pointer for string f) EDI = Destination pointer for string

g) ESP = Stack Pointer h) EBP = Stack frame base pointer (here's where the function starts) i) EIP = Pointer to next instruction (instruction pointer) read-only access via 'JUMP' or 'CALL' j) 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

2. Register Conventions (Prevent register access conflicts) a) 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. b) 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.

3. Saved at the beginning and restored at the end (looks pointless but very important for stomping) a) EFLAGS Register (32-bit of FLAGS) bit flagging (Boolean operations T/F Compare; set after each instruction) b) ZF (Zero Flag) = 1 if result is 0 c) 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

5.2 Bootloaders and Interfaces ✔ Boot-strap = Initial ROM instructions that start the loading of the Boot-loaders. (All Processors start execution at their 'reset vector' location which is the Boot-strap ROM)✔ Boot-loader = Small ROM Program that initiates access to devices (e.g. CD, Hard-drive, USB flash drive) allowing the operating system to load from said device.✔ Chain-loading = The process of loading boot-loaders one after the other with increasing complexity / functionality.

Page 33: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

1. PC/Embedded boot-loading methods in chronological order a) BIOS = Introduced in 1975 b) EFI = Extensible Firmware Interface – By Intel; deprecated in 2005 to UEFI c) UEFI = Unified Embedded Firmware Interface – By Unified EFI Forum

2. Special Purpose boot-loading a) CFE = Common Firmware Interface – Boot-loader & Firmware

run-time interface by Broadcom

✔ Reference◌ 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 ◌ Unified EFI http://www.uefi.org/ ◌ Wikipedia UEFI http://en.wikipedia.org/wiki/Unified_EFI_Forum◌ How computers boot up http://duartes.org/gustavo/blog/post/how-computers-boot-up/

5.3 Board Support Package (BSP) ✔ ESD = Embedded Software Development http://www.altera.com/devices/processor/nios2/tools/ni2-development_tools.html ✔ SBT = Software building tools for embedded systems

◌ A library for system-specific support code. (Run-time environment for NiosII)✔ EDS = Embedded Design Suite✔ HID = Human Interface Device

Software Development for the NiosII system - "Getting started with the Graphical User Interface" @ NiosII Software Developers Handbook http://www.altera.com/literature/hb/nios2/n2sw_nii52017.pdf

1. Start-Up Sequence a) Assembler code written specifically for the processor.

• Assert Reset – On power-up the reset circuit asserts the reset signal.• De-Assert Reset – Reset gets de-asserted when clocks reached running speeds and voltages stabilize.• Instruction Pointer → Reset Vector – Controller sets its instruction pointer to the "reset vector”. The controller fetches the instruction at that location.• Initialize Registers – Interrupts are disabled; Clear / Set register values such as the stack pointer. (Correctly set Register / Flag bits)• Start Interrupt service routines (ISR) – Device drivers are running in the form of ISRs.

b) C-Code• Library that matches interface of routines / data structures; – Boot-loader can jump to the main() function of some C-Code

✔ 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.

2. Altera SBT (The NiosII SBT (System Build Tools) Generates → HAL Board Support Package (BSP)) a) SBT for Eclipse takes the sopcinfo data and generates HAL(Hardware abstraction layer) -> 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() )

b) HAL = Hardware Abstraction Layer• newlib• Device drivers

c) 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

d) NiosII SBT Command Line e) Optional Libraries

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

5.4 Operating Systems (OS)

5.4.1 Real Time Operating System (RTOS)✔ RTOS is an Operating System (OS) for embedded systems that System Software can run on-top. http://en.wikipedia.org/wiki/List_of_real-time_operating_systems✔ RTOS are optional since embedded systems have dedicated purposes and Software can be compiled

1. Popular RTOS for Altera NiosII soft-core processor a) Micrium (MicroC/OS) – http://micrium.com/ http://en.wikipedia.org/wiki/MicroC/OS-II b) VxWorks

2. Reference a) How to write an OS in Assembly language http://wiki.osdev.org/Main_Page b) Hobby OS Development http://en.wikipedia.org/wiki/Hobbyist_operating_system_development

5.4.2 OS Memory ManagementSystems usually handle addresses through a Memory Management componentThis allows Virtual Address ↔ Physical Address managementIn Windows – User-Mode Processes are assigned their own virtual address space to operate inKernel-Mode processes share the “system space” virtual address space✔ OS 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.▪ See http://msdn.microsoft.com/en-us/Library/Windows/Hardware/hh439648%28v=vs.85%29.aspx

Page 34: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

5.4.3 OS Process Management✔ 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

✔ 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 and Power Interface (Introduced in 1996;

http://www.acpi.info/ )◌ APM = Advanced Power Management and Application Programming Interfaces (BIOS code)◌ PNP-BIOS = Plug & Play Application Programming Interfaces (BIOS code)◌ MPS = Multiprocessor Specification (BIOS code)◌ See Also

▪ HAL options after XP or Server 2003 @ http://support2.microsoft.com/kb/309283 ▪ UEFI = Unified Extensible Firmware Interface [ HAL ↔ OS ] interface specification @

http://www.uefi.org/

5.5 Device Drivers ✔ Communications

◌ Application → OS – Applications calls OS-API functions that send/receive hardware I/O requests◌ OS → Drivers – OS generates I/O Request Packet (IRP) objects and notifies the driver by calling driver Call-back functions◌ Drivers → HAL – Drivers (like OS-Plug-ins) work with OS-Architecture to communicate with the Hardware Abstraction Layer (HAL)◌ HAL → Device – HAL (Abstracting OS from hardware) takes standard calls and converts them to electrical signals (IE. Motherboard driver)

✔ Communication Terms◌ IRP = I/O Request Packet – OS Kernel data structure used to transfer data packets at the driver level◌ WMI = Windows Management Instrumentation – Microsoft's IT Distributed Management infrastructure◌ Port-IO = OS Initiated communication (MS-Windows uses 'IN' and 'OUT' Port access instead of Address Mapped I/O)◌ DMA = Direct Memory Access - Address space to hardware (Typically for high data devices like disks, networks or displays)◌ IRQ = Hardware initiated communication requiring reception by software/driver◌ ISR = Interrupt service routine – Function to handle a device interrupts (Each event = 1 interrupt)◌ DPC = 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)

✔ Reference◌ Wiki IRQ @ http://en.wikipedia.org/wiki/Interrupt_request

5.5.1 Device Tree / Driver Stack

✔ 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 = Entry point driver to the device tree (ACPI in the diagram)◌ Software = No hardware just used for Kernel-Mode access and/or User Mode drivers◌ Class = 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 DOFor 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✔ Reference

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

Illustration 2: ACPI HAL System Device Tree

Page 35: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

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

5.5.2 Driver Development Kits (DDK)

✔ Windows Driver Kits (WDK) – Microsoft's different driver kits through time

◌ TSR = Terminate and Stay Resident MS-DOS Real-Mode drivers (written in Assembly)◌ VDD = Virtual Device Drivers Windows 3.x, 95, 98, Me drivers Managed resource drivers (written in Assembly)◌ WDM = Windows Driver Model Windows NT/XP/2000 till 2005) Full managed drivers (calls OS-system service routines )◌ WDF = Windows Driver Foundation Windows Vista, 7, 8 (2005+) Helpful Abstraction layer framework to the WDM ( User-Mode -or- Kernel-Mode frameworks )

✔ File Extensions◌ SYS = Driver based on the Kernel-Mode device Driver Framework (KMDF)◌ DLL = Driver based on the User-Mode device Driver Framework (UMDF)◌ INF = Driver Installer file – Used by Add/Remove hardware to record in the windows registry which files are function/filter drivers for a device drivers package

✔ WDF Terms◌ DDI = Device Driver Interface – Abstract OS-kernel supplied driver interfaces that drivers need to implement (IE. The “Driver Model”)◌ SDV = Static Driver Verifier – Debugging / Verifying tool packaged in the WDK◌ PREfast – Debugging / Verifying tool packaged in the WDK◌ Checked Build OS – MS-Windows OS distribution that contains debug-related code/symbols specifically for driver debugging◌ Free Build OS – Normal/Released MS-Windows OS distribution◌ WDF Versioning – Drivers are compiled with WDF framework version # so OS can choose correct framework for each/every driver◌ Kernel-Mode – Shares the OS “system space” of allocated virtual memory which allows low-level system access (DMA, IRQ, WMI access)◌ User-Mode – Applications allocate virtual memory specific to the application itself and thus has no low-level system access◌ Permanent Object – Programming object that remains present through the life of a plugged-in device◌ Transient Object – 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

5.5.3 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 are 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 WdfChildList - List of child devices for a bus-driver▪ Collection WdfCollection - Similar objects container▪ Device WdfDevice - Driver contains one device object for each device it

controls▪ DMA

▫ Buffer WdfCommonBuffer - Buffer that connects device and driver▫ Enabler WdfDMAEnabler - Enables a DMA channel with a device▫ Transactions WdfDMATransaction - One DMA Transaction (like an IRP for DMA)

▪ DPC WdfDPC - Deferred Procedure Call▪ Driver WdfDriver - Top-level Driver Object▪ File WdfFileObject - File object for application and external driver access

to the driver [ Device ↔ DMA ↔ Driver ↔ File ↔ Application ]▫ 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 Object’s 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 Object’s 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.

Page 36: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▫ Register via FileObject for Create, Close, and Cleanup Callbacks of IRP(s)▪ General WdfObject – Driver Context object or object for any driver usage requirements▪ I/O

▫ Queue WdfQueue - Any I/O Queue▫ Request (IRP) WdfRequest - ▫ Target WdfIoTarget - Stack to which the driver is forwarding IRP(s)

▪ Interrupt WdfInterrupt - One device Interrupt Request(IRQ) -or- message-signaled interrupt(MSI)▪ Look-Aside List WdfLookAside - Dynamically sized list of identical buffers allocated from paged -or- nonpaged pool (Component memory buffers)▪ Memory WdfMemory - I/O memory buffer for the driver to store an IRP▪ Registry-Keys WdfKey - Represents one windows registry key▪ Resources

▫ List WdfCmResList - Devices list of resources▫ Range-List WdfIoResList - Configuration for a device▫ Requirements WdfIoResReqList - Set of I/O resources list and their configurations (Each element is a WdfIoResList)

▪ String WdfString - Unicode string▪ Synchronization

▫ SpinLock WdfSpinLock - Spin lock synchronization for DISPATCH_LEVEL data▫ WaitLock WdfWaitLock - Wait lock synchronization for PASSIVE_LEVEL data

▪ Timer WdfTimer - Object for timed callback routine execution▪ USB

▫ Device WdfUsbDevice - One USB device▫ Interface WdfUsbInterface - Interface for a USB device▫ Pipe WdfUsbPipe - Pipe for a USB device

▪ WMI WdfWMIInstance - Windows Management Instrumentation▪ Work-Items WdfWorkItem - PASSIVE_LEVEL system thread item

✔ KMDF Standard Syntax▪ WdfObjectOperation – KMDF Method naming notation▪ WdfObject{Set/Get}Data – KMDF No-Status Property naming notation▪ WdfObject{Assign/Retrieve}Data – 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 Refernce @ http://msdn.microsoft.com/en-us/library/windows/hardware/dn265636%28v=vs.85%29.aspx

Call-Back Methods Structures/Enums Initialization Functions

EvtDriverDeviceAddEvtDriverUnload

WdfDriverCreateWdfDriverGetRegistryPathWdfDriverIsVersionAvailableWdfDriverMiniportUnloadWdfDriverOpenParametersRegistryKey

WDF_DRIVER_CONFIGWDF_DRIVER_INIT_FLAGSWDF_DRIVER_VERSION_AVAILABLE_PARAMS

WDF_DRIVER_CONFIG_INITWDF_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.*

Page 37: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

* 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 status = STATUS_SUCCESS; WDF_DRIVER_CONFIG 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

✔ DevicePreFix Call Item Structure Structure Initializer

WdfDevice Create WDFDEVICE_INIT Device InitializerWdfDevice CreateDevice Interface Create InterfaceWdfDevice RetrieveDevice InterfaceString Retrieves symbolic link nameWdfDevice SetDevice InterfaceState Enables/Disables InterfaceEvtDevice Process QueryInterfaceRequest WDF_QUERY_INTERFACE_CONFIG WDF_QUERY_INTERFACE_CONFIG_INITWdfDevice Add QueryInterfaceWdfDevice Interface{Der/R}eferenceNoOpWdfDeviceWdfDevice SetDevice State WDF_DEVICE_STATEWdfDevice Create SymbolicLinkWdfDevice MiniportCreate Creates device for miniport driverWdfDevice InitAssign/RetrieveDevice Name WDFDEVICE_INITWdfDevice InitAssign SDDLString WDFDEVICE_INIT Security Setting

WdfDevice Init Free De-allocate WDFDEVICE_INITWdfDevice DeviceGet/InitSet/Set CharacteristicsWdfDevice InitSetDevice ClassWdfDevice InitSetDevice TypeWdfDevice InitSet ExclusiveWdfDevice Assign MofResourceNameWdfDevice Set Failed WDF_DEVICE_FAILED_ACTION Notify framework of FailureWdfDevice WdmGet DeviceObject WDM-model device objectWdfDevice WdmGet PhysicalDeviceWdfWdmDevice GetWdf DeviceHandle Device Object for WDM deviceWdfDevice/WdfFdoInit OpenRegistryKey Access Windows RegistryWdfFdo InitSet DefaultChildListConfigWdfFdo InitSet EventCallbacks WDF_FDO_EVENT_CALLBACKS WDF_FDO_EVENT_CALLBACKS_INITEvtDevice Filter{Add/Remove} ResourceRequirements FDOEvtDevice RemoveAdded Resources FDOWdfFdo InitSet FilterWdfFdo InitWdmGet PhysicalDeviceWdfFdo Add StaticChildWdfFdo Get DefaultChildList WDF_CHILD_LIST_CONFIGWdfFdo {Lock/Unlock} StaticChildListForIterationWdfFdo QueryFor InterfaceWdfFdo Retrieve NextStaticChildWdfPdo Init AddCompatibleIDWdfPdo InitAdd DeviceTextWdfPdo InitAdd HardwareIDWdfPdo Init AllocateWdfPdo InitAllow ForwardingRequestToParentWdfPdo InitAssign ContainerIDWdfPdo InitAssign DeviceIDWdfPdo InitAssign InstanceIDWdfPdo InitAssign RawDeviceWdfPdo InitSet DefaultLocaleWdfPdo InitSet EventCallbacks WDF_PDO_EVENT_CALLBACKS WDF_PDO_EVENT_CALLBACKS_INITEvtChildList CreateDeviceWdfChildList Get DeviceWdfChildList Retrieve AddressDescription WDF_CHILD_ADDRESS_DESCRIPTION_HEADER WDF_CHILD_ADDRESS_DESCRIPTION_HEADER_INITWdfChildList Retrieve PdoEvtChildList AddressDescription CleanupEvtChildList AddressDescription CopyEvtChildList AddressDescription DuplicateEvtChildListEvtChildList IdentificationDescription Cleanup WDF_CHILD_IDENTIFICATION_DESCRIPTION_HEADER WDF_CHILD_IDENTIFICATION_DESCRIPTION

_HEADER_INITEvtChildList IdentificationDescription CompareEvtChildList IdentificationDescription CopyEvtChildList IdentificationDescription DuplicateEvtChildList DeviceReenumerated

EvtChildList ScanForChildrenWdfChildList AddOrUpdate/UpdateAll ChildDescriptionAsPresent

Page 38: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

WdfChildList Update ChildDescriptionAsMissingWdfChildList {Begin/End} IterationWdfChildList {Begin/End} ScanWdfChildList Create

WdfChildList Request ChildEjectWdfPdo Add/Remove EjectionRelationsPhysicalDeviceWdfPdo Clear EjectionRelationsDevicesWdfChildList Retrieve NextDeviceWdfChildList

✔ Device DependenciesPreFix Call Item Structure Structure Initializer

WdfDevice Add/Remove DependentUsageDeviceObject Dependent driverWdfDevice Add/Remove RemovalRelationsPhysicalDevice Dependent driver/removeWdfDevice Clear RemovalRelationsDevices Remove all-drivers/dependenceWdfDevice WdmGet AttachedDevice Gets next-lower device

WdfPdo Get ParentWdfPdo MarkMissingWdfPdo Request EjectWdfPdo Retrieve/Update AddressDescriptionWdfPdo Retrieve IdentificationDescription

✔ FilePreFix Call Item Structure Structure Initializer

WdfDevice InitSet FileObjectConfig WDF_FILEOBJECT_CONFIG WDF_FILEOBJECT_CONFIG_INIT

WdfDevice Get FileObject

Evt File Cleanup EvtDeviceFileCreate HANDLE Close access to deviceEvt File Close EvtDeviceFileCreate HANDLE Close access to deviceWdfDevice 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 functionWdfDevice InitSet IoType Register function for IO buffers for special deviceWdfDevice/WdfFdoInit AllocAndQueryProperty

WdfDevice/WdfFdoInit QueryProperty Access device propertiesWdfDevice {Set/Get} AlignmentRequirement Devices address for memory transferWdfDevice Get DriverWdfDevice Get IoTarget Pointer to Function that handles I/OWdfDevice Set BusInformationForChildren PNP_BUS_INFORMATION Information about a busEvtDevice Prepare HardwareEvtDevice SelfManaged IoCleanupEvtDevice SelfManaged IoFlushEvtDevice SelfManaged IoInitEvtDevice SelfManaged IoRestartEvtDevice SelfManaged IoSuspendEvtDevice UsageNotification WDF_SPECIAL_FILE_TYPEEvtDeviceWdm IrpPreprocess IRP – Structure Receives IRP before frameworkEvtDeviceWdm DispatchPreprocessedIrp Returns Preprocessed IRP to the frameworkEvt IoInCallerContext 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;

Page 39: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

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 OperationsPreFix Call Item Structure Structure Initializer

WdfDevice Set PnpCapabilities WDF_DEVICE_PNP_CAPABILITIES WDF_DEVICE_PNP_CAPABILITIES_INITWdfDevice InitSet PnpPowerEventCallbacks WDF_PNPPOWER_EVENT_CALLBACKS WDF_PNPPOWER_EVENT_CALLBACKS_INITWdfDevice GetDevice PnpState WDF_DEVICE_PNP_STATE

EvtDevice PnpStateChange WDF_DEVICE_PNP_NOTIFICATION_DATA WDF_DEVICE_PNP_CAPABILITIES_INITEvtDevice ReleaseHardware When drive is no longer accessibleEvtDevice SurpriseRemoval When device is hot-removed/failedEvtDevice SelfManaged IoCleanupEvtDevice SelfManaged IoInit

//-- [ 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

✔ PowerPreFix Call Item Structure Structure Initializer

WdfDevice Set PowerCapabilities WDF_DEVICE_POWER_CAPABILITIES WDF_DEVICE_POWER_CAPABILITIES_INITWdfDevice InitSet PowerPolicyEventCallbacks WDF_POWER_POLICY_EVENT_CALLBACKS WDF_POWER_POLICY_EVENT_CALLBACKS_INITWdfDevice InitRegister PowerPolicyStateChangeCallbackWdfDevice InitSet PowerPolicyOwnershipEvtDevice PowerPolicyStateChange WDF_DEVICE_POWER_POLICY_NOTIFICATION_DATAWdfDevice GetDevice PowerPolicyStateWdfDevice GetDevice PowerState WDF_DEVICE_POWER_STATE (Returns)WdfDevice InitRegister PowerStateChangeCallbackEvtDevice PowerStateChange WDF_DEVICE_POWER_NOTIFICATION_DATAWdfDevice InitSet PowerInrush Device requires inrush current @ start-upWdfDevice InitSetPower{Not} Pageable Driver accepts pageable data during sleep or notWdfDevice {Set/Get}Device State WDF_DEVICE_STATE (Returns) WDF_DEVICE_STATE_INITWdfDevice Get SystemPowerAction Current system power action if anyWdfDevice Assign S0IdleSettings WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INITWdfDevice Assign SxWakeSettings WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS WDF_DEVICE_POWER_POLICY_WAKE_SETTINGS_INITWdfDevice Indicate WakeStatus Device has awokeWdfDevice {Stop/Resume}Idle Not in use; ok for idle stateWdfDevice Set StaticStopRemove Whether device can be removedEvtDevice {Arm/Disarm} WakeFromS0 WDF_DEVICE_PNP_CAPABILITIES WDF_DEVICE_PNP_CAPABILITIES_INITEvtDevice {Arm/Disarm} WakeFromSx WDF_PNPPOWER_EVENT_CALLBACKS WDF_PNPPOWER_EVENT_CALLBACKS_INITEvtDevice Arm WakeFromSxWithReasonEvtDevice WakeFromS0TriggeredEvtDevice WakeFromSxTriggeredEvtDevice D0{Entry/Exit} WDF_POWER_DEVICE_STATEEvtDevice D0Entry PostInterruptsEnabled WDF_POWER_DEVICE_STATEEvtDevice D0Exit PreInterruptsDisabledWdfDev StateIsNP WDF_DEVICE_POWER_STATE Is Non-PageableWdfDev StateNormalize State machine states as indexEvtDevice Disable/Enable WakeAtBus PDOEvtDevice Eject PDOEvtDevice ResourceRequirementsQueryEvtDevice ResourcesQueryEvtDevice Set LockEvtDevice ShutdownNotification WDF_DEVICE_SHUTDOWN_FLAGS

Page 40: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

Wdf ControlDeviceInit AllocateWdf ControlDeviceInitSet ShutdownNotificationWdf Control FinishInitializing

Po Register/Unregisted PowerSettingCallback

//-- [ 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)

Page 41: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▫ 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 = IRP has a pointer to Kernel buffer space (IE. METHOD_BUFFERED)▫ Direct = A Memory Descriptor List (MDL) is passed to the driver (IE. METHOD_DIRECT)▫ Neither = 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

✔ IRPPreFix Call Item Structure Structure Initializer

WdfDevice InitAssign WdmIrpPreprocessCallback IRP Major Code handlerWdfRequest Allocate TimerWdfRequest Cancel SentRequestWdfRequest Change TargetWdfRequest CompleteWdfRequest CompleteWithInformationWdfRequest CompleteWithPriorityBoostWdfRequest CreateWdfRequest CreateFromIrpWdfRequest Format RequestUsingCurrentTypeWdfRequest ForwardToIoQueueWdfRequest ForwardToParentDeviceIoQueueWdfRequest Get CompletionParamsWdfRequest Get FileObject

Get InformationGet IoQueueGet ParametersGet RequestorMode

✔ QueryPreFix Call Structure Structure Initializer

WdfDevice InitSetRequestAttributes Apply to IRP(s) attributes at QueueWdfDevice ConfigureRequestDispatching Assigns IRP to specific queueWdfDevice DeviceEnqueueRequest IRP Type → FrameworkWdfDevice GetDefaultQueue Devices default queue handleEvtDevice QueryRemoveEvtDevice QueryStopEvtDevice RelationsQuery

EvtIo AllocateRequestResourcesEvtIo AllocateResourcesForReservedRequestEvtIo CanceledOnQueueEvtIo Default

Page 42: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

EvtIo DeviceControlEvtIoWdm IrpForForwardProgress WDF_IO_FORWARD_PROGRESS_ACTIONWdfIoQueue AssignForwardProgressPolicy WDF_IO_QUEUE_FORWARD_PROGRESS_POLICYEvtIo InternalDeviceControlEvtIo QueueStateWdfIoQueue StartEvtIo ReadEvtIo ResumeWdfIoQueue/EvtIo StopWdfIoQueue StopSynchronouslyEvtIo WriteWdfIoQueue Create WDF_IO_QUEUE_CONFIG WDF_IO_QUEUE_CONFIG_INIT

WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUEWdfIoQueue DrainWdfIoQueue DrainSynchronouslyWdfIoQueue FindRequestWdfIoQueue GetDeviceWdfIoQueue GetStateWdfIoQueue PurgeWdfIoQueue PurgeSynchronouslyWdfIoQueue ReadyNotifyWdfIoQueue RetrieveFoundRequestWdfIoQueue RetrieveNextRequestWdfIoQueue RetrieveRequestByFileObject

//-- [ 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

Page 43: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

// 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;}

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

Page 44: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

* 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 status; PFDO_DATA 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));

Page 45: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

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 status; ULONG_PTR bytesCopied =0; WDFMEMORY 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) {

Page 46: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

NTSTATUS status= STATUS_SUCCESS; WDF_DEVICE_STATE deviceState; WDFDEVICE 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 loadedNTSTATUS 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;}

*/

5.5.4 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

Page 47: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

▫ 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

A. Reference

✔ Reference◌ Wiki-books Device Driver Introduction @ http://en.wikibooks.org/wiki/Windows_Programming/Device_Driver_Introduction◌ Windows driver development

▪ WDK Kit http://msdn.microsoft.com/en-US/windows/hardware/gg454513▪ Differences between WDM and WDF http://msdn.microsoft.com/en-us/library/windows/hardware/gg583838%28v=vs.85%29.aspx ▪ Device Driver Classes/Models 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

5.5.5 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, // for allocating resources.release = klife_release, // releasing resources.read = klife_read, // generating and reading states of the device.write = klife_write, // start-up settings.mmap = klife_mmap, // faster but more complex direct access to device.ioctl = klife_ioctl // querying device and enabling/disabling timer interrupts

};

User Space access to “major number”# mknod /dev/klife c 250 0 // creates file

Use Fileif ((kdf = open(“/dev/klife”, O_RDWR)) < 0 ) {

perror(“open /dev/klife”);exit(EXIT_FAILURE);

}

6. Altera Quartus-II 1. File extensions

• bdf - block design file (schematic)• bsf - block symbol file (symbol)• edf - EDIF; Vendor neutral schematic &amp;amp design file format (Electronic design interchange format)

Page 48: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

• lmf – ASCII files used to map EDIF(.edf) and Verilog Quartus mapping files (.vqm) (Other Vendor HDL → Quartus Logic Functions)• mif - memory initialization file• ncf - Altera Monitor Program [NiosII] Project File• pof - "Programmer object file" compiled project file to upload to FPGA's FLASH for Active-Serial mode (see also .sof)• ppf - Pin Planner• qar – Archived (like zipped) quartus project – Quartus → Project → “Archive Project” / “Restore archived project”• qip - Quartus IP-Core project file• qpf - Quartus project file• qsf - Quartus settings file – Can add PIN-Assignments here - set_location_assignment PIN_N25 -to x1 (File is in Tcl syntax)• qsys - Hardware contents of a Qsys System• sdc - Synopsys Design Constraints - Component Simulation parameters text file (Created manually or with the TimeQuest Timing Analyzer) (Tcl Syntax)• smf - State machine file• sof - "SRAM object file" compiled file to upload to FPGA• sopcinfo - Description details of the associated 'Qsys' file in XML (Used to generate the BSP for software design - the build tools)• sym - Symbol file• tdf - "text design file" written in AHDL Altera hardware description language (AHDL)• vho – Simulation structural NetList• vht – ModelSim generated VHDL test-bench files• vqm – Verilog Quartus mapping files – node-level or atom net-list text file• vwf - Simulation waveform to set node levels at simulation time.

2. Projects a) Project File = <ProjectName>(.qpf); a “revisions” text file that points to <ProjectNameRevision>(.qsf) b) Project Settings = (.qsf) projects contents and settings text file stores settings made in Quartus → Assignments menu c) Set Default Projects Folder = Menu → Tools → Options → General → “Default File Location” (@Bottom) d) Import/Export Pin Assignments = Menu → Assignments → Import (Retrieve Pin Assignments) or Export (Save Pin Assignments) e) Pin Driving (Including UN-Used) = Menu → Assignments → Device → “Device and Pin Options” (max I/O @ 240mA) f) Auto-settings by specification = Menu → Tools → “Laungh Design Space Explorer” (Uses SDC timing constraints file with TimeQuest to meet goals) g) Project Revisions (Diff settings) = Menu → Project → Revisions (IE. Compilation Settings Revisions not Source File Revisions :: Creates new .qsf file)

• Compare Revisions = Menu → Projects → Revisions → Compare• Select Revision for Synthesis = Project Navigator → Revisions → Right-Click and select “Set Current Revision”

h) Copy Project = Menu → Projects → “Copy Project” – Ideal way to create a new project based on existing one i) Specify timing constraints (SDC) = Menu → Tools → TimeQuest Timing Analyzer – Analyzes timing constraints on compiled design j) Quartus Database for teams = Menu → Projects → “Import/Export Database” and “Clean Project”

3. Quartus Folders a) Error Message Details = Menu → Help → Message List – Points to <Install-Path>/quartus/common/help/webhelp/) b) Altera Device List = Menu → Help → Devices and Adapters – Points to <Install-Path>/quartus/common/help/webhelp/) c) EDA Interfaces (Other EDA Tools) = Menu → Help → EDA Interfaces – Points to <Install-Path>/quartus/common/help/webhelp/) d) Getting Started Tutorial = Menu → Help → Getting Started Tutorial – Points to <Install-Path>/quartus/common/help/tutorial/qtutorial.htm) e) Altera supplied IP-Cores = Menu → Tools → IP Catalog (MegaWizard) – <Install-Path>/ip/altera/<IP-Core> f) 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'

4. Validation Tools a) Auto device selected by Fitter = feature that will pick a suitable Altera FPGA upon design compilation. b) Device Migration = tools that allow designs to move between different FGPA IC-Chips c) PowerPlay Power Analyzer = Estimates power usage for the Circuit implemented on a PCB board. d) Early Pin planning = PCB layout is determined before hand where pin locations must be verified by FPGA fitter software 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”

e) Simultaneous Switching Noise (SSN) = Analyzes / checks for noise /distortion voltage across I/O traces. f) Design Assistant = Checks design for adherence to Altera guidelines (Can also use a “lint” tool for coding style checks) g) 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

6.1 Qsys Designer (SOPC) 1. Qsys = Embedded System Design Tool (Previously SOPC-Builder)

a) Systems are constructed by adding (picking N choosing) Qsys Components• Qsys Components are IP-Blocks / Cores

b) Qsys auto-generates• HDL files – Circuit design files• Boot-loader – HEX-Code for the system start-up• “_hw.tcl” – Hardware Components Description File• SOPCinfo – Specification file for the Board Support Package (BSP)

c) Implementation• Component names (IP-Block Names) in Qsys are used by firmware to access

the hardware• System is synthesized

• [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

✔ Reference◌ Altera Tutorial “Nios II Hardware Development Tutorial”◌ Altera http://www.altera.com/support/examples/design-entry-tools/qsys/qsys.html

Page 49: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

◌ University Courses w/Qsys http://myweb.wit.edu/johnsont/

6.2 Soft Core Processors 1. NiosII ( Master of Avalon Interconnect Fabric )

a) /e b) /s – Standard Edition c) /f d) NiosII w/MMU = NiosII for Linux; no System Build Tools (SBT) support

2. Registers ( Memory Mapping I/O ) a) Register offsets are assigned within Qsys b) Avalon-MM ( Master / Slave type architecture ) c) Control Registers d) Status Registers e) Qsys sets up separate command / response networks to IP-Block

• 2x-throughput

3. Instruction Cache Memory

4. Ports a) data_master = The processors data bus

• Avalon-ST = Streaming interconnect fabric b) instruction_master = retrieves instructions

• instruction_master → jtag_debug_module ( connection to processor for debug/firmware download) 5. Interconnect Fabric

a) Connection Fabric = A "Standard" that allows internal connections between Processor and peripherals (A Standard Control, Data, and Address Bus connectors) b) Connection fabric also named NoC(Network-on-chip) Architecture; The arbiter for IP Packet transform to various IP components c) The Nios II HAL(Hardware abstraction layer) interprets low IRQ values as higher priority. d) HAL - Hardware abstraction layer and peripheral drivers (Software that generates C headers for Custom Nios) e) Examples;

ALTERA; Avalon Fabric including Avalon-MM(Memory-Mapped I/O) and Avalon-ST(Streaming) as well as ARM Structure and AIX4 6. Configure

a) Reset Vector Offset = 1st Address (boot-loader / image / custom ) b) 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

c) Pipe-lining Support for up to 4-pipelines d) 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)

7. SOPC-Peripherals a) SysID to match firmware with processor core b) Generating Systems with Qsys c) Simulation d) DMA direct memory access controller e) 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 f) “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. g) “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

h) What peripherals will Nios connect to (add/remove PIO, VGA, etc..) i)

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)

6.3 IP-Cores ✔ Altera Quartus installs off-the-shelf configurable IP cores optimized for Altera devices (OpenCore Plus IP) – Commonly named Mega-functions✔ 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 settingWhen searching for IP-Cores the project directory takes precedence over all others.

✔ See◌ DSP Solution Center http://www.altera.com/technology/dsp/dsp-index.jsp◌ Altera IP literature http://www.altera.com/literature/lit-ip.jsp

✔ IP-Cores can be instantiated in HDL code◌ By Name with parameters (In VHDL you must “include” the associated libraries)

▪ Verilog Altera IP-Core Instancealtfp_mult inst1 (.dataa(wire_dataa), .datab(datab), .clock(clock), .result(result));defparam

inst1.pipeline = 11,inst1.width_exp = 8,

Page 50: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

inst1.width_man = 23,inst1.exception_handling = "no";

▪ VHDL Alter IP-Core Instancelibrary 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);

6.4 Schematic & HDL Editors 1. Alteras University Program Training Resources at ftp://ftp.altera.com/up/pub/Altera_Material/13.0/Tutorials/ or { ftp://ftp.altera.com/ }

a) Steps of the flow can be set just below the project browser b) Chip Planner draws the FPGA/LAB/LE used on the chip c) RTL simulation?

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

3. Programming the FPGA a) JTAG - when switch position is in "Run" during programming b) AS (Active Serial) - Design is loaded into on-board flash; switch in "Prog" during programming

4. Backup DE2 FPGA Flash a) Open Programmer b) Set Mode to "Active Serial" and set board switch to "Prog" c) "Add Device" and choose "EPCS16" (the flash unit) d) Select "Examine" then "Start" to load the flash contents e) Click "Save" to save the contents to a .pof file.

5. Templates – Quartus → Edit → Insert Template (Drops template code in the open HDL file.)

6.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 waveforms; save)

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 - Embedded logic analyzer HPS - hard processor system (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

6.6 Bugs / Gotchas ✔ Below error occurs when using Eclipse Nios0 [main] bash 312 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer. Please report this problem tothe public mailing list [email protected]

{ 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_originalC:\altera\13.0sp1\quartus\bin64\cygwin to \cygwin_original

Created new empty ....\cygwin foldersCopy 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-coreNiosII/s proprietary = Remove ModelSim-Altera setting on project start-up

✔ Qsys - "Failed to query available BSP types"Have to take a different route

Page 51: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

error dialog shown below ("Failed to query available BSP typesI 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 in-production use)

7. 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)

Page 52: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

8. ModelSim 1. Altera Quartus-II Installer includes ModelSim-Altera Starter edition @ C:\altera\13.0sp1\modelsim_ase

a) .\altera\ – Altera Mega-function simulation files. b) .\docs\ – Documents and tutorial guides (as well as a Tcl help guide) c) .\examples\ – ModelSim Help/Tutorial example files d) .\modelsim.ini – Text file that will include all the locations of Altera Mega-function simulation code e) .\ieee\ – simulation code for the 'IEEE' library f) .\win32aloem\ – The ModelSim Executable directory

2. Preferred file association adjustments a) (.mpf) – ModelSim project file – Can be opened directly with ModelSim.exe – Text file containing all files and settings for a simulation project b) (.wlf) – Simulated Waveform – Can be opened directly from ModelSim.exe – Mentor graphics proprietary waveform

• See Also http://en.wikipedia.org/wiki/Waveform_viewer

3. ModelSim has a “Transcript” command prompt which is actually a TCL shell prompt with necessary imports.

4. Choose the directory that ModelSim will work out of a) From ModelSim> cd … b) Menu → File → Change Directory

5. The Directory chosen will need a “work” sub-folder (IE. Library) and can only be properly created by using a) ModelSim> vlib work b) Right-Click in the Library browser and select 'new' → 'library' → 'a new library' and give the new sub-folder / library a name.

6. Compile the Design Files (Verilog / VHDL) or Testbench files a) ModelSim> vcom -reportprogress 300 -work work D:/Electronics/CAD/_Projects/MyDFF2/MyDFF2.vhd b) Menu → Compile → Compile and choose File c) Once Compiled the output files will be stored in the 'work' library / folder. (Files .dat, .dbs, .prw, .psm )

7. Load / launch the simulator a) ModelSim> vsim -gui work.mydff2 b) Menu → Simulate → 'Start Simulation' and pick the Verilog / VHDL file to simulate c)

8.1 Projects 1. ModelSim GUI provides tools to create / simulate design projects

a) Menu → File → New → Project b) 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\ (Where modelsim.exe resides as well as 'vsim' and etc.. commands)•

Page 53: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

9. Industrial Control Systems (ICS)✔ ICS includes several types of control systems @ http://en.wikipedia.org/wiki/Industrial_Control_System

◌ SCADA = Supervisory control and data acquisition – Mostly composed of remote terminal units (RTU) across larger areas geographically◌ DCS = Distributed control system – Generally includes a network of PLC controllers◌ PLC = Programmable Logic Controller – Micro-controller device for industrial use http://en.wikipedia.org/wiki/Programmable_logic_controller ◌ RTU = Remote Terminal Unit – Device control with an interface to DCS or SCADA systems http://en.wikipedia.org/wiki/Remote_Terminal_Unit

1. Vendors http://www.directindustry.com/cat/automation-A.html

9.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

▪ Distributed I/O = Flex I/O

◌ ControlLogix System (Considered Programmable Automation Controller (PAC))▪ Programming Software = Rockwell RSLogix5000

Illustration 6: AB ControlLogix PLC ◌ CompactLogix System

▪ Programming Software = Rockwell RSLogix5000

Illustration 7: 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

1. Communications a) EtherNet/IP b) ControlNet c) DeviceNet d) Universal Remote I/O e) DH+, DH-486 (RS-232)

2. Software (Rockwell Automation) a) RSLogix = Ladder-Logic editor b) RSLinx = Connects RSLogix Programming software to the PLC-Controller c) RSView = Creates operator interfaces / human machine interface (HMI) d) RSNetWorx ???

3. Other Software of Interest a) 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/

Illustration 3: Allen-Bradley PLC-5 System

Illustration 5: Allen-Bradley SLC-500 System

Illustration 4: AB MicroLogix System

Illustration 8: Allen-Bradley Flex I/O (Distributed I/O Solution)

Page 54: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

9.2 PLC – Programmable Logic Controller ✔ PLC is programmed using Ladder-Logic which closely resembles wiring of relays

✔ Ladder-Logic comprises of◌ 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 )

✔ See Also◌ Diagrams here include Ladder-Diagrams and how they relate to Gate Logic Circuits http://www.allaboutcircuits.com/

9.3 Instrumentation 1. Motor Control

a) Starter – Safe starts a large-load motor and protects against under-voltage overload protection b) Contactor – Heavy current relay c) Drives – Sometimes short for VFD or to describe large scale VFD. d) VFD = Variable Frequency Drives – Adjusts AC frequency and voltage to produce motor speed control e) Encoder – Measures motor rotations / speed f) Meger – Hand-Held test equipment to measure wire insulation (Commonly used to find a faulty motor)

2. Valves a) Solenoid Valves = Commonly used device the PLC activates to turn on/off air pressure to devices like pneumatic vales / cylinders (rams) and etc... b) I/P Transducer = Converts electrical current/voltage to output pressure (I/P= Current → Pneumatic) c) Butter Fly Valve = 90-degree angle pipe valve d) Angle Seat Valve = Common Pneumatic actuated tank outlet valve

3. Sensors ( Transducers ) a) Condition

• Temperature• RTD = Resistance temperature detectors• Thermo-couples• Thermisters

• Pressure• Level• Flow• Speed• HVAC• pH Sensor

b) Proximity• Capacitive( Non-metal detection )• Inductive ( Metal object detection )• Photoelectric (Beam or Reflective)• Ultrasonic ( Reflective Sound – Level of water in tank )

c) Switches• Limit Switches• Safety Interlock switches

d) Flow• EMF – Electromagnetic Flow Meter (IE. MagMeter)• UFM = Ultrasonic Flow Meter

4. Acronyms a) CIP = Cleaning In Place

• An equipment cleaning process that doesn't require tear-down or removal(Flush/Clean pipes with chemicals)

b) SIP = Sterilization In Place

Illustration 11: PLC Panel with ControlLogix PLC(Top), VFDs(Center) and Starters(Bottom)

Illustration 10: Solenoid Valves

Illustration 9: I/P

Page 55: Electronics Engineering N2NO = Process of; Abstract desired circuit behavior (RTL) → Circuit design System Groups Computers (Software) – Preforms a variety of functions by means

10. IT Distributed Management (DMTF)✔ DMTF = Distributed Management Task Force (IT Enterprise Infrastructure Technology for containing routers, printers, and etc... on a common network)✔ DMI = Desktop Management Interface✔ MIB = Management Information Base/Database✔ SNMP = 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.

✔ Reference◌ 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

11. ONLINE RESOURCES 1. EDA.org http://www.eda.org/

a) 2. Electronic Circuits http://www.electronics-circuits.com/index.html

a) Circuit tutorials b) Circuit exampels (DIY) 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