]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/kernel/v2_0/doc/kernel.sgml
Merge branch 'master' of git+ssh://git.kernelconcepts.de/karo-tx-redboot
[karo-tx-redboot.git] / packages / kernel / v2_0 / doc / kernel.sgml
1 <!-- {{{ Banner                         -->
2
3 <!-- =============================================================== -->
4 <!--                                                                 -->
5 <!--     kernel.sgml                                                 -->
6 <!--                                                                 -->
7 <!--     eCos kernel documentation.                                  -->
8 <!--                                                                 -->
9 <!-- =============================================================== -->
10 <!-- ####COPYRIGHTBEGIN####                                          -->
11 <!--                                                                 -->
12 <!-- =============================================================== -->
13 <!-- Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.  -->
14 <!-- This material may be distributed only subject to the terms      -->
15 <!-- and conditions set forth in the Open Publication License, v1.0  -->
16 <!-- or later (the latest version is presently available at          -->
17 <!-- http://www.opencontent.org/openpub/)                            -->
18 <!-- Distribution of the work or derivative of the work in any       -->
19 <!-- standard (paper) book form is prohibited unless prior           -->
20 <!-- permission obtained from the copyright holder                   -->
21 <!-- =============================================================== -->
22 <!--                                                                 -->      
23 <!-- ####COPYRIGHTEND####                                            -->
24 <!-- =============================================================== -->
25 <!-- #####DESCRIPTIONBEGIN####                                       -->
26 <!--                                                                 -->
27 <!-- Author(s):    nickg, bartv, markg                               -->
28 <!-- Contributors: eCos team                                         -->
29 <!-- Date:        2002/02/13                                         -->
30 <!-- Version:     0.02                                               -->
31 <!--                                                                 -->
32 <!-- ####DESCRIPTIONEND####                                          -->
33 <!-- =============================================================== -->
34
35 <!-- }}} -->
36
37 <part id="kernel">
38   <title>The eCos Kernel</title>
39
40 <!-- {{{ Overview                       -->
41
42   <refentry id="kernel-overview">
43
44     <refmeta>
45     <refentrytitle>Kernel Overview</refentrytitle>
46     </refmeta>
47
48     <refnamediv>
49       <refname>Kernel</refname>
50       <refpurpose>Overview of the eCos Kernel</refpurpose>
51     </refnamediv>
52
53 <!-- {{{ Description                    -->
54
55     <refsect1 id="kernel-overview-description">
56       <title>Description</title>
57       <para>
58 The kernel is one of the key packages in all of eCos. It provides the
59 core functionality needed for developing multi-threaded applications:
60       </para>
61       <orderedlist>
62         <listitem><para>
63 The ability to create new threads in the system, either during startup
64 or when the system is already running.
65         </para></listitem>
66         <listitem><para>
67 Control over the various threads in the system, for example
68 manipulating their priorities.
69         </para></listitem>
70         <listitem><para>
71 A choice of schedulers, determining which thread should currently be
72 running. 
73         </para></listitem>
74         <listitem><para>
75 A range of synchronization primitives, allowing threads to interact
76 and share data safely.
77         </para></listitem>
78         <listitem><para>
79 Integration with the system's support for interrupts and exceptions.
80         </para></listitem>
81       </orderedlist>
82       <para>
83 In some other operating systems the kernel provides additional
84 functionality. For example the kernel may also provide memory
85 allocation functionality, and device drivers may be part of the kernel
86 as well. This is not the case for eCos. Memory allocation is handled
87 by a separate package. Similary each device driver will typically be a
88 separate package. Various packages are combined and configured using
89 the eCos configuration technology to meet the requirements of the
90 application.
91       </para>
92       <para>
93 The eCos kernel package is optional. It is possible to write
94 single-threaded applications which do not use any kernel
95 functionality, for example RedBoot. Typically such applications are
96 based around a central polling loop, continually checking all devices
97 and taking appropriate action when I/O occurs. A small amount of
98 calculation is possible every iteration, at the cost of an increased
99 delay between an I/O event occurring and the polling loop detecting
100 the event. When the requirements are straightforward it may well be
101 easier to develop the application using a polling loop, avoiding the
102 complexities of multiple threads and synchronization between threads.
103 As requirements get more complicated a multi-threaded solution becomes
104 more appropriate, requiring the use of the kernel. In fact some of the
105 more advanced packages in eCos, for example the TCP/IP stack, use
106 multi-threading internally. Therefore if the application uses any of
107 those packages then the kernel becomes a required package, not an
108 optional one.
109       </para>
110       <para>
111 The kernel functionality can be used in one of two ways. The kernel
112 provides its own C API, with functions like
113 <function>cyg_thread_create</function> and
114 <function>cyg_mutex_lock</function>. These can be called directly from
115 application code or from other packages. Alternatively there are a
116 number of packages which provide compatibility with existing API's,
117 for example POSIX threads or &micro;ITRON. These allow application
118 code to call standard functions such as
119 <function>pthread_create</function>, and those functions are
120 implemented using the basic functionality provided by the eCos kernel.
121 Using compatibility packages in an eCos application can make it much
122 easier to reuse code developed in other environments, and to share
123 code.
124       </para>
125       <para>
126 Although the different compatibility packages have similar
127 requirements on the underlying kernel, for example the ability to
128 create a new thread, there are differences in the exact semantics. For
129 example, strict &micro;ITRON compliance requires that kernel
130 timeslicing is disabled. This is achieved largely through the
131 configuration technology. The kernel provides a number of
132 configuration options that control the exact semantics that are
133 provided, and the various compatibility packages require particular
134 settings for those options. This has two important consequences.
135 First, it is not usually possible to have two different compatibility
136 packages in one eCos configuration because they will have conflicting
137 requirements on the underlying kernel. Second, the semantics of the
138 kernel's own API are only loosely defined because of the many
139 configuration options. For example <function>cyg_mutex_lock</function>
140 will always attempt to lock a mutex, but various configuration options
141 determine the behaviour when the mutex is already locked and there is
142 a possibility of priority inversion.
143       </para>
144       <para>
145 The optional nature of the kernel package presents some complications
146 for other code, especially device drivers. Wherever possible a device
147 driver should work whether or not the kernel is present. However there
148 are some parts of the system, especially those related to interrupt
149 handling, which should be implemented differently in multi-threaded
150 environments containing the eCos kernel and in single-threaded
151 environments without the kernel. To cope with both scenarios the
152 common HAL package provides a driver API, with functions such as
153 <function>cyg_drv_interrupt_attach</function>. When the kernel package
154 is present these driver API functions map directly on to the
155 equivalent kernel functions such as
156 <function>cyg_interrupt_attach</function>, using macros to avoid any
157 overheads. When the kernel is absent the common HAL package implements
158 the driver API directly, but this implementation is simpler than the
159 one in the kernel because it can assume a single-threaded environment. 
160       </para>
161     </refsect1>
162
163 <!-- }}} -->
164 <!-- {{{ Schedulers                     -->
165
166     <refsect1 id="kernel-overview-schedulers">
167       <title>Schedulers</title>
168       <para>
169 When a system involves multiple threads, a scheduler is needed to
170 determine which thread should currently be running. The eCos kernel
171 can be configured with one of two schedulers, the bitmap scheduler and
172 the multi-level queue (MLQ) scheduler. The bitmap scheduler is
173 somewhat more efficient, but has a number of limitations. Most systems
174 will instead use the MLQ scheduler. Other schedulers may be added in
175 the future, either as extensions to the kernel package or in separate
176 packages.
177       </para>
178       <para>
179 Both the bitmap and the MLQ scheduler use a simple numerical priority
180 to determine which thread should be running. The number of priority
181 levels is configurable via the option
182 <varname>CYGNUM_KERNEL_SCHED_PRIORITIES</varname>, but a typical
183 system will have up to 32 priority levels. Therefore thread priorities
184 will be in the range 0 to 31, with 0 being the highest priority and 31
185 the lowest. Usually only the system's idle thread will run at the
186 lowest priority. Thread priorities are absolute, so the kernel will
187 only run a lower-priority thread if all higher-priority threads are
188 currently blocked.
189       </para>
190       <para>
191 The bitmap scheduler only allows one thread per priority level, so if
192 the system is configured with 32 priority levels then it is limited to
193 only 32 threads &mdash; still enough for many applications. A simple
194 bitmap can be used to keep track of which threads are currently
195 runnable. Bitmaps can also be used to keep track of threads waiting on
196 a mutex or other synchronization primitive. Identifying the
197 highest-priority runnable or waiting thread involves a simple
198 operation on the bitmap, and an array index operation can then be used
199 to get hold of the thread data structure itself. This makes the
200 bitmap scheduler fast and totally deterministic.
201       </para>
202       <para>
203 The MLQ scheduler allows multiple threads to run at the same priority.
204 This means that there is no limit on the number of threads in the
205 system, other than the amount of memory available. However operations
206 such as finding the highest priority runnable thread are a little bit
207 more expensive than for the bitmap scheduler.
208       </para>
209       <para>
210 Optionally the MLQ scheduler supports timeslicing, where the scheduler
211 automatically switches from one runnable thread to another when some
212 number of clock ticks have occurred. Timeslicing only comes into play
213 when there are two runnable threads at the same priority and no higher
214 priority runnable threads. If timeslicing is disabled then a thread
215 will not be preempted by another thread of the same priority, and will
216 continue running until either it explicitly yields the processor or
217 until it blocks by, for example, waiting on a synchronization
218 primitive. The configuration options
219 <varname>CYGSEM_KERNEL_SCHED_TIMESLICE</varname> and
220 <varname>CYGNUM_KERNEL_SCHED_TIMESLICE_TICKS</varname> control
221 timeslicing. The bitmap scheduler does not provide timeslicing
222 support. It only allows one thread per priority level, so it is not
223 possible to preempt the current thread in favour of another one with
224 the same priority.
225       </para>
226       <para>
227 Another important configuration option that affects the MLQ scheduler
228 is <varname>CYGIMP_KERNEL_SCHED_SORTED_QUEUES</varname>. This
229 determines what happens when a thread blocks, for example by waiting
230 on a semaphore which has no pending events. The default behaviour of
231 the system is last-in-first-out queuing. For example if several
232 threads are waiting on a semaphore and an event is posted, the thread
233 that gets woken up is the last one that called
234 <function>cyg_semaphore_wait</function>. This allows for a simple and
235 fast implementation of both the queue and dequeue operations. However
236 if there are several queued threads with different priorities, it may
237 not be the highest priority one that gets woken up. In practice this
238 is rarely a problem: usually there will be at most one thread waiting
239 on a queue, or when there are several threads they will be of the same
240 priority. However if the application does require strict priority
241 queueing then the option
242 <varname>CYGIMP_KERNEL_SCHED_SORTED_QUEUES</varname> should be
243 enabled. There are disadvantages: more work is needed whenever a
244 thread is queued, and the scheduler needs to be locked for this
245 operation so the system's dispatch latency is worse. If the bitmap
246 scheduler is used then priority queueing is automatic and does not
247 involve any penalties.
248       </para>
249       <para>
250 Some kernel functionality is currently only supported with the MLQ
251 scheduler, not the bitmap scheduler. This includes support for SMP
252 systems, and protection against priority inversion using either mutex
253 priority ceilings or priority inheritance.
254       </para>
255     </refsect1>
256
257 <!-- }}} -->
258 <!-- {{{ Synch primitives               -->
259
260     <refsect1 id="kernel-overview-synch-primitives">
261       <title>Synchronization Primitives</title>
262       <para>
263 The eCos kernel provides a number of different synchronization
264 primitives: <link linkend="kernel-mutexes">mutexes</link>,
265 <link linkend="kernel-condition-variables">condition variables</link>,
266 <link linkend="kernel-semaphores">counting semaphores</link>,
267 <link linkend="kernel-mail-boxes">mail boxes</link> and
268 <link linkend="kernel-flags">event flags</link>.
269       </para>
270       <para>
271 Mutexes serve a very different purpose from the other primitives. A
272 mutex allows multiple threads to share a resource safely: a thread
273 locks a mutex, manipulates the shared resource, and then unlocks the
274 mutex again. The other primitives are used to communicate information
275 between threads, or alternatively from a DSR associated with an
276 interrupt handler to a thread.
277       </para>
278       <para>
279 When a thread that has locked a mutex needs to wait for some condition
280 to become true, it should use a condition variable. A condition
281 variable is essentially just a place for a thread to wait, and which
282 another thread, or DSR, can use to wake it up. When a thread waits on
283 a condition variable it releases the mutex before waiting, and when it
284 wakes up it reacquires it before proceeding. These operations are
285 atomic so that synchronization race conditions cannot be introduced.
286       </para>
287       <para>
288 A counting semaphore is used to indicate that a particular event has
289 occurred. A consumer thread can wait for this event to occur, and a
290 producer thread or a DSR can post the event. There is a count
291 associated with the semaphore so if the event occurs multiple times in
292 quick succession this information is not lost, and the appropriate
293 number of semaphore wait operations will succeed.
294       </para>
295       <para>
296 Mail boxes are also used to indicate that a particular event has
297 occurred, and allows for one item of data to be exchanged per event.
298 Typically this item of data would be a pointer to some data structure.
299 Because of the need to store this extra data, mail boxes have a
300 finite capacity. If a producer thread generates mail box events
301 faster than they can be consumed then, to avoid overflow, it will be
302 blocked until space is again available in the mail box. This means
303 that mail boxes usually cannot be used by a DSR to wake up a
304 thread. Instead mail boxes are typically only used between threads.
305       </para>
306       <para>
307 Event flags can be used to wait on some number of different events,
308 and to signal that one or several of these events have occurred. This
309 is achieved by associating bits in a bit mask with the different
310 events. Unlike a counting semaphore no attempt is made to keep track
311 of the number of events that have occurred, only the fact that an
312 event has occurred at least once. Unlike a mail box it is not
313 possible to send additional data with the event, but this does mean
314 that there is no possibility of an overflow and hence event flags can
315 be used between a DSR and a thread as well as between threads.
316       </para>
317       <para>
318 The eCos common HAL package provides its own device driver API which
319 contains some of the above synchronization primitives. These allow
320 the DSR for an interrupt handler to signal events to higher-level
321 code. If the configuration includes the eCos kernel package then
322 the driver API routines map directly on to the equivalent kernel
323 routines, allowing interrupt handlers to interact with threads. If the
324 kernel package is not included and the application consists of just a
325 single thread running in polled mode then the driver API is
326 implemented entirely within the common HAL, and with no need to worry
327 about multiple threads the implementation can obviously be rather
328 simpler. 
329       </para>
330     </refsect1>
331
332 <!-- }}} -->
333 <!-- {{{ Threads and interrupts         -->
334
335     <refsect1 id="kernel-overview-threads-interrupts">
336       <title>Threads and Interrupt Handling</title>
337       <para>
338 During normal operation the processor will be running one of the
339 threads in the system. This may be an application thread, a system
340 thread running inside say the TCP/IP stack, or the idle thread. From
341 time to time a hardware interrupt will occur, causing control to be
342 transferred briefly to an interrupt handler. When the interrupt has
343 been completed the system's scheduler will decide whether to return
344 control to the interrupted thread or to some other runnable thread.
345       </para>
346       <para>
347 Threads and interrupt handlers must be able to interact. If a thread
348 is waiting for some I/O operation to complete, the interrupt handler
349 associated with that I/O must be able to inform the thread that the
350 operation has completed. This can be achieved in a number of ways. One
351 very simple approach is for the interrupt handler to set a volatile
352 variable. A thread can then poll continuously until this flag is set,
353 possibly sleeping for a clock tick in between. Polling continuously
354 means that the cpu time is not available for other activities, which
355 may be acceptable for some but not all applications. Polling once
356 every clock tick imposes much less overhead, but means that the thread
357 may not detect that the I/O event has occurred until an entire clock
358 tick has elapsed. In typical systems this could be as long as 10
359 milliseconds. Such a delay might be acceptable for some applications,
360 but not all.
361       </para>
362       <para>
363 A better solution would be to use one of the synchronization
364 primitives. The interrupt handler could signal a condition variable,
365 post to a semaphore, or use one of the other primitives. The thread
366 would perform a wait operation on the same primitive. It would not
367 consume any cpu cycles until the I/O event had occurred, and when the
368 event does occur the thread can start running again immediately
369 (subject to any higher priority threads that might also be runnable).
370       </para>
371       <para>
372 Synchronization primitives constitute shared data, so care must be
373 taken to avoid problems with concurrent access. If the thread that was
374 interrupted was just performing some calculations then the interrupt
375 handler could manipulate the synchronization primitive quite safely.
376 However if the interrupted thread happened to be inside some kernel
377 call then there is a real possibility that some kernel data structure
378 will be corrupted. 
379       </para>
380       <para>
381 One way of avoiding such problems would be for the kernel functions to
382 disable interrupts when executing any critical region. On most
383 architectures this would be simple to implement and very fast, but it
384 would mean that interrupts would be disabled often and for quite a
385 long time. For some applications that might not matter, but many
386 embedded applications require that the interrupt handler run as soon
387 as possible after the hardware interrupt has occurred. If the kernel
388 relied on disabling interrupts then it would not be able to support
389 such applications.
390       </para>
391       <para>
392 Instead the kernel uses a two-level approach to interrupt handling.
393 Associated with every interrupt vector is an Interrupt Service Routine
394 or ISR, which will run as quickly as possible so that it can service
395 the hardware. However an ISR can make only a small number of kernel
396 calls, mostly related to the interrupt subsystem, and it cannot make
397 any call that would cause a thread to wake up. If an ISR detects that
398 an I/O operation has completed and hence that a thread should be woken
399 up, it can cause the associated Deferred Service Routine or DSR to
400 run. A DSR is allowed to make more kernel calls, for example it can
401 signal a condition variable or post to a semaphore.
402       </para>
403       <para>
404 Disabling interrupts prevents ISRs from running, but very few parts of
405 the system disable interrupts and then only for short periods of time.
406 The main reason for a thread to disable interrupts is to manipulate
407 some state that is shared with an ISR. For example if a thread needs
408 to add another buffer to a linked list of free buffers and the ISR may
409 remove a buffer from this list at any time, the thread would need to
410 disable interrupts for the few instructions needed to manipulate the
411 list. If the hardware raises an interrupt at this time, it remains
412 pending until interrupts are reenabled.
413       </para>
414       <para>
415 Analogous to interrupts being disabled or enabled, the kernel has a
416 scheduler lock. The various kernel functions such as
417 <function>cyg_mutex_lock</function> and
418 <function>cyg_semaphore_post</function> will claim the scheduler lock,
419 manipulate the kernel data structures, and then release the scheduler
420 lock. If an interrupt results in a DSR being requested and the
421 scheduler is currently locked, the DSR remains pending. When the
422 scheduler lock is released any pending DSRs will run. These may post
423 events to synchronization primitives, causing other higher priority
424 threads to be woken up.
425       </para>
426       <para>
427 For an example, consider the following scenario. The system has a high
428 priority thread A, responsible for processing some data coming from an
429 external device. This device will raise an interrupt when data is
430 available. There are two other threads B and C which spend their time
431 performing calculations and occasionally writing results to a display
432 of some sort. This display is a shared resource so a mutex is used to
433 control access.
434       </para>
435       <para>
436 At a particular moment in time thread A is likely to be blocked,
437 waiting on a semaphore or another synchronization primitive until data
438 is available. Thread B might be running performing some calculations,
439 and thread C is runnable waiting for its next timeslice. Interrupts
440 are enabled, and the scheduler is unlocked because none of the threads
441 are in the middle of a kernel operation. At this point the device
442 raises an interrupt. The hardware transfers control to a low-level
443 interrupt handler provided by eCos which works out exactly which
444 interrupt occurs, and then the corresponding ISR is run. This ISR
445 manipulates the hardware as appropriate, determines that there is now
446 data available, and wants to wake up thread A by posting to the
447 semaphore. However ISR's are not allowed to call
448 <function>cyg_semaphore_post</function> directly, so instead the ISR
449 requests that its associated DSR be run and returns. There are no more
450 interrupts to be processed, so the kernel next checks for DSR's. One
451 DSR is pending and the scheduler is currently unlocked, so the DSR can
452 run immediately and post the semaphore. This will have the effect of
453 making thread A runnable again, so the scheduler's data structures are
454 adjusted accordingly. When the DSR returns thread B is no longer the
455 highest priority runnable thread so it will be suspended, and instead
456 thread A gains control over the cpu.
457       </para>
458       <para>
459 In the above example no kernel data structures were being manipulated
460 at the exact moment that the interrupt happened. However that cannot
461 be assumed. Suppose that thread B had finished its current set of
462 calculations and wanted to write the results to the display. It would
463 claim the appropriate mutex and manipulate the display. Now suppose
464 that thread B was timesliced in favour of thread C, and that thread C
465 also finished its calculations and wanted to write the results to the
466 display. It would call <function>cyg_mutex_lock</function>. This
467 kernel call locks the scheduler, examines the current state of the
468 mutex, discovers that the mutex is already owned by another thread,
469 suspends the current thread, and switches control to another runnable
470 thread. Another interrupt happens in the middle of this
471 <function>cyg_mutex_lock</function> call, causing the ISR to run
472 immediately. The ISR decides that thread A should be woken up so it
473 requests that its DSR be run and returns back to the kernel. At this
474 point there is a pending DSR, but the scheduler is still locked by the
475 call to <function>cyg_mutex_lock</function> so the DSR cannot run
476 immediately. Instead the call to <function>cyg_mutex_lock</function>
477 is allowed to continue, which at some point involves unlocking the
478 scheduler. The pending DSR can now run, safely post the semaphore, and
479 thus wake up thread A.
480       </para>
481       <para>
482 If the ISR had called <function>cyg_semaphore_post</function> directly
483 rather than leaving it to a DSR, it is likely that there would have
484 been some sort of corruption of a kernel data structure. For example
485 the kernel might have completely lost track of one of the threads, and
486 that thread would never have run again. The two-level approach to
487 interrupt handling, ISR's and DSR's, prevents such problems with no
488 need to disable interrupts.
489       </para>
490     </refsect1>
491
492 <!-- }}} -->
493 <!-- {{{ Calling contexts               -->
494
495     <refsect1 id="kernel-overview-contexts">
496       <title>Calling Contexts</title>
497       <para>
498 eCos defines a number of contexts. Only certain calls are allowed from
499 inside each context, for example most operations on threads or
500 synchronization primitives are not allowed from ISR context. The
501 different contexts are initialization, thread, ISR and DSR.
502       </para>
503       <para>
504 When eCos starts up it goes through a number of phases, including
505 setting up the hardware and invoking C++ static constructors. During
506 this time interrupts are disabled and the scheduler is locked. When a
507 configuration includes the kernel package the final operation is a
508 call to <link
509 linkend="kernel-schedcontrol"><function>cyg_scheduler_start</function></link>.
510 At this point interrupts are enabled, the scheduler is unlocked, and
511 control is transferred to the highest priority runnable thread. If the
512 configuration also includes the C library package then usually the C
513 library startup package will have created a thread which will call the
514 application's <function>main</function> entry point.
515       </para>
516       <para>
517 Some application code can also run before the scheduler is started,
518 and this code runs in initialization context. If the application is
519 written partly or completely in C++ then the constructors for any
520 static objects will be run. Alternatively application code can define
521 a function <function>cyg_user_start</function> which gets called after
522 any C++ static constructors. This allows applications to be written
523 entirely in C.
524       </para>
525       <programlisting width=72>
526 void
527 cyg_user_start(void)
528 {
529     /* Perform application-specific initialization here */
530 }
531       </programlisting>
532       <para>
533 It is not necessary for applications to provide a
534 <function>cyg_user_start</function> function since the system will
535 provide a default implementation which does nothing.
536       </para>
537       <para>
538 Typical operations that are performed from inside static constructors
539 or <function>cyg_user_start</function> include creating threads,
540 synchronization primitives, setting up alarms, and registering
541 application-specific interrupt handlers. In fact for many applications
542 all such creation operations happen at this time, using statically
543 allocated data, avoiding any need for dynamic memory allocation or
544 other overheads.
545       </para>
546       <para>
547 Code running in initialization context runs with interrupts disabled
548 and the scheduler locked. It is not permitted to reenable interrupts
549 or unlock the scheduler because the system is not guaranteed to be in
550 a totally consistent state at this point. A consequence is that
551 initialization code cannot use synchronization primitives such as
552 <function>cyg_semaphore_wait</function> to wait for an external event.
553 It is permitted to lock and unlock a mutex: there are no other threads
554 running so it is guaranteed that the mutex is not yet locked, and
555 therefore the lock operation will never block; this is useful when
556 making library calls that may use a mutex internally.
557       </para>
558       <para>
559 At the end of the startup sequence the system will call
560 <function>cyg_scheduler_start</function> and the various threads will
561 start running. In thread context nearly all of the kernel functions
562 are available. There may be some restrictions on interrupt-related
563 operations, depending on the target hardware. For example the hardware
564 may require that interrupts be acknowledged in the ISR or DSR before
565 control returns to thread context, in which case
566 <filename>cyg_interrupt_acknowledge</filename> should not be called
567 by a thread.
568       </para>
569       <para>
570 At any time the processor may receive an external interrupt, causing
571 control to be transferred from the current thread. Typically a VSR
572 provided by eCos will run and determine exactly which interrupt
573 occurred. Then the VSR will switch to the appropriate ISR, which can
574 be provided by a HAL package, a device driver, or by the application.
575 During this time the system is running at ISR context, and most of the
576 kernel function calls are disallowed. This includes the various
577 synchronization primitives, so for example an ISR is not allowed to
578 post to a semaphore to indicate that an event has happened. Usually
579 the only operations that should be performed from inside an ISR are
580 ones related to the interrupt subsystem itself, for example masking an
581 interrupt or acknowledging that an interrupt has been processed. On
582 SMP systems it is also possible to use spinlocks from ISR context.
583       </para>
584       <para>
585 When an ISR returns it can request that the corresponding DSR be run
586 as soon as it is safe to do so, and that will run in DSR context. This
587 context is also used for running alarm functions, and threads can
588 switch temporarily to DSR context by locking the scheduler. Only
589 certain kernel functions can be called from DSR context, although more
590 than in ISR context. In particular it is possible to use any
591 synchronization primitives which cannot block.  These include
592 <function>cyg_semaphore_post</function>,
593 <filename>cyg_cond_signal</filename>,
594 <function>cyg_cond_broadcast</function>,
595 <function>cyg_flag_setbits</function>, and
596 <function>cyg_mbox_tryput</function>. It is not possible to use any
597 primitives that may block such as
598 <function>cyg_semaphore_wait</function>,
599 <function>cyg_mutex_lock</function>, or
600 <function>cyg_mbox_put</function>. Calling such functions from inside
601 a DSR may cause the system to hang.
602       </para>
603       <para>
604 The specific documentation for the various kernel functions gives more
605 details about valid contexts.
606       </para>
607     </refsect1>
608
609 <!-- }}} -->
610 <!-- {{{ Error handling                 -->
611
612     <refsect1 id="kernel-overview-errors">
613       <title>Error Handling and Assertions</title>
614       <para>
615 In many APIs each function is expected to perform some validation of
616 its parameters and possibly of the current state of the system. This
617 is supposed to ensure that each function is used correctly, and that
618 application code is not attempting to perform a semaphore operation on
619 a mutex or anything like that. If an error is detected then a suitable
620 error code is returned, for example the POSIX function
621 <function>pthread_mutex_lock</function> can return various error codes
622 including <literal>EINVAL</literal> and <literal>EDEADLK</literal>.
623 There are a number of problems with this approach, especially in the
624 context of deeply embedded systems:
625       </para>
626       <orderedlist>
627         <listitem><para>
628 Performing these checks inside the mutex lock and all the other
629 functions requires extra cpu cycles and adds significantly to the code
630 size. Even if the application is written correctly and only makes
631 system function calls with sensible arguments and under the right
632 conditions, these overheads still exist.
633         </para></listitem>
634         <listitem><para>
635 Returning an error code is only useful if the calling code detects
636 these error codes and takes appropriate action. In practice the
637 calling code will often ignore any errors because the programmer
638 <emphasis>&ldquo;knows&rdquo;</emphasis> that the function is being
639 used correctly. If the programmer is mistaken then an error condition
640 may be detected and reported, but the application continues running
641 anyway and is likely to fail some time later in mysterious ways.
642         </para></listitem>
643         <listitem><para>
644 If the calling code does always check for error codes, that adds yet
645 more cpu cycles and code size overhead. 
646         </para></listitem>
647         <listitem><para>
648 Usually there will be no way to recover from certain errors, so if the
649 application code detected an error such as <literal>EINVAL</literal>
650 then all it could do is abort the application somehow.
651         </para></listitem>
652       </orderedlist>
653       <para>
654 The approach taken within the eCos kernel is different. Functions such
655 as <function>cyg_mutex_lock</function> will not return an error code.
656 Instead they contain various assertions, which can be enabled or
657 disabled. During the development process assertions are normally left
658 enabled, and the various kernel functions will perform parameter
659 checks and other system consistency checks. If a problem is detected
660 then an assertion failure will be reported and the application will be
661 terminated. In a typical debug session a suitable breakpoint will have
662 been installed and the developer can now examine the state of the
663 system and work out exactly what is going on. Towards the end of the
664 development cycle assertions will be disabled by manipulating
665 configuration options within the eCos infrastructure package, and all
666 assertions will be eliminated at compile-time. The assumption is that
667 by this time the application code has been mostly debugged: the
668 initial version of the code might have tried to perform a semaphore
669 operation on a mutex, but any problems like that will have been fixed
670 some time ago. This approach has a number of advantages:
671       </para>
672       <orderedlist>
673         <listitem><para>
674 In the final application there will be no overheads for checking
675 parameters and other conditions. All that code will have been
676 eliminated at compile-time.
677         </para></listitem>
678         <listitem><para>
679 Because the final application will not suffer any overheads, it is
680 reasonable for the system to do more work during the development
681 process. In particular the various assertions can test for more error
682 conditions and more complicated errors. When an error is detected
683 it is possible to give a text message describing the error rather than
684 just return an error code.
685         </para></listitem>
686         <listitem><para>
687 There is no need for application programmers to handle error codes
688 returned by various kernel function calls. This simplifies the
689 application code.
690         </para></listitem>
691         <listitem><para>
692 If an error is detected then an assertion failure will be reported
693 immediately and the application will be halted. There is no
694 possibility of an error condition being ignored because application
695 code did not check for an error code.
696         </para></listitem>
697       </orderedlist>
698       <para>
699 Although none of the kernel functions return an error code, many of
700 them do return a status condition. For example the function
701 <function>cyg_semaphore_timed_wait</function> waits until either an
702 event has been posted to a semaphore, or until a certain number of
703 clock ticks have occurred. Usually the calling code will need to know
704 whether the wait operation succeeded or whether a timeout occurred.
705 <function>cyg_semaphore_timed_wait</function> returns a boolean: a
706 return value of zero or false indicates a timeout, a non-zero return
707 value indicates that the wait succeeded.
708       </para>
709       <para>
710 In conventional APIs one common error conditions is lack of memory.
711 For example the POSIX function <function>pthread_create</function>
712 usually has to allocate some memory dynamically for the thread stack
713 and other per-thread data. If the target hardware does not have enough
714 memory to meet all demands, or more commonly if the application
715 contains a memory leak, then there may not be enough memory available
716 and the function call would fail. The eCos kernel avoids such problems
717 by never performing any dynamic memory allocation. Instead it is the
718 responsibility of the application code to provide all the memory
719 required for kernel data structures and other needs. In the case of
720 <function>cyg_thread_create</function> this means a
721 <structname>cyg_thread</structname> data structure to hold the thread
722 details, and a <type>char</type> array for the thread stack.
723       </para>
724       <para>
725 In many applications this approach results in all data structures
726 being allocated statically rather than dynamically. This has several
727 advantages. If the application is in fact too large for the target
728 hardware's memory then there will be an error at link-time rather than
729 at run-time, making the problem much easier to diagnose. Static
730 allocation does not involve any of the usual overheads associated with
731 dynamic allocation, for example there is no need to keep track of the
732 various free blocks in the system, and it may be possible to eliminate
733 <function>malloc</function> from the system completely. Problems such
734 as fragmentation and memory leaks cannot occur if all data is
735 allocated statically. However, some applications are sufficiently
736 complicated that dynamic memory allocation is required, and the
737 various kernel functions do not distinguish between statically and
738 dynamically allocated memory. It still remains the responsibility of
739 the calling code to ensure that sufficient memory is available, and
740 passing null pointers to the kernel will result in assertions or
741 system failure.
742       </para>
743     </refsect1>
744
745 <!-- }}} -->
746
747   </refentry>
748
749 <!-- }}} -->
750 <!-- {{{ SMP                            -->
751
752   <refentry id="kernel-SMP">
753
754     <refmeta>
755     <refentrytitle>SMP Support</refentrytitle>
756     </refmeta>
757
758     <refnamediv>
759       <refname>SMP</refname>
760       <refpurpose>Support Symmetric Multiprocessing Systems</refpurpose>
761     </refnamediv>
762
763     <refsect1 id="kernel-smp-description">
764       <title>Description</title>
765       <para>
766 eCos contains support for limited Symmetric Multi-Processing (SMP).
767 This is only available on selected architectures and platforms.
768 The implementation has a number of restrictions on the kind of
769 hardware supported. These are described in <xref linkend="hal-smp-support">.
770     </para>
771
772     <para>
773 The following sections describe the changes that have been made to the
774 eCos kernel to support SMP operation.
775     </para>
776     </refsect1>
777
778     <refsect1 id="kernel-smp-startup">
779       <title>System Startup</title>
780       <para>
781 The system startup sequence needs to be somewhat different on an SMP
782 system, although this is largely transparent to application code. The
783 main startup takes place on only one CPU, called the primary CPU. All
784 other CPUs, the secondary CPUs, are either placed in suspended state
785 at reset, or are captured by the HAL and put into a spin as they start
786 up. The primary CPU is responsible for copying the DATA segment and
787 zeroing the BSS (if required), calling HAL variant and platform
788 initialization routines and invoking constructors. It then calls
789 <function>cyg_start</function> to enter the application. The
790 application may then create extra threads and other objects.
791       </para>
792       <para>
793 It is only when the application calls
794 <function>cyg_scheduler_start</function> that the secondary CPUs are
795 initialized. This routine scans the list of available secondary CPUs
796 and invokes <function>HAL_SMP_CPU_START</function> to start each
797 CPU. Finally it calls an internal function
798 <function>Cyg_Scheduler::start_cpu</function> to enter the scheduler
799 for the primary CPU.
800       </para>
801       <para>
802 Each secondary CPU starts in the HAL, where it completes any per-CPU
803 initialization before calling into the kernel at
804 <function>cyg_kernel_cpu_startup</function>. Here it claims the
805 scheduler lock and calls
806 <function>Cyg_Scheduler::start_cpu</function>.
807       </para>
808       <para>
809 <function>Cyg_Scheduler::start_cpu</function> is common to both the
810 primary and secondary CPUs. The first thing this code does is to
811 install an interrupt object for this CPU's inter-CPU interrupt. From
812 this point on the code is the same as for the single CPU case: an
813 initial thread is chosen and entered.
814       </para>
815       <para>
816 From this point on the CPUs are all equal, eCos makes no further
817 distinction between the primary and secondary CPUs. However, the
818 hardware may still distinguish between them as far as interrupt
819 delivery is concerned.
820       </para>
821     </refsect1>
822
823     <refsect1 id="kernel-smp-scheduling">
824       <title>Scheduling</title>
825       <para>
826 To function correctly an operating system kernel must protect its
827 vital data structures, such as the run queues, from concurrent
828 access. In a single CPU system the only concurrent activities to worry
829 about are asynchronous interrupts. The kernel can easily guard its
830 data structures against these by disabling interrupts. However, in a
831 multi-CPU system, this is inadequate since it does not block access by
832 other CPUs.
833       </para>
834       <para>
835 The eCos kernel protects its vital data structures using the scheduler
836 lock. In single CPU systems this is a simple counter that is
837 atomically incremented to acquire the lock and decremented to release
838 it. If the lock is decremented to zero then the scheduler may be
839 invoked to choose a different thread to run. Because interrupts may
840 continue to be serviced while the scheduler lock is claimed, ISRs are
841 not allowed to access kernel data structures, or call kernel routines
842 that can. Instead all such operations are deferred to an associated
843 DSR routine that is run during the lock release operation, when the
844 data structures are in a consistent state.
845       </para>
846       <para>
847 By choosing a kernel locking mechanism that does not rely on interrupt
848 manipulation to protect data structures, it is easier to convert eCos
849 to SMP than would otherwise be the case. The principal change needed to
850 make eCos SMP-safe is to convert the scheduler lock into a nestable
851 spin lock. This is done by adding a spinlock and a CPU id to the
852 original counter.
853       </para>
854       <para>
855 The algorithm for acquiring the scheduler lock is very simple. If the
856 scheduler lock's CPU id matches the current CPU then it can just increment
857 the counter and continue. If it does not match, the CPU must spin on
858 the spinlock, after which it may increment the counter and store its
859 own identity in the CPU id.
860       </para>
861       <para>
862 To release the lock, the counter is decremented. If it goes to zero
863 the CPU id value must be set to NONE and the spinlock cleared.
864       </para>
865       <para>
866 To protect these sequences against interrupts, they must be performed
867 with interrupts disabled. However, since these are very short code
868 sequences, they will not have an adverse effect on the interrupt
869 latency.
870       </para>
871       <para>
872 Beyond converting the scheduler lock, further preparing the kernel for
873 SMP is a relatively minor matter. The main changes are to convert
874 various scalar housekeeping variables into arrays indexed by CPU
875 id. These include the current thread pointer, the need_reschedule
876 flag and the timeslice counter.
877       </para>
878       <para>
879 At present only the Multi-Level Queue (MLQ) scheduler is capable of
880 supporting SMP configurations. The main change made to this scheduler
881 is to cope with having several threads in execution at the same
882 time. Running threads are marked with the CPU that they are executing on.
883 When scheduling a thread, the scheduler skips past any running threads
884 until it finds a thread that is pending. While not a constant-time
885 algorithm, as in the single CPU case, this is still deterministic,
886 since the worst case time is bounded by the number of CPUs in the
887 system.
888       </para>
889       <para>
890 A second change to the scheduler is in the code used to decide when
891 the scheduler should be called to choose a new thread. The scheduler
892 attempts to keep the <property>n</property> CPUs running the
893 <property>n</property> highest priority threads. Since an event or
894 interrupt on one CPU may require a reschedule on another CPU, there
895 must be a mechanism for deciding this. The algorithm currently
896 implemented is very simple. Given a thread that has just been awakened
897 (or had its priority changed), the scheduler scans the CPUs, starting
898 with the one it is currently running on, for a current thread that is
899 of lower priority than the new one. If one is found then a reschedule
900 interrupt is sent to that CPU and the scan continues, but now using
901 the current thread of the rescheduled CPU as the candidate thread. In
902 this way the new thread gets to run as quickly as possible, hopefully
903 on the current CPU, and the remaining CPUs will pick up the remaining
904 highest priority threads as a consequence of processing the reschedule
905 interrupt.
906       </para>
907       <para>
908 The final change to the scheduler is in the handling of
909 timeslicing. Only one CPU receives timer interrupts, although all CPUs
910 must handle timeslicing. To make this work, the CPU that receives the
911 timer interrupt decrements the timeslice counter for all CPUs, not
912 just its own. If the counter for a CPU reaches zero, then it sends a
913 timeslice interrupt to that CPU. On receiving the interrupt the
914 destination CPU enters the scheduler and looks for another thread at
915 the same priority to run. This is somewhat more efficient than
916 distributing clock ticks to all CPUs, since the interrupt is only
917 needed when a timeslice occurs.
918       </para>
919       <para>
920 All existing synchronization mechanisms work as before in an SMP
921 system. Additional synchronization mechanisms have been added to
922 provide explicit synchronization for SMP, in the form of
923 <link linkend="kernel-spinlocks">spinlocks</link>.
924       </para>
925     </refsect1>
926
927     <refsect1 id="kernel-smp-interrupts">
928       <title>SMP Interrupt Handling</title>
929       <para>
930 The main area where the SMP nature of a system requires special
931 attention is in device drivers and especially interrupt handling. It
932 is quite possible for the ISR, DSR and thread components of a device
933 driver to execute on different CPUs. For this reason it is much more
934 important that SMP-capable device drivers use the interrupt-related
935 functions correctly. Typically a device driver would use the driver
936 API rather than call the kernel directly, but it is unlikely that
937 anybody would attempt to use a multiprocessor system without the
938 kernel package.
939       </para>
940       <para>
941 Two new functions have been added to the Kernel API
942 to do <link linkend="kernel-interrupts-smp">interrupt
943 routing</link>: <function>cyg_interrupt_set_cpu</function> and
944 <function>cyg_interrupt_get_cpu</function>. Although not currently
945 supported, special values for the cpu argument may be used in future
946 to indicate that the interrupt is being routed dynamically or is
947 CPU-local. Once a vector has been routed to a new CPU, all other
948 interrupt masking and configuration operations are relative to that
949 CPU, where relevant.
950       </para>
951
952       <para>
953 There are more details of how interrupts should be handled in SMP
954 systems in <xref linkend="devapi-smp-support">.
955       </para>
956     </refsect1>
957
958   </refentry>
959
960 <!-- }}} -->
961
962 <!-- {{{ cyg_thread_create()            -->
963
964   <refentry id="kernel-thread-create">
965
966     <refmeta>
967     <refentrytitle>Thread creation</refentrytitle>
968     </refmeta>
969
970     <refnamediv>
971       <refname>cyg_thread_create</refname>
972       <refpurpose>Create a new thread</refpurpose>
973     </refnamediv>
974
975     <refsynopsisdiv>
976       <funcsynopsis>
977         <funcsynopsisinfo>
978 #include &lt;cyg/kernel/kapi.h&gt;    
979         </funcsynopsisinfo>
980         <funcprototype>
981           <funcdef>void <function>cyg_thread_create</function></funcdef>
982           <paramdef>cyg_addrword_t <parameter>sched_info</parameter></paramdef>
983           <paramdef>cyg_thread_entry_t* <parameter>entry</parameter></paramdef>
984           <paramdef>cyg_addrword_t <parameter>entry_data</parameter></paramdef>
985           <paramdef>char* <parameter>name</parameter></paramdef>
986           <paramdef>void* <parameter>stack_base</parameter></paramdef>
987           <paramdef>cyg_ucount32 <parameter>stack_size</parameter></paramdef>
988           <paramdef>cyg_handle_t* <parameter>handle</parameter></paramdef>
989           <paramdef>cyg_thread* <parameter>thread</parameter></paramdef>
990         </funcprototype>
991       </funcsynopsis>
992     </refsynopsisdiv>
993
994     <refsect1 id="kernel-thread-create-description"><title>Description</title>
995       <para>
996 The <function>cyg_thread_create</function> function allows application
997 code and eCos packages to create new threads. In many applications
998 this only happens during system initialization and all required data
999 is allocated statically.  However additional threads can be created at
1000 any time, if necessary. A newly created thread is always in suspended
1001 state and will not start running until it has been resumed via a call
1002 to <function>cyg_thread_resume</function>. Also, if threads are
1003 created during system initialization then they will not start running
1004 until the eCos scheduler has been started.
1005       </para>
1006       <para>
1007 The <parameter class="function">name</parameter> argument is used
1008 primarily for debugging purposes, making it easier to keep track of
1009 which <structname>cyg_thread</structname> structure is associated with
1010 which application-level thread. The kernel configuration option
1011 <varname>CYGVAR_KERNEL_THREADS_NAME</varname> controls whether or not
1012 this name is actually used.
1013       </para>
1014       <para>
1015 On creation each thread is assigned a unique handle, and this will be
1016 stored in the location pointed at by the <parameter
1017 class="function">handle</parameter> argument. Subsequent operations on
1018 this thread including the required
1019 <function>cyg_thread_resume</function> should use this handle to
1020 identify the thread.
1021       </para>
1022       <para>
1023 The kernel requires a small amount of space for each thread, in the
1024 form of a <structname>cyg_thread</structname> data structure, to hold
1025 information such as the current state of that thread. To avoid any
1026 need for dynamic memory allocation within the kernel this space has to
1027 be provided by higher-level code, typically in the form of a static
1028 variable. The <parameter class="function">thread</parameter> argument
1029 provides this space.
1030       </para>
1031     </refsect1>
1032
1033     <refsect1 id="kernel-thread-create-entry"><title>Thread Entry Point</title>
1034       <para>
1035 The entry point for a thread takes the form:
1036       </para>
1037       <programlisting width=72>
1038 void
1039 thread_entry_function(cyg_addrword_t data)
1040 {
1041     &hellip;
1042 }
1043       </programlisting>
1044       <para>
1045 The second argument to <function>cyg_thread_create</function> is a
1046 pointer to such a function. The third argument <parameter
1047 class="function">entry_data</parameter> is used to pass additional
1048 data to the function. Typically this takes the form of a pointer to
1049 some static data, or a small integer, or <literal>0</literal> if the
1050 thread does not require any additional data.
1051       </para>
1052       <para>
1053 If the thread entry function ever returns then this is equivalent to
1054 the thread calling <function>cyg_thread_exit</function>. Even though
1055 the thread will no longer run again, it remains registered with the
1056 scheduler. If the application needs to re-use the
1057 <structname>cyg_thread</structname> data structure then a call to
1058 <function>cyg_thread_delete</function> is required first.
1059       </para>
1060     </refsect1>
1061
1062     <refsect1 id="kernel-thread-create-priorities"><title>Thread Priorities</title>
1063       <para>
1064 The <parameter class="function">sched_info</parameter> argument
1065 provides additional information to the scheduler. The exact details
1066 depend on the scheduler being used. For the bitmap and mlqueue
1067 schedulers it is a small integer, typically in the range 0 to 31, with
1068 0 being the highest priority. The lowest priority is normally used
1069 only by the system's idle thread. The exact number of priorities is
1070 controlled by the kernel configuration option
1071 <varname>CYGNUM_KERNEL_SCHED_PRIORITIES</varname>. 
1072       </para>
1073       <para>
1074 It is the responsibility of the application developer to be aware of
1075 the various threads in the system, including those created by eCos
1076 packages, and to ensure that all threads run at suitable priorities.
1077 For threads created by other packages the documentation provided by
1078 those packages should indicate any requirements.
1079       </para>
1080       <para>
1081 The functions <function>cyg_thread_set_priority</function>,
1082 <function>cyg_thread_get_priority</function>, and
1083 <function>cyg_thread_get_current_priority</function> can be used to
1084 manipulate a thread's priority.
1085       </para>
1086     </refsect1>
1087
1088     <refsect1 id="kernel-thread-create-stack"><title>Stacks and Stack Sizes</title>
1089       <para>
1090 Each thread needs its own stack for local variables and to keep track
1091 of function calls and returns. Again it is expected that this stack is
1092 provided by the calling code, usually in the form of static data, so
1093 that the kernel does not need any dynamic memory allocation
1094 facilities. <function>cyg_thread_create</function> takes two arguments
1095 related to the stack, a pointer to the base of the stack and the total
1096 size of this stack. On many processors stacks actually descend from the
1097 top down, so the kernel will add the stack size to the base address to
1098 determine the starting location.
1099       </para>
1100       <para>
1101 The exact stack size requirements for any given thread depend on a
1102 number of factors. The most important is of course the code that will
1103 be executed in the context of this code: if this involves significant
1104 nesting of function calls, recursion, or large local arrays, then the
1105 stack size needs to be set to a suitably high value. There are some
1106 architectural issues, for example the number of cpu registers and the
1107 calling conventions will have some effect on stack usage. Also,
1108 depending on the configuration, it is possible that some other code
1109 such as interrupt handlers will occasionally run on the current
1110 thread's stack. This depends in part on configuration options such as
1111 <varname>CYGIMP_HAL_COMMON_INTERRUPTS_USE_INTERRUPT_STACK</varname>
1112 and <varname>CYGSEM_HAL_COMMON_INTERRUPTS_ALLOW_NESTING</varname>.
1113       </para>
1114       <para>
1115 Determining an application's actual stack size requirements is the
1116 responsibility of the application developer, since the kernel cannot
1117 know in advance what code a given thread will run. However, the system
1118 does provide some hints about reasonable stack sizes in the form of
1119 two constants: <varname>CYGNUM_HAL_STACK_SIZE_MINIMUM</varname> and
1120 <varname>CYGNUM_HAL_STACK_SIZE_TYPICAL</varname>. These are defined by
1121 the appropriate HAL package. The <varname>MINIMUM</varname> value is
1122 appropriate for a thread that just runs a single function and makes
1123 very simple system calls. Trying to create a thread with a smaller
1124 stack than this is illegal. The <varname>TYPICAL</varname> value is
1125 appropriate for applications where application calls are nested no
1126 more than half a dozen or so levels, and there are no large arrays on
1127 the stack.
1128       </para>
1129       <para>
1130 If the stack sizes are not estimated correctly and a stack overflow
1131 occurs, the probably result is some form of memory corruption. This
1132 can be very hard to track down. The kernel does contain some code to
1133 help detect stack overflows, controlled by the configuration option
1134 <varname>CYGFUN_KERNEL_THREADS_STACK_CHECKING</varname>: a small
1135 amount of space is reserved at the stack limit and filled with a
1136 special signature: every time a thread context switch occurs this
1137 signature is checked, and if invalid that is a good indication (but
1138 not absolute proof) that a stack overflow has occurred. This form of
1139 stack checking is enabled by default when the system is built with
1140 debugging enabled. A related configuration option is
1141 <varname>CYGFUN_KERNEL_THREADS_STACK_MEASUREMENT</varname>: enabling
1142 this option means that a thread can call the function
1143 <function>cyg_thread_measure_stack_usage</function> to find out the
1144 maximum stack usage to date. Note that this is not necessarily the
1145 true maximum because, for example, it is possible that in the current
1146 run no interrupt occurred at the worst possible moment.
1147       </para>
1148     </refsect1>
1149
1150     <refsect1 id="kernel-thread-create-context"><title>Valid contexts</title>
1151       <para>
1152 <function>cyg_thread_create</function> may be called during
1153 initialization and from within thread context. It may not be called
1154 from inside a DSR.
1155       </para>
1156     </refsect1>
1157
1158     <refsect1 id="kernel-thread-create-example"><title>Example</title>
1159       <para>
1160 A simple example of thread creation is shown below. This involves
1161 creating five threads, one producer and four consumers or workers. The
1162 threads are created in the system's
1163 <function>cyg_user_start</function>: depending on the configuration it
1164 might be more appropriate to do this elsewhere, for example inside
1165 <function>main</function>.
1166       </para>
1167       <programlisting width=72>
1168 #include &lt;cyg/hal/hal_arch.h&gt;
1169 #include &lt;cyg/kernel/kapi.h&gt;
1170
1171 // These numbers depend entirely on your application
1172 #define NUMBER_OF_WORKERS    4
1173 #define PRODUCER_PRIORITY   10
1174 #define WORKER_PRIORITY     11
1175 #define PRODUCER_STACKSIZE  CYGNUM_HAL_STACK_SIZE_TYPICAL
1176 #define WORKER_STACKSIZE    (CYGNUM_HAL_STACK_SIZE_MINIMUM + 1024)
1177
1178 static unsigned char producer_stack[PRODUCER_STACKSIZE];
1179 static unsigned char worker_stacks[NUMBER_OF_WORKERS][WORKER_STACKSIZE];
1180 static cyg_handle_t producer_handle, worker_handles[NUMBER_OF_WORKERS];
1181 static cyg_thread   producer_thread, worker_threads[NUMBER_OF_WORKERS];
1182
1183 static void
1184 producer(cyg_addrword_t data)
1185 {
1186     &hellip;
1187 }
1188
1189 static void
1190 worker(cyg_addrword_t data)
1191 {
1192     &hellip;
1193 }
1194
1195 void
1196 cyg_user_start(void)
1197 {
1198     int i;
1199
1200     cyg_thread_create(PRODUCER_PRIORITY, &amp;producer, 0, "producer",
1201                       producer_stack, PRODUCER_STACKSIZE,
1202                       &amp;producer_handle, &amp;producer_thread);
1203     cyg_thread_resume(producer_handle);
1204     for (i = 0; i < NUMBER_OF_WORKERS; i++) {
1205         cyg_thread_create(WORKER_PRIORITY, &amp;worker, i, "worker",
1206                           worker_stacks[i], WORKER_STACKSIZE,
1207                           &amp;(worker_handles[i]), &amp;(worker_threads[i]));
1208         cyg_thread_resume(worker_handles[i]);
1209     }
1210 }
1211       </programlisting>
1212     </refsect1>
1213
1214
1215     <refsect1 id="kernel-thread-create-cxx"><title>Thread Entry Points and C++</title>
1216       <para>
1217 For code written in C++ the thread entry function must be either a
1218 static member function of a class or an ordinary function outside any
1219 class. It cannot be a normal member function of a class because such
1220 member functions take an implicit additional argument
1221 <varname>this</varname>, and the kernel has no way of knowing what
1222 value to use for this argument. One way around this problem is to make
1223 use of a special static member function, for example:
1224       </para>
1225       <programlisting width=72>
1226 class fred {
1227   public:
1228     void thread_function();
1229     static void static_thread_aux(cyg_addrword_t);
1230 };
1231
1232 void
1233 fred::static_thread_aux(cyg_addrword_t objptr)
1234 {
1235     fred* object = static_cast&lt;fred*&gt;(objptr);
1236     object-&gt;thread_function();
1237 }
1238
1239 static fred instance;
1240
1241 extern "C" void
1242 cyg_start( void )
1243 {
1244     &hellip;
1245     cyg_thread_create( &hellip;,
1246                       &amp;fred::static_thread_aux,
1247                       reinterpret_cast&lt;cyg_addrword_t&gt;(&amp;instance),
1248                       &hellip;);
1249     &hellip;
1250 }
1251       </programlisting>
1252       <para>
1253 Effectively this uses the <parameter
1254 class="function">entry_data</parameter> argument to
1255 <function>cyg_thread_create</function> to hold the
1256 <varname>this</varname> pointer. Unfortunately this approach does
1257 require the use of some C++ casts, so some of the type safety that can
1258 be achieved when programming in C++ is lost.
1259       </para>
1260     </refsect1>
1261
1262   </refentry>
1263
1264 <!-- }}} -->
1265 <!-- {{{ Thread info                    -->
1266
1267   <refentry id="kernel-thread-info">
1268
1269     <refmeta>
1270     <refentrytitle>Thread information</refentrytitle>
1271     </refmeta>
1272
1273     <refnamediv>
1274       <refname>cyg_thread_self</refname>
1275       <refname>cyg_thread_idle_thread</refname>
1276       <refname>cyg_thread_get_stack_base</refname>
1277       <refname>cyg_thread_get_stack_size</refname>
1278       <refname>cyg_thread_measure_stack_usage</refname>
1279       <refname>cyg_thread_get_next</refname>
1280       <refname>cyg_thread_get_info</refname>
1281       <refname>cyg_thread_get_id</refname>
1282       <refname>cyg_thread_find</refname>
1283       <refpurpose>Get basic thread information</refpurpose>
1284     </refnamediv>
1285
1286     <refsynopsisdiv>
1287       <funcsynopsis>
1288         <funcsynopsisinfo>
1289 #include &lt;cyg/kernel/kapi.h&gt;    
1290         </funcsynopsisinfo>
1291         <funcprototype>
1292           <funcdef>cyg_handle_t <function>cyg_thread_self</function></funcdef>
1293           <void>
1294         </funcprototype>
1295         <funcprototype>
1296           <funcdef>cyg_handle_t <function>cyg_thread_idle_thread</function></funcdef>
1297           <void>
1298         </funcprototype>
1299         <funcprototype>
1300           <funcdef>cyg_addrword_t <function>cyg_thread_get_stack_base</function></funcdef>
1301           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1302         </funcprototype>
1303         <funcprototype>
1304           <funcdef>cyg_uint32 <function>cyg_thread_get_stack_size</function></funcdef>
1305           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1306         </funcprototype>
1307         <funcprototype>
1308           <funcdef>cyg_uint32 <function>cyg_thread_measure_stack_usage</function></funcdef>
1309           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1310         </funcprototype>        
1311         <funcprototype>
1312           <funcdef>cyg_bool <function>cyg_thread_get_next</function></funcdef>
1313           <paramdef>cyg_handle_t *<parameter>thread</parameter></paramdef>
1314           <paramdef>cyg_uint16 *<parameter>id</parameter></paramdef>
1315         </funcprototype>        
1316         <funcprototype>
1317           <funcdef>cyg_bool <function>cyg_thread_get_info</function></funcdef>
1318           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1319           <paramdef>cyg_uint16 <parameter>id</parameter></paramdef>
1320           <paramdef>cyg_thread_info *<parameter>info</parameter></paramdef>
1321         </funcprototype>        
1322         <funcprototype>
1323           <funcdef>cyg_uint16 <function>cyg_thread_get_id</function></funcdef>
1324           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1325         </funcprototype>        
1326         <funcprototype>
1327           <funcdef>cyg_handle_t <function>cyg_thread_find</function></funcdef>
1328           <paramdef>cyg_uint16 <parameter>id</parameter></paramdef>
1329         </funcprototype>        
1330       </funcsynopsis>
1331     </refsynopsisdiv>
1332
1333     <refsect1 id="kernel-thread-info-description"><title>Description</title>
1334       <para>
1335 These functions can be used to obtain some basic information about
1336 various threads in the system. Typically they serve little or no
1337 purpose in real applications, but they can be useful during debugging.
1338       </para>
1339       <para>
1340 <function>cyg_thread_self</function> returns a handle corresponding
1341 to the current thread. It will be the same as the value filled in by
1342 <function>cyg_thread_create</function> when the current thread was
1343 created. This handle can then be passed to other functions such as
1344 <function>cyg_thread_get_priority</function>.
1345       </para>
1346       <para>
1347 <function>cyg_thread_idle_thread</function> returns the handle
1348 corresponding to the idle thread. This thread is created automatically
1349 by the kernel, so application-code has no other way of getting hold of
1350 this information.
1351       </para>
1352       <para>
1353 <function>cyg_thread_get_stack_base</function> and
1354 <function>cyg_thread_get_stack_size</function> return information
1355 about a specific thread's stack. The values returned will match the
1356 values passed to <function>cyg_thread_create</function> when this
1357 thread was created.
1358       </para>
1359       <para>
1360 <function>cyg_thread_measure_stack_usage</function> is only available
1361 if the configuration option
1362 <varname>CYGFUN_KERNEL_THREADS_STACK_MEASUREMENT</varname> is enabled.
1363 The return value is the maximum number of bytes of stack space used so
1364 far by the specified thread. Note that this should not be considered a
1365 true upper bound, for example it is possible that in the current test
1366 run the specified thread has not yet been interrupted at the deepest
1367 point in the function call graph. Never the less the value returned
1368 can give some useful indication of the thread's stack requirements.
1369       </para>
1370       <para>
1371 <function>cyg_thread_get_next</function> is used to enumerate all the
1372 current threads in the system. It should be called initially with the
1373 locations pointed to by <parameter>thread</parameter> and
1374 <parameter>id</parameter> set to zero. On return these will be set to
1375 the handle and ID of the first thread. On subsequent calls, these
1376 parameters should be left set to the values returned by the previous
1377 call.  The handle and ID of the next thread in the system will be
1378 installed each time, until a <literal>false</literal> return value
1379 indicates the end of the list.
1380       </para>
1381       <para>
1382 <function>cyg_thread_get_info</function> fills in the
1383 <type>cyg_thread_info</type> structure with information about the
1384 thread described by the <parameter>thread</parameter> and
1385 <parameter>id</parameter> arguments. The information returned includes
1386 the thread's handle and id, its state and name, priorities and stack
1387 parameters. If the thread does not exist the function returns
1388 <literal>false</literal>.
1389     </para>
1390     <para>
1391 The <type>cyg_thread_info</type> structure is defined as follows by
1392 &lt;<filename class=headerfile>cyg/kernel/kapi.h</filename>&gt;, but may
1393 be extended in future with additional members, and so its size should
1394 not be relied upon:
1395 <programlisting>
1396 typedef struct
1397 {
1398     <type>cyg_handle_t</type>        <structfield>handle</structfield>;
1399     <type>cyg_uint16</type>          <structfield>id</structfield>;
1400     <type>cyg_uint32</type>          <structfield>state</structfield>;
1401     <type>char</type>                <structfield>*name</structfield>;
1402     <type>cyg_priority_t</type>      <structfield>set_pri</structfield>;
1403     <type>cyg_priority_t</type>      <structfield>cur_pri</structfield>;
1404     <type>cyg_addrword_t</type>      <structfield>stack_base</structfield>;
1405     <type>cyg_uint32</type>          <structfield>stack_size</structfield>;
1406     <type>cyg_uint32</type>          <structfield>stack_used</structfield>;
1407 } cyg_thread_info;
1408 </programlisting>
1409     </para>
1410     <para>
1411 <function>cyg_thread_get_id</function> returns the unique thread ID for
1412 the thread identified by <parameter>thread</parameter>.
1413     </para>
1414     <para>
1415 <function>cyg_thread_find</function> returns a handle for the thread
1416 whose ID is <parameter>id</parameter>. If no such thread exists, a
1417 zero handle is returned.
1418     </para>
1419     </refsect1>
1420
1421     <refsect1 id="kernel-thread-info-context"><title>Valid contexts</title>
1422       <para>
1423 <function>cyg_thread_self</function> may only be called from thread
1424 context. <function>cyg_thread_idle_thread</function> may be called
1425 from thread or DSR context, but only after the system has been
1426 initialized. <function>cyg_thread_get_stack_base</function>,
1427 <function>cyg_thread_get_stack_size</function> and
1428 <function>cyg_thread_measure_stack_usage</function> may be called
1429 any time after the specified thread has been created, but measuring
1430 stack usage involves looping over at least part of the thread's stack
1431 so this should normally only be done from thread context.
1432 <function>cyg_thread_get_id</function> may be called from any context
1433 as long as the caller can guarantee that the supplied thread handle
1434 remains valid.
1435       </para>
1436     </refsect1>
1437
1438     <refsect1 id="kernel-thread-info-examples"><title>Examples</title>
1439       <para>
1440 A simple example of the use of the
1441 <function>cyg_thread_get_next</function> and
1442 <function>cyg_thread_get_info</function> follows:      
1443       </para>
1444       <programlisting width=72>
1445
1446 #include &lt;cyg/kernel/kapi.h&gt;
1447 #include &lt;stdio.h&gt;
1448
1449 void show_threads(void)
1450 {
1451     cyg_handle_t thread = 0;
1452     cyg_uint16 id = 0;
1453
1454     while( cyg_thread_get_next( &amp;thread, &amp;id ) )
1455     {
1456         cyg_thread_info info;
1457
1458         if( !cyg_thread_get_info( thread, id, &amp;info ) )
1459             break;
1460
1461         printf("ID: %04x name: %10s pri: %d\n",
1462                 info.id, info.name?info.name:"----", info.set_pri );
1463     }
1464 }
1465
1466       </programlisting>
1467     </refsect1>
1468
1469   </refentry>
1470
1471 <!-- }}} -->
1472 <!-- {{{ Thread control                 -->
1473
1474   <refentry id="kernel-thread-control">
1475
1476     <refmeta>
1477     <refentrytitle>Thread control</refentrytitle>
1478     </refmeta>
1479
1480     <refnamediv>
1481       <refname>cyg_thread_yield</refname>
1482       <refname>cyg_thread_delay</refname>
1483       <refname>cyg_thread_suspend</refname>
1484       <refname>cyg_thread_resume</refname>
1485       <refname>cyg_thread_release</refname>
1486       <refpurpose>Control whether or not a thread is running</refpurpose>
1487     </refnamediv>
1488
1489     <refsynopsisdiv>
1490       <funcsynopsis>
1491         <funcsynopsisinfo>
1492 #include &lt;cyg/kernel/kapi.h&gt;
1493         </funcsynopsisinfo>
1494         <funcprototype>
1495           <funcdef>void <function>cyg_thread_yield</function></funcdef>
1496           <void>
1497         </funcprototype>
1498         <funcprototype>
1499           <funcdef>void <function>cyg_thread_delay</function></funcdef>
1500           <paramdef>cyg_tick_count_t <parameter>delay</parameter></paramdef>
1501         </funcprototype>
1502         <funcprototype>
1503            <funcdef>void <function>cyg_thread_suspend</function></funcdef>
1504            <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1505         </funcprototype>
1506         <funcprototype>
1507            <funcdef>void <function>cyg_thread_resume</function></funcdef>
1508            <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1509         </funcprototype>
1510         <funcprototype>
1511            <funcdef>void <function>cyg_thread_release</function></funcdef>
1512            <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1513         </funcprototype>
1514       </funcsynopsis>
1515     </refsynopsisdiv>
1516
1517     <refsect1><title id="kernel-thread-control-description">Description</title>
1518       <para>
1519 These functions provide some control over whether or not a particular
1520 thread can run. Apart from the required use of
1521 <function>cyg_thread_resume</function> to start a newly-created
1522 thread, application code should normally use proper synchronization
1523 primitives such as condition variables or mail boxes.
1524       </para>
1525     </refsect1>
1526
1527     <refsect1><title id="kernel-thread-control-yield">Yield</title>
1528       <para>
1529 <function>cyg_thread_yield</function> allows a thread to relinquish
1530 control of the processor to some other runnable thread which has the
1531 same priority. This can have no effect on any higher-priority thread
1532 since, if such a thread were runnable, the current thread would have
1533 been preempted in its favour. Similarly it can have no effect on any
1534 lower-priority thread because the current thread will always be run in
1535 preference to those. As a consequence this function is only useful
1536 in configurations with a scheduler that allows multiple threads to run
1537 at the same priority, for example the mlqueue scheduler. If instead
1538 the bitmap scheduler was being used then
1539 <function>cyg_thread_yield()</function> would serve no purpose.
1540       </para>
1541       <para>
1542 Even if a suitable scheduler such as the mlqueue scheduler has been
1543 configured, <function>cyg_thread_yield</function> will still rarely
1544 prove useful: instead timeslicing will be used to ensure that all
1545 threads of a given priority get a fair slice of the available
1546 processor time. However it is possible to disable timeslicing via the
1547 configuration option <varname>CYGSEM_KERNEL_SCHED_TIMESLICE</varname>,
1548 in which case <function>cyg_thread_yield</function> can be used to
1549 implement a form of cooperative multitasking.
1550       </para>
1551     </refsect1>
1552
1553     <refsect1><title id="kernel-thread-control-delay">Delay</title>
1554       <para>
1555 <function>cyg_thread_delay</function> allows a thread to suspend until
1556 the specified number of clock ticks have occurred. For example, if a
1557 value of 1 is used and the system clock runs at a frequency of 100Hz
1558 then the thread will sleep for up to 10 milliseconds. This
1559 functionality depends on the presence of a real-time system clock, as
1560 controlled by the configuration option
1561 <varname>CYGVAR_KERNEL_COUNTERS_CLOCK</varname>.
1562       </para>
1563       <para>
1564 If the application requires delays measured in milliseconds or similar
1565 units rather than in clock ticks, some calculations are needed to
1566 convert between these units as described in <xref
1567 linkend="kernel-clocks">. Usually these calculations can be done by
1568 the application developer, or at compile-time. Performing such
1569 calculations prior to every call to
1570 <function>cyg_thread_delay</function> adds unnecessary overhead to the
1571 system. 
1572       </para>
1573     </refsect1>
1574
1575     <refsect1><title id="kernel-thread-control-suspend">Suspend and Resume</title>
1576       <para>
1577 Associated with each thread is a suspend counter. When a thread is
1578 first created this counter is initialized to 1.
1579 <function>cyg_thread_suspend</function> can be used to increment the
1580 suspend counter, and <function>cyg_thread_resume</function> decrements
1581 it. The scheduler will never run a thread with a non-zero suspend
1582 counter. Therefore a newly created thread will not run until it has
1583 been resumed.
1584       </para>
1585       <para>
1586 An occasional problem with the use of suspend and resume functionality
1587 is that a thread gets suspended more times than it is resumed and
1588 hence never becomes runnable again. This can lead to very confusing
1589 behaviour. To help with debugging such problems the kernel provides a
1590 configuration option
1591 <varname>CYGNUM_KERNEL_MAX_SUSPEND_COUNT_ASSERT</varname> which
1592 imposes an upper bound on the number of suspend calls without matching
1593 resumes, with a reasonable default value. This functionality depends
1594 on infrastructure assertions being enabled.
1595       </para>
1596     </refsect1>
1597
1598     <refsect1><title id="kernel-thread-control-release">Releasing a Blocked Thread</title>
1599       <para>
1600 When a thread is blocked on a synchronization primitive such as a
1601 semaphore or a mutex, or when it is waiting for an alarm to trigger,
1602 it can be forcibly woken up using
1603 <function>cyg_thread_release</function>. Typically this will call the
1604 affected synchronization primitive to return false, indicating that
1605 the operation was not completed successfully. This function has to be
1606 used with great care, and in particular it should only be used on
1607 threads that have been designed appropriately and check all return
1608 codes. If instead it were to be used on, say, an arbitrary thread that
1609 is attempting to claim a mutex then that thread might not bother to
1610 check the result of the mutex lock operation - usually there would be
1611 no reason to do so. Therefore the thread will now continue running in
1612 the false belief that it has successfully claimed a mutex lock, and
1613 the resulting behaviour is undefined. If the system has been built
1614 with assertions enabled then it is possible that an assertion will
1615 trigger when the thread tries to release the mutex it does not
1616 actually own.
1617       </para>
1618       <para>
1619 The main use of <function>cyg_thread_release</function> is in the
1620 POSIX compatibility layer, where it is used in the implementation of
1621 per-thread signals and cancellation handlers.
1622       </para>
1623     </refsect1>
1624
1625     <refsect1 id="kernel-thread-control-context"><title>Valid contexts</title>
1626       <para>
1627 <function>cyg_thread_yield</function> can only be called from thread
1628 context, A DSR must always run to completion and cannot yield the
1629 processor to some thread. <function>cyg_thread_suspend</function>,
1630 <function>cyg_thread_resume</function>, and
1631 <function>cyg_thread_release</function> may be called from thread or
1632 DSR context. 
1633       </para>
1634     </refsect1>
1635
1636   </refentry>
1637
1638 <!-- }}} -->
1639 <!-- {{{ Thread termination             -->
1640
1641   <refentry id="kernel-thread-termination">
1642
1643     <refmeta>
1644     <refentrytitle>Thread termination</refentrytitle>
1645     </refmeta>
1646
1647     <refnamediv>
1648       <refname>cyg_thread_exit</refname>
1649       <refname>cyg_thread_kill</refname>
1650       <refname>cyg_thread_delete</refname>
1651       <refpurpose>Allow threads to terminate</refpurpose>
1652     </refnamediv>
1653
1654     <refsynopsisdiv>
1655       <funcsynopsis>
1656         <funcsynopsisinfo>
1657 #include &lt;cyg/kernel/kapi.h&gt;
1658         </funcsynopsisinfo>
1659         <funcprototype>
1660           <funcdef>void <function>cyg_thread_exit</function></funcdef>
1661           <void>
1662         </funcprototype>
1663         <funcprototype>
1664           <funcdef>void <function>cyg_thread_kill</function></funcdef>
1665           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1666         </funcprototype>
1667         <funcprototype>
1668           <funcdef>cyg_bool_t <function>cyg_thread_delete</function></funcdef>
1669           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1670         </funcprototype>
1671       </funcsynopsis>
1672     </refsynopsisdiv>
1673
1674     <refsect1><title id="kernel-thread-termination-description">Description</title>
1675       <para>
1676 In many embedded systems the various threads are allocated statically,
1677 created during initialization, and never need to terminate. This
1678 avoids any need for dynamic memory allocation or other resource
1679 management facilities. However if a given application does have a
1680 requirement that some threads be created dynamically, must terminate,
1681 and their resources such as the stack be reclaimed, then the kernel
1682 provides the functions <function>cyg_thread_exit</function>,
1683 <function>cyg_thread_kill</function>, and
1684 <function>cyg_thread_delete</function>.
1685       </para>
1686       <para>
1687 <function>cyg_thread_exit</function> allows a thread to terminate
1688 itself, thus ensuring that it will not be run again by the scheduler.
1689 However the <structname>cyg_thread</structname> data structure passed
1690 to <function>cyg_thread_create</function> remains in use, and the
1691 handle returned by <function>cyg_thread_create</function> remains
1692 valid. This allows other threads to perform certain operations on the
1693 terminated thread, for example to determine its stack usage via
1694 <function>cyg_thread_measure_stack_usage</function>. When the handle
1695 and <structname>cyg_thread</structname> structure are no longer
1696 required, <function>cyg_thread_delete</function> should be called to
1697 release these resources. If the stack was dynamically allocated then
1698 this should not be freed until after the call to
1699 <function>cyg_thread_delete</function>.
1700       </para>
1701       <para>
1702 Alternatively, one thread may use <function>cyg_thread_kill</function>
1703 on another This has much the same effect as the affected thread
1704 calling <function>cyg_thread_exit</function>. However killing a thread
1705 is generally rather dangerous because no attempt is made to unlock any
1706 synchronization primitives currently owned by that thread or release
1707 any other resources that thread may have claimed. Therefore use of
1708 this function should be avoided, and
1709 <function>cyg_thread_exit</function> is preferred.
1710 <function>cyg_thread_kill</function> cannot be used by a thread to
1711 kill itself.
1712       </para>
1713       <para>
1714 <function>cyg_thread_delete</function> should be used on a thread
1715 after it has exited and is no longer required. After this call the
1716 thread handle is no longer valid, and both the
1717 <structname>cyg_thread</structname> structure and the thread stack can
1718 be re-used or freed. If <function>cyg_thread_delete</function> is
1719 invoked on a thread that is still running then there is an implicit
1720 call to <function>cyg_thread_kill</function>. This function returns
1721 <literal>true</literal> if the delete was successful, and
1722 <literal>false</literal> if the delete did not happen. The delete
1723 may not happen for example if the thread being destroyed is a lower
1724 priority thread than the running thread, and will thus not wake up
1725 in order to exit until it is rescheduled.
1726       </para>
1727     </refsect1>
1728
1729     <refsect1 id="kernel-thread-termination-context"><title>Valid contexts</title>
1730       <para>
1731 <function>cyg_thread_exit</function>,
1732 <function>cyg_thread_kill</function> and
1733 <function>cyg_thread_delete</function> can only be called from thread
1734 context. 
1735       </para>
1736     </refsect1>
1737
1738   </refentry>
1739
1740 <!-- }}} -->
1741 <!-- {{{ Thread priorities              -->
1742
1743   <refentry id="kernel-thread-priorities">
1744
1745     <refmeta>
1746     <refentrytitle>Thread priorities</refentrytitle>
1747     </refmeta>
1748
1749     <refnamediv>
1750       <refname>cyg_thread_get_priority</refname>
1751       <refname>cyg_thread_get_current_priority</refname>
1752       <refname>cyg_thread_set_priority</refname>
1753       <refpurpose>Examine and manipulate thread priorities</refpurpose>
1754     </refnamediv>
1755     <refsynopsisdiv>
1756       <funcsynopsis>
1757         <funcsynopsisinfo>
1758 #include &lt;cyg/kernel/kapi.h&gt;
1759         </funcsynopsisinfo>
1760         <funcprototype>
1761           <funcdef>cyg_priority_t <function>cyg_thread_get_priority</function></funcdef>
1762           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1763         </funcprototype>
1764         <funcprototype>
1765           <funcdef>cyg_priority_t <function>cyg_thread_get_current_priority</function></funcdef>
1766           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1767         </funcprototype>
1768         <funcprototype>
1769           <funcdef>void <function>cyg_thread_set_priority</function></funcdef>
1770           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
1771           <paramdef>cyg_priority_t <parameter>priority</parameter></paramdef>
1772         </funcprototype>
1773       </funcsynopsis>
1774     </refsynopsisdiv>
1775
1776     <refsect1><title id="kernel-thread-priorities-description">Description</title>
1777       <para>
1778 Typical schedulers use the concept of a thread priority to determine
1779 which thread should run next. Exactly what this priority consists of
1780 will depend on the scheduler, but a typical implementation would be a
1781 small integer in the range 0 to 31, with 0 being the highest priority.
1782 Usually only the idle thread will run at the lowest priority. The
1783 exact number of priority levels available depends on the
1784 configuration, typically the option
1785 <varname>CYGNUM_KERNEL_SCHED_PRIORITIES</varname>.
1786       </para>
1787       <para>
1788 <function>cyg_thread_get_priority</function> can be used to determine
1789 the priority of a thread, or more correctly the value last used in a
1790 <function>cyg_thread_set_priority</function> call or when the thread
1791 was first created. In some circumstances it is possible that the
1792 thread is actually running at a higher priority. For example, if it
1793 owns a mutex and priority ceilings or inheritance is being used to
1794 prevent priority inversion problems, then the thread's priority may
1795 have been boosted temporarily.
1796 <function>cyg_thread_get_current_priority</function> returns the real
1797 current priority.
1798       </para>
1799       <para>
1800 In many applications appropriate thread priorities can be determined
1801 and allocated statically. However, if it is necessary for a thread's
1802 priority to change at run-time then the
1803 <function>cyg_thread_set_priority</function> function provides this
1804 functionality. 
1805       </para>
1806     </refsect1>
1807
1808     <refsect1 id="kernel-thread-priorities-context"><title>Valid contexts</title>
1809       <para>
1810 <function>cyg_thread_get_priority</function> and
1811 <function>cyg_thread_get_current_priority</function> can be called
1812 from thread or DSR context, although the latter is rarely useful.
1813 <function>cyg_thread_set_priority</function> should also only be
1814 called from thread context.
1815       </para>
1816     </refsect1>
1817   </refentry>
1818
1819 <!-- }}} -->
1820 <!-- {{{ Per-thread data                -->
1821
1822   <refentry id="kernel-thread-data">
1823
1824     <refmeta>
1825     <refentrytitle>Per-thread data</refentrytitle>
1826     </refmeta>
1827
1828     <refnamediv>
1829       <refname>cyg_thread_new_data_index</refname>
1830       <refname>cyg_thread_free_data_index</refname>
1831       <refname>cyg_thread_get_data</refname>
1832       <refname>cyg_thread_get_data_ptr</refname>
1833       <refname>cyg_thread_set_data</refname>
1834       <refpurpose>Manipulate per-thread data</refpurpose>
1835     </refnamediv>
1836     <refsynopsisdiv>
1837       <funcsynopsis>
1838         <funcsynopsisinfo>
1839 #include &lt;cyg/kernel/kapi.h&gt;
1840         </funcsynopsisinfo>
1841         <funcprototype>
1842           <funcdef>cyg_ucount32 <function>cyg_thread_new_data_index</function></funcdef>
1843           <void>
1844         </funcprototype>
1845         <funcprototype>
1846           <funcdef>void <function>cyg_thread_free_data_index</function></funcdef>
1847           <paramdef>cyg_ucount32 <parameter>index</parameter></paramdef>
1848         </funcprototype>
1849         <funcprototype>
1850           <funcdef>cyg_addrword_t <function>cyg_thread_get_data</function></funcdef>
1851           <paramdef>cyg_ucount32 <parameter>index</parameter></paramdef>
1852         </funcprototype>
1853         <funcprototype>
1854           <funcdef>cyg_addrword_t* <function>cyg_thread_get_data_ptr</function></funcdef>
1855           <paramdef>cyg_ucount32 <parameter>index</parameter></paramdef>
1856         </funcprototype>
1857         <funcprototype>
1858           <funcdef>void <function>cyg_thread_set_data</function></funcdef>
1859           <paramdef>cyg_ucount32 <parameter>index</parameter></paramdef>
1860           <paramdef>cyg_addrword_t <parameter>data</parameter></paramdef>
1861         </funcprototype>
1862       </funcsynopsis>
1863     </refsynopsisdiv>
1864
1865     <refsect1><title id="kernel-thread-data-description">Description</title>
1866       <para>
1867 In some applications and libraries it is useful to have some data that
1868 is specific to each thread. For example, many of the functions in the
1869 POSIX compatibility package return -1 to indicate an error and store
1870 additional information in what appears to be a global variable
1871 <varname>errno</varname>. However, if multiple threads make concurrent
1872 calls into the POSIX library and if <varname>errno</varname> were
1873 really a global variable then a thread would have no way of knowing
1874 whether the current <varname>errno</varname> value really corresponded
1875 to the last POSIX call it made, or whether some other thread had run
1876 in the meantime and made a different POSIX call which updated the
1877 variable. To avoid such confusion <varname>errno</varname> is instead
1878 implemented as a per-thread variable, and each thread has its own
1879 instance.
1880       </para>
1881       <para>
1882 The support for per-thread data can be disabled via the configuration
1883 option <varname>CYGVAR_KERNEL_THREADS_DATA</varname>. If enabled, each
1884 <structname>cyg_thread</structname> data structure holds a small array
1885 of words. The size of this array is determined by the configuration
1886 option <varname>CYGNUM_KERNEL_THREADS_DATA_MAX</varname>. When a
1887 thread is created the array is filled with zeroes.
1888       </para>
1889       <para>
1890 If an application needs to use per-thread data then it needs an index
1891 into this array which has not yet been allocated to other code. This
1892 index can be obtained by calling
1893 <function>cyg_thread_new_data_index</function>, and then used in
1894 subsequent calls to <function>cyg_thread_get_data</function>.
1895 Typically indices are allocated during system initialization and
1896 stored in static variables. If for some reason a slot in the array is
1897 no longer required and can be re-used then it can be released by calling
1898 <function>cyg_thread_free_data_index</function>, 
1899       </para>
1900       <para>
1901 The current per-thread data in a given slot can be obtained using
1902 <function>cyg_thread_get_data</function>. This implicitly operates on
1903 the current thread, and its single argument should be an index as
1904 returned by <function>cyg_thread_new_data_index</function>. The
1905 per-thread data can be updated using
1906 <function>cyg_thread_set_data</function>. If a particular item of
1907 per-thread data is needed repeatedly then
1908 <function>cyg_thread_get_data_ptr</function> can be used to obtain the
1909 address of the data, and indirecting through this pointer allows the
1910 data to be examined and updated efficiently.
1911       </para>
1912       <para>
1913 Some packages, for example the error and POSIX packages, have
1914 pre-allocated slots in the array of per-thread data. These slots
1915 should not normally be used by application code, and instead slots
1916 should be allocated during initialization by a call to
1917 <function>cyg_thread_new_data_index</function>. If it is known that,
1918 for example, the configuration will never include the POSIX
1919 compatibility package then application code may instead decide to
1920 re-use the slot allocated to that package,
1921 <varname>CYGNUM_KERNEL_THREADS_DATA_POSIX</varname>, but obviously
1922 this does involve a risk of strange and subtle bugs if the
1923 application's requirements ever change.
1924       </para>
1925     </refsect1>
1926
1927     <refsect1 id="kernel-thread-data-context"><title>Valid contexts</title>
1928       <para>
1929 Typically <function>cyg_thread_new_data_index</function> is only
1930 called during initialization, but may also be called at any time in
1931 thread context. <function>cyg_thread_free_data_index</function>, if
1932 used at all, can also be called during initialization or from thread
1933 context. <function>cyg_thread_get_data</function>,
1934 <function>cyg_thread_get_data_ptr</function>, and
1935 <function>cyg_thread_set_data</function> may only be called from
1936 thread context because they implicitly operate on the current thread.
1937       </para>
1938     </refsect1>
1939
1940   </refentry>
1941
1942 <!-- }}} -->
1943 <!-- {{{ Thread destructors             -->
1944
1945   <refentry id="kernel-thread-destructors">
1946
1947     <refmeta>
1948     <refentrytitle>Thread destructors</refentrytitle>
1949     </refmeta>
1950
1951     <refnamediv>
1952       <refname>cyg_thread_add_destructor</refname>
1953       <refname>cyg_thread_rem_destructor</refname>
1954       <refpurpose>Call functions on thread termination</refpurpose>
1955     </refnamediv>
1956     <refsynopsisdiv>
1957       <funcsynopsis>
1958         <funcsynopsisinfo>
1959 #include &lt;cyg/kernel/kapi.h&gt;
1960 typedef void (*<type>cyg_thread_destructor_fn</type>)(<type>cyg_addrword_t</type>);
1961         </funcsynopsisinfo>
1962         <funcprototype>
1963           <funcdef>cyg_bool_t <function>cyg_thread_add_destructor</function></funcdef>
1964           <paramdef>cyg_thread_destructor_fn <parameter>fn</parameter></paramdef>
1965           <paramdef>cyg_addrword_t <parameter>data</parameter></paramdef>
1966         </funcprototype>
1967         <funcprototype>
1968           <funcdef>cyg_bool_t <function>cyg_thread_rem_destructor</function></funcdef>
1969           <paramdef>cyg_thread_destructor_fn <parameter>fn</parameter></paramdef>
1970           <paramdef>cyg_addrword_t <parameter>data</parameter></paramdef>
1971         </funcprototype>
1972       </funcsynopsis>
1973     </refsynopsisdiv>
1974
1975     <refsect1><title id="kernel-thread-destructors-description">Description</title>
1976       <para>
1977 These functions are provided for cases when an application requires a
1978 function to be automatically called when a thread exits. This is often
1979 useful when, for example, freeing up resources allocated by the thread.
1980       </para>
1981       <para>
1982 This support must be enabled with the configuration option
1983 <varname>CYGPKG_KERNEL_THREADS_DESTRUCTORS</varname>. When enabled,
1984 you may register a function of type
1985 <type>cyg_thread_destructor_fn</type> to be called on thread
1986 termination using <function>cyg_thread_add_destructor</function>. You
1987 may also provide it with a piece of arbitrary information in the
1988 <parameter>data</parameter> argument which will be passed to the
1989 destructor function <parameter>fn</parameter> when the thread
1990 terminates. If you no longer wish to call a function previous
1991 registered with <function>cyg_thread_add_destructor</function>, you
1992 may call <function>cyg_thread_rem_destructor</function> with the same
1993 parameters used to register the destructor function. Both these
1994 functions return <literal>true</literal> on success and
1995 <literal>false</literal> on failure.
1996       </para>
1997       <para>
1998 By default, thread destructors are per-thread, which means that registering
1999 a destructor function only registers that function for the current thread.
2000 In other words, each thread has its own list of destructors.
2001 Alternatively you may disable the configuration option
2002 <varname>CYGSEM_KERNEL_THREADS_DESTRUCTORS_PER_THREAD</varname> in which
2003 case any registered destructors will be run when <emphasis>any</emphasis>
2004 threads exit. In other words, the thread destructor list is global and all
2005 threads have the same destructors.
2006       </para>
2007       <para>
2008 There is a limit to the number of destructors which may be registered,
2009 which can be controlled with the
2010 <varname>CYGNUM_KERNEL_THREADS_DESTRUCTORS</varname> configuration
2011 option. Increasing this value will very slightly increase the amount
2012 of memory in use, and when
2013 <varname>CYGSEM_KERNEL_THREADS_DESTRUCTORS_PER_THREAD</varname> is
2014 enabled, the amount of memory used per thread will increase. When the
2015 limit has been reached, <function>cyg_thread_add_destructor</function>
2016 will return <literal>false</literal>.
2017       </para>
2018     </refsect1>
2019
2020     <refsect1 id="kernel-thread-destructors-context"><title>Valid contexts</title>
2021       <para>
2022 When <varname>CYGSEM_KERNEL_THREADS_DESTRUCTORS_PER_THREAD</varname>
2023 is enabled, these functions must only be called from a thread context
2024 as they implicitly operate on the current thread. When
2025 <varname>CYGSEM_KERNEL_THREADS_DESTRUCTORS_PER_THREAD</varname> is
2026 disabled, these functions may be called from thread or DSR context,
2027 or at initialization time.
2028       </para>
2029     </refsect1>
2030
2031   </refentry>
2032
2033 <!-- }}} -->
2034 <!-- {{{ Exceptions                     -->
2035
2036   <refentry id="kernel-exceptions">
2037
2038     <refmeta>
2039     <refentrytitle>Exception handling</refentrytitle>
2040     </refmeta>
2041
2042     <refnamediv>
2043       <refname>cyg_exception_set_handler</refname>
2044       <refname>cyg_exception_clear_handler</refname>
2045       <refname>cyg_exception_call_handler</refname>
2046       <refpurpose>Handle processor exceptions</refpurpose>
2047     </refnamediv>
2048     <refsynopsisdiv>
2049       <funcsynopsis>
2050         <funcsynopsisinfo>
2051 #include &lt;cyg/kernel/kapi.h&gt;
2052         </funcsynopsisinfo>
2053         <funcprototype>
2054           <funcdef>void <function>cyg_exception_set_handler</function></funcdef>
2055           <paramdef>cyg_code_t <parameter>exception_number</parameter></paramdef>
2056           <paramdef>cyg_exception_handler_t* <parameter>new_handler</parameter></paramdef>
2057           <paramdef>cyg_addrword_t <parameter>new_data</parameter></paramdef>
2058           <paramdef>cyg_exception_handler_t** <parameter>old_handler</parameter></paramdef>
2059           <paramdef>cyg_addrword_t* <parameter>old_data</parameter></paramdef>
2060         </funcprototype>
2061         <funcprototype>
2062           <funcdef>void <function>cyg_exception_clear_handler</function></funcdef>
2063           <paramdef>cyg_code_t <parameter>exception_number</parameter></paramdef>
2064         </funcprototype>
2065         <funcprototype>
2066           <funcdef>void <function>cyg_exception_call_handler</function></funcdef>
2067           <paramdef>cyg_handle_t <parameter>thread</parameter></paramdef>
2068           <paramdef>cyg_code_t <parameter>exception_number</parameter></paramdef>
2069           <paramdef>cyg_addrword_t <parameter>exception_info</parameter></paramdef>
2070         </funcprototype>
2071       </funcsynopsis>
2072     </refsynopsisdiv>
2073
2074     <refsect1><title id="kernel-exceptions-description">Description</title>
2075       <para>
2076 Sometimes code attempts operations that are not legal on the current
2077 hardware, for example dividing by zero, or accessing data through a
2078 pointer that is not properly aligned. When this happens the hardware
2079 will raise an exception. This is very similar to an interrupt, but
2080 happens synchronously with code execution rather than asynchronously
2081 and hence can be tied to the thread that is currently running.
2082       </para>
2083       <para>
2084 The exceptions that can be raised depend very much on the hardware,
2085 especially the processor. The corresponding documentation should be
2086 consulted for more details. Alternatively the architectural HAL header
2087 file <filename class="headerfile">hal_intr.h</filename>, or one of the
2088 variant or platform header files it includes, will contain appropriate
2089 definitions. The details of how to handle exceptions, including
2090 whether or not it is possible to recover from them, also depend on the
2091 hardware. 
2092       </para>
2093       <para>
2094 Exception handling is optional, and can be disabled through the
2095 configuration option <varname>CYGPKG_KERNEL_EXCEPTIONS</varname>. If
2096 an application has been exhaustively tested and is trusted never to
2097 raise a hardware exception then this option can be disabled and code
2098 and data sizes will be reduced somewhat. If exceptions are left
2099 enabled then the system will provide default handlers for the various
2100 exceptions, but these do nothing. Even the specific type of exception
2101 is ignored, so there is no point in attempting to decode this and
2102 distinguish between say a divide-by-zero and an unaligned access.
2103 If the application installs its own handlers and wants details of the
2104 specific exception being raised then the configuration option
2105 <varname>CYGSEM_KERNEL_EXCEPTIONS_DECODE</varname> has to be enabled.
2106       </para>
2107       <para>
2108 An alternative handler can be installed using
2109 <function>cyg_exception_set_handler</function>. This requires a code
2110 for the exception, a function pointer for the new exception handler,
2111 and a parameter to be passed to this handler. Details of the
2112 previously installed exception handler will be returned via the
2113 remaining two arguments, allowing that handler to be reinstated, or
2114 null pointers can be used if this information is of no interest. An
2115 exception handling function should take the following form:
2116       </para>
2117       <programlisting width=72>
2118 void
2119 my_exception_handler(cyg_addrword_t data, cyg_code_t exception, cyg_addrword_t info)
2120 {
2121     &hellip;
2122 }
2123       </programlisting>
2124       <para>
2125 The data argument corresponds to the <parameter class="function">new_data</parameter> 
2126 parameter supplied to <function>cyg_exception_set_handler</function>.
2127 The exception code is provided as well, in case a single handler is
2128 expected to support multiple exceptions. The <parameter class="function">info</parameter> 
2129 argument will depend on the hardware and on the specific exception.
2130       </para>
2131       <para>
2132 <function>cyg_exception_clear_handler</function> can be used to
2133 restore the default handler, if desired. It is also possible for
2134 software to raise an exception and cause the current handler to be
2135 invoked, but generally this is useful only for testing.
2136       </para>
2137       <para>
2138 By default the system maintains a single set of global exception
2139 handlers. However, since exceptions occur synchronously it is
2140 sometimes useful to handle them on a per-thread basis, and have a
2141 different set of handlers for each thread. This behaviour can be
2142 obtained by disabling the configuration option
2143 <varname>CYGSEM_KERNEL_EXCEPTIONS_GLOBAL</varname>. If per-thread
2144 exception handlers are being used then
2145 <function>cyg_exception_set_handler</function> and
2146 <function>cyg_exception_clear_handler</function> apply to the current
2147 thread. Otherwise they apply to the global set of handlers.
2148       </para>
2149
2150       <caution><para>
2151 In the current implementation
2152 <function>cyg_exception_call_handler</function> can only be used on
2153 the current thread. There is no support for delivering an exception to
2154 another thread.
2155       </para></caution>
2156       <note><para>
2157 Exceptions at the eCos kernel level refer specifically to
2158 hardware-related events such as unaligned accesses to memory or
2159 division by zero. There is no relation with other concepts that are
2160 also known as exceptions, for example the <literal>throw</literal> and
2161 <literal>catch</literal> facilities associated with C++.
2162       </para></note>
2163
2164     </refsect1>
2165
2166     <refsect1 id="kernel-exceptions-context"><title>Valid contexts</title>
2167       <para>
2168 If the system is configured with a single set of global exception
2169 handlers then
2170 <function>cyg_exception_set_handler</function> and
2171 <function>cyg_exception_clear_handler</function> may be called during
2172 initialization or from thread context. If instead per-thread exception
2173 handlers are being used then it is not possible to install new
2174 handlers during initialization because the functions operate
2175 implicitly on the current thread, so they can only be called from
2176 thread context. <function>cyg_exception_call_handler</function> should
2177 only be called from thread context.
2178       </para>
2179     </refsect1>
2180
2181   </refentry>
2182
2183 <!-- }}} -->
2184 <!-- {{{ Counters                       -->
2185
2186   <refentry id="kernel-counters">
2187
2188     <refmeta>
2189     <refentrytitle>Counters</refentrytitle>
2190     </refmeta>
2191
2192     <refnamediv>
2193       <refname>cyg_counter_create</refname>
2194       <refname>cyg_counter_delete</refname>
2195       <refname>cyg_counter_current_value</refname>
2196       <refname>cyg_counter_set_value</refname>
2197       <refname>cyg_counter_tick</refname>
2198       <refpurpose>Count event occurrences</refpurpose>
2199     </refnamediv>
2200
2201     <refsynopsisdiv>
2202       <funcsynopsis>
2203         <funcsynopsisinfo>
2204 #include &lt;cyg/kernel/kapi.h&gt;
2205         </funcsynopsisinfo>
2206         <funcprototype>
2207           <funcdef>void <function>cyg_counter_create</function></funcdef>
2208           <paramdef>cyg_handle_t* <parameter>handle</parameter></paramdef>
2209           <paramdef>cyg_counter* <parameter>counter</parameter></paramdef>
2210         </funcprototype>
2211         <funcprototype>
2212           <funcdef>void <function>cyg_counter_delete</function></funcdef>
2213           <paramdef>cyg_handle_t <parameter>counter</parameter></paramdef>
2214         </funcprototype>
2215         <funcprototype>
2216           <funcdef>cyg_tick_count_t <function>cyg_counter_current_value</function></funcdef>
2217           <paramdef>cyg_handle_t <parameter>counter</parameter></paramdef>
2218         </funcprototype>
2219         <funcprototype>
2220           <funcdef>void <function>cyg_counter_set_value</function></funcdef>
2221           <paramdef>cyg_handle_t <parameter>counter</parameter></paramdef>
2222           <paramdef>cyg_tick_count_t <parameter>new_value</parameter></paramdef>
2223         </funcprototype>
2224         <funcprototype>
2225           <funcdef>void <function>cyg_counter_tick</function></funcdef>
2226           <paramdef>cyg_handle_t <parameter>counter</parameter></paramdef>
2227         </funcprototype>
2228       </funcsynopsis>
2229     </refsynopsisdiv>
2230
2231     <refsect1 id="kernel-counters-description"><title>Description</title>
2232       <para>
2233 Kernel counters can be used to keep track of how many times a
2234 particular event has occurred. Usually this event is an external
2235 signal of some sort. The most common use of counters is in the
2236 implementation of clocks, but they can be useful with other event
2237 sources as well. Application code can attach <link
2238 linkend="kernel-alarms">alarms</link> to counters, causing a function
2239 to be called when some number of events have occurred.
2240       </para>
2241       <para>
2242 A new counter is initialized by a call to
2243 <function>cyg_counter_create</function>. The first argument is used to
2244 return a handle to the new counter which can be used for subsequent
2245 operations. The second argument allows the application to provide the
2246 memory needed for the object, thus eliminating any need for dynamic
2247 memory allocation within the kernel. If a counter is no longer
2248 required and does not have any alarms attached then
2249 <function>cyg_counter_delete</function> can be used to release the
2250 resources, allowing the <structname>cyg_counter</structname> data
2251 structure to be re-used.
2252       </para>
2253       <para>
2254 Initializing a counter does not automatically attach it to any source
2255 of events. Instead some other code needs to call
2256 <function>cyg_counter_tick</function> whenever a suitable event
2257 occurs, which will cause the counter to be incremented and may cause
2258 alarms to trigger. The current value associated with the counter can
2259 be retrieved using <function>cyg_counter_current_value</function> and
2260 modified with <function>cyg_counter_set_value</function>. Typically
2261 the latter function is only used during initialization, for example to
2262 set a clock to wallclock time, but it can be used to reset a counter
2263 if necessary. However <function>cyg_counter_set_value</function> will
2264 never trigger any alarms. A newly initialized counter has a starting
2265 value of 0.
2266       </para>
2267       <para>
2268 The kernel provides two different implementations of counters. The
2269 default is <varname>CYGIMP_KERNEL_COUNTERS_SINGLE_LIST</varname> which
2270 stores all alarms attached to the counter on a single list. This is
2271 simple and usually efficient. However when a tick occurs the kernel
2272 code has to traverse this list, typically at DSR level, so if there
2273 are a significant number of alarms attached to a single counter this
2274 will affect the system's dispatch latency. The alternative
2275 implementation, <varname>CYGIMP_KERNEL_COUNTERS_MULTI_LIST</varname>,
2276 stores each alarm in one of an array of lists such that at most one of
2277 the lists needs to be searched per clock tick. This involves extra
2278 code and data, but can improve real-time responsiveness in some
2279 circumstances. Another configuration option that is relevant here
2280 is <varname>CYGIMP_KERNEL_COUNTERS_SORT_LIST</varname>, which is
2281 disabled by default. This provides a trade off between doing work
2282 whenever a new alarm is added to a counter and doing work whenever a
2283 tick occurs. It is application-dependent which of these is more
2284 appropriate.
2285       </para>
2286     </refsect1>
2287
2288     <refsect1 id="kernel-counters-context"><title>Valid contexts</title>
2289       <para>
2290 <function>cyg_counter_create</function> is typically called during
2291 system initialization but may also be called in thread context.
2292 Similarly <function>cyg_counter_delete</function> may be called during
2293 initialization or in thread context.
2294 <function>cyg_counter_current_value</function>,
2295 <function>cyg_counter_set_value</function> and
2296 <function>cyg_counter_tick</function> may be called during
2297 initialization or from thread or DSR context. In fact,
2298 <function>cyg_counter_tick</function> is usually called from inside a
2299 DSR in response to an external event of some sort.
2300       </para>
2301     </refsect1>
2302
2303   </refentry>
2304
2305 <!-- }}} -->
2306 <!-- {{{ Clocks                         -->
2307
2308   <refentry id="kernel-clocks">
2309
2310     <refmeta>
2311     <refentrytitle>Clocks</refentrytitle>
2312     </refmeta>
2313
2314     <refnamediv>
2315       <refname>cyg_clock_create</refname>
2316       <refname>cyg_clock_delete</refname>
2317       <refname>cyg_clock_to_counter</refname>
2318       <refname>cyg_clock_set_resolution</refname>
2319       <refname>cyg_clock_get_resolution</refname>
2320       <refname>cyg_real_time_clock</refname>
2321       <refname>cyg_current_time</refname>
2322       <refpurpose>Provide system clocks</refpurpose>
2323     </refnamediv>
2324
2325     <refsynopsisdiv>
2326       <funcsynopsis>
2327         <funcsynopsisinfo>
2328 #include &lt;cyg/kernel/kapi.h&gt;
2329         </funcsynopsisinfo>
2330         <funcprototype>
2331           <funcdef>void <function>cyg_clock_create</function></funcdef>
2332           <paramdef>cyg_resolution_t <parameter>resolution</parameter></paramdef>
2333           <paramdef>cyg_handle_t* <parameter>handle</parameter></paramdef>
2334           <paramdef>cyg_clock* <parameter>clock</parameter></paramdef>
2335         </funcprototype>
2336         <funcprototype>
2337           <funcdef>void <function>cyg_clock_delete</function></funcdef>
2338           <paramdef>cyg_handle_t <parameter>clock</parameter></paramdef>
2339         </funcprototype>
2340         <funcprototype>
2341           <funcdef>void <function>cyg_clock_to_counter</function></funcdef>
2342           <paramdef>cyg_handle_t <parameter>clock</parameter></paramdef>
2343           <paramdef>cyg_handle_t* <parameter>counter</parameter></paramdef>
2344         </funcprototype>
2345         <funcprototype>
2346           <funcdef>void <function>cyg_clock_set_resolution</function></funcdef>
2347           <paramdef>cyg_handle_t <parameter>clock</parameter></paramdef>
2348           <paramdef>cyg_resolution_t <parameter>resolution</parameter></paramdef>
2349         </funcprototype>
2350         <funcprototype>
2351           <funcdef>cyg_resolution_t <function>cyg_clock_get_resolution</function></funcdef>
2352           <paramdef>cyg_handle_t <parameter>clock</parameter></paramdef>
2353         </funcprototype>
2354         <funcprototype>
2355           <funcdef>cyg_handle_t <function>cyg_real_time_clock</function></funcdef>
2356           <void>
2357         </funcprototype>
2358         <funcprototype>
2359           <funcdef>cyg_tick_count_t <function>cyg_current_time</function></funcdef>
2360           <void>
2361         </funcprototype>
2362       </funcsynopsis>
2363     </refsynopsisdiv>
2364
2365     <refsect1 id="kernel-clocks-description"><title>Description</title>
2366       <para>
2367 In the eCos kernel clock objects are a special form of <link
2368 linkend="kernel-counters">counter</link> objects. They are attached to
2369 a specific type of hardware, clocks that generate ticks at very
2370 specific time intervals, whereas counters can be used with any event
2371 source.
2372       </para>
2373       <para>
2374 In a default configuration the kernel provides a single clock
2375 instance, the real-time clock. This gets used for timeslicing and for
2376 operations that involve a timeout, for example
2377 <function>cyg_semaphore_timed_wait</function>. If this functionality
2378 is not required it can be removed from the system using the
2379 configuration option <varname>CYGVAR_KERNEL_COUNTERS_CLOCK</varname>.
2380 Otherwise the real-time clock can be accessed by a call to
2381 <function>cyg_real_time_clock</function>, allowing applications to
2382 attach alarms, and the current counter value can be obtained using
2383 <function>cyg_current_time</function>.
2384       </para>
2385       <para>
2386 Applications can create and destroy additional clocks if desired,
2387 using <function>cyg_clock_create</function> and
2388 <function>cyg_clock_delete</function>. The first argument to
2389 <function>cyg_clock_create</function> specifies the
2390 <link linkend="kernel-clocks-resolution">resolution</link> this clock
2391 will run at. The second argument is used to return a handle for this
2392 clock object, and the third argument provides the kernel with the
2393 memory needed to hold this object. This clock will not actually tick
2394 by itself. Instead it is the responsibility of application code to
2395 initialize a suitable hardware timer to generate interrupts at the
2396 appropriate frequency, install an interrupt handler for this, and
2397 call <function>cyg_counter_tick</function> from inside the DSR.
2398 Associated with each clock is a kernel counter, a handle for which can
2399 be obtained using <function>cyg_clock_to_counter</function>.
2400       </para>
2401     </refsect1>
2402
2403     <refsect1 id="kernel-clocks-resolution"><title>Clock Resolutions and Ticks</title>
2404       <para>
2405 At the kernel level all clock-related operations including delays,
2406 timeouts and alarms work in units of clock ticks, rather than in units
2407 of seconds or milliseconds. If the calling code, whether the
2408 application or some other package, needs to operate using units such
2409 as milliseconds then it has to convert from these units to clock
2410 ticks.
2411       </para>
2412       <para>
2413 The main reason for this is that it accurately reflects the
2414 hardware: calling something like <function>nanosleep</function> with a
2415 delay of ten nanoseconds will not work as intended on any real
2416 hardware because timer interrupts simply will not happen that
2417 frequently; instead calling <function>cyg_thread_delay</function> with
2418 the equivalent delay of 0 ticks gives a much clearer indication that
2419 the application is attempting something inappropriate for the target
2420 hardware. Similarly, passing a delay of five ticks to
2421 <function>cyg_thread_delay</function> makes it fairly obvious that
2422 the current thread will be suspended for somewhere between four and
2423 five clock periods, as opposed to passing 50000000 to
2424 <function>nanosleep</function> which suggests a granularity that is
2425 not actually provided.
2426       </para>
2427       <para>
2428 A secondary reason is that conversion between clock ticks and units
2429 such as milliseconds can be somewhat expensive, and whenever possible
2430 should be done at compile-time or by the application developer rather
2431 than at run-time. This saves code size and cpu cycles.
2432       </para>
2433       <para>
2434 The information needed to perform these conversions is the clock
2435 resolution. This is a structure with two fields, a dividend and a
2436 divisor, and specifies the number of nanoseconds between clock ticks.
2437 For example a clock that runs at 100Hz will have 10 milliseconds
2438 between clock ticks, or 10000000 nanoseconds. The ratio between the
2439 resolution's dividend and divisor will therefore be 10000000 to 1, and
2440 typical values for these might be 1000000000 and 100. If the clock
2441 runs at a different frequency, say 60Hz, the numbers could be
2442 1000000000 and 60 respectively. Given a delay in nanoseconds, this can
2443 be converted to clock ticks by multiplying with the the divisor and
2444 then dividing by the dividend. For example a delay of 50 milliseconds
2445 corresponds to 50000000 nanoseconds, and with a clock frequency of
2446 100Hz this can be converted to
2447 ((50000000&nbsp;*&nbsp;100)&nbsp;/&nbsp;1000000000)&nbsp;=&nbsp;5
2448 clock ticks. Given the large numbers involved this arithmetic normally
2449 has to be done using 64-bit precision and the
2450 <type>long&nbsp;long</type> data type, but allows code to run on
2451 hardware with unusual clock frequencies.
2452       </para>
2453       <para>
2454 The default frequency for the real-time clock on any platform is
2455 usually about 100Hz, but platform-specific documentation should be
2456 consulted for this information. Usually it is possible to override
2457 this default by configuration options, but again this depends on the
2458 capabilities of the underlying hardware. The resolution for any clock
2459 can be obtained using <function>cyg_clock_get_resolution</function>.
2460 For clocks created by application code, there is also a function
2461 <function>cyg_clock_set_resolution</function>. This does not affect
2462 the underlying hardware timer in any way, it merely updates the
2463 information that will be returned in subsequent calls to
2464 <function>cyg_clock_get_resolution</function>: changing the actual
2465 underlying clock frequency will require appropriate manipulation of
2466 the timer hardware.
2467       </para>
2468     </refsect1>
2469
2470     <refsect1 id="kernel-clocks-context"><title>Valid contexts</title>
2471       <para>
2472 <function>cyg_clock_create</function> is usually only called during
2473 system initialization (if at all), but may also be called from thread
2474 context. The same applies to <function>cyg_clock_delete</function>.
2475 The remaining functions may be called during initialization, from
2476 thread context, or from DSR context, although it should be noted that
2477 there is no locking between
2478 <function>cyg_clock_get_resolution</function> and
2479 <function>cyg_clock_set_resolution</function> so theoretically it is
2480 possible that the former returns an inconsistent data structure.
2481       </para>
2482     </refsect1>
2483
2484   </refentry>
2485
2486 <!-- }}} -->
2487 <!-- {{{ Alarms                         -->
2488
2489   <refentry id="kernel-alarms">
2490
2491     <refmeta>
2492     <refentrytitle>Alarms</refentrytitle>
2493     </refmeta>
2494
2495     <refnamediv>
2496       <refname>cyg_alarm_create</refname>
2497       <refname>cyg_alarm_delete</refname>
2498       <refname>cyg_alarm_initialize</refname>
2499       <refname>cyg_alarm_enable</refname>
2500       <refname>cyg_alarm_disable</refname>
2501       <refpurpose>Run an alarm function when a number of events have occurred</refpurpose>
2502     </refnamediv>
2503
2504     <refsynopsisdiv>
2505       <funcsynopsis>
2506         <funcsynopsisinfo>
2507 #include &lt;cyg/kernel/kapi.h&gt;
2508         </funcsynopsisinfo>
2509         <funcprototype>
2510           <funcdef>void <function>cyg_alarm_create</function></funcdef>
2511           <paramdef>cyg_handle_t <parameter>counter</parameter></paramdef>
2512           <paramdef>cyg_alarm_t* <parameter>alarmfn</parameter></paramdef>
2513           <paramdef>cyg_addrword_t <parameter>data</parameter></paramdef>
2514           <paramdef>cyg_handle_t* <parameter>handle</parameter></paramdef>
2515           <paramdef>cyg_alarm* <parameter>alarm</parameter></paramdef>
2516         </funcprototype>
2517         <funcprototype>
2518           <funcdef>void <function>cyg_alarm_delete</function></funcdef>
2519           <paramdef>cyg_handle_t <parameter>alarm</parameter></paramdef>
2520         </funcprototype>
2521         <funcprototype>
2522           <funcdef>void <function>cyg_alarm_initialize</function></funcdef>
2523           <paramdef>cyg_handle_t <parameter>alarm</parameter></paramdef>
2524           <paramdef>cyg_tick_count_t <parameter>trigger</parameter></paramdef>
2525           <paramdef>cyg_tick_count_t <parameter>interval</parameter></paramdef>
2526         </funcprototype>
2527         <funcprototype>
2528           <funcdef>void <function>cyg_alarm_enable</function></funcdef>
2529           <paramdef>cyg_handle_t <parameter>alarm</parameter></paramdef>
2530         </funcprototype>
2531         <funcprototype>
2532           <funcdef>void <function>cyg_alarm_disable</function></funcdef>
2533           <paramdef>cyg_handle_t <parameter>alarm</parameter></paramdef>
2534         </funcprototype>
2535       </funcsynopsis>
2536     </refsynopsisdiv>
2537
2538     <refsect1 id="kernel-alarms-description"><title>Description</title>
2539       <para>
2540 Kernel alarms are used together with counters and allow for action to
2541 be taken when a certain number of events have occurred. If the counter
2542 is associated with a clock then the alarm action happens when the
2543 appropriate number of clock ticks have occurred, in other words after
2544 a certain period of time.
2545       </para>
2546       <para>
2547 Setting up an alarm involves a two-step process. First the alarm must
2548 be created with a call to <function>cyg_alarm_create</function>. This
2549 takes five arguments. The first identifies the counter to which the
2550 alarm should be attached. If the alarm should be attached to the
2551 system's real-time clock then <function>cyg_real_time_clock</function>
2552 and <function>cyg_clock_to_counter</function> can be used to get hold
2553 of the appropriate handle. The next two arguments specify the action
2554 to be taken when the alarm is triggered, in the form of a function
2555 pointer and some data. This function should take the form:
2556       </para>
2557       <programlisting width=72>
2558 void
2559 alarm_handler(cyg_handle_t alarm, cyg_addrword_t data)
2560 {
2561     &hellip;
2562 }
2563       </programlisting>
2564       <para>
2565 The data argument passed to the alarm function corresponds to the
2566 third argument passed to <function>cyg_alarm_create</function>.
2567 The fourth argument to <function>cyg_alarm_create</function> is used
2568 to return a handle to the newly-created alarm object, and the final
2569 argument provides the memory needed for the alarm object and thus
2570 avoids any need for dynamic memory allocation within the kernel.
2571       </para>
2572       <para>
2573 Once an alarm has been created a further call to
2574 <function>cyg_alarm_initialize</function> is needed to activate it.
2575 The first argument specifies the alarm. The second argument indicates
2576 the number of events, for example clock ticks, that need to occur
2577 before the alarm triggers. If the third argument is 0 then the alarm
2578 will only trigger once. A non-zero value specifies that the alarm
2579 should trigger repeatedly, with an interval of the specified number of
2580 events.
2581       </para>
2582       <para>
2583 Alarms can be temporarily disabled and reenabled using
2584 <function>cyg_alarm_disable</function> and
2585 <function>cyg_alarm_enable</function>. Alternatively another call to
2586 <function>cyg_alarm_initialize</function> can be used to modify the
2587 behaviour of an existing alarm. If an alarm is no longer required then
2588 the associated resources can be released using
2589 <function>cyg_alarm_delete</function>. 
2590       </para>
2591       <para>
2592 The alarm function is invoked when a counter tick occurs, in other
2593 words when there is a call to <function>cyg_counter_tick</function>,
2594 and will happen in the same context. If the alarm is associated with
2595 the system's real-time clock then this will be DSR context, following
2596 a clock interrupt. If the alarm is associated with some other
2597 application-specific counter then the details will depend on how that
2598 counter is updated.
2599       </para>
2600       <para>
2601 If two or more alarms are registered for precisely the same counter tick,
2602 the order of execution of the alarm functions is unspecified.
2603       </para>
2604     </refsect1>
2605
2606     <refsect1 id="kernel-alarms-context"><title>Valid contexts</title>
2607       <para>
2608 <function>cyg_alarm_create</function>
2609 <function>cyg_alarm_initialize</function> is typically called during
2610 system initialization but may also be called in thread context. The
2611 same applies to <function>cyg_alarm_delete</function>.
2612 <function>cyg_alarm_initialize</function>,
2613 <function>cyg_alarm_disable</function> and
2614 <function>cyg_alarm_enable</function> may be called during
2615 initialization or from thread or DSR context, but
2616 <function>cyg_alarm_enable</function> and
2617 <function>cyg_alarm_initialize</function> may be expensive operations
2618 and should only be called when necessary.
2619       </para>
2620     </refsect1>
2621
2622   </refentry>
2623
2624 <!-- }}} -->
2625 <!-- {{{ Mutexes                        -->
2626
2627   <refentry id="kernel-mutexes">
2628
2629     <refmeta>
2630     <refentrytitle>Mutexes</refentrytitle>
2631     </refmeta>
2632
2633     <refnamediv>
2634       <refname>cyg_mutex_init</refname>
2635       <refname>cyg_mutex_destroy</refname>
2636       <refname>cyg_mutex_lock</refname>
2637       <refname>cyg_mutex_trylock</refname>
2638       <refname>cyg_mutex_unlock</refname>
2639       <refname>cyg_mutex_release</refname>
2640       <refname>cyg_mutex_set_ceiling</refname>
2641       <refname>cyg_mutex_set_protocol</refname>
2642       <refpurpose>Synchronization primitive</refpurpose>
2643     </refnamediv>
2644
2645     <refsynopsisdiv>
2646       <funcsynopsis>
2647         <funcsynopsisinfo>
2648 #include &lt;cyg/kernel/kapi.h&gt;
2649         </funcsynopsisinfo>
2650         <funcprototype>
2651           <funcdef>void <function>cyg_mutex_init</function></funcdef>
2652           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2653         </funcprototype>
2654         <funcprototype>
2655           <funcdef>void <function>cyg_mutex_destroy</function></funcdef>
2656           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2657         </funcprototype>
2658         <funcprototype>
2659           <funcdef>cyg_bool_t <function>cyg_mutex_lock</function></funcdef>
2660           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2661         </funcprototype>
2662         <funcprototype>
2663           <funcdef>cyg_bool_t <function>cyg_mutex_trylock</function></funcdef>
2664           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2665         </funcprototype>
2666         <funcprototype>
2667           <funcdef>void <function>cyg_mutex_unlock</function></funcdef>
2668           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2669         </funcprototype>
2670         <funcprototype>
2671           <funcdef>void <function>cyg_mutex_release</function></funcdef>
2672           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2673         </funcprototype>
2674         <funcprototype>
2675           <funcdef>void <function>cyg_mutex_set_ceiling</function></funcdef>
2676           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2677           <paramdef>cyg_priority_t <parameter>priority</parameter></paramdef>
2678         </funcprototype>
2679         <funcprototype>
2680           <funcdef>void <function>cyg_mutex_set_protocol</function></funcdef>
2681           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
2682           <paramdef>enum cyg_mutex_protocol <parameter>protocol/</parameter></paramdef>
2683         </funcprototype>
2684       </funcsynopsis>
2685     </refsynopsisdiv>
2686
2687     <refsect1 id="kernel-mutexes-description"><title>Description</title>
2688       <para>
2689 The purpose of mutexes is to let threads share resources safely. If
2690 two or more threads attempt to manipulate a data structure with no
2691 locking between them then the system may run for quite some time
2692 without apparent problems, but sooner or later the data structure will
2693 become inconsistent and the application will start behaving strangely
2694 and is quite likely to crash. The same can apply even when
2695 manipulating a single variable or some other resource. For example,
2696 consider:
2697       </para>
2698 <programlisting width=72>
2699 static volatile int counter = 0;
2700
2701 void
2702 process_event(void)
2703 {
2704     &hellip;
2705
2706     counter++;
2707 }
2708 </programlisting>
2709       <para>
2710 Assume that after a certain period of time <varname>counter</varname>
2711 has a value of 42, and two threads A and B running at the same
2712 priority call <function>process_event</function>. Typically thread A
2713 will read the value of <varname>counter</varname> into a register,
2714 increment this register to 43, and write this updated value back to
2715 memory. Thread B will do the same, so usually
2716 <varname>counter</varname> will end up with a value of 44. However if
2717 thread A is timesliced after reading the old value 42 but before
2718 writing back 43, thread B will still read back the old value and will
2719 also write back 43. The net result is that the counter only gets
2720 incremented once, not twice, which depending on the application may
2721 prove disastrous.
2722       </para>
2723       <para>
2724 Sections of code like the above which involve manipulating shared data
2725 are generally known as critical regions. Code should claim a lock
2726 before entering a critical region and release the lock when leaving.
2727 Mutexes provide an appropriate synchronization primitive for this.
2728       </para>
2729       <programlisting width=72>
2730 static volatile int counter = 0;
2731 static cyg_mutex_t  lock;
2732
2733 void
2734 process_event(void)
2735 {
2736     &hellip;
2737
2738     cyg_mutex_lock(&amp;lock);
2739     counter++;
2740     cyg_mutex_unlock(&amp;lock);
2741 }
2742       </programlisting>
2743       <para>
2744 A mutex must be initialized before it can be used, by calling
2745 <function>cyg_mutex_init</function>. This takes a pointer to a
2746 <structname>cyg_mutex_t</structname> data structure which is typically
2747 statically allocated, and may be part of a larger data structure. If a
2748 mutex is no longer required and there are no threads waiting on it
2749 then <function>cyg_mutex_destroy</function> can be used.
2750       </para>
2751       <para>
2752 The main functions for using a mutex are
2753 <function>cyg_mutex_lock</function> and
2754 <function>cyg_mutex_unlock</function>. In normal operation
2755 <function>cyg_mutex_lock</function> will return success after claiming
2756 the mutex lock, blocking if another thread currently owns the mutex.
2757 However the lock operation may fail if other code calls
2758 <function>cyg_mutex_release</function> or
2759 <function>cyg_thread_release</function>, so if these functions may get
2760 used then it is important to check the return value. The current owner
2761 of a mutex should call <function>cyg_mutex_unlock</function> when a
2762 lock is no longer required. This operation must be performed by the
2763 owner, not by another thread.
2764       </para>
2765       <para>
2766 <function>cyg_mutex_trylock</function> is a variant of
2767 <function>cyg_mutex_lock</function> that will always return
2768 immediately, returning success or failure as appropriate. This
2769 function is rarely useful. Typical code locks a mutex just before
2770 entering a critical region, so if the lock cannot be claimed then
2771 there may be nothing else for the current thread to do. Use of this
2772 function may also cause a form of priority inversion if the owner
2773 owner runs at a lower priority, because the priority inheritance code
2774 will not be triggered. Instead the current thread continues running,
2775 preventing the owner from getting any cpu time, completing the
2776 critical region, and releasing the mutex.
2777       </para>
2778       <para>
2779 <function>cyg_mutex_release</function> can be used to wake up all
2780 threads that are currently blocked inside a call to
2781 <function>cyg_mutex_lock</function> for a specific mutex. These lock
2782 calls will return failure. The current mutex owner is not affected.
2783       </para>
2784     </refsect1>
2785
2786     <refsect1 id="kernel-mutexes-priority-inversion"><title>Priority Inversion</title>
2787       <para>
2788 The use of mutexes gives rise to a problem known as priority
2789 inversion. In a typical scenario this requires three threads A, B, and
2790 C, running at high, medium and low priority respectively. Thread A and
2791 thread B are temporarily blocked waiting for some event, so thread C
2792 gets a chance to run, needs to enter a critical region, and locks
2793 a mutex. At this point threads A and B are woken up - the exact order
2794 does not matter. Thread A needs to claim the same mutex but has to
2795 wait until C has left the critical region and can release the mutex.
2796 Meanwhile thread B works on something completely different and can
2797 continue running without problems. Because thread C is running a lower
2798 priority than B it will not get a chance to run until B blocks for
2799 some reason, and hence thread A cannot run either. The overall effect
2800 is that a high-priority thread A cannot proceed because of a lower
2801 priority thread B, and priority inversion has occurred.
2802       </para>
2803       <para>
2804 In simple applications it may be possible to arrange the code such
2805 that priority inversion cannot occur, for example by ensuring that a
2806 given mutex is never shared by threads running at different priority
2807 levels. However this may not always be possible even at the
2808 application level. In addition mutexes may be used internally by
2809 underlying code, for example the memory allocation package, so careful
2810 analysis of the whole system would be needed to be sure that priority
2811 inversion cannot occur. Instead it is common practice to use one of
2812 two techniques: priority ceilings and priority inheritance.
2813       </para>
2814       <para>
2815 Priority ceilings involve associating a priority with each mutex.
2816 Usually this will match the highest priority thread that will ever
2817 lock the mutex. When a thread running at a lower priority makes a
2818 successful call to <function>cyg_mutex_lock</function> or
2819 <function>cyg_mutex_trylock</function> its priority will be boosted to
2820 that of the mutex. For example, given the previous example the
2821 priority associated with the mutex would be that of thread A, so for
2822 as long as it owns the mutex thread C will run in preference to thread
2823 B. When C releases the mutex its priority drops to the normal value
2824 again, allowing A to run and claim the mutex. Setting the
2825 priority for a mutex involves a call to
2826 <function>cyg_mutex_set_ceiling</function>, which is typically called
2827 during initialization. It is possible to change the ceiling
2828 dynamically but this will only affect subsequent lock operations, not
2829 the current owner of the mutex.
2830       </para>
2831       <para>
2832 Priority ceilings are very suitable for simple applications, where for
2833 every thread in the system it is possible to work out which mutexes
2834 will be accessed. For more complicated applications this may prove
2835 difficult, especially if thread priorities change at run-time. An
2836 additional problem occurs for any mutexes outside the application, for
2837 example used internally within eCos packages. A typical eCos package
2838 will be unaware of the details of the various threads in the system,
2839 so it will have no way of setting suitable ceilings for its internal
2840 mutexes. If those mutexes are not exported to application code then 
2841 using priority ceilings may not be viable. The kernel does provide a
2842 configuration option
2843 <varname>CYGSEM_KERNEL_SYNCH_MUTEX_PRIORITY_INVERSION_PROTOCOL_DEFAULT_PRIORITY</varname>
2844 that can be used to set the default priority ceiling for all mutexes,
2845 which may prove sufficient.
2846       </para>
2847       <para>
2848 The alternative approach is to use priority inheritance: if a thread
2849 calls <function>cyg_mutex_lock</function> for a mutex that it
2850 currently owned by a lower-priority thread, then the owner will have
2851 its priority raised to that of the current thread. Often this is more
2852 efficient than priority ceilings because priority boosting only
2853 happens when necessary, not for every lock operation, and the required
2854 priority is determined at run-time rather than by static analysis.
2855 However there are complications when multiple threads running at
2856 different priorities try to lock a single mutex, or when the current
2857 owner of a mutex then tries to lock additional mutexes, and this makes
2858 the implementation significantly more complicated than priority
2859 ceilings. 
2860       </para>
2861       <para>
2862 There are a number of configuration options associated with priority
2863 inversion. First, if after careful analysis it is known that priority
2864 inversion cannot arise then the component
2865 <function>CYGSEM_KERNEL_SYNCH_MUTEX_PRIORITY_INVERSION_PROTOCOL</function>
2866 can be disabled. More commonly this component will be enabled, and one
2867 of either
2868 <varname>CYGSEM_KERNEL_SYNCH_MUTEX_PRIORITY_INVERSION_PROTOCOL_INHERIT</varname>
2869 or
2870 <varname>CYGSEM_KERNEL_SYNCH_MUTEX_PRIORITY_INVERSION_PROTOCOL_CEILING</varname>
2871 will be selected, so that one of the two protocols is available for
2872 all mutexes. It is possible to select multiple protocols, so that some
2873 mutexes can have priority ceilings while others use priority
2874 inheritance or no priority inversion protection at all. Obviously this
2875 flexibility will add to the code size and to the cost of mutex
2876 operations. The default for all mutexes will be controlled by
2877 <varname>CYGSEM_KERNEL_SYNCH_MUTEX_PRIORITY_INVERSION_PROTOCOL_DEFAULT</varname>,
2878 and can be changed at run-time using
2879 <function>cyg_mutex_set_protocol</function>. 
2880       </para>
2881       <para>
2882 Priority inversion problems can also occur with other synchronization
2883 primitives such as semaphores. For example there could be a situation
2884 where a high-priority thread A is waiting on a semaphore, a
2885 low-priority thread C needs to do just a little bit more work before
2886 posting the semaphore, but a medium priority thread B is running and
2887 preventing C from making progress. However a semaphore does not have
2888 the concept of an owner, so there is no way for the system to know
2889 that it is thread C which would next post to the semaphore. Hence
2890 there is no way for the system to boost the priority of C
2891 automatically and prevent the priority inversion. Instead situations
2892 like this have to be detected by application developers and
2893 appropriate precautions have to be taken, for example making sure that
2894 all the threads run at suitable priorities at all times.
2895       </para>
2896       <warning><para>
2897 The current implementation of priority inheritance within the eCos
2898 kernel does not handle certain exceptional circumstances completely
2899 correctly. Problems will only arise if a thread owns one mutex,
2900 then attempts to claim another mutex, and there are other threads
2901 attempting to lock these same mutexes. Although the system will
2902 continue running, the current owners of the various mutexes involved
2903 may not run at the priority they should. This situation never arises
2904 in typical code because a mutex will only be locked for a small
2905 critical region, and there is no need to manipulate other shared resources
2906 inside this region. A more complicated implementation of priority
2907 inheritance is possible but would add significant overhead and certain
2908 operations would no longer be deterministic.
2909       </para></warning>
2910       <warning><para>
2911 Support for priority ceilings and priority inheritance is not
2912 implemented for all schedulers. In particular neither priority
2913 ceilings nor priority inheritance are currently available for the
2914 bitmap scheduler.
2915       </para></warning>
2916     </refsect1>
2917
2918     <refsect1 id="kernel-mutexes-alternatives"><title>Alternatives</title>
2919       <para>
2920 In nearly all circumstances, if two or more threads need to share some
2921 data then protecting this data with a mutex is the correct thing to
2922 do. Mutexes are the only primitive that combine a locking mechanism
2923 and protection against priority inversion problems. However this
2924 functionality is achieved at a cost, and in exceptional circumstances
2925 such as an application's most critical inner loop it may be desirable
2926 to use some other means of locking.
2927       </para>
2928       <para>
2929 When a critical region is very very small it is possible to lock the
2930 scheduler, thus ensuring that no other thread can run until the
2931 scheduler is unlocked again. This is achieved with calls to <link
2932 linkend="kernel-schedcontrol"><function>cyg_scheduler_lock</function></link>
2933 and <function>cyg_scheduler_unlock</function>. If the critical region
2934 is sufficiently small then this can actually improve both performance
2935 and dispatch latency because <function>cyg_mutex_lock</function> also
2936 locks the scheduler for a brief period of time. This approach will not
2937 work on SMP systems because another thread may already be running on a
2938 different processor and accessing the critical region.
2939       </para>
2940       <para>
2941 Another way of avoiding the use of mutexes is to make sure that all
2942 threads that access a particular critical region run at the same
2943 priority and configure the system with timeslicing disabled
2944 (<varname>CYGSEM_KERNEL_SCHED_TIMESLICE</varname>). Without
2945 timeslicing a thread can only be preempted by a higher-priority one,
2946 or if it performs some operation that can block. This approach
2947 requires that none of the operations in the critical region can block,
2948 so for example it is not legal to call
2949 <function>cyg_semaphore_wait</function>. It is also vulnerable to
2950 any changes in the configuration or to the various thread priorities:
2951 any such changes may now have unexpected side effects. It will not
2952 work on SMP systems.
2953       </para>
2954     </refsect1>
2955
2956     <refsect1 id="kernel-mutexes-recursive"><title>Recursive Mutexes</title>
2957       <para>
2958 The implementation of mutexes within the eCos kernel does not support
2959 recursive locks. If a thread has locked a mutex and then attempts to
2960 lock the mutex again, typically as a result of some recursive call in
2961 a complicated call graph, then either an assertion failure will be
2962 reported or the thread will deadlock. This behaviour is deliberate.
2963 When a thread has just locked a mutex associated with some data
2964 structure, it can assume that that data structure is in a consistent
2965 state. Before unlocking the mutex again it must ensure that the data
2966 structure is again in a consistent state. Recursive mutexes allow a
2967 thread to make arbitrary changes to a data structure, then in a
2968 recursive call lock the mutex again while the data structure is still
2969 inconsistent. The net result is that code can no longer make any
2970 assumptions about data structure consistency, which defeats the
2971 purpose of using mutexes.
2972       </para>
2973     </refsect1>
2974
2975     <refsect1 id="kernel-mutexes-context"><title>Valid contexts</title>
2976       <para>
2977 <function>cyg_mutex_init</function>,
2978 <function>cyg_mutex_set_ceiling</function> and
2979 <function>cyg_mutex_set_protocol</function> are normally called during
2980 initialization but may also be called from thread context. The
2981 remaining functions should only be called from thread context. Mutexes
2982 serve as a mutual exclusion mechanism between threads, and cannot be
2983 used to synchronize between threads and the interrupt handling
2984 subsystem. If a critical region is shared between a thread and a DSR
2985 then it must be protected using <link
2986 linkend="kernel-schedcontrol"><function>cyg_scheduler_lock</function></link>
2987 and <function>cyg_scheduler_unlock</function>. If a critical region is
2988 shared between a thread and an ISR, it must be protected by disabling
2989 or masking interrupts. Obviously these operations must be used with
2990 care because they can affect dispatch and interrupt latencies.
2991       </para>
2992     </refsect1>
2993
2994   </refentry>
2995
2996 <!-- }}} -->
2997 <!-- {{{ Condition variables            -->
2998
2999   <refentry id="kernel-condition-variables">
3000
3001     <refmeta>
3002     <refentrytitle>Condition Variables</refentrytitle>
3003     </refmeta>
3004
3005     <refnamediv>
3006       <refname>cyg_cond_init</refname>
3007       <refname>cyg_cond_destroy</refname>
3008       <refname>cyg_cond_wait</refname>
3009       <refname>cyg_cond_timed_wait</refname>
3010       <refname>cyg_cond_signal</refname>
3011       <refname>cyg_cond_broadcast</refname>
3012       <refpurpose>Synchronization primitive</refpurpose>
3013     </refnamediv>
3014
3015     <refsynopsisdiv>
3016       <funcsynopsis>
3017         <funcsynopsisinfo>
3018 #include &lt;cyg/kernel/kapi.h&gt;
3019         </funcsynopsisinfo>
3020         <funcprototype>
3021           <funcdef>void <function>cyg_cond_init</function></funcdef>
3022           <paramdef>cyg_cond_t* <parameter>cond</parameter></paramdef>
3023           <paramdef>cyg_mutex_t* <parameter>mutex</parameter></paramdef>
3024         </funcprototype>
3025         <funcprototype>
3026           <funcdef>void <function>cyg_cond_destroy</function></funcdef>
3027           <paramdef>cyg_cond_t* <parameter>cond</parameter></paramdef>
3028         </funcprototype>
3029         <funcprototype>
3030           <funcdef>cyg_bool_t <function>cyg_cond_wait</function></funcdef>
3031           <paramdef>cyg_cond_t* <parameter>cond</parameter></paramdef>
3032         </funcprototype>
3033         <funcprototype>
3034           <funcdef>cyg_bool_t <function>cyg_cond_timed_wait</function></funcdef>
3035           <paramdef>cyg_cond_t* <parameter>cond</parameter></paramdef>
3036           <paramdef>cyg_tick_count_t <parameter>abstime</parameter></paramdef>
3037         </funcprototype>
3038         <funcprototype>
3039           <funcdef>void <function>cyg_cond_signal</function></funcdef>
3040           <paramdef>cyg_cond_t* <parameter>cond</parameter></paramdef>
3041         </funcprototype>
3042         <funcprototype>
3043           <funcdef>void <function>cyg_cond_broadcast</function></funcdef>
3044           <paramdef>cyg_cond_t* <parameter>cond</parameter></paramdef>
3045         </funcprototype>
3046       </funcsynopsis>
3047     </refsynopsisdiv>
3048
3049     <refsect1 id="kernel-condition-variables-description"><title>Description</title>
3050
3051       <para>
3052 Condition variables are used in conjunction with mutexes to implement
3053 long-term waits for some condition to become true. For example
3054 consider a set of functions that control access to a pool of
3055 resources:
3056       </para>
3057
3058       <programlisting width=72>
3059
3060 cyg_mutex_t res_lock;
3061 res_t res_pool[RES_MAX];
3062 int res_count = RES_MAX;
3063
3064 void res_init(void)
3065 {
3066     cyg_mutex_init(&amp;res_lock);
3067     &lt;fill pool with resources&gt;
3068 }
3069
3070 res_t res_allocate(void)
3071 {
3072     res_t res;
3073
3074     cyg_mutex_lock(&amp;res_lock);               // lock the mutex
3075
3076     if( res_count == 0 )                     // check for free resource
3077         res = RES_NONE;                      // return RES_NONE if none
3078     else
3079     {
3080         res_count--;                         // allocate a resources
3081         res = res_pool[res_count];
3082     }
3083
3084     cyg_mutex_unlock(&amp;res_lock);             // unlock the mutex
3085
3086     return res;
3087 }
3088
3089 void res_free(res_t res)
3090 {
3091     cyg_mutex_lock(&amp;res_lock);               // lock the mutex
3092
3093     res_pool[res_count] = res;               // free the resource
3094     res_count++;
3095
3096     cyg_mutex_unlock(&amp;res_lock);             // unlock the mutex
3097 }
3098       </programlisting>
3099
3100       <para>
3101 These routines use the variable <varname>res_count</varname> to keep
3102 track of the resources available. If there are none then
3103 <function>res_allocate</function> returns <literal>RES_NONE</literal>,
3104 which the caller must check for and take appropriate error handling
3105 actions.
3106       </para>
3107
3108       <para>
3109 Now suppose that we do not want to return
3110 <literal>RES_NONE</literal> when there are no resources, but want to
3111 wait for one to become available. This is where a condition variable
3112 can be used:
3113       </para>
3114
3115       <programlisting width=72>
3116
3117 cyg_mutex_t res_lock;
3118 cyg_cond_t res_wait;
3119 res_t res_pool[RES_MAX];
3120 int res_count = RES_MAX;
3121
3122 void res_init(void)
3123 {
3124     cyg_mutex_init(&amp;res_lock);
3125     cyg_cond_init(&amp;res_wait, &amp;res_lock);
3126     &lt;fill pool with resources&gt;
3127 }
3128
3129 res_t res_allocate(void)
3130 {
3131     res_t res;
3132
3133     cyg_mutex_lock(&amp;res_lock);               // lock the mutex
3134
3135     while( res_count == 0 )                  // wait for a resources
3136         cyg_cond_wait(&amp;res_wait);
3137
3138     res_count--;                             // allocate a resource
3139     res = res_pool[res_count];
3140
3141     cyg_mutex_unlock(&amp;res_lock);             // unlock the mutex
3142
3143     return res;
3144 }
3145
3146 void res_free(res_t res)
3147 {
3148     cyg_mutex_lock(&amp;res_lock);               // lock the mutex
3149
3150     res_pool[res_count] = res;               // free the resource
3151     res_count++;
3152
3153     cyg_cond_signal(&amp;res_wait);              // wake up any waiting allocators
3154
3155     cyg_mutex_unlock(&amp;res_lock);             // unlock the mutex
3156 }
3157       </programlisting>
3158
3159       <para>
3160 In this version of the code, when <function>res_allocate</function>
3161 detects that there are no resources it calls
3162 <function>cyg_cond_wait</function>. This does two things: it unlocks
3163 the mutex, and puts the calling thread to sleep on the condition
3164 variable. When <function>res_free</function> is eventually called, it
3165 puts a resource back into the pool and calls
3166 <function>cyg_cond_signal</function> to wake up any thread waiting on
3167 the condition variable. When the waiting thread eventually gets to run again,
3168 it will re-lock the mutex before returning from
3169 <function>cyg_cond_wait</function>.
3170       </para>
3171
3172       <para>
3173 There are two important things to note about the way in which this
3174 code works. The first is that the mutex unlock and wait in
3175 <function>cyg_cond_wait</function> are atomic: no other thread can run
3176 between the unlock and the wait. If this were not the case then a call
3177 to <function>res_free</function> by that thread would release the
3178 resource but the call to <function>cyg_cond_signal</function> would be
3179 lost, and the first thread would end up waiting when there were
3180 resources available.
3181       </para>
3182
3183       <para>
3184 The second feature is that the call to
3185 <function>cyg_cond_wait</function> is in a <literal>while</literal>
3186 loop and not a simple <literal>if</literal> statement. This is because
3187 of the need to re-lock the mutex in <function>cyg_cond_wait</function>
3188 when the signalled thread reawakens. If there are other threads
3189 already queued to claim the lock then this thread must wait. Depending
3190 on the scheduler and the queue order, many other threads may have
3191 entered the critical section before this one gets to run. So the
3192 condition that it was waiting for may have been rendered false. Using
3193 a loop around all condition variable wait operations is the only way
3194 to guarantee that the condition being waited for is still true after
3195 waiting.
3196       </para>
3197
3198       <para>
3199 Before a condition variable can be used it must be initialized with a
3200 call to <function>cyg_cond_init</function>. This requires two
3201 arguments, memory for the data structure and a pointer to an existing
3202 mutex. This mutex will not be initialized by
3203 <function>cyg_cond_init</function>, instead a separate call to
3204 <function>cyg_mutex_init</function> is required. If a condition
3205 variable is no longer required and there are no threads waiting on it
3206 then <function>cyg_cond_destroy</function> can be used.
3207       </para>
3208       <para>
3209 When a thread needs to wait for a condition to be satisfied it can
3210 call <function>cyg_cond_wait</function>. The thread must have already
3211 locked the mutex that was specified in the
3212 <function>cyg_cond_init</function> call. This mutex will be unlocked
3213 and the current thread will be suspended in an atomic operation. When
3214 some other thread performs a signal or broadcast operation the current
3215 thread will be woken up and automatically reclaim ownership of the mutex
3216 again, allowing it to examine global state and determine whether or
3217 not the condition is now satisfied.
3218       </para>
3219       <para>
3220 The kernel supplies a variant of this function,
3221 <function>cyg_cond_timed_wait</function>, which can be used to wait on
3222 the condition variable or until some number of clock ticks have
3223 occurred. The number of ticks is specified as an absolute, not
3224 relative tick count, and so in order to wait for a relative number of
3225 ticks, the return value of the <function>cyg_current_time()</function>
3226 function should be added to determine the absolute number of ticks.
3227 The mutex will always be reclaimed before
3228 <function>cyg_cond_timed_wait</function> returns, regardless of
3229 whether it was a result of a signal operation or a timeout.
3230       </para>
3231       <para>
3232 There is no <function>cyg_cond_trywait</function> function because
3233 this would not serve any purpose. If a thread has locked the mutex and
3234 determined that the condition is satisfied, it can just release the
3235 mutex and return. There is no need to perform any operation on the
3236 condition variable.
3237       </para>
3238       <para>
3239 When a thread changes shared state that may affect some other thread
3240 blocked on a condition variable, it should call either
3241 <function>cyg_cond_signal</function> or
3242 <function>cyg_cond_broadcast</function>. These calls do not require
3243 ownership of the mutex, but usually the mutex will have been claimed
3244 before updating the shared state. A signal operation only wakes up the
3245 first thread that is waiting on the condition variable, while a
3246 broadcast wakes up all the threads. If there are no threads waiting on
3247 the condition variable at the time, then the signal or broadcast will
3248 have no effect: past signals are not counted up or remembered in any
3249 way. Typically a signal should be used when all threads will check the
3250 same condition and at most one thread can continue running. A
3251 broadcast should be used if threads check slightly different
3252 conditions, or if the change to the global state might allow multiple
3253 threads to proceed.
3254       </para>
3255     </refsect1>
3256
3257     <refsect1 id="kernel-condition-variables-context"><title>Valid contexts</title>
3258       <para>
3259 <function>cyg_cond_init</function> is typically called during system
3260 initialization but may also be called in thread context. The same
3261 applies to <function>cyg_cond_delete</function>.
3262 <function>cyg_cond_wait</function> and
3263 <function>cyg_cond_timedwait</function> may only be called from thread
3264 context since they may block. <function>cyg_cond_signal</function> and
3265 <function>cyg_cond_broadcast</function> may be called from thread or
3266 DSR context.
3267       </para>
3268     </refsect1>
3269
3270   </refentry>
3271
3272 <!-- }}} -->
3273 <!-- {{{ Semaphores                     -->
3274
3275   <refentry id="kernel-semaphores">
3276
3277     <refmeta>
3278     <refentrytitle>Semaphores</refentrytitle>
3279     </refmeta>
3280
3281     <refnamediv>
3282       <refname>cyg_semaphore_init</refname>
3283       <refname>cyg_semaphore_destroy</refname>
3284       <refname>cyg_semaphore_wait</refname>
3285       <refname>cyg_semaphore_timed_wait</refname>
3286       <refname>cyg_semaphore_post</refname>
3287       <refname>cyg_semaphore_peek</refname>
3288       <refpurpose>Synchronization primitive</refpurpose>
3289     </refnamediv>
3290
3291     <refsynopsisdiv>
3292       <funcsynopsis>
3293         <funcsynopsisinfo>
3294 #include &lt;cyg/kernel/kapi.h&gt;
3295         </funcsynopsisinfo>
3296         <funcprototype>
3297           <funcdef>void <function>cyg_semaphore_init</function></funcdef>
3298           <paramdef>cyg_sem_t* <parameter>sem</parameter></paramdef>
3299           <paramdef>cyg_count32 <parameter>val</parameter></paramdef>
3300         </funcprototype>
3301         <funcprototype>
3302           <funcdef>void <function>cyg_semaphore_destroy</function></funcdef>
3303           <paramdef>cyg_sem_t* <parameter>sem</parameter></paramdef>
3304         </funcprototype>
3305         <funcprototype>
3306           <funcdef>cyg_bool_t <function>cyg_semaphore_wait</function></funcdef>
3307           <paramdef>cyg_sem_t* <parameter>sem</parameter></paramdef>
3308         </funcprototype>
3309         <funcprototype>
3310           <funcdef>cyg_bool_t <function>cyg_semaphore_timed_wait</function></funcdef>
3311           <paramdef>cyg_sem_t* <parameter>sem</parameter></paramdef>
3312           <paramdef>cyg_tick_count_t <parameter>abstime</parameter></paramdef>
3313         </funcprototype>
3314         <funcprototype>
3315           <funcdef>cyg_bool_t <function>cyg_semaphore_trywait</function></funcdef>
3316           <paramdef>cyg_sem_t* <parameter>sem</parameter></paramdef>
3317         </funcprototype>
3318         <funcprototype>
3319           <funcdef>void <function>cyg_semaphore_post</function></funcdef>
3320           <paramdef>cyg_sem_t* <parameter>sem</parameter></paramdef>
3321         </funcprototype>
3322         <funcprototype>
3323           <funcdef>void <function>cyg_semaphore_peek</function></funcdef>
3324           <paramdef>cyg_sem_t* <parameter>sem</parameter></paramdef>
3325           <paramdef>cyg_count32* <parameter>val</parameter></paramdef>
3326         </funcprototype>
3327       </funcsynopsis>
3328     </refsynopsisdiv>
3329
3330     <refsect1 id="kernel-semaphores-description"><title>Description</title>
3331       <para>
3332 Counting semaphores are a <link
3333 linkend="kernel-overview-synch-primitives">synchronization
3334 primitive</link> that allow threads to wait until an event has
3335 occurred. The event may be generated by a producer thread, or by a DSR
3336 in response to a hardware interrupt. Associated with each semaphore is
3337 an integer counter that keeps track of the number of events that have
3338 not yet been processed. If this counter is zero, an attempt by a
3339 consumer thread to wait on the semaphore will block until some other
3340 thread or a DSR posts a new event to the semaphore. If the counter is
3341 greater than zero then an attempt to wait on the semaphore will
3342 consume one event, in other words decrement the counter, and return
3343 immediately. Posting to a semaphore will wake up the first thread that
3344 is currently waiting, which will then resume inside the semaphore wait
3345 operation and decrement the counter again.
3346       </para>
3347       <para>
3348 Another use of semaphores is for certain forms of resource management.
3349 The counter would correspond to how many of a certain type of resource
3350 are currently available, with threads waiting on the semaphore to
3351 claim a resource and posting to release the resource again. In
3352 practice <link linkend="kernel-condition-variables">condition
3353 variables</link> are usually much better suited for operations like
3354 this.
3355       </para>
3356       <para>
3357 <function>cyg_semaphore_init</function> is used to initialize a
3358 semaphore. It takes two arguments, a pointer to a
3359 <structname>cyg_sem_t</structname> structure and an initial value for
3360 the counter. Note that semaphore operations, unlike some other parts
3361 of the kernel API, use pointers to data structures rather than
3362 handles. This makes it easier to embed semaphores in a larger data
3363 structure. The initial counter value can be any number, zero, positive
3364 or negative, but typically a value of zero is used to indicate that no
3365 events have occurred yet.
3366       </para>
3367       <para>
3368 <function>cyg_semaphore_wait</function> is used by a consumer thread
3369 to wait for an event. If the current counter is greater than 0, in
3370 other words if the event has already occurred in the past, then the
3371 counter will be decremented and the call will return immediately.
3372 Otherwise the current thread will be blocked until there is a
3373 <function>cyg_semaphore_post</function> call.
3374       </para>
3375       <para>
3376 <function>cyg_semaphore_post</function> is called when an event has
3377 occurs. This increments the counter and wakes up the first thread
3378 waiting on the semaphore (if any). Usually that thread will then
3379 continue running inside <function>cyg_semaphore_wait</function> and
3380 decrement the counter again. However other scenarioes are possible.
3381 For example the thread calling <function>cyg_semaphore_post</function>
3382 may be running at high priority, some other thread running at medium
3383 priority may be about to call <function>cyg_semaphore_wait</function>
3384 when it next gets a chance to run, and a low priority thread may be
3385 waiting on the semaphore. What will happen is that the current high
3386 priority thread continues running until it is descheduled for some
3387 reason, then the medium priority thread runs and its call to
3388 <function>cyg_semaphore_wait</function> succeeds immediately, and
3389 later on the low priority thread runs again, discovers a counter value
3390 of 0, and blocks until another event is posted. If there are multiple
3391 threads blocked on a semaphore then the configuration option
3392 <varname>CYGIMP_KERNEL_SCHED_SORTED_QUEUES</varname> determines which
3393 one will be woken up by a post operation.
3394       </para>
3395       <para>
3396 <function>cyg_semaphore_wait</function> returns a boolean. Normally it
3397 will block until it has successfully decremented the counter, retrying
3398 as necessary, and return success. However the wait operation may be
3399 aborted by a call to <link
3400 linkend="kernel-thread-control"><function>cyg_thread_release</function></link>,
3401 and <function>cyg_semaphore_wait</function> will then return false.
3402       </para>
3403       <para>
3404 <function>cyg_semaphore_timed_wait</function> is a variant of
3405 <function>cyg_semaphore_wait</function>. It can be used to wait until
3406 either an event has occurred or a number of clock ticks have happened.
3407 The number of ticks is specified as an absolute, not relative tick
3408 count, and so in order to wait for a relative number of ticks, the
3409 return value of the <function>cyg_current_time()</function> function
3410 should be added to determine the absolute number of ticks. The
3411 function returns success if the semaphore wait operation succeeded, or
3412 false if the operation timed out or was aborted by
3413 <function>cyg_thread_release</function>.
3414 If support for the real-time
3415 clock has been removed from the current configuration then this
3416 function will not be available.
3417 <function>cyg_semaphore_trywait</function> is another variant which
3418 will always return immediately rather than block, again returning
3419 success or failure. If <function>cyg_semaphore_timedwait</function>
3420 is given a timeout in the past, it operates like
3421 <function>cyg_semaphore_trywait</function>.
3422       </para>
3423       <para>
3424 <function>cyg_semaphore_peek</function> can be used to get hold of the
3425 current counter value. This function is rarely useful except for
3426 debugging purposes since the counter value may change at any time if
3427 some other thread or a DSR performs a semaphore operation.
3428       </para>
3429     </refsect1>
3430
3431     <refsect1 id="kernel-semaphores-context"><title>Valid contexts</title>
3432       <para>
3433 <function>cyg_semaphore_init</function> is normally called during
3434 initialization but may also be called from thread context.
3435 <function>cyg_semaphore_wait</function> and
3436 <function>cyg_semaphore_timed_wait</function> may only be called from
3437 thread context because these operations may block.
3438 <function>cyg_semaphore_trywait</function>,
3439 <function>cyg_semaphore_post</function> and
3440 <function>cyg_semaphore_peek</function> may be called from thread or
3441 DSR context.
3442       </para>
3443     </refsect1>
3444
3445   </refentry>
3446
3447 <!-- }}} -->
3448 <!-- {{{ Mail boxes                     -->
3449
3450   <refentry id="kernel-mail-boxes">
3451
3452     <refmeta>
3453     <refentrytitle>Mail boxes</refentrytitle>
3454     </refmeta>
3455
3456     <refnamediv>
3457       <refname>cyg_mbox_create</refname>
3458       <refname>cyg_mbox_delete</refname>
3459       <refname>cyg_mbox_get</refname>
3460       <refname>cyg_mbox_timed_get</refname>
3461       <refname>cyg_mbox_tryget</refname>
3462       <refname>cyg_mbox_peek_item</refname>
3463       <refname>cyg_mbox_put</refname>
3464       <refname>cyg_mbox_timed_put</refname>
3465       <refname>cyg_mbox_tryput</refname>
3466       <refname>cyg_mbox_peek</refname>
3467       <refname>cyg_mbox_waiting_to_get</refname>
3468       <refname>cyg_mbox_waiting_to_put</refname>
3469       <refpurpose>Synchronization primitive</refpurpose>
3470     </refnamediv>
3471
3472     <refsynopsisdiv>
3473       <funcsynopsis>
3474         <funcsynopsisinfo>
3475 #include &lt;cyg/kernel/kapi.h&gt;
3476         </funcsynopsisinfo>
3477         <funcprototype>
3478           <funcdef>void <function>cyg_mbox_create</function></funcdef>
3479           <paramdef>cyg_handle_t* <parameter>handle</parameter></paramdef>
3480           <paramdef>cyg_mbox* <parameter>mbox</parameter></paramdef>
3481         </funcprototype>
3482         <funcprototype>
3483           <funcdef>void <function>cyg_mbox_delete</function></funcdef>
3484           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3485         </funcprototype>
3486         <funcprototype>
3487           <funcdef>void* <function>cyg_mbox_get</function></funcdef>
3488           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3489         </funcprototype>
3490         <funcprototype>
3491           <funcdef>void* <function>cyg_mbox_timed_get</function></funcdef>
3492           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3493           <paramdef>cyg_tick_count_t <parameter>abstime</parameter></paramdef>
3494         </funcprototype>
3495         <funcprototype>
3496           <funcdef>void* <function>cyg_mbox_tryget</function></funcdef>
3497           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3498         </funcprototype>
3499         <funcprototype>
3500           <funcdef>cyg_count32 <function>cyg_mbox_peek</function></funcdef>
3501           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3502         </funcprototype>
3503         <funcprototype>
3504           <funcdef>void* <function>cyg_mbox_peek_item</function></funcdef>
3505           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3506         </funcprototype>
3507         <funcprototype>
3508           <funcdef>cyg_bool_t <function>cyg_mbox_put</function></funcdef>
3509           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3510           <paramdef>void* <parameter>item</parameter></paramdef>
3511         </funcprototype>
3512         <funcprototype>
3513           <funcdef>cyg_bool_t <function>cyg_mbox_timed_put</function></funcdef>
3514           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3515           <paramdef>void* <parameter>item</parameter></paramdef>
3516           <paramdef>cyg_tick_count_t <parameter>abstime</parameter></paramdef>
3517         </funcprototype>
3518         <funcprototype>
3519           <funcdef>cyg_bool_t <function>cyg_mbox_tryput</function></funcdef>
3520           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3521           <paramdef>void* <parameter>item</parameter></paramdef>
3522         </funcprototype>
3523         <funcprototype>
3524           <funcdef>cyg_bool_t <function>cyg_mbox_waiting_to_get</function></funcdef>
3525           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3526         </funcprototype>
3527         <funcprototype>
3528           <funcdef>cyg_bool_t <function>cyg_mbox_waiting_to_put</function></funcdef>
3529           <paramdef>cyg_handle_t <parameter>mbox</parameter></paramdef>
3530         </funcprototype>
3531       </funcsynopsis>
3532     </refsynopsisdiv>
3533
3534     <refsect1 id="kernel-mail-boxes-description"><title>Description</title>
3535       <para>
3536 Mail boxes are a synchronization primitive. Like semaphores they
3537 can be used by a consumer thread to wait until a certain event has
3538 occurred, but the producer also has the ability to transmit some data
3539 along with each event. This data, the message, is normally a pointer
3540 to some data structure. It is stored in the mail box itself, so the
3541 producer thread that generates the event and provides the data usually
3542 does not have to block until some consumer thread is ready to receive
3543 the event. However a mail box will only have a finite capacity,
3544 typically ten slots. Even if the system is balanced and events are
3545 typically consumed at least as fast as they are generated, a burst of
3546 events can cause the mail box to fill up and the generating thread
3547 will block until space is available again. This behaviour is very
3548 different from semaphores, where it is only necessary to maintain a
3549 counter and hence an overflow is unlikely.
3550       </para>
3551       <para>
3552 Before a mail box can be used it must be created with a call to
3553 <function>cyg_mbox_create</function>. Each mail box has a unique
3554 handle which will be returned via the first argument and which should
3555 be used for subsequent operations.
3556 <function>cyg_mbox_create</function> also requires an area of memory
3557 for the kernel structure, which is provided by the
3558 <structname>cyg_mbox</structname> second argument. If a mail box is
3559 no longer required then <function>cyg_mbox_delete</function> can be
3560 used. This will simply discard any messages that remain posted.
3561       </para>
3562       <para>
3563 The main function for waiting on a mail box is
3564 <function>cyg_mbox_get</function>. If there is a pending message
3565 because of a call to <function>cyg_mbox_put</function> then
3566 <function>cyg_mbox_get</function> will return immediately with the
3567 message that was put into the mail box. Otherwise this function
3568 will block until there is a put operation. Exceptionally the thread
3569 can instead be unblocked by a call to
3570 <function>cyg_thread_release</function>, in which case
3571 <function>cyg_mbox_get</function> will return a null pointer. It is
3572 assumed that there will never be a call to
3573 <function>cyg_mbox_put</function> with a null pointer, because it
3574 would not be possible to distinguish between that and a release
3575 operation. Messages are always retrieved in the order in which they
3576 were put into the mail box, and there is no support for messages
3577 with different priorities.
3578       </para>
3579       <para>
3580 There are two variants of <function>cyg_mbox_get</function>. The
3581 first, <function>cyg_mbox_timed_get</function> will wait until either
3582 a message is available or until a number of clock ticks have occurred.
3583 The number of ticks is specified as an absolute, not relative tick
3584 count, and so in order to wait for a relative number of ticks, the
3585 return value of the <function>cyg_current_time()</function> function
3586 should be added to determine the absolute number of ticks.  If no
3587 message is posted within the timeout then a null pointer will be
3588 returned. <function>cyg_mbox_tryget</function> is a non-blocking
3589 operation which will either return a message if one is available or a
3590 null pointer.
3591       </para>
3592       <para>
3593 New messages are placed in the mail box by calling
3594 <function>cyg_mbox_put</function> or one of its variants. The main put
3595 function takes two arguments, a handle to the mail box and a
3596 pointer for the message itself. If there is a spare slot in the
3597 mail box then the new message can be placed there immediately, and
3598 if there is a waiting thread it will be woken up so that it can
3599 receive the message. If the mail box is currently full then
3600 <function>cyg_mbox_put</function> will block until there has been a
3601 get operation and a slot is available. The
3602 <function>cyg_mbox_timed_put</function> variant imposes a time limit
3603 on the put operation, returning false if the operation cannot be
3604 completed within the specified number of clock ticks and as for
3605 <function>cyg_mbox_timed_get</function> this is an absolute tick
3606 count. The <function>cyg_mbox_tryput</function> variant is
3607 non-blocking, returning false if there are no free slots available and
3608 the message cannot be posted without blocking.
3609       </para>
3610       <para>
3611 There are a further four functions available for examining the current
3612 state of a mailbox. The results of these functions must be used with
3613 care because usually the state can change at any time as a result of
3614 activity within other threads, but they may prove occasionally useful
3615 during debugging or in special situations.
3616 <function>cyg_mbox_peek</function> returns a count of the number of
3617 messages currently stored in the mail box.
3618 <function>cyg_mbox_peek_item</function> retrieves the first message,
3619 but it remains in the mail box until a get operation is performed.
3620 <function>cyg_mbox_waiting_to_get</function> and
3621 <function>cyg_mbox_waiting_to_put</function> indicate whether or not
3622 there are currently threads blocked in a get or a put operation on a
3623 given mail box.
3624       </para>
3625       <para>
3626 The number of slots in each mail box is controlled by a
3627 configuration option
3628 <varname>CYGNUM_KERNEL_SYNCH_MBOX_QUEUE_SIZE</varname>, with a default
3629 value of 10. All mail boxes are the same size.
3630       </para>
3631     </refsect1>
3632
3633     <refsect1 id="kernel-mail-boxes-context"><title>Valid contexts</title>
3634       <para>
3635 <function>cyg_mbox_create</function> is typically called during
3636 system initialization but may also be called in thread context.
3637 The remaining functions are normally called only during thread
3638 context. Of special note is <function>cyg_mbox_put</function> which
3639 can be a blocking operation when the mail box is full, and which
3640 therefore must never be called from DSR context. It is permitted to
3641 call <function>cyg_mbox_tryput</function>,
3642 <function>cyg_mbox_tryget</function>, and the information functions
3643 from DSR context but this is rarely useful.
3644       </para>
3645     </refsect1>
3646
3647   </refentry>
3648
3649 <!-- }}} -->
3650 <!-- {{{ Flags                          -->
3651
3652   <refentry id="kernel-flags">
3653
3654     <refmeta>
3655     <refentrytitle>Event Flags</refentrytitle>
3656     </refmeta>
3657
3658     <refnamediv>
3659       <refname>cyg_flag_init</refname>
3660       <refname>cyg_flag_destroy</refname>
3661       <refname>cyg_flag_setbits</refname>
3662       <refname>cyg_flag_maskbits</refname>
3663       <refname>cyg_flag_wait</refname>
3664       <refname>cyg_flag_timed_wait</refname>
3665       <refname>cyg_flag_poll</refname>
3666       <refname>cyg_flag_peek</refname>
3667       <refname>cyg_flag_waiting</refname>
3668       <refpurpose>Synchronization primitive</refpurpose>
3669     </refnamediv>
3670
3671     <refsynopsisdiv>
3672       <funcsynopsis>
3673         <funcsynopsisinfo>
3674 #include &lt;cyg/kernel/kapi.h&gt;
3675         </funcsynopsisinfo>
3676         <funcprototype>
3677           <funcdef>void <function>cyg_flag_init</function></funcdef>
3678           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3679         </funcprototype>
3680         <funcprototype>
3681           <funcdef>void <function>cyg_flag_destroy</function></funcdef>
3682           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3683         </funcprototype>
3684         <funcprototype>
3685           <funcdef>void <function>cyg_flag_setbits</function></funcdef>
3686           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3687           <paramdef>cyg_flag_value_t <parameter>value</parameter></paramdef>
3688         </funcprototype>
3689         <funcprototype>
3690           <funcdef>void <function>cyg_flag_maskbits</function></funcdef>
3691           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3692           <paramdef>cyg_flag_value_t <parameter>value</parameter></paramdef>
3693         </funcprototype>
3694         <funcprototype>
3695           <funcdef>cyg_flag_value_t <function>cyg_flag_wait</function></funcdef>
3696           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3697           <paramdef>cyg_flag_value_t <parameter>pattern</parameter></paramdef>
3698           <paramdef>cyg_flag_mode_t <parameter>mode</parameter></paramdef>
3699         </funcprototype>
3700         <funcprototype>
3701           <funcdef>cyg_flag_value_t <function>cyg_flag_timed_wait</function></funcdef>
3702           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3703           <paramdef>cyg_flag_value_t <parameter>pattern</parameter></paramdef>
3704           <paramdef>cyg_flag_mode_t <parameter>mode</parameter></paramdef>
3705           <paramdef>cyg_tick_count_t <parameter>abstime</parameter></paramdef>
3706         </funcprototype>
3707         <funcprototype>
3708           <funcdef>cyg_flag_value_t <function>cyg_flag_poll</function></funcdef>
3709           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3710           <paramdef>cyg_flag_value_t <parameter>pattern</parameter></paramdef>
3711           <paramdef>cyg_flag_mode_t <parameter>mode</parameter></paramdef>
3712         </funcprototype>
3713         <funcprototype>
3714           <funcdef>cyg_flag_value_t <function>cyg_flag_peek</function></funcdef>
3715           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3716         </funcprototype>
3717         <funcprototype>
3718           <funcdef>cyg_bool_t <function>cyg_flag_waiting</function></funcdef>
3719           <paramdef>cyg_flag_t* <parameter>flag</parameter></paramdef>
3720         </funcprototype>
3721       </funcsynopsis>
3722     </refsynopsisdiv>
3723
3724     <refsect1 id="kernel-flags-description"><title>Description</title>
3725       <para>
3726 Event flags allow a consumer thread to wait for one of several
3727 different types of event to occur. Alternatively it is possible to
3728 wait for some combination of events. The implementation is relatively
3729 straightforward. Each event flag contains a 32-bit integer.
3730 Application code associates these bits with specific events, so for
3731 example bit 0 could indicate that an I/O operation has completed and
3732 data is available, while bit 1 could indicate that the user has
3733 pressed a start button. A producer thread or a DSR can cause one or
3734 more of the bits to be set, and a consumer thread currently waiting
3735 for these bits will be woken up.
3736       </para>
3737       <para>
3738 Unlike semaphores no attempt is made to keep track of event counts. It
3739 does not matter whether a given event occurs once or multiple times
3740 before being consumed, the corresponding bit in the event flag will
3741 change only once. However semaphores cannot easily be used to handle
3742 multiple event sources. Event flags can often be used as an
3743 alternative to condition variables, although they cannot be used for
3744 completely arbitrary conditions and they only support the equivalent
3745 of condition variable broadcasts, not signals.
3746       </para>
3747       <para>
3748 Before an event flag can be used it must be initialized by a call to
3749 <function>cyg_flag_init</function>. This takes a pointer to a
3750 <structname>cyg_flag_t</structname> data structure, which can be part of a
3751 larger structure. All 32 bits in the event flag will be set to 0,
3752 indicating that no events have yet occurred. If an event flag is no
3753 longer required it can be cleaned up with a call to
3754 <function>cyg_flag_destroy</function>, allowing the memory for the
3755 <structfield>cyg_flag_t</structfield> structure to be re-used.
3756       </para>
3757       <para>
3758 A consumer thread can wait for one or more events by calling
3759 <function>cyg_flag_wait</function>. This takes three arguments. The
3760 first identifies a particular event flag. The second is some
3761 combination of bits, indicating which events are of interest. The
3762 final argument should be one of the following:
3763       </para>
3764       <variablelist>
3765         <varlistentry>
3766           <term><literal>CYG_FLAG_WAITMODE_AND</literal></term>
3767           <listitem><para>
3768 The call to <function>cyg_flag_wait</function> will block until all
3769 the specified event bits are set. The event flag is not cleared when
3770 the wait succeeds, in other words all the bits remain set.
3771           </para></listitem>
3772         </varlistentry>
3773         <varlistentry>
3774           <term><literal>CYG_FLAG_WAITMODE_OR</literal></term>
3775           <listitem><para>
3776 The call will block until at least one of the specified event bits is
3777 set. The event flag is not cleared on return.
3778           </para></listitem>
3779         </varlistentry>
3780         <varlistentry>
3781           <term><literal>CYG_FLAG_WAITMODE_AND | CYG_FLAG_WAITMODE_CLR</literal></term>
3782           <listitem><para>
3783 The call will block until all the specified event bits are set, and
3784 the entire event flag is cleared when the call succeeds. Note that
3785 if this mode of operation is used then a single event flag cannot be
3786 used to store disjoint sets of events, even though enough bits might
3787 be available. Instead each disjoint set of events requires its own
3788 event flag.
3789           </para></listitem>
3790         </varlistentry>
3791         <varlistentry>
3792           <term><literal>CYG_FLAG_WAITMODE_OR | CYG_FLAG_WAITMODE_CLR</literal></term>
3793           <listitem><para>
3794 The call will block until at least one of the specified event bits is
3795 set, and the entire flag is cleared when the call succeeds.
3796           </para></listitem>
3797         </varlistentry>
3798       </variablelist>
3799       <para>
3800 A call to <function>cyg_flag_wait</function> normally blocks until the
3801 required condition is satisfied. It will return the value of the event
3802 flag at the point that the operation succeeded, which may be a
3803 superset of the requested events. If
3804 <function>cyg_thread_release</function> is used to unblock a thread
3805 that is currently in a wait operation, the
3806 <function>cyg_flag_wait</function> call will instead return 0.
3807       </para>
3808       <para>
3809 <function>cyg_flag_timed_wait</function> is a variant of
3810 <function>cyg_flag_wait</function> which adds a timeout: the wait
3811 operation must succeed within the specified number of ticks, or it
3812 will fail with a return value of 0. The number of ticks is specified
3813 as an absolute, not relative tick count, and so in order to wait for a
3814 relative number of ticks, the return value of the
3815 <function>cyg_current_time()</function> function should be added to
3816 determine the absolute number of ticks.
3817 <function>cyg_flag_poll</function> is a non-blocking variant: if the
3818 wait operation can succeed immediately it acts like
3819 <function>cyg_flag_wait</function>, otherwise it returns immediately
3820 with a value of 0.
3821       </para>
3822       <para>
3823 <function>cyg_flag_setbits</function> is called by a producer thread
3824 or from inside a DSR when an event occurs. The specified bits are or'd
3825 into the current event flag value. This may cause one or more waiting 
3826 threads to be woken up, if their conditions are now satisfied. How many 
3827 threads are awoken depends on the use of <literal>CYG_FLAG_WAITMODE_CLR
3828 </literal>. The queue of threads waiting on the flag is walked to find 
3829 threads which now have their wake condition fulfilled. If the awoken thread 
3830 has passed <literal>CYG_FLAG_WAITMODE_CLR</literal> the walking of the queue 
3831 is terminated, otherwise the walk continues. Thus if no threads have passed 
3832 <literal>CYG_FLAG_WAITMORE_CLR</literal> all threads with fulfilled 
3833 conditions will be awoken. If <literal>CYG_FLAG_WAITMODE_CLR</literal> is 
3834 passed by threads with fulfilled conditions, the number of awoken threads 
3835 will depend on the order the threads are in the queue.
3836       </para>
3837       <para>
3838 <function>cyg_flag_maskbits</function> can be used to clear one or
3839 more bits in the event flag. This can be called from a producer when a
3840 particular condition is no longer satisfied, for example when the user
3841 is no longer pressing a particular button. It can also be used by a
3842 consumer thread if <literal>CYG_FLAG_WAITMODE_CLR</literal> was not
3843 used as part of the wait operation, to indicate that some but not all
3844 of the active events have been consumed. If there are multiple
3845 consumer threads performing wait operations without using
3846 <function>CYG_FLAG_WAITMODE_CLR</function> then typically some
3847 additional synchronization such as a mutex is needed to prevent
3848 multiple threads consuming the same event.
3849       </para>
3850       <para>
3851 Two additional functions are provided to query the current state of an
3852 event flag. <function>cyg_flag_peek</function> returns the current
3853 value of the event flag, and <function>cyg_flag_waiting</function> can
3854 be used to find out whether or not there are any threads currently
3855 blocked on the event flag. Both of these functions must be used with
3856 care because other threads may be operating on the event flag.
3857       </para>
3858     </refsect1>
3859
3860     <refsect1 id="kernel-flags-context"><title>Valid contexts</title>
3861       <para>
3862 <function>cyg_flag_init</function> is typically called during system
3863 initialization but may also be called in thread context. The same
3864 applies to <function>cyg_flag_destroy</function>.
3865 <function>cyg_flag_wait</function> and
3866 <function>cyg_flag_timed_wait</function> may only be called from
3867 thread context. The remaining functions may be called from thread or
3868 DSR context.
3869       </para>
3870     </refsect1>
3871
3872   </refentry>
3873
3874 <!-- }}} -->
3875 <!-- {{{ Spinlocks                      -->
3876
3877   <refentry id="kernel-spinlocks">
3878
3879     <refmeta>
3880     <refentrytitle>Spinlocks</refentrytitle>
3881     </refmeta>
3882
3883     <refnamediv>
3884       <refname>cyg_spinlock_create</refname>
3885       <refname>cyg_spinlock_destroy</refname>
3886       <refname>cyg_spinlock_spin</refname>
3887       <refname>cyg_spinlock_clear</refname>
3888       <refname>cyg_spinlock_test</refname>
3889       <refname>cyg_spinlock_spin_intsave</refname>
3890       <refname>cyg_spinlock_clear_intsave</refname>
3891       <refpurpose>Low-level Synchronization Primitive</refpurpose>
3892     </refnamediv>
3893
3894     <refsynopsisdiv>
3895       <funcsynopsis>
3896         <funcsynopsisinfo>
3897 #include &lt;cyg/kernel/kapi.h&gt;
3898         </funcsynopsisinfo>
3899         <funcprototype>
3900           <funcdef>void <function>cyg_spinlock_init</function></funcdef>
3901           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3902           <paramdef>cyg_bool_t <parameter>locked</parameter></paramdef>
3903         </funcprototype>
3904         <funcprototype>
3905           <funcdef>void <function>cyg_spinlock_destroy</function></funcdef>
3906           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3907         </funcprototype>
3908         <funcprototype>
3909           <funcdef>void <function>cyg_spinlock_spin</function></funcdef>
3910           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3911         </funcprototype>
3912         <funcprototype>
3913           <funcdef>void <function>cyg_spinlock_clear</function></funcdef>
3914           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3915         </funcprototype>
3916         <funcprototype>
3917           <funcdef>cyg_bool_t <function>cyg_spinlock_try</function></funcdef>
3918           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3919         </funcprototype>
3920         <funcprototype>
3921           <funcdef>cyg_bool_t <function>cyg_spinlock_test</function></funcdef>
3922           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3923         </funcprototype>
3924         <funcprototype>
3925           <funcdef>void <function>cyg_spinlock_spin_intsave</function></funcdef>
3926           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3927           <paramdef>cyg_addrword_t* <parameter>istate</parameter></paramdef>
3928         </funcprototype>
3929         <funcprototype>
3930           <funcdef>void <function>cyg_spinlock_clear_intsave</function></funcdef>
3931           <paramdef>cyg_spinlock_t* <parameter>lock</parameter></paramdef>
3932           <paramdef>cyg_addrword_t <parameter>istate</parameter></paramdef>
3933         </funcprototype>
3934       </funcsynopsis>
3935     </refsynopsisdiv>
3936
3937     <refsect1 id="kernel-spinlocks-description"><title>Description</title>
3938       <para>
3939 Spinlocks provide an additional synchronization primitive for
3940 applications running on SMP systems. They operate at a lower level
3941 than the other primitives such as mutexes, and for most purposes the
3942 higher-level primitives should be preferred. However there are some
3943 circumstances where a spinlock is appropriate, especially when
3944 interrupt handlers and threads need to share access to hardware, and
3945 on SMP systems the kernel implementation itself depends on spinlocks.
3946       </para>
3947       <para>
3948 Essentially a spinlock is just a simple flag. When code tries to claim
3949 a spinlock it checks whether or not the flag is already set. If not
3950 then the flag is set and the operation succeeds immediately. The exact
3951 implementation of this is hardware-specific, for example it may use a
3952 test-and-set instruction to guarantee the desired behaviour even if
3953 several processors try to access the spinlock at the exact same time.
3954 If it is not possible to claim a spinlock then the current thead spins
3955 in a tight loop, repeatedly checking the flag until it is clear. This
3956 behaviour is very different from other synchronization primitives such
3957 as mutexes, where contention would cause a thread to be suspended. The
3958 assumption is that a spinlock will only be held for a very short time.
3959 If claiming a spinlock could cause the current thread to be suspended
3960 then spinlocks could not be used inside interrupt handlers, which is
3961 not acceptable.
3962       </para>
3963       <para>
3964 This does impose a constraint on any code which uses spinlocks.
3965 Specifically it is important that spinlocks are held only for a short
3966 period of time, typically just some dozens of instructions. Otherwise
3967 another processor could be blocked on the spinlock for a long time,
3968 unable to do any useful work. It is also important that a thread which
3969 owns a spinlock does not get preempted because that might cause
3970 another processor to spin for a whole timeslice period, or longer. One
3971 way of achieving this is to disable interrupts on the current
3972 processor, and the function
3973 <function>cyg_spinlock_spin_intsave</function> is provided to
3974 facilitate this.
3975       </para>
3976       <para>
3977 Spinlocks should not be used on single-processor systems. Consider a
3978 high priority thread which attempts to claim a spinlock already held
3979 by a lower priority thread: it will just loop forever and the lower
3980 priority thread will never get another chance to run and release the
3981 spinlock. Even if the two threads were running at the same priority,
3982 the one attempting to claim the spinlock would spin until it was
3983 timesliced and a lot of cpu time would be wasted. If an interrupt
3984 handler tried to claim a spinlock owned by a thread, the interrupt
3985 handler would loop forever. Therefore spinlocks are only appropriate
3986 for SMP systems where the current owner of a spinlock can continue
3987 running on a different processor.
3988       </para>
3989       <para>
3990 Before a spinlock can be used it must be initialized by a call to
3991 <function>cyg_spinlock_init</function>. This takes two arguments, a
3992 pointer to a <function>cyg_spinlock_t</function> data structure, and
3993 a flag to specify whether the spinlock starts off locked or unlocked.
3994 If a spinlock is no longer required then it can be destroyed by a call
3995 to <function>cyg_spinlock_destroy</function>.
3996       </para>
3997       <para>
3998 There are two routines for claiming a spinlock:
3999 <function>cyg_spinlock_spin</function> and
4000 <function>cyg_spinlock_spin_intsave</function>. The former can be used
4001 when it is known the current code will not be preempted, for example
4002 because it is running in an interrupt handler or because interrupts
4003 are disabled. The latter will disable interrupts in addition to
4004 claiming the spinlock, so is safe to use in all circumstances. The
4005 previous interrupt state is returned via the second argument, and
4006 should be used in a subsequent call to
4007 <function>cyg_spinlock_clear_intsave</function>. 
4008       </para>
4009       <para>
4010 Similarly there are two routines for releasing a spinlock:
4011 <function>cyg_spinlock_clear</function> and
4012 <function>cyg_spinlock_clear_intsave</function>. Typically
4013 the former will be used if the spinlock was claimed by a call to
4014 <function>cyg_spinlock_spin</function>, and the latter when
4015 <function>cyg_spinlock_intsave</function> was used.
4016       </para>
4017       <para>
4018 There are two additional routines.
4019 <function>cyg_spinlock_try</function> is a non-blocking version of
4020 <function>cyg_spinlock_spin</function>: if possible the lock will be
4021 claimed and the function will return <literal>true</literal>; otherwise the function
4022 will return immediately with failure.
4023 <function>cyg_spinlock_test</function> can be used to find out whether
4024 or not the spinlock is currently locked. This function must be used
4025 with care because, especially on a multiprocessor system, the state of
4026 the spinlock can change at any time.
4027       </para>
4028       <para>
4029 Spinlocks should only be held for a short period of time, and
4030 attempting to claim a spinlock will never cause a thread to be
4031 suspended. This means that there is no need to worry about priority
4032 inversion problems, and concepts such as priority ceilings and
4033 inheritance do not apply.
4034       </para>
4035     </refsect1>
4036
4037     <refsect1 id="kernel-spinlocks-context"><title>Valid contexts</title>
4038       <para>
4039 All of the spinlock functions can be called from any context,
4040 including ISR and DSR context. Typically
4041 <function>cyg_spinlock_init</function> is only called during system
4042 initialization. 
4043       </para>
4044     </refsect1>
4045
4046   </refentry>
4047
4048 <!-- }}} -->
4049 <!-- {{{ Scheduler control              -->
4050
4051   <refentry id="kernel-schedcontrol">
4052
4053     <refmeta>
4054     <refentrytitle>Scheduler Control</refentrytitle>
4055     </refmeta>
4056
4057     <refnamediv>
4058       <refname>cyg_scheduler_start</refname>
4059       <refname>cyg_scheduler_lock</refname>
4060       <refname>cyg_scheduler_unlock</refname>
4061       <refname>cyg_scheduler_safe_lock</refname>
4062       <refname>cyg_scheduler_read_lock</refname>
4063       <refpurpose>Control the state of the scheduler</refpurpose>
4064     </refnamediv>
4065
4066     <refsynopsisdiv>
4067       <funcsynopsis>
4068         <funcsynopsisinfo>
4069 #include &lt;cyg/kernel/kapi.h&gt;
4070         </funcsynopsisinfo>
4071         <funcprototype>
4072           <funcdef>void <function>cyg_scheduler_start</function></funcdef>
4073           <void>
4074         </funcprototype>
4075         <funcprototype>
4076           <funcdef>void <function>cyg_scheduler_lock</function></funcdef>
4077           <void>
4078         </funcprototype>
4079         <funcprototype>
4080           <funcdef>void <function>cyg_scheduler_unlock</function></funcdef>
4081           <void>
4082         </funcprototype>
4083         <funcprototype>
4084           <funcdef>cyg_ucount32 <function>cyg_scheduler_read_lock</function></funcdef>
4085           <void>
4086         </funcprototype>
4087       </funcsynopsis>
4088     </refsynopsisdiv>
4089
4090     <refsect1 id="kernel-schedcontrol-description"><title>Description</title>
4091       <para>
4092 <function>cyg_scheduler_start</function> should only be called once,
4093 to mark the end of system initialization. In typical configurations it
4094 is called automatically by the system startup, but some applications
4095 may bypass the standard startup in which case
4096 <function>cyg_scheduler_start</function> will have to be called
4097 explicitly. The call will enable system interrupts, allowing I/O
4098 operations to commence. Then the scheduler will be invoked and control
4099 will be transferred to the highest priority runnable thread. The call
4100 will never return.
4101       </para>
4102       <para>
4103 The various data structures inside the eCos kernel must be protected
4104 against concurrent updates. Consider a call to
4105 <function>cyg_semaphore_post</function> which causes a thread to be
4106 woken up: the semaphore data structure must be updated to remove the
4107 thread from its queue; the scheduler data structure must also be
4108 updated to mark the thread as runnable; it is possible that the newly
4109 runnable thread has a higher priority than the current one, in which
4110 case preemption is required. If in the middle of the semaphore post
4111 call an interrupt occurred and the interrupt handler tried to
4112 manipulate the same data structures, for example by making another
4113 thread runnable, then it is likely that the structures will be left in
4114 an inconsistent state and the system will fail.
4115       </para>
4116       <para>
4117 To prevent such problems the kernel contains a special lock known as
4118 the scheduler lock. A typical kernel function such as
4119 <function>cyg_semaphore_post</function> will claim the scheduler lock,
4120 do all its manipulation of kernel data structures, and then release
4121 the scheduler lock. The current thread cannot be preempted while it
4122 holds the scheduler lock. If an interrupt occurs and a DSR is supposed
4123 to run to signal that some event has occurred, that DSR is postponed
4124 until the scheduler unlock operation. This prevents concurrent updates
4125 of kernel data structures.
4126       </para>
4127       <para>
4128 The kernel exports three routines for manipulating the scheduler lock.
4129 <function>cyg_scheduler_lock</function> can be called to claim the
4130 lock. On return it is guaranteed that the current thread will not be
4131 preempted, and that no other code is manipulating any kernel data
4132 structures. <function>cyg_scheduler_unlock</function> can be used to
4133 release the lock, which may cause the current thread to be preempted.
4134 <function>cyg_scheduler_read_lock</function> can be used to query the
4135 current state of the scheduler lock. This function should never be
4136 needed because well-written code should always know whether or not the
4137 scheduler is currently locked, but may prove useful during debugging.
4138       </para>
4139       <para>
4140 The implementation of the scheduler lock involves a simple counter.
4141 Code can call <function>cyg_scheduler_lock</function> multiple times,
4142 causing the counter to be incremented each time, as long as
4143 <function>cyg_scheduler_unlock</function> is called the same number of
4144 times. This behaviour is different from mutexes where an attempt by a
4145 thread to lock a mutex multiple times will result in deadlock or an
4146 assertion failure.
4147       </para>
4148       <para>
4149 Typical application code should not use the scheduler lock. Instead
4150 other synchronization primitives such as mutexes and semaphores should
4151 be used. While the scheduler is locked the current thread cannot be
4152 preempted, so any higher priority threads will not be able to run.
4153 Also no DSRs can run, so device drivers may not be able to service
4154 I/O requests. However there is one situation where locking the
4155 scheduler is appropriate: if some data structure needs to be shared
4156 between an application thread and a DSR associated with some interrupt
4157 source, the thread can use the scheduler lock to prevent concurrent
4158 invocations of the DSR and then safely manipulate the structure. It is
4159 desirable that the scheduler lock is held for only a short period of
4160 time, typically some tens of instructions. In exceptional cases there
4161 may also be some performance-critical code where it is more
4162 appropriate to use the scheduler lock rather than a mutex, because the
4163 former is more efficient.
4164       </para>
4165     </refsect1>
4166
4167     <refsect1 id="kernel-schedcontrol-context"><title>Valid contexts</title>
4168       <para>
4169 <function>cyg_scheduler_start</function> can only be called during
4170 system initialization, since it marks the end of that phase. The
4171 remaining functions may be called from thread or DSR context. Locking
4172 the scheduler from inside the DSR has no practical effect because the
4173 lock is claimed automatically by the interrupt subsystem before
4174 running DSRs, but allows functions to be shared between normal thread
4175 code and DSRs.
4176       </para>
4177     </refsect1>
4178
4179   </refentry>
4180
4181 <!-- }}} -->
4182 <!-- {{{ Interrupt handling             -->
4183
4184   <refentry id="kernel-interrupts">
4185
4186     <refmeta>
4187     <refentrytitle>Interrupt Handling</refentrytitle>
4188     </refmeta>
4189
4190     <refnamediv>
4191       <refname>cyg_interrupt_create</refname>
4192       <refname>cyg_interrupt_delete</refname>
4193       <refname>cyg_interrupt_attach</refname>
4194       <refname>cyg_interrupt_detach</refname>
4195       <refname>cyg_interrupt_configure</refname>
4196       <refname>cyg_interrupt_acknowledge</refname>
4197       <refname>cyg_interrupt_enable</refname>
4198       <refname>cyg_interrupt_disable</refname>
4199       <refname>cyg_interrupt_mask</refname>
4200       <refname>cyg_interrupt_mask_intunsafe</refname>
4201       <refname>cyg_interrupt_unmask</refname>
4202       <refname>cyg_interrupt_unmask_intunsafe</refname>
4203       <refname>cyg_interrupt_set_cpu</refname>
4204       <refname>cyg_interrupt_get_cpu</refname>
4205       <refname>cyg_interrupt_get_vsr</refname>
4206       <refname>cyg_interrupt_set_vsr</refname>
4207       <refpurpose>Manage interrupt handlers</refpurpose>
4208     </refnamediv>
4209
4210     <refsynopsisdiv>
4211       <funcsynopsis>
4212         <funcsynopsisinfo>
4213 #include &lt;cyg/kernel/kapi.h&gt;
4214         </funcsynopsisinfo>
4215         <funcprototype>
4216           <funcdef>void <function>cyg_interrupt_create</function></funcdef>
4217           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4218           <paramdef>cyg_priority_t <parameter>priority</parameter></paramdef>
4219           <paramdef>cyg_addrword_t <parameter>data</parameter></paramdef>
4220           <paramdef>cyg_ISR_t* <parameter>isr</parameter></paramdef>
4221           <paramdef>cyg_DSR_t* <parameter>dsr</parameter></paramdef>
4222           <paramdef>cyg_handle_t* <parameter>handle</parameter></paramdef>
4223           <paramdef>cyg_interrupt* <parameter>intr</parameter></paramdef>
4224         </funcprototype>
4225         <funcprototype>
4226           <funcdef>void <function>cyg_interrupt_delete</function></funcdef>
4227           <paramdef>cyg_handle_t <parameter>interrupt</parameter></paramdef>
4228         </funcprototype>
4229         <funcprototype>
4230           <funcdef>void <function>cyg_interrupt_attach</function></funcdef>
4231           <paramdef>cyg_handle_t <parameter>interrupt</parameter></paramdef>
4232         </funcprototype>
4233         <funcprototype>
4234           <funcdef>void <function>cyg_interrupt_detach</function></funcdef>
4235           <paramdef>cyg_handle_t <parameter>interrupt</parameter></paramdef>
4236         </funcprototype>
4237         <funcprototype>
4238           <funcdef>void <function>cyg_interrupt_configure</function></funcdef>
4239           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4240           <paramdef>cyg_bool_t <parameter>level</parameter></paramdef>
4241           <paramdef>cyg_bool_t <parameter>up</parameter></paramdef>
4242         </funcprototype>
4243         <funcprototype>
4244           <funcdef>void <function>cyg_interrupt_acknowledge</function></funcdef>
4245           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4246         </funcprototype>
4247         <funcprototype>
4248           <funcdef>void <function>cyg_interrupt_disable</function></funcdef>
4249           <void>
4250         </funcprototype>
4251         <funcprototype>
4252           <funcdef>void <function>cyg_interrupt_enable</function></funcdef>
4253           <void>
4254         </funcprototype>
4255         <funcprototype>
4256           <funcdef>void <function>cyg_interrupt_mask</function></funcdef>
4257           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4258         </funcprototype>
4259         <funcprototype>
4260           <funcdef>void <function>cyg_interrupt_mask_intunsafe</function></funcdef>
4261           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4262         </funcprototype>
4263         <funcprototype>
4264           <funcdef>void <function>cyg_interrupt_unmask</function></funcdef>
4265           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4266         </funcprototype>
4267         <funcprototype>
4268           <funcdef>void <function>cyg_interrupt_unmask_intunsafe</function></funcdef>
4269           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4270         </funcprototype>
4271         <funcprototype>
4272           <funcdef>void <function>cyg_interrupt_set_cpu</function></funcdef>
4273           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4274           <paramdef>cyg_cpu_t <parameter>cpu</parameter></paramdef>
4275         </funcprototype>
4276         <funcprototype>
4277           <funcdef>cyg_cpu_t <function>cyg_interrupt_get_cpu</function></funcdef>
4278           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4279         </funcprototype>
4280         <funcprototype>
4281           <funcdef>void <function>cyg_interrupt_get_vsr</function></funcdef>
4282           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4283           <paramdef>cyg_VSR_t** <parameter>vsr</parameter></paramdef>
4284         </funcprototype>
4285         <funcprototype>
4286           <funcdef>void <function>cyg_interrupt_set_vsr</function></funcdef>
4287           <paramdef>cyg_vector_t <parameter>vector</parameter></paramdef>
4288           <paramdef>cyg_VSR_t* <parameter>vsr</parameter></paramdef>
4289         </funcprototype>
4290       </funcsynopsis>
4291     </refsynopsisdiv>
4292
4293     <refsect1 id="kernel-interrupts-description"><title>Description</title>
4294       <para>
4295 The kernel provides an interface for installing interrupt handlers and
4296 controlling when interrupts occur. This functionality is used
4297 primarily by eCos device drivers and by any application code that
4298 interacts directly with hardware. However in most cases it is better
4299 to avoid using this kernel functionality directly, and instead the
4300 device driver API provided by the common HAL package should be used.
4301 Use of the kernel package is optional, and some applications such as
4302 RedBoot work with no need for multiple threads or synchronization
4303 primitives. Any code which calls the kernel directly rather than the
4304 device driver API will not function in such a configuration. When the
4305 kernel package is present the device driver API is implemented as
4306 <literal>#define</literal>'s to the equivalent kernel calls, otherwise
4307 it is implemented inside the common HAL package. The latter
4308 implementation can be simpler than the kernel one because there is no
4309 need to consider thread preemption and similar issues.
4310       </para>
4311       <para>
4312 The exact details of interrupt handling vary widely between
4313 architectures. The functionality provided by the kernel abstracts away
4314 from many of the details of the underlying hardware, thus simplifying
4315 application development. However this is not always successful. For
4316 example, if some hardware does not provide any support at all for
4317 masking specific interrupts then calling
4318 <function>cyg_interrupt_mask</function> may not behave as intended:
4319 instead of masking just the one interrupt source it might disable all
4320 interrupts, because that is as close to the desired behaviour as is
4321 possible given the hardware restrictions. Another possibility is that
4322 masking a given interrupt source also affects all lower-priority
4323 interrupts, but still allows higher-priority ones. The documentation
4324 for the appropriate HAL packages should be consulted for more
4325 information about exactly how interrupts are handled on any given
4326 hardware. The HAL header files will also contain useful information. 
4327       </para>
4328     </refsect1>
4329
4330     <refsect1 id="kernel-interrupts-handlers"><title>Interrupt Handlers</title>
4331       <para>
4332 Interrupt handlers are created by a call to
4333 <function>cyg_interrupt_create</function>. This takes the following
4334 arguments: 
4335       </para>
4336       <variablelist>
4337         <varlistentry>
4338           <term>cyg_vector_t <parameter>vector</parameter></term>
4339           <listitem><para>
4340 The interrupt vector, a small integer, identifies the specific
4341 interrupt source. The appropriate hardware documentation or HAL header
4342 files should be consulted for details of which vector corresponds to
4343 which device.
4344           </para></listitem>
4345         </varlistentry>
4346         <varlistentry>
4347           <term>cyg_priority_t <parameter>priority</parameter></term>
4348           <listitem><para>
4349 Some hardware may support interrupt priorities, where a low priority
4350 interrupt handler can in turn be interrupted by a higher priority one.
4351 Again hardware-specific documentation should be consulted for details
4352 about what the valid interrupt priority levels are.
4353           </para></listitem>
4354         </varlistentry>
4355         <varlistentry>
4356           <term>cyg_addrword_t <parameter>data</parameter></term>
4357           <listitem><para>
4358 When an interrupt occurs eCos will first call the associated
4359 interrupt service routine or ISR, then optionally a deferred service
4360 routine or DSR. The <parameter>data</parameter> argument to
4361 <function>cyg_interrupt_create</function> will be passed to both these
4362 functions. Typically it will be a pointer to some data structure.
4363           </para></listitem>
4364         </varlistentry>
4365         <varlistentry>
4366           <term>cyg_ISR_t <parameter>isr</parameter></term>
4367           <listitem><para>
4368 When an interrupt occurs the hardware will transfer control to the
4369 appropriate vector service routine or VSR, which is usually provided
4370 by eCos. This performs any appropriate processing, for example to work
4371 out exactly which interrupt occurred, and then as quickly as possible
4372 transfers control the installed ISR. An ISR is a C function which
4373 takes the following form:
4374           </para>
4375           <programlisting width=72>
4376 cyg_uint32
4377 isr_function(cyg_vector_t vector, cyg_addrword_t data)
4378 {
4379     cyg_bool_t dsr_required = 0;
4380
4381     &hellip;
4382
4383     return dsr_required ?
4384         (CYG_ISR_CALL_DSR | CYG_ISR_HANDLED) :
4385         CYG_ISR_HANDLED;
4386 }
4387           </programlisting>
4388           <para>
4389 The first argument identifies the particular interrupt source,
4390 especially useful if there multiple instances of a given device and a
4391 single ISR can be used for several different interrupt vectors. The
4392 second argument is the <parameter>data</parameter> field passed to
4393 <function>cyg_interrupt_create</function>, usually a pointer to some
4394 data structure. The exact conditions under which an ISR runs will
4395 depend partly on the hardware and partly on configuration options.
4396 Interrupts may currently be disabled globally, especially if the
4397 hardware does not support interrupt priorities. Alternatively
4398 interrupts may be enabled such that higher priority interrupts are
4399 allowed through. The ISR may be running on a separate interrupt stack,
4400 or on the stack of whichever thread was running at the time the
4401 interrupt happened.
4402           </para>
4403           <para>
4404 A typical ISR will do as little work as possible, just enough to meet
4405 the needs of the hardware and then acknowledge the interrupt by
4406 calling <function>cyg_interrupt_acknowledge</function>. This ensures
4407 that interrupts will be quickly reenabled, so higher priority devices
4408 can be serviced. For some applications there may be one device which
4409 is especially important and whose ISR can take much longer than
4410 normal. However eCos device drivers usually will not assume that they
4411 are especially important, so their ISRs will be as short as possible.
4412           </para>
4413           <para>
4414 The return value of an ISR is normally a bit mask containing zero, one
4415 or both of the following bits: <literal>CYG_ISR_CALL_DSR</literal> or
4416 <literal>CYG_ISR_HANDLED</literal>. The former indicates that further
4417 processing is required at DSR level, and the interrupt handler's DSR
4418 will be run as soon as possible. The latter indicates that the
4419 interrupt was handled by this ISR so there is no need to call other
4420 interrupt handlers which might be chained on this interrupt vector. If
4421 this ISR did not handle the interrupt it should not set the
4422 CYG_ISR_HANDLED bit so that other chained interrupt handlers may
4423 handle the interrupt.
4424           </para>
4425           <para>
4426 An ISR is allowed to make very few kernel calls. It can manipulate the
4427 interrupt mask, and on SMP systems it can use spinlocks. However an
4428 ISR must not make higher-level kernel calls such as posting to a
4429 semaphore, instead any such calls must be made from the DSR. This
4430 avoids having to disable interrupts throughout the kernel and thus
4431 improves interrupt latency.
4432           </para></listitem>
4433         </varlistentry>
4434         <varlistentry>
4435           <term>cyg_DSR_t <parameter>dsr</parameter></term>
4436           <listitem><para>
4437 If an interrupt has occurred and the ISR has returned a value
4438 with <literal>CYG_ISR_CALL_DSR</literal> bit being set, the system
4439 will call the DSR associated with this interrupt
4440 handler. If the scheduler is not currently locked then the DSR will
4441 run immediately. However if the interrupted thread was in the middle
4442 of a kernel call and had locked the scheduler, then the DSR will be
4443 deferred until the scheduler is again unlocked. This allows the
4444 DSR to make certain kernel calls safely, for example posting to a
4445 semaphore or signalling a condition variable. A DSR is a C function
4446 which takes the following form:
4447           </para>
4448           <programlisting width=72>
4449 void
4450 dsr_function(cyg_vector_t vector,
4451              cyg_ucount32 count,
4452              cyg_addrword_t data)
4453 {
4454 }
4455           </programlisting>
4456           <para>
4457 The first argument identifies the specific interrupt that has caused
4458 the DSR to run. The second argument indicates the number of these
4459 interrupts that have occurred and for which the ISR requested a DSR.
4460 Usually this will be <literal>1</literal>, unless the system is
4461 suffering from a very heavy load. The third argument is the
4462 <parameter>data</parameter> field passed to
4463 <function>cyg_interrupt_create</function>. 
4464           </para></listitem>
4465         </varlistentry>
4466         <varlistentry>
4467           <term>cyg_handle_t* <parameter>handle</parameter></term>
4468           <listitem><para>
4469 The kernel will return a handle to the newly created interrupt handler
4470 via this argument. Subsequent operations on the interrupt handler such
4471 as attaching it to the interrupt source will use this handle.
4472           </para></listitem>
4473         </varlistentry>
4474         <varlistentry>
4475           <term>cyg_interrupt* <parameter>intr</parameter></term>
4476           <listitem><para>
4477 This provides the kernel with an area of memory for holding this
4478 interrupt handler and associated data.
4479           </para></listitem>
4480         </varlistentry>
4481       </variablelist>
4482       <para>
4483 The call to <function>cyg_interrupt_create</function> simply fills in
4484 a kernel data structure. A typical next step is to call
4485 <function>cyg_interrupt_attach</function> using the handle returned by
4486 the create operation. This makes it possible to have several different
4487 interrupt handlers for a given vector, attaching whichever one is
4488 currently appropriate. Replacing an interrupt handler requires a call
4489 to <function>cyg_interrupt_detach</function>, followed by another call
4490 to <function>cyg_interrupt_attach</function> for the replacement
4491 handler. <function>cyg_interrupt_delete</function> can be used if an
4492 interrupt handler is no longer required.
4493       </para>
4494       <para>
4495 Some hardware may allow for further control over specific interrupts,
4496 for example whether an interrupt is level or edge triggered. Any such
4497 hardware functionality can be accessed using
4498 <function>cyg_interrupt_configure</function>: the
4499 <parameter>level</parameter> argument selects between level versus
4500 edge triggered; the <parameter>up</parameter> argument selects between
4501 high and low level, or between rising and falling edges.
4502       </para>
4503       <para>
4504 Usually interrupt handlers are created, attached and configured during
4505 system initialization, while global interrupts are still disabled. On
4506 most hardware it will also be necessary to call
4507 <function>cyg_interrupt_unmask</function>, since the sensible default
4508 for interrupt masking is to ignore any interrupts for which no handler
4509 is installed.
4510       </para>
4511     </refsect1>
4512
4513     <refsect1 id="kernel-interrupts-enable"><title>Controlling Interrupts</title>
4514       <para>
4515 eCos provides two ways of controlling whether or not interrupts
4516 happen. It is possible to disable and reenable all interrupts
4517 globally, using <function>cyg_interrupt_disable</function> and
4518 <function>cyg_interrupt_enable</function>. Typically this works by
4519 manipulating state inside the cpu itself, for example setting a flag
4520 in a status register or executing special instructions. Alternatively
4521 it may be possible to mask a specific interrupt source by writing to
4522 one or to several interrupt mask registers. Hardware-specific
4523 documentation should be consulted for the exact details of how
4524 interrupt masking works, because a full implementation is not possible
4525 on all hardware.
4526       </para>
4527       <para>
4528 The primary use for these functions is to allow data to be shared
4529 between ISRs and other code such as DSRs or threads. If both a thread
4530 and an ISR need to manipulate either a data structure or the hardware
4531 itself, there is a possible conflict if an interrupt happens just when
4532 the thread is doing such manipulation. Problems can be avoided by the
4533 thread either disabling or masking interrupts during the critical
4534 region. If this critical region requires only a few instructions then
4535 usually it is more efficient to disable interrupts. For larger
4536 critical regions it may be more appropriate to use interrupt masking,
4537 allowing other interrupts to occur. There are other uses for interrupt
4538 masking. For example if a device is not currently being used by the
4539 application then it may be desirable to mask all interrupts generated
4540 by that device.
4541       </para>
4542       <para>
4543 There are two functions for masking a specific interrupt source,
4544 <function>cyg_interrupt_mask</function> and
4545 <function>cyg_interrupt_mask_intunsafe</function>. On typical hardware
4546 masking an interrupt is not an atomic operation, so if two threads
4547 were to perform interrupt masking operations at the same time there
4548 could be problems. <function>cyg_interrupt_mask</function> disables
4549 all interrupts while it manipulates the interrupt mask. In situations
4550 where interrupts are already know to be disabled,
4551 <function>cyg_interrupt_mask_intunsafe</function> can be used
4552 instead. There are matching functions
4553 <function>cyg_interrupt_unmask</function> and
4554 <function>cyg_interrupt_unmask_intsafe</function>.
4555       </para>
4556     </refsect1>
4557
4558     <refsect1 id="kernel-interrupts-smp"><title>SMP Support</title>
4559       <para>
4560 On SMP systems the kernel provides an additional two functions related
4561 to interrupt handling. <function>cyg_interrupt_set_cpu</function>
4562 specifies that a particular hardware interrupt should always be
4563 handled on one specific processor in the system. In other words when
4564 the interrupt triggers it is only that processor which detects it, and
4565 it is only on that processor that the VSR and ISR will run. If a DSR
4566 is requested then it will also run on the same CPU. The
4567 function <function>cyg_interrupt_get_cpu</function> can be used to
4568 find out which interrupts are handled on which processor. 
4569       </para>
4570     </refsect1>
4571
4572     <refsect1 id="kernel-interrupts-vsr"><title>VSR Support</title>
4573       <para>
4574 When an interrupt occurs the hardware will transfer control to a piece
4575 of code known as the VSR, or Vector Service Routine. By default this
4576 code is provided by eCos. Usually it is written in assembler, but on
4577 some architectures it may be possible to implement VSRs in C by
4578 specifying an interrupt attribute. Compiler documentation should be
4579 consulted for more information on this. The default eCos VSR will work
4580 out which ISR function should process the interrupt, and set up a C
4581 environment suitable for this ISR.
4582       </para>
4583       <para>
4584 For some applications it may be desirable to replace the default eCos
4585 VSR and handle some interrupts directly. This minimizes interrupt
4586 latency, but it requires application developers to program at a lower
4587 level. Usually the best way to write a custom VSR is to copy the
4588 existing one supplied by eCos and then make appropriate modifications.
4589 The function <function>cyg_interrupt_get_vsr</function> can be used to
4590 get hold of the current VSR for a given interrupt vector, allowing it
4591 to be restored if the custom VSR is no longer required.
4592 <function>cyg_interrupt_set_vsr</function> can be used to install a
4593 replacement VSR. Usually the <parameter>vsr</parameter> argument will
4594 correspond to an exported label in an assembler source file.
4595       </para>
4596     </refsect1>
4597
4598     <refsect1 id="kernel-interrupts-context"><title>Valid contexts</title>
4599       <para>
4600 In a typical configuration interrupt handlers are created and attached
4601 during system initialization, and never detached or deleted. However
4602 it is possible to perform these operations at thread level, if
4603 desired. Similarly <function>cyg_interrupt_configure</function>,
4604 <function>cyg_interrupt_set_vsr</function>, and
4605 <function>cyg_interrupt_set_cpu</function> are usually called only
4606 during system initialization, but on typical hardware may be called at
4607 any time. <function>cyg_interrupt_get_vsr</function> and
4608 <function>cyg_interrupt_get_cpu</function> may be called at any time.
4609       </para>
4610       <para>
4611 The functions for enabling, disabling, masking and unmasking
4612 interrupts can be called in any context, when appropriate. It is the
4613 responsibility of application developers to determine when the use of
4614 these functions is appropriate.
4615       </para>
4616     </refsect1>
4617
4618   </refentry>
4619
4620 <!-- }}} -->
4621 <!-- {{{ tm_basic                       -->
4622
4623   <refentry id="kernel-characterization">
4624
4625     <refmeta>
4626     <refentrytitle>Kernel Real-time Characterization</refentrytitle>
4627     </refmeta>
4628     <refnamediv>
4629       <refname>tm_basic</refname>
4630       <refpurpose>Measure the performance of the eCos kernel</refpurpose>
4631     </refnamediv>
4632
4633     <refsect1 id="kernel-characterization-description">
4634       <title>Description</title>
4635         <para>
4636 When building a real-time system, care must be taken to ensure that
4637 the system will be able to perform properly within the constraints of
4638 that system. One of these constraints may be how fast certain
4639 operations can be performed. Another might be how deterministic the
4640 overall behavior of the system is. Lastly the memory footprint (size)
4641 and unit cost may be important.
4642         </para>
4643         <para>
4644 One of the major problems encountered while evaluating a system will
4645 be how to compare it with possible alternatives. Most manufacturers of
4646 real-time systems publish performance numbers, ostensibly so that
4647 users can compare the different offerings. However, what these numbers
4648 mean and how they were gathered is often not clear. The values are
4649 typically measured on a particular piece of hardware, so in order to
4650 truly compare, one must obtain measurements for exactly the same set
4651 of hardware that were gathered in a similar fashion.
4652         </para>
4653         <para>
4654 Two major items need to be present in any given set of measurements.
4655 First, the raw values for the various operations; these are typically
4656 quite easy to measure and will be available for most systems. Second,
4657 the determinacy of the numbers; in other words how much the value
4658 might change depending on other factors within the system. This value
4659 is affected by a number of factors: how long interrupts might be
4660 masked, whether or not the function can be interrupted, even very
4661 hardware-specific effects such as cache locality and pipeline usage.
4662 It is very difficult to measure the determinacy of any given
4663 operation, but that determinacy is fundamentally important to proper
4664 overall characterization of a system.
4665         </para>
4666         <para>
4667 In the discussion and numbers that follow, three key measurements are
4668 provided. The first measurement is an estimate of the interrupt
4669 latency: this is the length of time from when a hardware interrupt
4670 occurs until its Interrupt Service Routine (ISR) is called. The second
4671 measurement is an estimate of overall interrupt overhead: this is the
4672 length of time average interrupt processing takes, as measured by the
4673 real-time clock interrupt (other interrupt sources will certainly take
4674 a different amount of time, but this data cannot be easily gathered).
4675 The third measurement consists of the timings for the various kernel
4676 primitives.
4677           </para>
4678         </refsect1>
4679         <refsect1 id="kernel-characterization-methodology">
4680           <title>Methodology</title>
4681           <para>
4682 Key operations in the kernel were measured by using a simple test
4683 program which exercises the various kernel primitive operations. A
4684 hardware timer, normally the one used to drive the real-time clock,
4685 was used for these measurements. In most cases this timer can be read
4686 with quite high resolution, typically in the range of a few
4687 microseconds. For each measurement, the operation was repeated a
4688 number of times. Time stamps were obtained directly before and after
4689 the operation was performed. The data gathered for the entire set of
4690 operations was then analyzed, generating average (mean), maximum and
4691 minimum values. The sample variance (a measure of how close most
4692 samples are to the mean) was also calculated. The cost of obtaining
4693 the real-time clock timer values was also measured, and was subtracted
4694 from all other times.
4695           </para>
4696           <para>
4697 Most kernel functions can be measured separately. In each case, a
4698 reasonable number of iterations are performed. Where the test case
4699 involves a kernel object, for example creating a task, each iteration
4700 is performed on a different object. There is also a set of tests which
4701 measures the interactions between multiple tasks and certain kernel
4702 primitives. Most functions are tested in such a way as to determine
4703 the variations introduced by varying numbers of objects in the system.
4704 For example, the mailbox tests measure the cost of a 'peek' operation
4705 when the mailbox is empty, has a single item, and has multiple items
4706 present. In this way, any effects of the state of the object or how
4707 many items it contains can be determined.
4708           </para>
4709           <para>
4710 There are a few things to consider about these measurements. Firstly,
4711 they are quite micro in scale and only measure the operation in
4712 question. These measurements do not adequately describe how the
4713 timings would be perturbed in a real system with multiple interrupting
4714 sources. Secondly, the possible aberration incurred by the real-time
4715 clock (system heartbeat tick) is explicitly avoided. Virtually all
4716 kernel functions have been designed to be interruptible. Thus the
4717 times presented are typical, but best case, since any particular
4718 function may be interrupted by the clock tick processing. This number
4719 is explicitly calculated so that the value may be included in any
4720 deadline calculations required by the end user. Lastly, the reported
4721 measurements were obtained from a system built with all options at
4722 their default values. Kernel instrumentation and asserts are also
4723 disabled for these measurements. Any number of configuration options
4724 can change the measured results, sometimes quite dramatically. For
4725 example, mutexes are using priority inheritance in these measurements.
4726 The numbers will change if the system is built with priority
4727 inheritance on mutex variables turned off.
4728           </para>
4729           <para>
4730 The final value that is measured is an estimate of interrupt latency.
4731 This particular value is not explicitly calculated in the test program
4732 used, but rather by instrumenting the kernel itself. The raw number of
4733 timer ticks that elapse between the time the timer generates an
4734 interrupt and the start of the timer ISR is kept in the kernel. These
4735 values are printed by the test program after all other operations have
4736 been tested. Thus this should be a reasonable estimate of the
4737 interrupt latency over time.
4738           </para>
4739         </refsect1>
4740
4741         <refsect1 id="kernel-characterization-using-measurements">
4742           <title>Using these Measurements</title>
4743           <para>
4744 These measurements can be used in a number of ways. The most typical
4745 use will be to compare different real-time kernel offerings on similar
4746 hardware, another will be to estimate the cost of implementing a task
4747 using eCos (applications can be examined to see what effect the kernel
4748 operations will have on the total execution time). Another use would
4749 be to observe how the tuning of the kernel affects overall operation.
4750           </para>
4751         </refsect1>
4752
4753         <refsect1 id="kernel-characterization-influences">
4754           <title>Influences on Performance</title>
4755             <para>
4756 A number of factors can affect real-time performance in a system. One
4757 of the most common factors, yet most difficult to characterize, is the
4758 effect of device drivers and interrupts on system timings. Different
4759 device drivers will have differing requirements as to how long
4760 interrupts are suppressed, for example. The eCos system has been
4761 designed with this in mind, by separating the management of interrupts
4762 (ISR handlers) and the processing required by the interrupt
4763 (DSR&mdash;Deferred Service Routine&mdash; handlers). However, since
4764 there is so much variability here, and indeed most device drivers will
4765 come from the end users themselves, these effects cannot be reliably
4766 measured. Attempts have been made to measure the overhead of the
4767 single interrupt that eCos relies on, the real-time clock timer. This
4768 should give you a reasonable idea of the cost of executing interrupt
4769 handling for devices.
4770           </para>
4771         </refsect1>
4772
4773        <refsect1 id="kernel-characterization-measured-items">
4774          <title>Measured Items</title>
4775          <para>
4776 This section describes the various tests and the numbers presented.
4777 All tests use the C kernel API (available by way of
4778 <filename>cyg/kernel/kapi.h</filename>). There is a single main thread
4779 in the system that performs the various tests. Additional threads may
4780 be created as part of the testing, but these are short lived and are
4781 destroyed between tests unless otherwise noted. The terminology
4782 &ldquo;lower priority&rdquo; means a priority that is less important,
4783 not necessarily lower in numerical value. A higher priority thread
4784 will run in preference to a lower priority thread even though the
4785 priority value of the higher priority thread may be numerically less
4786 than that of the lower priority thread.
4787           </para>
4788
4789           <refsect2 id="kernel-characterization-measure-threads">
4790             <title>Thread Primitives</title>
4791             <variablelist>
4792               <varlistentry>
4793                 <term>Create thread</term>
4794                 <listitem><para>
4795 This test measures the <function>cyg_thread_create()</function> call.
4796 Each call creates a totally new thread. The set of threads created by
4797 this test will be reused in the subsequent thread primitive tests.
4798                 </para></listitem>
4799               </varlistentry>
4800               <varlistentry>
4801                 <term>Yield thread</term>
4802                 <listitem><para>
4803 This test measures the <function>cyg_thread_yield()</function> call.
4804 For this test, there are no other runnable threads, thus the test
4805 should just measure the overhead of trying to give up the CPU.
4806                 </para></listitem>
4807               </varlistentry>
4808               <varlistentry>
4809                 <term>Suspend &lsqb;suspended&rsqb; thread</term>
4810                 <listitem><para>
4811 This test measures the <function>cyg_thread_suspend()</function> call.
4812 A thread may be suspended multiple times; each thread is already
4813 suspended from its initial creation, and is suspended again.
4814                 </para></listitem>
4815               </varlistentry>
4816               <varlistentry>
4817                 <term>Resume thread</term>
4818                 <listitem><para>
4819 This test measures the <function>cyg_thread_resume()</function> call.
4820 All of the threads have a suspend count of 2, thus this call does not
4821 make them runnable. This test just measures the overhead of resuming a
4822 thread.
4823                 </para></listitem>
4824               </varlistentry>
4825               <varlistentry>
4826                 <term>Set priority</term>
4827                 <listitem><para>
4828 This test measures the <function>cyg_thread_set_priority()</function>
4829 call. Each thread, currently suspended, has its priority set to a new
4830 value.
4831                 </para></listitem>
4832               </varlistentry>
4833               <varlistentry>
4834                 <term>Get priority</term>
4835                 <listitem><para>
4836 This test measures the <function>cyg_thread_get_priority()</function>
4837 call.
4838                 </para></listitem>
4839               </varlistentry>
4840               <varlistentry>
4841                 <term>Kill &lsqb;suspended&rsqb; thread</term>
4842                 <listitem><para>
4843 This test measures the <function>cyg_thread_kill()</function> call.
4844 Each thread in the set is killed. All threads are known to be
4845 suspended before being killed.
4846                 </para></listitem>
4847               </varlistentry>
4848               <varlistentry>
4849                 <term>Yield &lsqb;no other&rsqb; thread</term>
4850                 <listitem><para>
4851 This test measures the <function>cyg_thread_yield()</function> call
4852 again. This is to demonstrate that the
4853 <function>cyg_thread_yield()</function> call has a fixed overhead,
4854 regardless of whether there are other threads in the system.
4855                 </para></listitem>
4856               </varlistentry>
4857               <varlistentry>
4858                 <term>Resume &lsqb;suspended low priority&rsqb; thread</term>
4859                 <listitem><para>
4860 This test measures the <function>cyg_thread_resume()</function> call
4861 again. In this case, the thread being resumed is lower priority than
4862 the main thread, thus it will simply become ready to run but not be
4863 granted the CPU. This test measures the cost of making a thread ready
4864 to run.
4865                 </para></listitem>
4866               </varlistentry>
4867               <varlistentry>
4868                 <term>Resume &lsqb;runnable low priority&rsqb; thread</term>
4869                 <listitem><para>
4870 This test measures the <function>cyg_thread_resume()</function> call
4871 again. In this case, the thread being resumed is lower priority than
4872 the main thread and has already been made runnable, so in fact the
4873 resume call has no effect.
4874                 </para></listitem>
4875               </varlistentry>
4876               <varlistentry>
4877                 <term>Suspend &lsqb;runnable&rsqb; thread</term>
4878                 <listitem><para>
4879 This test measures the <function>cyg_thread_suspend()</function> call
4880 again. In this case, each thread has already been made runnable (by
4881 previous tests).
4882                 </para></listitem>
4883               </varlistentry>
4884               <varlistentry>
4885                 <term>Yield &lsqb;only low priority&rsqb; thread</term>
4886                 <listitem><para>
4887 This test measures the <function>cyg_thread_yield()</function> call.
4888 In this case, there are many other runnable threads, but they are all
4889 lower priority than the main thread, thus no thread switches will take
4890 place.
4891                 </para></listitem>
4892               </varlistentry>
4893               <varlistentry>
4894                 <term>Suspend &lsqb;runnable-&gt;not runnable&rsqb; thread</term>
4895                 <listitem><para>
4896 This test measures the <function>cyg_thread_suspend()</function> call
4897 again. The thread being suspended will become non-runnable by this
4898 action.
4899                 </para></listitem>
4900               </varlistentry>
4901               <varlistentry>
4902                 <term>Kill &lsqb;runnable&rsqb; thread</term>
4903                 <listitem><para>
4904 This test measures the <function>cyg_thread_kill()</function> call
4905 again. In this case, the thread being killed is currently runnable,
4906 but lower priority than the main thread.
4907                 </para></listitem>
4908               </varlistentry>
4909               <varlistentry>
4910                 <term>Resume &lsqb;high priority&rsqb; thread</term>
4911                 <listitem><para>
4912 This test measures the <function>cyg_thread_resume()</function> call.
4913 The thread being resumed is higher priority than the main thread, thus
4914 a thread switch will take place on each call. In fact there will be
4915 two thread switches; one to the new higher priority thread and a
4916 second back to the test thread. The test thread exits immediately.
4917                 </para></listitem>
4918               </varlistentry>
4919               <varlistentry>
4920                 <term>Thread switch</term>
4921                 <listitem><para>
4922 This test attempts to measure the cost of switching from one thread to
4923 another. Two equal priority threads are started and they will each
4924 yield to the other for a number of iterations. A time stamp is
4925 gathered in one thread before the
4926 <function>cyg_thread_yield()</function> call and after the call in the
4927 other thread.
4928                 </para></listitem>
4929               </varlistentry>
4930             </variablelist>
4931           </refsect2>
4932
4933           <refsect2 id="kernel-characterization-measure-scheduler"
4934             <title>Scheduler Primitives</title>
4935             <variablelist>
4936               <varlistentry>
4937                 <term>Scheduler lock</term>
4938                 <listitem><para>
4939 This test measures the <function>cyg_scheduler_lock()</function> call.
4940                 </para></listitem>
4941               </varlistentry>
4942               <varlistentry>
4943                 <term>Scheduler unlock &lsqb;0 threads&rsqb;</term>
4944                 <listitem><para>
4945 This test measures the <function>cyg_scheduler_unlock()</function>
4946 call. There are no other threads in the system and the unlock happens
4947 immediately after a lock so there will be no pending DSR&rsquo;s to
4948 run.
4949                 </para></listitem>
4950               </varlistentry>
4951               <varlistentry>
4952                 <term>Scheduler unlock &lsqb;1 suspended thread&rsqb;</term>
4953                 <listitem><para>
4954 This test measures the <function>cyg_scheduler_unlock()</function>
4955 call. There is one other thread in the system which is currently
4956 suspended.
4957                 </para></listitem>
4958               </varlistentry>
4959               <varlistentry>
4960                 <term>Scheduler unlock &lsqb;many suspended threads&rsqb;</term>
4961                 <listitem><para>
4962 This test measures the <function>cyg_scheduler_unlock()</function>
4963 call. There are many other threads in the system which are currently
4964 suspended. The purpose of this test is to determine the cost of having
4965 additional threads in the system when the scheduler is activated by
4966 way of <function>cyg_scheduler_unlock()</function>.
4967                 </para></listitem>
4968               </varlistentry>
4969               <varlistentry>
4970                 <term>Scheduler unlock &lsqb;many low priority threads&rsqb;</term>
4971                 <listitem><para>
4972 This test measures the <function>cyg_scheduler_unlock()</function>
4973 call. There are many other threads in the system which are runnable
4974 but are lower priority than the main thread. The purpose of this test
4975 is to determine the cost of having additional threads in the system
4976 when the scheduler is activated by way of
4977 <function>cyg_scheduler_unlock()</function>.
4978                 </para></listitem>
4979               </varlistentry>
4980             </variablelist>
4981           </refsect2>
4982
4983           <refsect2 id="kernel-characterization-measure-mutex">
4984             <title>Mutex Primitives</title>
4985             <variablelist>
4986               <varlistentry>
4987                 <term>Init mutex</term>
4988                 <listitem><para>
4989 This test measures the <function>cyg_mutex_init()</function> call. A
4990 number of separate mutex variables are created. The purpose of this
4991 test is to measure the cost of creating a new mutex and introducing it
4992 to the system.
4993                 </para></listitem>
4994               </varlistentry>
4995               <varlistentry>
4996                 <term>Lock &lsqb;unlocked&rsqb; mutex</term>
4997                 <listitem><para>
4998 This test measures the <function>cyg_mutex_lock()</function> call. The
4999 purpose of this test is to measure the cost of locking a mutex which
5000 is currently unlocked. There are no other threads executing in the
5001 system while this test runs.
5002                 </para></listitem>
5003               </varlistentry>
5004               <varlistentry>
5005                 <term>Unlock &lsqb;locked&rsqb; mutex</term>
5006                 <listitem><para>
5007 This test measures the <function>cyg_mutex_unlock()</function> call.
5008 The purpose of this test is to measure the cost of unlocking a mutex
5009 which is currently locked. There are no other threads executing in the
5010 system while this test runs.
5011                 </para></listitem>
5012               </varlistentry>
5013               <varlistentry>
5014                 <term>Trylock &lsqb;unlocked&rsqb; mutex</term>
5015                 <listitem><para>
5016 This test measures the <function>cyg_mutex_trylock()</function> call.
5017 The purpose of this test is to measure the cost of locking a mutex
5018 which is currently unlocked. There are no other threads executing in
5019 the system while this test runs.
5020                 </para></listitem>
5021               </varlistentry>
5022               <varlistentry>
5023                 <term>Trylock &lsqb;locked&rsqb; mutex</term>
5024                 <listitem><para>
5025 This test measures the <function>cyg_mutex_trylock()</function> call.
5026 The purpose of this test is to measure the cost of locking a mutex
5027 which is currently locked. There are no other threads executing in the
5028 system while this test runs.
5029                 </para></listitem>
5030               </varlistentry>
5031               <varlistentry>
5032                 <term>Destroy mutex</term>
5033                 <listitem><para>
5034 This test measures the <function>cyg_mutex_destroy()</function> call.
5035 The purpose of this test is to measure the cost of deleting a mutex
5036 from the system. There are no other threads executing in the system
5037 while this test runs.
5038                 </para></listitem>
5039               </varlistentry>
5040               <varlistentry>
5041                 <term>Unlock/Lock mutex</term>
5042                 <listitem><para>
5043 This test attempts to measure the cost of unlocking a mutex for which
5044 there is another higher priority thread waiting. When the mutex is
5045 unlocked, the higher priority waiting thread will immediately take the
5046 lock. The time from when the unlock is issued until after the lock
5047 succeeds in the second thread is measured, thus giving the round-trip
5048 or circuit time for this type of synchronizer.
5049                 </para></listitem>
5050               </varlistentry>
5051             </variablelist>
5052           </refsect2>
5053
5054           <refsect2 id="kernel-characterization-measure-mailbox">
5055             <title>Mailbox Primitives</title>
5056             <variablelist>
5057               <varlistentry>
5058                 <term>Create mbox</term>
5059                 <listitem><para>
5060 This test measures the <function>cyg_mbox_create()</function> call. A
5061 number of separate mailboxes is created. The purpose of this test is
5062 to measure the cost of creating a new mailbox and introducing it to
5063 the system.
5064                 </para></listitem>
5065               </varlistentry>
5066               <varlistentry>
5067                 <term>Peek &lsqb;empty&rsqb; mbox</term>
5068                 <listitem><para>
5069 This test measures the <function>cyg_mbox_peek()</function> call. An
5070 attempt is made to peek the value in each mailbox, which is currently
5071 empty. The purpose of this test is to measure the cost of checking a
5072 mailbox for a value without blocking.
5073                 </para></listitem>
5074               </varlistentry>
5075               <varlistentry>
5076                 <term>Put &lsqb;first&rsqb; mbox</term>
5077                 <listitem><para>
5078 This test measures the <function>cyg_mbox_put()</function> call. One
5079 item is added to a currently empty mailbox. The purpose of this test
5080 is to measure the cost of adding an item to a mailbox. There are no
5081 other threads currently waiting for mailbox items to arrive.
5082                 </para></listitem>
5083               </varlistentry>
5084               <varlistentry>
5085                 <term>Peek &lsqb;1 msg&rsqb; mbox</term>
5086                 <listitem><para>
5087 This test measures the <function>cyg_mbox_peek()</function> call. An
5088 attempt is made to peek the value in each mailbox, which contains a
5089 single item. The purpose of this test is to measure the cost of
5090 checking a mailbox which has data to deliver.
5091                 </para></listitem>
5092               </varlistentry>
5093               <varlistentry>
5094                 <term>Put &lsqb;second&rsqb; mbox</term>
5095                 <listitem><para>
5096 This test measures the <function>cyg_mbox_put()</function> call. A
5097 second item is added to a mailbox. The purpose of this test is to
5098 measure the cost of adding an additional item to a mailbox. There are
5099 no other threads currently waiting for mailbox items to arrive.
5100                 </para></listitem>
5101               </varlistentry>
5102               <varlistentry>
5103                 <term>Peek &lsqb;2 msgs&rsqb; mbox</term>
5104                 <listitem><para>
5105 This test measures the <function>cyg_mbox_peek()</function> call. An
5106 attempt is made to peek the value in each mailbox, which contains two
5107 items. The purpose of this test is to measure the cost of checking a
5108 mailbox which has data to deliver.
5109                 </para></listitem>
5110               </varlistentry>
5111               <varlistentry>
5112                 <term>Get &lsqb;first&rsqb; mbox</term>
5113                 <listitem><para>
5114 This test measures the <function>cyg_mbox_get()</function> call. The
5115 first item is removed from a mailbox that currently contains two
5116 items. The purpose of this test is to measure the cost of obtaining an
5117 item from a mailbox without blocking.
5118               </para></listitem>
5119               </varlistentry>
5120               <varlistentry>
5121                 <term>Get &lsqb;second&rsqb; mbox</term>
5122                 <listitem><para>
5123 This test measures the <function>cyg_mbox_get()</function> call. The
5124 last item is removed from a mailbox that currently contains one item.
5125 The purpose of this test is to measure the cost of obtaining an item
5126 from a mailbox without blocking.
5127                 </para></listitem>
5128               </varlistentry>
5129               <varlistentry>
5130                 <term>Tryput &lsqb;first&rsqb; mbox</term>
5131                 <listitem><para>
5132 This test measures the <function>cyg_mbox_tryput()</function> call. A
5133 single item is added to a currently empty mailbox. The purpose of this
5134 test is to measure the cost of adding an item to a mailbox.
5135                 </para></listitem>
5136               </varlistentry>
5137               <varlistentry>
5138                 <term>Peek item &lsqb;non-empty&rsqb; mbox</term>
5139                 <listitem><para>
5140 This test measures the <function>cyg_mbox_peek_item()</function> call.
5141 A single item is fetched from a mailbox that contains a single item.
5142 The purpose of this test is to measure the cost of obtaining an item
5143 without disturbing the mailbox.
5144                 </para></listitem>
5145               </varlistentry>
5146               <varlistentry>
5147                 <term>Tryget &lsqb;non-empty&rsqb; mbox</term>
5148                 <listitem><para>
5149 This test measures the <function>cyg_mbox_tryget()</function> call. A
5150 single item is removed from a mailbox that contains exactly one item.
5151 The purpose of this test is to measure the cost of obtaining one item
5152 from a non-empty mailbox.
5153                 </para></listitem>
5154               </varlistentry>
5155               <varlistentry>
5156                 <term>Peek item &lsqb;empty&rsqb; mbox</term>
5157                 <listitem><para>
5158 This test measures the <function>cyg_mbox_peek_item()</function> call.
5159 An attempt is made to fetch an item from a mailbox that is empty. The
5160 purpose of this test is to measure the cost of trying to obtain an
5161 item when the mailbox is empty.
5162                 </para></listitem>
5163               </varlistentry>
5164               <varlistentry>
5165                 <term>Tryget &lsqb;empty&rsqb; mbox</term>
5166                 <listitem><para>
5167 This test measures the <function>cyg_mbox_tryget()</function> call. An
5168 attempt is made to fetch an item from a mailbox that is empty. The
5169 purpose of this test is to measure the cost of trying to obtain an
5170 item when the mailbox is empty.
5171                 </para></listitem>
5172               </varlistentry>
5173               <varlistentry>
5174                 <term>Waiting to get mbox</term>
5175                 <listitem><para>
5176 This test measures the <function>cyg_mbox_waiting_to_get()</function>
5177 call. The purpose of this test is to measure the cost of determining
5178 how many threads are waiting to obtain a message from this mailbox.
5179                 </para></listitem>
5180               </varlistentry>
5181               <varlistentry>
5182                 <term>Waiting to put mbox</term>
5183                 <listitem><para>
5184 This test measures the <function>cyg_mbox_waiting_to_put()</function>
5185 call. The purpose of this test is to measure the cost of determining
5186 how many threads are waiting to put a message into this mailbox.
5187                 </para></listitem>
5188               </varlistentry>
5189               <varlistentry>
5190                 <term>Delete mbox</term>
5191                 <listitem><para>
5192 This test measures the <function>cyg_mbox_delete()</function> call.
5193 The purpose of this test is to measure the cost of destroying a
5194 mailbox and removing it from the system.
5195                 </para></listitem>
5196               </varlistentry>
5197               <varlistentry>
5198                 <term>Put/Get mbox</term>
5199                 <listitem><para>
5200 In this round-trip test, one thread is sending data to a mailbox that
5201 is being consumed by another thread. The time from when the data is
5202 put into the mailbox until it has been delivered to the waiting thread
5203 is measured. Note that this time will contain a thread switch.
5204                 </para></listitem>
5205               </varlistentry>
5206             </variablelist>
5207           </refsect2>
5208
5209           <refsect2 id="kernel-characterization-measure-semaphore">
5210             <title>Semaphore Primitives</title>
5211             <variablelist>
5212               <varlistentry>
5213                 <term>Init semaphore</term>
5214                 <listitem><para>
5215 This test measures the <function>cyg_semaphore_init()</function> call.
5216 A number of separate semaphore objects are created and introduced to
5217 the system. The purpose of this test is to measure the cost of
5218 creating a new semaphore.
5219                 </para></listitem>
5220               </varlistentry>
5221               <varlistentry>
5222                 <term>Post &lsqb;0&rsqb; semaphore</term>
5223                 <listitem><para>
5224 This test measures the <function>cyg_semaphore_post()</function> call.
5225 Each semaphore currently has a value of 0 and there are no other
5226 threads in the system. The purpose of this test is to measure the
5227 overhead cost of posting to a semaphore. This cost will differ if
5228 there is a thread waiting for the semaphore.
5229                 </para></listitem>
5230               </varlistentry>
5231               <varlistentry>
5232                 <term>Wait &lsqb;1&rsqb; semaphore</term>
5233                 <listitem><para>
5234 This test measures the <function>cyg_semaphore_wait()</function> call.
5235 The semaphore has a current value of 1 so the call is non-blocking.
5236 The purpose of the test is to measure the overhead of
5237 &ldquo;taking&rdquo; a semaphore.
5238                 </para></listitem>
5239               </varlistentry>
5240               <varlistentry>
5241                 <term>Trywait &lsqb;0&rsqb; semaphore</term>
5242                 <listitem><para>
5243 This test measures the <function>cyg_semaphore_trywait()</function>
5244 call. The semaphore has a value of 0 when the call is made. The
5245 purpose of this test is to measure the cost of seeing if a semaphore
5246 can be &ldquo;taken&rdquo; without blocking. In this case, the answer
5247 would be no.
5248                 </para></listitem>
5249               </varlistentry>
5250               <varlistentry>
5251                 <term>Trywait &lsqb;1&rsqb; semaphore</term>
5252                 <listitem><para>
5253 This test measures the <function>cyg_semaphore_trywait()</function>
5254 call. The semaphore has a value of 1 when the call is made. The
5255 purpose of this test is to measure the cost of seeing if a semaphore
5256 can be &ldquo;taken&rdquo; without blocking. In this case, the answer
5257 would be yes.
5258                 </para></listitem>
5259               </varlistentry>
5260               <varlistentry>
5261                 <term>Peek semaphore</term>
5262                 <listitem><para>
5263 This test measures the <function>cyg_semaphore_peek()</function> call.
5264 The purpose of this test is to measure the cost of obtaining the
5265 current semaphore count value.
5266                 </para></listitem>
5267               </varlistentry>
5268               <varlistentry>
5269                 <term>Destroy semaphore</term>
5270                 <listitem><para>
5271 This test measures the <function>cyg_semaphore_destroy()</function>
5272 call. The purpose of this test is to measure the cost of deleting a
5273 semaphore from the system.
5274                 </para></listitem>
5275               </varlistentry>
5276               <varlistentry>
5277                 <term>Post/Wait semaphore</term>
5278                 <listitem><para>
5279 In this round-trip test, two threads are passing control back and
5280 forth by using a semaphore. The time from when one thread calls
5281 <function>cyg_semaphore_post()</function> until the other thread
5282 completes its <function>cyg_semaphore_wait()</function> is measured.
5283 Note that each iteration of this test will involve a thread switch.
5284                 </para></listitem>
5285               </varlistentry>
5286             </variablelist>
5287           </refsect2>
5288
5289           <refsect2 id="kernel-characterization-measure-counters">
5290             <title>Counters</title>
5291             <variablelist>
5292               <varlistentry>
5293                 <term>Create counter</term>
5294                 <listitem><para>
5295 This test measures the <function>cyg_counter_create()</function> call.
5296 A number of separate counters are created. The purpose of this test is
5297 to measure the cost of creating a new counter and introducing it to
5298 the system.
5299                 </para></listitem>
5300               </varlistentry>
5301               <varlistentry>
5302                 <term>Get counter value</term>
5303                 <listitem><para>
5304 This test measures the
5305 <function>cyg_counter_current_value()</function> call. The current
5306 value of each counter is obtained.
5307                 </para></listitem>
5308               </varlistentry>
5309               <varlistentry>
5310                 <term>Set counter value</term>
5311                 <listitem><para>
5312 This test measures the <function>cyg_counter_set_value()</function>
5313 call. Each counter is set to a new value.
5314                 </para></listitem>
5315               </varlistentry>
5316               <varlistentry>
5317                 <term>Tick counter</term>
5318                 <listitem><para>
5319 This test measures the <function>cyg_counter_tick()</function> call.
5320 Each counter is &ldquo;ticked&rdquo; once.
5321                 </para></listitem>
5322               </varlistentry>
5323               <varlistentry>
5324                 <term>Delete counter</term>
5325                 <listitem><para>
5326 This test measures the <function>cyg_counter_delete()</function> call.
5327 Each counter is deleted from the system. The purpose of this test is
5328 to measure the cost of deleting a counter object.
5329                 </para></listitem>
5330               </varlistentry>
5331             </variablelist>
5332           </refsect2>
5333
5334           <refsect2 id="kernel-characterization-measure-alarms">
5335             <title>Alarms</title>
5336             <variablelist>
5337               <varlistentry>
5338                 <term>Create alarm</term>
5339                 <listitem><para>
5340 This test measures the <function>cyg_alarm_create()</function> call. A
5341 number of separate alarms are created, all attached to the same
5342 counter object. The purpose of this test is to measure the cost of
5343 creating a new counter and introducing it to the system.
5344                 </para></listitem>
5345               </varlistentry>
5346               <varlistentry>
5347                 <term>Initialize alarm</term>
5348                 <listitem><para>
5349 This test measures the <function>cyg_alarm_initialize()</function>
5350 call. Each alarm is initialized to a small value.
5351                 </para></listitem>
5352               </varlistentry>
5353               <varlistentry>
5354                 <term>Disable alarm</term>
5355                 <listitem><para>
5356 This test measures the <function>cyg_alarm_disable()</function> call.
5357 Each alarm is explicitly disabled.
5358                 </para></listitem>
5359               </varlistentry>
5360               <varlistentry>
5361                 <term>Enable alarm</term>
5362                 <listitem><para>
5363 This test measures the <function>cyg_alarm_enable()</function> call.
5364 Each alarm is explicitly enabled.
5365                 </para></listitem>
5366               </varlistentry>
5367               <varlistentry>
5368                 <term>Delete alarm</term>
5369                 <listitem><para>
5370 This test measures the <function>cyg_alarm_delete()</function> call.
5371 Each alarm is destroyed. The purpose of this test is to measure the
5372 cost of deleting an alarm and removing it from the system.
5373                 </para></listitem>
5374               </varlistentry>
5375               <varlistentry>
5376                 <term>Tick counter &lsqb;1 alarm&rsqb;</term>
5377                 <listitem><para>
5378 This test measures the <function>cyg_counter_tick()</function> call. A
5379 counter is created that has a single alarm attached to it. The purpose
5380 of this test is to measure the cost of &ldquo;ticking&rdquo; a counter
5381 when it has a single attached alarm. In this test, the alarm is not
5382 activated (fired).
5383                 </para></listitem>
5384               </varlistentry>
5385               <varlistentry>
5386                 <term>Tick counter &lsqb;many alarms&rsqb;</term>
5387                 <listitem><para>
5388 This test measures the <function>cyg_counter_tick()</function> call. A
5389 counter is created that has multiple alarms attached to it. The
5390 purpose of this test is to measure the cost of &ldquo;ticking&rdquo; a
5391 counter when it has many attached alarms. In this test, the alarms are
5392 not activated (fired).
5393                 </para></listitem>
5394               </varlistentry>
5395               <varlistentry>
5396                 <term>Tick &amp; fire counter &lsqb;1 alarm&rsqb;</term>
5397                 <listitem><para>
5398 This test measures the <function>cyg_counter_tick()</function> call. A
5399 counter is created that has a single alarm attached to it. The purpose
5400 of this test is to measure the cost of &ldquo;ticking&rdquo; a counter
5401 when it has a single attached alarm. In this test, the alarm is
5402 activated (fired). Thus the measured time will include the overhead of
5403 calling the alarm callback function.
5404                 </para></listitem>
5405               </varlistentry>
5406               <varlistentry>
5407                 <term>Tick &amp; fire counter &lsqb;many alarms&rsqb;</term>
5408                 <listitem><para>
5409 This test measures the <function>cyg_counter_tick()</function> call. A
5410 counter is created that has multiple alarms attached to it. The
5411 purpose of this test is to measure the cost of &ldquo;ticking&rdquo; a
5412 counter when it has many attached alarms. In this test, the alarms are
5413 activated (fired). Thus the measured time will include the overhead of
5414 calling the alarm callback function.
5415                 </para></listitem>
5416               </varlistentry>
5417               <varlistentry>
5418                 <term>Alarm latency &lsqb;0 threads&rsqb;</term>
5419                 <listitem><para>
5420 This test attempts to measure the latency in calling an alarm callback
5421 function. The time from the clock interrupt until the alarm function
5422 is called is measured. In this test, there are no threads that can be
5423 run, other than the system idle thread, when the clock interrupt
5424 occurs (all threads are suspended).
5425                 </para></listitem>
5426               </varlistentry>
5427               <varlistentry>
5428                 <term>Alarm latency &lsqb;2 threads&rsqb;</term>
5429                 <listitem><para>
5430 This test attempts to measure the latency in calling an alarm callback
5431 function. The time from the clock interrupt until the alarm function
5432 is called is measured. In this test, there are exactly two threads
5433 which are running when the clock interrupt occurs. They are simply
5434 passing back and forth by way of the
5435 <function>cyg_thread_yield()</function> call. The purpose of this test
5436 is to measure the variations in the latency when there are executing
5437 threads.
5438                 </para></listitem>
5439               </varlistentry>
5440               <varlistentry>
5441                 <term>Alarm latency &lsqb;many threads&rsqb;</term>
5442                 <listitem><para>
5443 This test attempts to measure the latency in calling an alarm callback
5444 function. The time from the clock interrupt until the alarm function
5445 is called is measured. In this test, there are a number of threads
5446 which are running when the clock interrupt occurs. They are simply
5447 passing back and forth by way of the
5448 <function>cyg_thread_yield()</function> call. The purpose of this test
5449 is to measure the variations in the latency when there are many
5450 executing threads.
5451                 </para></listitem>
5452               </varlistentry>
5453             </variablelist>
5454           </refsect2>
5455
5456     </refsect1>
5457
5458   </refentry>
5459
5460 <!-- }}} -->
5461
5462 </part>