aboutsummaryrefslogtreecommitdiffstats
path: root/os/kernel/src/chcond.c
blob: 92e1a4eb4ae880d54a72a40c85ad8b87415b74d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
    ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 Giovanni Di Sirio.

    This file is part of ChibiOS/RT.

    ChibiOS/RT is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    ChibiOS/RT is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
   Concepts and parts of this file have been contributed by Leon Woestenberg.
 */

/**
 * @file    chcond.c
 * @brief   Condition Variables code.
 *
 * @addtogroup condvars Condition Variables
 * @details This module implements the Condition Variables mechanism. Condition
 *          variables are an extensions to the Mutex subsystem and cannot
 *          work alone.
 *          <h2>Operation mode</h2>
 *          The condition variable is a synchronization object meant to be
 *          used inside a zone protected by a @p Mutex. Mutexes and CondVars
 *          together can implement a Monitor construct.<br>
 *          In order to use the Condition Variables APIs the @p CH_USE_CONDVARS
 *          option must be enabled in @p chconf.h.
 * @{
 */

#include "ch.h"

#if CH_USE_CONDVARS && CH_USE_MUTEXES

/**
 * @brief   Initializes s @p CondVar structure.
 * @note    This function can be invoked from within an interrupt handler even
 *          if it is not an I-Class API because it does not touch any critical
 *          kernel data structure.
 *
 * @param[out] cp       pointer to a @p CondVar structure
 */
void chCondInit(CondVar *cp) {

  chDbgCheck(cp != NULL, "chCondInit");

  queue_init(&cp->c_queue);
}

/**
 * @brief   Signals one thread that is waiting on the condition variable.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 */
void chCondSignal(CondVar *cp) {

  chDbgCheck(cp != NULL, "chCondSignal");

  chSysLock();
  if (notempty(&cp->c_queue))
    chSchWakeupS(fifo_remove(&cp->c_queue), RDY_OK);
  chSysUnlock();
}

/**
 * @brief   Signals one thread that is waiting on the condition variable.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 */
void chCondSignalI(CondVar *cp) {

  chDbgCheck(cp != NULL, "chCondSignalI");

  if (notempty(&cp->c_queue))
    chSchReadyI(fifo_remove(&cp->c_queue))->p_u.rdymsg = RDY_OK;
}

/**
 * @brief   Signals all threads that are waiting on the condition variable.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 */
void chCondBroadcast(CondVar *cp) {

  chSysLock();
  chCondBroadcastI(cp);
  chSchRescheduleS();
  chSysUnlock();
}

/**
 * @brief   Signals all threads that are waiting on the condition variable.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 */
void chCondBroadcastI(CondVar *cp) {

  chDbgCheck(cp != NULL, "chCondBroadcastI");

  /* Empties the condition variable queue and inserts all the Threads into the
     ready list in FIFO order. The wakeup message is set to @p RDY_RESET in
     order to make a chCondBroadcast() detectable from a chCondSignal().*/
  while (cp->c_queue.p_next != (void *)&cp->c_queue)
    chSchReadyI(fifo_remove(&cp->c_queue))->p_u.rdymsg = RDY_RESET;
}

/**
 * @brief   Waits on the condition variable releasing the mutex lock.
 * @details Releases the currently owned mutex, waits on the condition
 *          variable, and finally acquires the mutex again. All the sequence
 *          is performed atomically.
 * @note    The invoking thread <b>must</b> have at least one owned mutex on
 *          entry.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 * @return              The wakep mode.
 * @retval RDY_OK       if the condvar was signaled using @p chCondSignal().
 * @retval RDY_RESET    if the condvar was signaled using @p chCondBroadcast().
 */
msg_t chCondWait(CondVar *cp) {
  msg_t msg;

  chSysLock();
  msg = chCondWaitS(cp);
  chSysUnlock();
  return msg;
}

/**
 * @brief   Waits on the condition variable releasing the mutex lock.
 * @details Releases the currently owned mutex, waits on the condition
 *          variable, and finally acquires the mutex again. All the sequence
 *          is performed atomically.
 * @note    The invoking thread <b>must</b> have at least one owned mutex on
 *          entry.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 * @return              The wakep mode.
 * @retval RDY_OK       if the condvar was signaled using @p chCondSignal().
 * @retval RDY_RESET    if the condvar was signaled using @p chCondBroadcast().
 */
msg_t chCondWaitS(CondVar *cp) {
  Thread *ctp = currp;
  Mutex *mp;
  msg_t msg;

  chDbgCheck(cp != NULL, "chCondWaitS");
  chDbgAssert(ctp->p_mtxlist != NULL,
              "chCondWaitS(), #1",
              "not owning a mutex");

  mp = chMtxUnlockS();
  ctp->p_u.wtobjp = cp;
  prio_insert(ctp, &cp->c_queue);
  chSchGoSleepS(THD_STATE_WTCOND);
  msg = ctp->p_u.rdymsg;
  chMtxLockS(mp);
  return msg;
}

#if CH_USE_CONDVARS_TIMEOUT
/**
 * @brief   Waits on the condition variable releasing the mutex lock.
 * @details Releases the currently owned mutex, waits on the condition
 *          variable, and finally acquires the mutex again. All the sequence
 *          is performed atomically.
 * @note    The invoking thread <b>must</b> have at least one owned mutex on
 *          entry.
 * @note    Exiting the function because a timeout does not re-acquire the
 *          mutex, the mutex ownership is lost.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 * @param[in] time      the number of ticks before the operation timeouts,
 *                      the special value @p TIME_INFINITE is allowed.
 *                      It is not possible to specify zero @p TIME_IMMEDIATE
 *                      as timeout specification because it would make no sense
 *                      in this function.
 * @return              The wakep mode.
 * @retval RDY_OK       if the condvar was signaled using @p chCondSignal().
 * @retval RDY_RESET    if the condvar was signaled using @p chCondBroadcast().
 * @retval RDY_TIMEOUT  if the condvar was not signaled @p within the specified
 *                      timeout.
 */
msg_t chCondWaitTimeout(CondVar *cp, systime_t time) {
  msg_t msg;

  chSysLock();
  msg = chCondWaitTimeoutS(cp, time);
  chSysUnlock();
  return msg;
}

/**
 * @brief   Waits on the condition variable releasing the mutex lock.
 * @details Releases the currently owned mutex, waits on the condition
 *          variable, and finally acquires the mutex again. All the sequence
 *          is performed atomically.
 * @note    The invoking thread <b>must</b> have at least one owned mutex on
 *          entry.
 * @note    Exiting the function because a timeout does not re-acquire the
 *          mutex, the mutex ownership is lost.
 *
 * @param[in] cp        pointer to the @p CondVar structure
 * @param[in] time      the number of ticks before the operation timeouts,
 *                      the special value @p TIME_INFINITE is allowed.
 *                      It is not possible to specify zero @p TIME_IMMEDIATE
 *                      as timeout specification because it would make no sense
 *                      in this function.
 * @return              The wakep mode.
 * @retval RDY_OK       if the condvar was signaled using @p chCondSignal().
 * @retval RDY_RESET    if the condvar was signaled using @p chCondBroadcast().
 * @retval RDY_TIMEOUT  if the condvar was not signaled within the specified
 *                      timeout.
 */
msg_t chCondWaitTimeoutS(CondVar *cp, systime_t time) {
  Mutex *mp;
  msg_t msg;

  chDbgCheck(cp != NULL, "chCondWaitTimeoutS");
  chDbgAssert(currp->p_mtxlist != NULL,
              "chCondWaitTimeoutS(), #1",
              "not owning a mutex");

  mp = chMtxUnlockS();
  currp->p_u.wtobjp = cp;
  prio_insert(currp, &cp->c_queue);
  msg = chSchGoSleepTimeoutS(THD_STATE_WTCOND, time);
  if (msg != RDY_TIMEOUT)
    chMtxLockS(mp);
  return msg;
}
#endif /* CH_USE_CONDVARS_TIMEOUT */

#endif /* CH_USE_CONDVARS && CH_USE_MUTEXES */

/** @} */
this block memories to address decoders and flip-flops, unless the option {\tt -nomap} is used, in which case the multi-port block memories stay in the design and can then be mapped to architecture-specific memory primitives using other commands. \item The command {\tt techmap} turns a high-level circuit with coarse grain cells such as wide adders and multipliers to a fine-grain circuit of simple logic primitives and single-bit storage elements. The command does that by substituting the complex cells by circuits of simpler cells. It is possible to provide a custom set of rules for this process in the form of a Verilog source file, as we will see in the next section. \end{itemize} Now Yosys can be run with the filename of the synthesis script as argument: \begin{figure}[H] \begin{lstlisting}[language=sh] yosys softusb_navre.ys \end{lstlisting} \renewcommand{\figurename}{Listing} \caption{Calling Yosys with script file} \end{figure} \medskip Now that we are using a synthesis script we can easily modify how Yosys synthesizes the design. The first thing we should customize is the call to the {\tt hierarchy} command: Whenever it is known that there are no implicit blackboxes in the design, i.e. modules that are referenced but are not defined, the {\tt hierarchy} command should be called with the {\tt -check} option. This will then cause synthesis to fail when implicit blackboxes are found in the design. The 2nd thing we can improve regarding the {\tt hierarchy} command is that we can tell it the name of the top level module of the design hierarchy. It will then automatically remove all modules that are not referenced from this top level module. \medskip For many designs it is also desired to optimize the encodings for the finite state machines (FSMs) in the design. The {\tt fsm} command finds FSMs, extracts them, performs some basic optimizations and then generate a circuit from the extracted and optimized description. It would also be possible to tell the {\tt fsm} command to leave the FSMs in their extracted form, so they can be further processed using custom commands. But in this case we don't want that. \medskip So now we have the final synthesis script for generating a BLIF file for the Navr\'e CPU: \begin{figure}[H] \begin{lstlisting}[language=sh] read_verilog softusb_navre.v hierarchy -check -top softusb_navre proc; opt; memory; opt; fsm; opt; techmap; opt write_blif softusb_navre.blif \end{lstlisting} \renewcommand{\figurename}{Listing} \caption{{\tt softusb\_navre.ys} (improved)} \end{figure} \section{Advanced Example: The Amber23 ARMv2a CPU} Our 2nd example is the Amber23 \cite{amber} ARMv2a CPU. Once again we base our example on the Verilog code that is included in yosys-bigsim \cite{bigsim}. \begin{figure}[b!] \begin{lstlisting}[language=sh] read_verilog a23_alu.v read_verilog a23_barrel_shift_fpga.v read_verilog a23_barrel_shift.v read_verilog a23_cache.v read_verilog a23_coprocessor.v read_verilog a23_core.v read_verilog a23_decode.v read_verilog a23_execute.v read_verilog a23_fetch.v read_verilog a23_multiply.v read_verilog a23_ram_register_bank.v read_verilog a23_register_bank.v read_verilog a23_wishbone.v read_verilog generic_sram_byte_en.v read_verilog generic_sram_line_en.v hierarchy -check -top a23_core add -global_input globrst 1 proc -global_arst globrst techmap -map adff2dff.v opt; memory; opt; fsm; opt; techmap write_blif amber23.blif \end{lstlisting} \renewcommand{\figurename}{Listing} \caption{\tt amber23.ys} \label{aber23.ys} \end{figure} The problem with this core is that it contains no dedicated reset logic. Instead the coding techniques shown in Listing~\ref{glob_arst} are used to define reset values for the global asynchronous reset in an FPGA implementation. This design can not be expressed in BLIF as it is. Instead we need to use a synthesis script that transforms this form to synchronous resets that can be expressed in BLIF. (Note that there is no problem if this coding techniques are used to model ROM, where the register is initialized using this syntax but is never updated otherwise.) \medskip Listing~\ref{aber23.ys} shows the synthesis script for the Amber23 core. In line 17 the {\tt add} command is used to add a 1-bit wide global input signal with the name {\tt globrst}. That means that an input with that name is added to each module in the design hierarchy and then all module instantiations are altered so that this new signal is connected throughout the whole design hierarchy. \begin{figure}[t!] \begin{lstlisting}[language=Verilog] reg [7:0] a = 13, b; initial b = 37; \end{lstlisting} \renewcommand{\figurename}{Listing} \caption{Implicit coding of global asynchronous resets} \label{glob_arst} \end{figure} \begin{figure}[b!] \begin{lstlisting}[language=Verilog] (* techmap_celltype = "$adff" *) module adff2dff (CLK, ARST, D, Q); parameter WIDTH = 1; parameter CLK_POLARITY = 1; parameter ARST_POLARITY = 1; parameter ARST_VALUE = 0; input CLK, ARST; input [WIDTH-1:0] D; output reg [WIDTH-1:0] Q; wire [1023:0] _TECHMAP_DO_ = "proc"; wire _TECHMAP_FAIL_ = !CLK_POLARITY || !ARST_POLARITY; always @(posedge CLK) if (ARST) Q <= ARST_VALUE; else Q <= D; endmodule \end{lstlisting} \renewcommand{\figurename}{Listing} \caption{\tt adff2dff.v} \label{adff2dff.v} \end{figure} In line 18 the {\tt proc} command is called. But in this script the signal name {\tt globrst} is passed to the command as a global reset signal for resetting the registers to their assigned initial values. Finally in line 19 the {\tt techmap} command is used to replace all instances of flip-flops with asynchronous resets with flip-flops with synchronous resets. The map file used for this is shown in Listing~\ref{adff2dff.v}. Note how the {\tt techmap\_celltype} attribute is used in line 1 to tell the techmap command which cells to replace in the design, how the {\tt \_TECHMAP\_FAIL\_} wire in lines 15 and 16 (which evaluates to a constant value) determines if the parameter set is compatible with this replacement circuit, and how the {\tt \_TECHMAP\_DO\_} wire in line 13 provides a mini synthesis-script to be used to process this cell. \begin{figure*} \begin{lstlisting}[language=C] #include <stdint.h> #include <stdbool.h> #define BITMAP_SIZE 64 #define OUTPORT 0x10000000 static uint32_t bitmap[BITMAP_SIZE/32]; static void bitmap_set(uint32_t idx) { bitmap[idx/32] |= 1 << (idx % 32); } static bool bitmap_get(uint32_t idx) { return (bitmap[idx/32] & (1 << (idx % 32))) != 0; } static void output(uint32_t val) { *((volatile uint32_t*)OUTPORT) = val; } int main() { uint32_t i, j, k; output(2); for (i = 0; i < BITMAP_SIZE; i++) { if (bitmap_get(i)) continue; output(3+2*i); for (j = 2*(3+2*i);; j += 3+2*i) { if (j%2 == 0) continue; k = (j-3)/2; if (k >= BITMAP_SIZE) break; bitmap_set(k); } } output(0); return 0; } \end{lstlisting} \renewcommand{\figurename}{Listing} \caption{Test program for the Amber23 CPU (Sieve of Eratosthenes). Compiled using GCC 4.6.3 for ARM with {\tt -Os -marm -march=armv2a -mno-thumb-interwork -ffreestanding}, linked with {\tt -{}-fix-v4bx} set and booted with a custom setup routine written in ARM assembler.} \label{sieve} \end{figure*} \section{Verification of the Amber23 CPU} The BLIF file for the Amber23 core, generated using Listings~\ref{aber23.ys} and \ref{adff2dff.v} and the version of the Amber23 RTL source that is bundled with yosys-bigsim, was verified using the test-bench from yosys-bigsim. It successfully executed the program shown in Listing~\ref{sieve} in the test-bench. For simulation the BLIF file was converted back to Verilog using ABC \cite{ABC}. So this test includes the successful transformation of the BLIF file into ABC's internal format as well. The only thing left to write about the simulation itself is that it probably was one of the most energy inefficient and time consuming ways of successfully calculating the first 31 primes the author has ever conducted. \section{Limitations} At the time of this writing Yosys does not support multi-dimensional memories, does not support writing to individual bits of array elements, does not support initialization of arrays with {\tt \$readmemb} and {\tt \$readmemh}, and has only limited support for tristate logic, to name just a few limitations. That being said, Yosys can synthesize an overwhelming majority of real-world Verilog RTL code. The remaining cases can usually be modified to be compatible with Yosys quite easily. The various designs in yosys-bigsim are a good place to look for examples of what is within the capabilities of Yosys. \section{Conclusion} Yosys is a feature-rich Verilog-2005 synthesis tool. It has many uses, but one is to provide an easy gateway from high-level Verilog code to low-level logic circuits. The command line option {\tt -S} can be used to quickly synthesize Verilog code to BLIF files without a hassle. With custom synthesis scripts it becomes possible to easily perform high-level optimizations, such as re-encoding FSMs. In some extreme cases, such as the Amber23 ARMv2 CPU, the more advanced Yosys features can be used to change a design to fit a certain need without actually touching the RTL code. \begin{thebibliography}{9} \bibitem{yosys} Clifford Wolf. The Yosys Open SYnthesis Suite. \\ \url{http://www.clifford.at/yosys/} \bibitem{bigsim} yosys-bigsim, a collection of real-world Verilog designs for regression testing purposes. \\ \url{https://github.com/cliffordwolf/yosys-bigsim} \bibitem{navre} Sebastien Bourdeauducq. Navr\'e AVR clone (8-bit RISC). \\ \url{http://opencores.org/project,navre} \bibitem{amber} Conor Santifort. Amber ARM-compatible core. \\ \url{http://opencores.org/project,amber} \bibitem{ABC} Berkeley Logic Synthesis and Verification Group. ABC: A System for Sequential Synthesis and Verification. \\ \url{http://www.eecs.berkeley.edu/~alanmi/abc/} \bibitem{blif} Berkeley Logic Interchange Format (BLIF) \\ \url{http://vlsi.colorado.edu/~vis/blif.ps} \end{thebibliography} \end{document}