Embedded Systems Design, May 2010 (h33t) (Mkrandow)
Embedded Systems Design, May 2010 (h33t) (Mkrandow)
NUMBER 4
MAY 2010
Using an FPGA
to test a PLL
band calibration
algorithm, 23
Object-code
generation fix, 29
Ganssle: More
on test driven
development, 33
Protect against
malicious software
16
HCC-Embedded
FILE SYSTEMS WITH A DIFFERENCE ZbWZYYZY
www.hcc-embedded.com • [email protected]
INTEGRITY RTOS has it.
No one else does.
Copyright © 2010 Green Hills Software, Inc. Green Hills, the Green Hills logo, and INTEGRITY are
trademarks of Green Hills Software, Inc. in the U.S. and/or internationally. All other trademarks are
the property of their respective owners.
www.ghs.com
The Newest Products
For Your Newest Designs
Embed Your Innovation into the Market Place.
SocketModem® iCell / Cell Embedded ZICM2410P2 MeshConnect™ Module A1084-B GPS receiver module
Wireless Modems mouser.com/celzicm2410p2 mouser.com/vincotecha1084b
mouser.com/multitechicell/
The newest embedded and wireless products and technologies make designing
even more fun. Experience Mouser’s time-to-market advantage with no
minimums and same-day shipping of the newest products from more than 400
leading suppliers.
Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners.
T H E O F F I C I A L P U B L I C AT I O N O F T H E E M B E D D E D S Y S T E M S C O N F E R E N C E S A N D E M B E D D E D. C O M
COLUMNS
programming
pointers 9
Alternative models for
memory-mapped devices
BY DAN SAKS
Traditional techniques for communi-
cating with hardware devices can be
inconvenient and error-prone. Here are
EMBEDDED SYSTEMS DESIGN ways to make them simpler and robust.
VOLUME 23, NUMBER 4
MAY 2010 break points 33
An interview with James
Grenning, Part 2
16 BY JACK G. GANSSLE
Is test driven development viable for
embedded systems? Ganssle continues
to grill Grenning on TDD.
DEPARTMENTS
#include 5
Virtualization extends down to
mobile devices
BY RICHARD NASS
The BOM on a virtualized handset can
be reduced significantly over a more
traditional design.
23
June 7–9, 2010
How to use an FPGA to test a PLL band esc-chicago.techinsightsevents.com/
calibration algorithm ESC India
BY RUSSELL MOHN July 21–23, 2010
Prototyping an ASIC design first on an FPGA is not only useful www.esc-india.com/
for verification but allows more room for algorithm experimen- ESC Boston
tation. September 20–23, 2010
www.embedded.com/esc/boston
RUN it [Fast]
With Express Logic’s small, fast, royalty-free and industry leading
ThreadX® RTOS, NetX™ TCP/IP stack, FileX® FAT file system, and USBX™
T H R E A D
USB stack.
ANALYZE it [Easily]
T
With Express Logic’s graphical TraceX® event analysis tool, and new
R
StackX™ stack usage analysis tool. See exactly what is happening in your
A
C
E
SHIP it [Confidently]
No matter what “it” is you’re developing, Express Logic’s solutions will
help you build it, analyze it, run it, and ship it better and in less time. Join
the success of over 600,000,000 deployed products using
Express Logic’s ThreadX!
B E N C H T H R E A D T R A C E S T A C K
Newnes
ion
Second Edit
E
REAL-TIM
ED
EMBEDD ADING
RE
MULTITH dX
With Threa
re,
ARM, Coldfi
CD-R OM
INCL UDED
ThreadX
Containing
ThreadX, BenchX, TraceX and FileX are a registered trademarks of Express Logic, Inc. All other trade-
n system
demonstratio
examples
and C code
L. Lamie
Edward
EMBEDDED SYSTEMS DESIGN
Editorial Director
BY Richard Nass #include
Richard Nass
(201) 288-1904
[email protected]
Managing Editor
Susan Rambo
[email protected]
Virtualization extends down
Contributing Editors
Michael Barr, John Canosa,
Jack W. Crenshaw, Jack G. Ganssle,
Dan Saks, Larry Mittag
to mobile devices
Art Director
Debee Rommel
[email protected]
European Correspondent
Colin Holland
[email protected]
I t wasn’t too long ago that you had
to explain to designers what the
term “virtualization” was all about.
That’s generally not the case anymore.
In fact, the number of systems that are
Kernel Labs (OK Labs, for short)
shows a significant cost savings, up to
46% over a similar, nonvirtualized de-
sign. The biggest savings comes from
being able to eliminate the applica-
Embedded.com Site Editor
Bernard Cole
“virtualized” as part of the design tions processor, which could cost as
[email protected] process has increased considerably. much as $30, depending on the re-
Production Director In most cases, the systems that quired performance, functionality,
Donna Ambrosino were candidates for virtualization and feature set of the handset.
[email protected]
were those of the high-performance Eliminating that apps processor
Subscription Customer Service
P.O. Box 2165, Skokie, IL 60076 variety. Today, you can make an argu- reduces the memory footprint, there-
(800) 577-5356 (toll free) ment to go the virtual route for almost by savings a few dollars. The only ad-
Fax: (847) 763-9606
[email protected] any type of embedded system, includ- ditional cost to the BOM comes in the
www.customerserviceesp.com ing mobile devices. The technology way of the hypervisor needed to do
Article Reprints, E-prints, and that’s been deployed for years in enter- the virtualization, which is where OK
Permissions
Mike O’Brien prise data centers can be driven down Labs comes in. They provide that hy-
Wright’s Reprints into consumer devices. pervisor software.
(877) 652-5295 (toll free)
(281) 419-5725 ext.117 While traditional virtualization of- One example of a handset that
Fax: (281) 419-5712 ten concentrates on a high-end (even was virtualized using the OK Labs
www.wrightsreprints.com/reprints/index.cfm
?magid=2210 multicore) processor and chipset, mo- technology is the Motorola Evoke. It
Publisher
bile virtualization tends to look at the employs an embedded hypervisor
David Blaza paradigm a little differently. For exam- from OK Labs, called the OKL4 (note
(415) 947-6929
[email protected]
ple, it’s no surprise to see multiple that the Motorola Evoke will be the
chips consolidated into a unified object of an upcoming Tear Down ar-
Editorial Review Board
Michael Barr, Jack W. Crenshaw, processor, with dedicated DRAM, glue ticle, where we really get into the nuts
Jack G. Ganssle, Bill Gatliff, logic, and so on. At the same time, and bolts of how the handset was de-
Nigel Jones, Niall Murphy, Dan Saks,
Miro Samek multiple functions can be ported to signed, with a particular focus on the
that single virtualized processor. While virtualization aspect).
potentially increasing performance, The bottom line is that you
there’s a big upside in the reduced shouldn’t dismiss virtualization tech-
number of interconnects required. nology as just being for high-end de-
Corporate—EE Times Group
Paul Miller Chief Executive Officer The single virtualized processor also vices. You could be missing an oppor-
Felicia Hamerman Group Marketing Director
Brent Pearson Chief Information Officer reduces the overall memory footprint tunity to reduce your BOM and
Jean-Marie Enjuto Financial Director
Amandeep Sandhu Manager Audience Engagement required by the system. ultimately simplify your design, espe-
Barbara Couchois Vice President Sales Ops
A side-by-side comparison of a cially if your product lends itself to
handset that was virtualized by Open multiple versions/family members.
Richard Nass
Corporate—UBM LLC ([email protected])
Marie Myers Senior Vice President,
Manufacturing
is the editorial direc-
Pat Nohilly Senior Vice President, Strategic tor of Embedded
Development and Business
Administration
Systems Design maga- Richard Nass
zine, Embedded.com, [email protected]
and the Embedded
Systems Conference.
Developing a commercially viable fuel cell vehicle has been a significant challenge because
of the considerable expense of designing and testing each new concept. With NI LabVIEW
graphical programming and NI CompactRIO hardware, Ford quickly prototyped fuel cell control
unit iterations, resulting in the world’s first fuel cell plug-in hybrid.
MEASURE IT FIX IT
Ford is just one of many customers using the NI graphical system design platform to improve the world around
them. Engineers and scientists in virtually every industry are creating new ways to measure and fix industrial
machines and processes so they can do their jobs better and more efficiently. And, along the way, they are
creating innovative solutions to address some of today’s most pressing environmental issues.
>> Download the Ford technical case study at ni.com/336 800 258 7018
©2009 National Instruments. All rights reserved. CompactRIO, LabVIEW, National Instruments, NI, and ni.com are trademarks of National Instruments.
Other product and company names listed are trademarks or trade names of their respective companies. 1121
parity bit
Debating test driven development
W ith respect to the guest (Jack
Ganssle, “An interview with
James Grenning,”April 2010,
p.35, www.embedded.com/224200702),
he is an example of the kind of software
against it. But so far, it is the best tool
going for managing complexity and risk
in real-world projects. You can use TDD
or OOD or whatever you need to use
inside your waterfall block, but your
code correct rather than to prove it in-
correct. Under time pressure, this be-
comes a subconscious driver. It would
be really easy to write “soft” tests in
TDD as well. Addressing this would
person who focuses too much on the block has to be correct in relation to the probably result in developers complain-
software itself and not enough on the other blocks of the project. ing about BTUF (Big Testing Up Front).
whole system. Consider: “The code — Larry Martin —lwriemen
specifies the behavior of the executable Owner, www.GlueLogix.com Chief Frog
program in all its necessary detail.”
That’s a true statement but a mis- I think we all agree that the product
leading one. Only the target processor must be tested as whole in its intend-
can read the code to the level of preci- ed environment. Or...? The require-
sion needed to answer key questions, ments may be flawed or incomplete,
like, “What is the maximum travel of numerous research have labelled poor
this actuator?” or, “What is the maxi- requirements as the most common
mum RPM of this motor?” Therefore, cause for disaster.
human reading of source code is no Also, no matter how loose cou-
substitute for a concise, accurate, top- pling your code has, there might be
level specification, which feeds both im- unforseen dependencies arising when
plementation and system test activities. the code is put together. All modules
Here’s an example. Some years ago,
I heard about a software-related inci-
dent at an automated sawmill. The tar-
! One difference between
embedded and other
in your project will also share the
same system resources. And there will
always be the top-down dependancy
get processor was 16 bits, and the soft-
ware was calibrated in .001-inch units.
The first log that came through the sys- ! software is that physical
systems often have
from main thread -> code modules -
> objects/functions. So the code, too,
needs to be tested in its intended soft-
! complex requirements
tem with diameter greater than 32.767 ware environment, just like the final
inches caused a reversal of some actua- product needs to be tested in the in-
tor that broke stuff and injured the op- of their own. tended “real world” environment.
erator. So code may equal design, but in None of the this excludes TDD.
this case something more explicit was But of course TDD can’t be used as a
needed. I daresay that TDD-style unit TDD is a way to ensure that some replacement for final verification/vali-
testing would not have caught that analysis and design is being addressed dation, that would just be plain stu-
problem either. “up-front”, but this article didn’t cover pid, for the above mentioned reasons.
One difference between embedded all my concerns. I really don’t hope that’s the case...
and other software is that physical sys- I’ve seen a lot of projects run into I’m going to be mean and shoot
tems often have complex requirements trouble, when integration occurs, due to down [Larry Martin’s] example [about
of their own. Those requirements need a lack of planning for integration of the the automated sawmill]. Any decent
to be captured independently of the units. TDD doesn’t seem to address static analyzer (and good compilers as
code, and need system-level testing in- this. well) would have attacked that particu-
dependent of any in-code specification. I also believe it’s very beneficial to lar bug saying something like “implicit
I think a certain personality type have independence in testing, even at conversion between signed and un-
likes to pick apart the waterfall method, the unit test level. It is too common for signed int.” If you scratch your head for
and there are obvious arguments developers to write tests to prove their CONTINUED ON PAGE 32
!
the Intel x86 processors, to move data cusing more on the interface de-
to or from device registers. To a C or ware devices can be incon- sign issues than on the imple-
C++ programmer, port-mapped de- venient and error-prone. mentation details.
vice registers don’t look like ordinary
memory.
The C and C++ standards say
nothing about port-mapped I/O. Pro-
grams that perform port-mapped I/O
! Here are ways to make
them simpler and robust.
MAPPING MEMORY THE
OLD-FASHIONED WAY
Let’s consider a machine with a
variety of devices, including a
must use nonstandard, platform-specific language or li- programmable timer and a couple of UARTs (serial
brary extensions, or worse, assembly code. On the other ports), each of which employs a small collection of device
hand, programs can perform memory-mapped I/O using registers. The timer registers start at location
only standard language features. Fortunately, port- 0xFFFF6000. The registers for UART0 and UART1 start at
mapped I/O appears to be gradually fading away, and few- 0xFFFFD000 and 0xFFFFE000, respectively.
er programmers need to fuss with it. For simplicity, let’s assume that every device register
is a four-byte word aligned to an address that’s a multiple
of four, so that you can manipulate each device register as
an unsigned int. Many programmers prefer to use an
Dan Saks is president of Saks & Associates, a C/C++
training and consulting company. For more informa- exact-width type such as uint32_t. (Types such as
tion about Dan Saks, visit his website at uint32_t are defined in the C99 header <stdint.h>.)5
www.dansaks.com. Dan also welcomes your feed- I prefer to use a symbolic type whose name conveys
back: e-mail him at [email protected].
the meaning of the type rather than its physical extent,
such as:
*TMOD &= ~TE; This works for the timer because there’s only one timer.
However, my sample machine has two UARTs, each with six
or prepare the timer to count for two seconds using: registers, and many UART operations employ more than one
register.
*TDATA = 2 * TICKS_PER_SEC; For example, to send data out a port, you must use both
*TCNT = 0; the UART status register and the transmit buffer register. The
function call might look like:
Other devices require similar clusters of macros, such as
Listing 1. In this case, UART0 and UART1 have identical sets
of registers, but at different memory-mapped addresses. They Listing 1
can share a common set of bit masks:
// UART 0 registers
#define ULCON0 ((unsigned volatile *)0xFFFFD000)
#define RDR 0x20 ~~~
#define TBE 0x40 #define USTAT0 ((unsigned volatile *)0xFFFFD008)
#define UTXBUF0 ((unsigned volatile *)0xFFFFD00C)
SO WHAT’S NOT TO LIKE? ~~~
This approach leaves a lot to be desired. As Scott Meyers likes
to say, interfaces should be “easy to use correctly and hard to // UART 1 registers
use incorrectly.”8 Well, this scheme leads to just the opposite. #define ULCON1 ((unsigned volatile *)0xFFFFE000)
By itself, disabling a timer isn’t a hard thing to do. When ~~~
#define USTAT1 ((unsigned volatile *)0xFFFFE008)
you’re putting together a system with thousands of lines of
#define UTXBUF1 ((unsigned volatile *)0xFFFFE00C)
code controlling dozens of devices, writing:
~~~
which passes registers from two different UARTs. In fact, the To make this work, you need a scheme that converts integers
function even lets you accidentally pass a timer register to a into register addresses at run time. Plus, you have to worry
UART operation, as in: about what happens when you pass an integer that’s out of
range.
UART_put(USTAT, TDATA, c);
USING STRUCTURES
Ideally, compilers should catch these errors, but they Structures provide a better way to model memory-mapped
can’t. The problem is that, although each macro has a differ- devices. You can use a structure to represent each collection
ent value, they all yield expressions of the same type, namely, of device registers as a distinct type. For example:
“pointer to volatile unsigned.” Consequently, compilers can’t
use type checking to tell them apart. typedef uint32_t volatile device_register;
Using different typedefs doesn’t help. A typedef doesn’t
define a new type; it’s just an alias for some other type. Thus, typedef struct timer_registers timer_registers;
even if you define the registers as: struct timer_registers
{
// timer registers device_register TMOD;
typedef uint32_t volatile timer_register; device_register TDATA;
device_register TCNT;
#define TMOD ((timer_register *)0xFFFF6000) };
#define TDATA ((timer_register *)0xFFFF6004)
~~~ The typedef before the struct definition elevates the
tag name timer_registers from a mere tag to a full-
// UART 0 registers fledged type name.9 It lets you refer to the struct type as
typedef uint32_t volatile UART_register; just timer_registers rather than as struct timer_
registers.
#define ULCON0 ((UART_register *)0xFFFFD000) You can provide corresponding structures for each device
#define UCON0 ((UART_register *)0xFFFFD004) type:
~~~
typedef struct UART_registers UART_registers;
then timer_register and UART_register are just two dif- struct UART_registers
ferent names for the same type, and you can use them inter- {
changeably throughout your code. Even if you take pains to device_register ULCON;
declare the UART_put function as: device_register UCON;
device_register USTAT;
void UART_put(UART_register *s, device_register UTXBUF;
UART_register *b, int c); ~~~
};
you can still pass it a timer register as a UART register. By any
name, an volatile unsigned is still an volatile unsigned. Using these structures, you can define pointers that let
Again, you could write the UART functions so that they you access device registers. You can define the pointers as
know which registers to use. But there are two UARTs, so macros:
you’d have to write pairs of nearly identical functions, such as:
#define the_timer
void UART0_put(int c); ((timer_registers *)0xFFFF6000)
void UART1_put(int c); #define UART0 ((UART_registers *)0xFFFFD000)
thEy'rE counting
on mE to dElivEr.
!
have to use compile switches or
Whichever way you define the pointers,
For device operations that pragma directives to get your struc-
you can use them to access the actual de- use more than one regis- tures just so.4 You can also use com-
vice registers. pile-time assertions to verify that
For example, you can disable the
timer using the expression:
! ter, you can pass just the
address of the entire
the structure members are laid as
they should be.11
You’re invited.
Power2Solve is a series of FREE technical seminars for Design Hands-on Training
Engineers and Educators, offering practical, how-to training on the
latest troubleshooting techniques for embedded system design.
You’ll spend a day working side-by-side with your peers and industry
experts from Tektronix finding solutions to your debugging challenges.
Courses Include:
• Power Analysis
Use Tektronix cutting-edge
• Debugging Digital Designs oscilloscopes to perform
• Serial and Parallel Data Debug hands-on digital debug and
• Characterization & Jitter Analysis serial data measurements.
Bullet-proofing your
software design
BY NAT HILLARY
I
n August 2003, a rolling blackout affected 10 million people in Ontario
and 45 million people in the eastern part of the United States, raising
concern that a cyber-attack by a hostile force was underway. Ultimately
the causes of the blackout were traced to a slew of system, procedur-
al, and human errors and not an act of aggression. Nevertheless, the
event brought home the vulnerability of critical infrastructures connect-
ed to the Internet, raising awareness of the need for secure system
components that are immune to cyber attack.
This increasing dependence on In- definition of secure software will follow
ternet connectivity demonstrates the that provided by the U.S. Department
growing need to build security into of Homeland Security (DHS) Software
software to protect against currently Assurance initiative in “Enhancing the
known and future vulnerabilities. This Development Life Cycle to Produce Se-
article will look specifically at the best cure Software: A Reference Guidebook
practices, knowledge, and tools avail- on Software Assurance.” DHS main-
able for building secure software that’s tains that software, to be considered se-
free from vulnerabilities. cure, must exhibit three properties:
!
“Resilience”)—Software that is re- security risk assessment, a process that
silient enough to withstand attack
requirements ensures ensures the nature and impact of a se-
and to recover as quickly as possi- that security is included curity breach are assessed prior to de-
ble, and with as little damage as ployment in order to identify the secu-
possible from those attacks that it
can neither resist nor tolerate.
Application partitioning
VCC: 1.7V to 3.6V
and IP protection
Microcontroller Peripherals
• 16-bit MAXQ RISC core • Two USARTs and one SPI master/slave
• 64KB flash memory, 2KB SRAM communication port
• Ultra-low supply current • Two 16-bit timers/counters
– Active mode: 3.75mA at 12MHz • 8kHz nanoring functions as programmable
– Stop mode: 200nA (typ), 2.0μA (max) wakeup timer
• Wide, 1.7V to 3.6V operating voltage range • IR timer simplifies support for low-
• IP protection speed infrared communication
– Secure MMU supports multiple privilege • IR driver capable of 25mA
levels, helps protect code from copying and sink current
reverse engineering
Temp Range Program Data Operating Price†
Part Package
(°C) Memory Memory Voltage (V) ($)
MAXQ610B 0 to 70 64KB flash 2KB SRAM 1.7 to 3.6 40-TQFN 1.45
www.maxim-ic.com/MAXQ610-info
DIRECT ™
www.maxim-ic.com/shop www.em.avnet.com/maxim TM
!
Mellon. These secure coding stan- data types.
dards can be enforced by the use of
under analysis without Static software analysis tools assess
static analysis tools, so that even executing it and are the code under analysis without actual-
novice secure software developers can ly executing it. They are particularly
benefit from the experience and
knowledge encapsulated within the
standards.
The use of coding standards to
! adept at identifying cod-
ing standard violations.
adept at identifying coding standard vi-
olations. In addition, they can provide a
range of metrics that can be used to as-
sess and improve the quality of the code
eliminate ambiguities and weaknesses under development, such as the cyclo-
in the code under development has CVE dictionary, some occur more than matic complexity metric that identifies
been proven extremely successful in the others—user input validation, buffer unnecessarily complex software that’s
creation of high-reliability software, overflows, improper data types, and difficult to test.
such as the use of the Motor Industry improper use of error and exception When using static analysis tools for
Software Reliability Association (MIS- handling. The CWE and CERT-C dic- building secure software, the primary
RA) Guidelines for the use of the C lan- tionaries identify coding weaknesses objective is to identify potential vulner-
abilities in code. Example errors that
static analysis tools identify include:
• Insecure functions
• Array overflows
Embedded •
•
Array underflows
Incorrectly used signed and
!
code paths or an excessive number of test-case generation, execution and
loops.
The most effective and maintenance streamline the unit
By eliminating security vulnerabili- cheapest way of ensuring testing process, easing the unit test-
ties, identifying latent errors, and en- ing burden and reinforcing unit
suring the testability of the code under
development, static analysis tools help
ensure that the code is of the highest
! that the code under
development meets its •
test accuracy and completeness.
Dynamic analysis—analyses per-
formed while the code is executing
quality and secure against not only cur-
rent threats but unknown threats as
well. ! security requirements is
via unit testing.
provide valuable insight into the
code under analysis that goes be-
yond test-case execution. Structur-
al coverage analysis, one of the
FITTING TOOLS INTO THE more popular dynamic analysis
PROCESS ments from their source through all methods, has been proven to be in-
Tools that automate the process of stat- of the development phases and valuable for ensuring that the veri-
ic analysis and enforcement of coding down to the verification activities fication test cases execute all of the
standards such as CWE or CERT C Se- and artifacts ensures the highest code under development. This
cure Coding guidelines ensure that a quality, secure software. helps ensure that there are no hid-
higher percentage of errors are identi-
fied in less time. This rigor is compli-
• Unit testing—the most effective
and cheapest way of ensuring that
den vulnerabilities or defects in the
code under development.
mented by additional tools for: the code under development meets
its security requirements is via unit While these various capabilities can
• Requirements traceability—a good
requirements traceability tool is in-
testing. Creating and maintaining
the test cases required for this,
be pieced together from a number of
suppliers, some companies offer an in-
valuable to the build security in however, can be an onerous task. tegrated tool suite that facilitates the
process. Being able to trace require- Unit testing tools that assist in the building security in process, providing
LDRA TBvision screenshot showing improper data type sign usage resulting in buffer overflow vulnerability.
Figure 2
Planning Implementation
Automated
testing unit
Configuration
and change
management
Evaluation Testing
Deployment
Test completeness
verification
Figure 3
BUILDING
! It’s not surprising that the processes for
building security into software echoes the
SECURITY
It’s not surprising
that the processes
for building secu-
! high-level processes required for building
quality into software.
rity into software
echoes the high-level processes required CERT-C Secure Coding Guidelines and
for building quality into software. CWE dictionary, static analysis tools
Adding security considerations into the help make this objective both practical
process from the requirements phase and cost effective. Combine this with
onwards is the best way of ensuring the the improved productivity and accura-
development of secure code, as de- cy of requirements traceability, unit
scribed in Figure 3. High-quality code testing and dynamic analysis and the
is not necessarily secure code, but se- elimination of exploitable software
cure code is always high-quality code. weaknesses become inevitable. ■
An increased dependence on inter-
net connectivity is driving the demand
for more secure software. With the Nat Hillary is a field applications engi-
neer with LDRA Technologies, Inc., a po-
bulk of vulnerabilities being attributa- sition that he comes to via an extensive
ble to coding errors, reducing or elimi- background in software engineering,
nating exploitable software security sales and marketing. He is an experi-
weaknesses in new products through enced presenter in the use of software
analysis solutions for real-time safety crit-
the adoption of secure development ical software who has been invited to
practices should be achievable within participate in a number of international
our lifetime. forums and seminars on the topic.
By leveraging the knowledge and
experience encapsulated within the
Prototyping an ASIC design first on an FPGA is not only useful for verification but allows
more room for algorithm experimentation.
I
t’s a common technique to split the required frequency tuning
range of a controlled oscillator into discrete bands. The advantage
of having many bands is that a wide tuning range can be covered
while keeping a relatively low voltage-controlled oscillator (VCO)
gain within each band. Low VCO gain is good for achieving low
VCO phase noise. It’s required that the frequency bands overlap.
The tuning bands are changed with a digital band control signal.
!
In communications chips, frequency range is split up into dis- correct that phase difference.
synthesizers are ubiquitous functional For the application at hand, the
blocks. A frequency synthesizer is loosely crete bands. synthesizer needed to create frequencies
defined as a PLL that generates an out- from 3,000 to 4,000 MHz. Continuous
put frequency that’s directly proportion- tuning of the VCO is accomplished by
al to a reference frequency. The constant the output of the VCO, and R is anoth- changing the bias voltage across a var-
of proportionality is a specific subset of er integer divide ratio for dividing the actor which is part of the parallel in-
integer or real numbers, depending on reference oscillator. If even finer fre- ductor-capacitor (LC) resonant circuit.
the synthesizer implementation. quency resolution is needed, the N val- The fabrication technology limits the
One use for a synthesizer in a re- ue can be added to a sigma-delta mod- control voltage to a maximum change
ceiver front-end is the creation of the ulated code that dithers the divider of about 1.5 V. It’s difficult to build a
varactor that will change its reactance
The band calibration testbench implemented on the FPGA is analogous enough to cause a frequency change of
to band calibration used in a frequency synthesizer on an ASIC. 1,000 MHz with only a control voltage
change of 1.5 V.
Furthermore, a large VCO gain of
BCAL Ndiv 1,000 MHz/1.5 V would make the PLL
8b
susceptible to high phase noise. For
VCO
these reasons, the tuning range is split
PFD Filter MMD
REF
VC
RF up into discrete bands. The discrete
xtal
Disabled bands are implemented by adding bina-
ry-weighted capacitors to the parallel
LC tank circuit. They are switched on
or off depending on the digital band
setting. The band must be set before the
FPGA band-calibration testbench
PLL can be allowed to lock and track in
7-segment a continuous manner.
display
The BCAL circuit operates as a sec-
ond feedback loop controlling the VCO
REF BCAL NCO
signal source
8b Proto pin for through its band input. During band
viewing on scope
calibration, the VCO control voltage is
Push-button reset fixed at a convenient voltage, usually
the mid-point of its allowable control
Figure 1
!
phase noise, a crystal generates the fre- with the HIT_VALUE, and the XOR of
quency reference. The reference fre- output value and deter- the two comparison results is used to
quency is typically in the tens of MHz, mines what the next band clock a “1” into a D flip-flop.
which is well below the maximum When both count values are less
speed of the logic that can be imple-
mented on today’s FPGAs. The BCAL
algorithm itself can be described and
designed with digital techniques.
! value will be based on
which clock won the race.
than HIT_VALUE, the comparators
both output 0, and the XOR result is 0.
At the instant one of the values ex-
ceeds the HIT_VALUE, the XOR out-
At its simplest, its inputs are two put transitions to 1 and captures a 1
clocks, the reference and the output of DESIGN AND PROTOTYPING on the DFF output. Sometime there-
the NCO; its output is the band signal PROCEDURE after, the other count value will get to
for the NCO. The combination of the The design and prototyping procedure HIT_VALUE, and the XOR result re-
band calibration, NCO, and an external- is the iteration of the following familiar turns to 0.
ly applied reference signal forms a steps: 1. Design Entry; 2. Test; 3. Debug; Another comparator is used to
closed loop system with negative feed- 4. Go To 2. This cycle is repeated as compare the reference counter to a
back that is analogous to the PLL oper- many times as necessary until the de- constant RESET_VALUE, and when
ating during its band calibration mode, sired functionality is reached. the count exceeds this value, both
all of which can be coded in RTL and First, I built the NCO as a Simulink counters are reset to 0 and the race be-
tested on an FPGA before spending subsystem. The NCO Simulink model gins over again. If the HIT_VALUE is
money on an ASIC fabrication. was reverse-engineered from the verilog 230, a plausible RESET_VALUE is 240.
for an NCO I found on the web at Meanwhile, the bit of information
WHAT YOU NEED www.mindspring.com/~tcoonan/nco.v. about which clock was faster is used as
1. An FPGA and its programming The NCO was based on a programma- input to a binary search block.
software ble modulo counter. Its output frequen- The binary search block holds the
2. Matlab/Simulink for algorithm de- cy equals Fs*(BAND+STEP)/MOD current band output value and deter-
velopment and verification where STEP and MOD are fixed values mines what the next band value will be
3. A signal source for generating the and BAND is the 8-bit band signal. based on which clock won the race.
reference clock, such as 10 to 15 The NCO’s functionality was veri- The binary search block either adds or
MHz fied by running transient simulations subtracts the appropriate binary
4. An oscilloscope for debugging using Fs=11MHz and sweeping weighted value from its current out-
through the BAND values, 0 to 255, put. For an 8-bit band, the initial band
I used Matlab/Simulink to enter the and calculating the resulting output value is mid-range at 128, and seven
initial design and testbench. The sup- frequency. The resulting output fre- consecutive races are conducted to fill
port for fixed-point numbers that quency versus BAND, or band tuning in the 8-bits from MSB to LSB. An ex-
comes with the Fixed-Point Toolbox curve, was monotonic but not perfect- ample run of the BCAL algorithm is
and Simulink Fixed Point is useful for ly linear. Since it was monotonic, it shown in Figure 2.
!
The test schematic includes the increments of approximately 100 kHz.
was pass/fail tested for 50 NCO which is controlled by the The test setup is shown in Figure 3. At
possible frequencies. BCAL band output. each reference frequency, the band cali-
To complete the loop, the bration was initiated by a reset tied to a
NCO output is used as one of push-button. Switch debouncing would
After building the band calibration the clock inputs to the BCAL. The BCAL have made a cleaner testbench but was
algorithm in Simulink from logic gates, reference input was wired through one not necessary.
comparators, registers, delays, and of the FPGA pins to an SMA connector Multiple resets caused by the switch
look-up tables, the design was entered on the board so it could be clocked with bounce cause the algorithm to start
in the Quartus II software. To make de- an external signal source. over repeatedly; when the switch stops
bugging easier, every wire in the The BCAL testbench was synthe- bouncing, the BCAL operates normally.
Simulink model was named. sized and fitted, and the timing netlist The 8-bit band value was mapped to
During the translation process, I was simulated. Immediately, it was ap- two 7-segment displays on the FPGA
used the same names for signals in the parent there was a bug in the design be- board to display the final band value in
Verilog code. If a signal originated cause some of the band bits were going hexadecimal.
from a register (or a delay in a trig- into undefined states, shown as “U” in The BCAL algorithm finishes in
gered subsystem) in the Simulink Quartus II. 146 µs (= 7*230/11 MHz), so only the
model, I made it a register in Verilog; The bug came from the asynchro- final value appears to a human observ-
otherwise the signal was a wire. As a nous comparisons of the counter values er. The readout made it easy to compare
result, the design entry from Simulink to the HIT_VALUE. After registering against the theoretical value from the
primitive subsystems to Verilog was these comparison results and retiming Simulink model. In this way, the BCAL
straightforward. the asynchronous data paths to the ref- algorithm was pass/fail tested for 50
possible frequencies from its minimum
to maximum band values.
An example band calibration run with REF = 14.3MHz; the band
settles to 227. POTENTIAL PITFALLS AND TIPS
260
One of the challenges of this particular
design was its asynchronous nature.
BCAL The frequency of the NCO clock
240
changes during the band calibration,
Target and some logic elements in the BCAL
220 depend on the timing of the edges of
that clock. Likewise, other logic ele-
ments change synchronously to the ref-
200
erence clock edges.
Band [LSB]
REF
frequency [MHz]
NCO output
~14.3 MHz
REF input
to FPGA
Figure 3
Live Webinar
Registration information
2010 Distributor Brand Preference Study ■ Register by 4/30/10: $250.00
(USD)
OEMs rank distributors based on how well they help them achieve their
■ Register between 5/1/10 and
operating goals and today, more than ever, it’s crucial for distributor partners 5/14/10: $299.00 (USD)
to understand how they stack up in the face of their vendor partners and end
The registration fee is payable by
customers, how they are measured and where they rate compared to their
American Express, Mastercard,
competitors in order to strengthen revenues and plan for a strong year ahead. or Visa. All paid registrants will
Tune in on May 14 as EE Times Group unveils the 2010 Distributor Brand be given a confirmation number
Preference Study, our annual benchmark research on the $40 billion+ and a url which will enable them
distribution market where design engineers, technical managers, supply to view the study, at their leisure,
chain management, purchasing and corporate managers across the OEM from May 14 to December 31, 2010.
market have weighed in on:
Please contact EE Times’
■ Which distributors are preferred and what criteria matters the most Webinar Support with
such as ease of doing business, customer service, pricing and website any questions at
capabilities. [email protected]
■ How distributor brand preference varies across product categories such
as semiconductors, connectors & interconnects, passive components
and electromechanical devices
Presenter:
■ What factors influence purchasing decisions from the same distributor
Presented by EE Times, this landmark research is a key measurement Jim McLeod-Warrick
tool for OEM’s, CEM’s, distributors and suppliers. If you are a distributor, an Founding Partner of Beacon
OEM or a decision maker in the purchase process of electronic components Technology Partners LLC
you need to attend this webinar.
Dealing with
misbehaving tools
BY ANDERS HOLMBERG
!
tougher by requiring extensive im- chain and the vendor should be subject
pact analysis of the changes prior to
but methods and tools to a lot of scrutiny before selection. And
performing them. to avoid or minimize the the typical scenario is that once a partic-
• The goodwill view: Frequent or ular compiler and version is selected,
large code changes in the final
stages of a project can make stake-
holders nervous about the end
product. If the product has already
! impact of changes can
be extremely helpful.
you stay with it throughout the project.
Some high-integrity process frameworks
even require the tools selection to be
subject to a formalized process where
reached the market, the situation in the future. However, as this kind the tools are prequalified or validated ac-
can be a real nightmare. of latent bug is mainly a process cording to certain criteria.
and knowledge issue, it will not be We will now take a look at a special
So, it’s not always possible to avoid discussed further here. technique that can be used if you have a
code changes, but methods and tools to
avoid or minimize the impact of
• This leaves us with the main focus
for this article, the object-code-gen-
close relationship with your compiler
vendor. Consider a compiler for a 32-bit
changes can be extremely helpful. eration-tool bug. We will restrict architecture. Many 32-bit CPU kernels
Three broad categories cause most the discussion to bugs in the build incorporate some kind of instruction
of the late code changes: chain, in other words, the compiler, pipeline to increase performance by di-
assembler, and linker. viding complex instructions into 1-cycle
• The source-code bug: This kind of
error is either due to mistakes or Consider the following situation. A
pieces that are executed in their own
pipeline stage.
misunderstandings by the pro- bug you have found is the result of the In this way a throughput of one in-
grammer in the implementation or compiler making wrong assumptions struction per clock cycle can be
an ambiguous or incomplete func- about register allocation and stack allo- achieved under ideal circumstances. It is
tional specification that leaves too cation of variables that are local to a however very easy to break this if subse-
much open to interpretation. Al- function. The bug is exposed when quent instructions are competing for
though this is a common occur- many variables compete for the avail- the same resource. An example is if the
rence, I won’t be discussing it in able CPU registers and some variables first instruction writes to a particular
this article. have to be temporarily moved to the register and the directly following in-
• The latent non-ANSI C/C++ source
bug: The ANSI C standard has
stack. You have found the bug in a large
function with a lot of arithmetic com-
struction reads from the same register.
On many pipelined architectures, this
some dark corners where behavior putations, but that is no guarantee that will cause a so called pipeline stall that
is either implementation defined or the bug will only manifest itself in large means that one-cycle processing is in-
undefined. If you’ve implemented functions with a lot of computations. terrupted while the second instruction
parts of the source code to depend So we end up with the question of waits for the first instruction to finish
on how a particular compiler be- whether to persuade the compiler ven- writing to the register.
haves for these corner cases of the dor to supply a fix or applying the A good compiler for such a CPU ar-
standard, you can expect a problem workaround(s) throughout the code chitecture will try to rearrange or sched-
Listing 1 Listing 2
Bool AreIndependent(Instr inst1, Instr inst2) void ChangeMOVOrder(Instr inst1, Instr inst2)
{ {
if (IndependentSourceAndDest(Inst1, Inst2)) // Do other processing first
{ …
return true; if (AreIndependent(inst1, inst2))
} {
else ChangeOrderHelper(inst1, inst2);
{ }
return false; }
}
}
!
ate a new pipeline stall by moving two tor code in the buggy function! If we
instructions to avoid another stall.
user’s code base that is would have done so, it would report
Let’s return to the function in Listing affected by the bug. every occurrence of possibly erroneous
1 and the compiler that uses this func- MOV instructions.
tion. When a customer compiles a cer- Even this simplified example showed
tain program with this compiler, it works does he have more affected locations? us one of the pitfalls in creating a pro-
flawlessly, except that he notes that two Finding that out effectively amounts to duction quality bug detector. It can be
memory writes are done in the wrong or- going through the complete code base simple to isolate the root cause of the
der as opposed to how they are specified looking for accesses to volatile variables bug but complicated to determine when
in the program. Usually this is the princi- and examining the generated code; so this bug will actually result in the gener-
ple that the scheduler is dependent on to we’re back to the central theme of this ation of wrong code. We could for exam-
perform its magic, but in this case it’s not article—how can the customer’s change ple have a number of different functions
OK because the user has specified that management be simplified? of varying complexity that depend on
both variables that are affected by the Here is one possible remedy to the the AreIndependent() function.
MOV instructions are declared as situation: a special version of the origi- But if it’s practically possible to create
volatile, which has implies that the or- nal compiler can try to identify all code the bug detector, it can now be used to
der of the writes should not change. If, in the user’s code base that is actually af- pinpoint the exact locations of any other
for example, the memory writes are in- fected by the bug. code that is affected by the original bug.
tended to initialize some external hard- Here is how the compiler can be In this way, we can avoid going through
ware, this can be extremely important. turned into a bug detector. The function all object code by hand to look for possi-
The AreIndependent() function in Listing 1 is used in another function ble occurrences of the problem. ■
ignores the volatile attribute of both in- (Listing 2) that changes the order of two
structions and thus reports that it’s OK instructions when that function has de- Anders Holmberg is software tools prod-
to rearrange these instructions. cided that it is beneficial to do so. uct manager at IAR Systems.
DCC Corp.
7300 N. Crescent Blvd., Pennsauken NJ 08110
PH: 856-662-7272 • Fax: 856-662-7862
Web: www.dccCorporation.com
is telling you: “why are you using a release program that was a total mess, Sales Contacts
600 Harrison St., 5th Flr,
signed int to store a diameter for? It and I’m sure that was deliberate ob-
San Francisco, CA 94107
doesn’t make sense.” You will then no fuscation. Most developers seem to be
doubt start digging in that code piece, able to divide a program into reason- David Blaza
Publisher
finding numerous other bugs. able modules and implement these (415) 947-6929
So I daresay that any form of test modules intelligently, no matter the [email protected]
would have found that bug in a few process they follow. Bob Dumas
minutes, if it involved a good compiler It is enhancements that destroy Associate Publisher
or static analyzer. As I see it, the bug the programs. This was true when (516) 562-5742
[email protected]
was likely caused by any combination of new breath types were added to a
the following: medical ventilator, new measure- Advertising Coordination and
ments to optical inspection systems, Production
• A poor requirements specification.
Did the specification state how
or new protocols to telemetry sys-
tems. These changes are almost always
600 Community Drive,
Manhasset, NY 11030
Donna Ambrosino
thick logs that were allowed? If it made under time pressure and use as Production Director
did, was the product tested against much existing code as possible. The (516) 562-5115
that requirment? result is usually that pretty decent [email protected]
• Poor test tools or no test tools at all. modules grow to be untestable and
• Insufficient knowledge in embed-
ded programming. A qualified
unmaintainable. I have had to take
over far too much such legacy sys-
developed whatever the official process
may be.
guess is that the program was writ- tems, and it’s very hard to convince —The Heretic
ten by an unskilled programmer managers that it’s costing them more Software Department
who was using the default “int” than it’s worth. If TDD can stop this
type—a deadly sin in any embed- code rot and force needed refactoring, Editor’s note: James Grenning responds
ded programming. But in that case I hope every organization whose code at www.embedded.com/224200702.
the real culprit was poor coding I ever have to maintain will adopt it.
standards at the company, or no P.S. Kent Beck may have taken the, We welcome your feedback. Letters to the
coding standards at all. write a little code, test it, and extend it, editor may be edited. Send your comments to
method past any reasonable point, but Richard Nass at [email protected] or fill
—Lundin
out one of our feedback forms online, under
R&D Manager that is how real working programs are the article you wish to discuss.
!
of tests required to ensure the system clomatic complexity,” you can find arti-
has been adequately verified.
Is test driven development cles supporting this conclusion.
James: You are right; TDD practi- viable for embedded sys- Jack: Who tests the tests?
tioners do not generally measure these James: In part, the production code
things. There is nothing said in TDD
about these metrics. It certainly does
not prohibit them. You know, we have ! tems? It may be part of
the answer. Ganssle con-
tests the test code. Bob Martin wrote a
blog a few years ago describing how
TDD is like double entry accounting.
not really defined TDD yet, so here
goes. This is the TDD micro cycle:
!
around long enough to ever make it into TDD, but that’s OK. Let me start by say-
a bug-tracking system.
are managing dependen- ing that it is a misconception that there
I think TDD is only part of the an- cies, this is not hard. is no barrier to requirements changes,
swer. Reviews, inspections, and pair pro- and feature creep. For successful out-
gramming are orthogonal and comple- come, requirements have to be carefully
mentary to TDD. cution must also be kept short. managed.
There is another form of TDD, a To avoid the target bottleneck, I rec- In Agile projects there is usually a
more requirements-centric activity called ommend that TDD practitioners first single person that is responsible for driv-
Acceptance Test Driven Development run their unit tests in their development ing the development to a successful de-
(ATDD). In ATDD, the customer repre- system. If you are practicing the SOLID livery. Some refer to this as the customer
sentative defines tests that describe the design principles it is natural to manage or the product owner (PO). The product
features of the system. Each iteration, the the dependencies on the hardware and owner might be from marketing, prod-
team works to complete specific stories operating system. uct management, or systems engineer-
defined by the customer. A story is like a If there is a lengthy control process ing. She usually heads a team of skilled
use case, or a specific usage scenario. The being test driven, we need to take control people who know the product domain,
acceptance tests describe the definition of the clock. If we are managing depend- the market, the technology, and testing.
of done for the story. These acceptance encies, this is not hard. A time-driven She is responsible for making trade-offs.
tests are also automated. If the new and event eventually resolves to a function Team members advise her, of course.
all prior tests pass, the story is done. call. The test fixture can call the event To manage development, we create
That is an important a quality gate. processing code as well as some operat- and maintain something called the
Don’t get me wrong, I am a proponent ing system, or interrupt-based event product backlog. The backlog is the list
of reviews, but I think that TDD is supe- handler. If your code needs to ask some of all the features (we can think of) that
rior to inspections at preventing defects. time service what the current millisec- should go into the product. There is a
I did a case study on the Zune bug ond is, we can intercept those calls and strong preference to make the work visi-
that illustrates my point. This bug mimic any time-based scenario we like ble to the PO, over work that only engi-
caused the 30G Zune model to freeze on without any of the real delays slowing neers understand. It is mostly feature
New Year’s Eve 2008. My informal re- the test execution time. oriented, not engineering-task oriented,
search on the bug (www.renaissancesoft- With that said about unit tests, you focusing on value delivery. We prevent
ware.net/blog/archives/38) showed that might have the same issue when it comes surprises by taking three month engi-
most online code pundits who inspected to a more thorough integration, or sys- neering deliverables and splitting them
! encompass cross-functional
needs. While the product is
PCB Assembly
$50 in 3-Days
Advanced Assembly specializes in fast assembly for R&D prototypes, NPI, and low-
volume orders. We machine-place all SMT parts and carefully follow each board through
the entire process to deliver accurately assembled boards in three days or less.
aapcb.com/esd4
1.800.838.5650