]> sigrok.org Git - libsigrok.git/blob - src/input/protocoldata.c
feed_queue: rename routines for submission of a single sample value
[libsigrok.git] / src / input / protocoldata.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2019-2023 Gerhard Sittig <gerhard.sittig@gmx.net>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*
21  * This input module reads data values from an input stream, and sends
22  * the corresponding samples to the sigrok session feed which form the
23  * respective waveform, pretending that a logic analyzer had captured
24  * wire traffic. This allows to feed data to protocol decoders which
25  * were recorded by different means (COM port redirection, pcap(3)
26  * recordings, 3rd party bus analyzers). It can also simplify the
27  * initial creation of protocol decoders by generating synthetic
28  * input data, before real world traffic captures become available.
29  *
30  * This input module "assumes ideal traffic" and absence of protocol
31  * errors. Does _not_ inject error conditions, instead generates valid
32  * bit patterns by naively filling blanks to decorate the payload data
33  * which the input file provides. To yield a stream of samples which
34  * successfully decodes at the recipient's, and upper layer decoders
35  * will see valid data which corresponds to the file's content. Edge
36  * positions and minute timnig details are not adjustable either in
37  * this module (no support for setup or hold times or slew rates etc).
38  * The goal is not to emulate a protocol with all its possibilities to
39  * the fullest detail. The module's purpose is to simplify the import
40  * of values while no capture of the wire traffic was available.
41  *
42  * There are several approaches to using the input module:
43  * - Input data can be a mere bytes sequence. While attributes can get
44  *   specified by means of input module options. This is the fastest
45  *   approach to accessing raw data that's externally made available.
46  * - An optional leading magic literal supports automatic file type
47  *   detection, and obsoletes the -I input module selection. Unwanted
48  *   automatic detection is possible but very unlikely. The magic text
49  *   was chosen such that its occurance at the very start of payload
50  *   data is extremely unlikely, and is easy to work around should the
51  *   situation happen. Of course specifying input module options does
52  *   necessitate the selection of the input module.
53  * - When the file type magic is present, an optional header section
54  *   can follow, and can carry parameters which obsolete the necessity
55  *   to specify input module options. The choice of header section
56  *   boundaries again reduces the likelyhood of false detection. When
57  *   input module options were specified, they take precedence over
58  *   input stream content.
59  * - The payload of the input stream (the protocol values) can take
60  *   the form of a mere bytes sequence where every byte is a value
61  *   (this is the default). Or values can be represented in textual
62  *   format when either an input module option or the header section
63  *   specify that the input is text. Individual protocol handlers can
64  *   also prefer one format over another, while file content and
65  *   module options take precedence as usual. Some protocols may not
66  *   usefully be described by values only, or may involve values and
67  *   numbers larger than a byte, which essentially makes text format
68  *   a non-option for these situations.
69  * - The text format supports coments which silently get discarded.
70  *   As well as pseudo comments which can affect the interpretation
71  *   of the input text, and/or can control properties of protocols
72  *   that exceed the mere submission of values. Think chip-select or
73  *   ACK/NAK slots or similar.
74  * - It's understood that the text format is more expensive to process,
75  *   but is also more versatile. It's assumed that the 'protocoldata'
76  *   input format is used for small or mid size capture lengths. The
77  *   input module enables quick access to data that became available
78  *   by other means. For higher fidelity of real world traffic and for
79  *   long captures the native format should be preferred. For error
80  *   injection the VCD format might be a better match.
81  * - It should be obvious that raw bytes or input data in text form,
82  *   as well as header fields can either be the content of a file on
83  *   disk, or can be part of a pipe input. Either the earlier process
84  *   in the pipe which provides the values, or an intermediate filter
85  *   in the pipe, can provide the decoration.
86  *     $ ./gen-values.sh | sigrok-cli -i - ...
87  *     $ ./gen-values.sh | cat header - | sigrok-cli -i - ...
88  * - Since the input format supports automatic detection as well as
89  *   parameter specs by means of input module options as well as in
90  *   file content, the format lends itself equally well to pipelined
91  *   or scripted as well as interactive use in different applications.
92  *   For pipelines, the header as well as the values (as well as any
93  *   mix of these pieces) can be kept in separate locations. Generators
94  *   need not provide all of the input stream in a single invocation.
95  * - As a matter of convenience, especially when targetting upper layer
96  *   protocol decoders, users need not construct "correctly configured"
97  *   from the lower protocol's perspective) waveforms on the wire.
98  *   Instead "naive" waveforms which match the decoders' default options
99  *   can be used, which eliminates the need to configure non-default
100  *   options in decoders (and redundantly do the same thing in the
101  *   input module, just to have them match again).
102  *     $ ./gen-values.sh | sigrok-cli \
103  *       -i - -I protocoldata:protocol=uart:bitrate=57600:frameformat=8e2 \
104  *       -P uart:parity=even:baudrate=57600
105  *     $ ./gen-values.sh | sigrok-cli \
106  *       -i - -I protocoldata:protocol=uart -P uart,midi
107  *
108  * Example invocations:
109  *
110  *   $ sigrok-cli -I protocoldata --show
111  *
112  *   $ echo "Hello sigrok protocol values!" | \
113  *     sigrok-cli \
114  *       -I protocoldata:protocol=uart -i - \
115  *       -P uart:format=ascii -A uart=rx-data
116  *
117  *   $ sigrok-cli -i file.bin -P uart -A uart=rx-data
118  *   $ sigrok-cli -i file.txt -P uart:rx=rxtx -A uart
119  *   $ sigrok-cli -i file.txt --show
120  *   $ sigrok-cli -i file.txt -O ascii:width=4000 | $PAGER
121  *
122  *   $ echo "# -- sigrok protocol data values file --" > header.txt
123  *   $ echo "# -- sigrok protocol data header start --" >> header.txt
124  *   $ echo "protocol=uart" >> header.txt
125  *   $ echo "bitrate=100000" >> header.txt
126  *   $ echo "frameformat=8e2" >> header.txt
127  *   $ echo "textinput=yes" >> header.txt
128  *   $ echo "# -- sigrok protocol data header end --" >> header.txt
129  *   $ echo "# textinput: radix=16" > values.txt
130  *   $ echo "0f  40 a6 28 fa 78 05 19 ee c2 92 70 58 62 09 a9 f1 ca 44 90 d1 07 19  02  00" >> values.txt
131  *   $ head header.txt values.txt
132  *   $ cat values.txt | cat header.txt - | \
133  *     sigrok-cli -i - -P uart:baudrate=100000:parity=even,sbus_futaba -A sbus_futaba
134  *
135  *   $ pulseview -i file-spi-text.txt &
136  *
137  * Known issues:
138  * - Only few protocols are implemented so far. Existing handlers have
139  *   suggested which infrastructure is required for future extension.
140  *   But future handlers may reveal more omissions or assumptions that
141  *   need addressing.
142  * - Terminology may be inconsistent, because this input module supports
143  *   several protocols which often differ in how they use terms. What is
144  *   available:
145  *   - The input module constructs waveforms that span multiple traces.
146  *     Resulting waveforms are said to have a samplerate. Data that is
147  *     kept in that waveform can have a bitrate. Which is essential for
148  *     asynchronous communication, but could be unimportant for clocked
149  *     protocols. Protocol handlers may adjust their output to enforce
150  *     a bitrate, but need not. The timing is an approximation anyway,
151  *     does not reflect pauses or jitter or turnarounds which real world
152  *     traffic would reveal.
153  *   - Protocol handlers can generate an arbitrary number of samples for
154  *     a protocol data value. A maximum number of samples per value is
155  *     assumed. Variable length samples sequences per data value or per
156  *     invocation is supported (and can be considered the typical case).
157  *   - Protocol handlers can configure differing widths for the samples
158  *     that they derived from input data. These quanta get configured
159  *     when the frame format gets interpreted, and are assumed to remain
160  *     as they are across data value processing.
161  *   - Data values can be considered "a frame" (as seen with UART). But
162  *     data values could also be "bytes" or "words" in a protocol, while
163  *     "frames" or "transfers" are implemented by different means (as
164  *     seen with SPI or I2C). The typical approach would be to control a
165  *     "select" signal by means of pseudo comments which are interleaved
166  *     with data values.
167  *   - Data values need not get forwarded to decoders. They might also
168  *     control the processing of the following data values as well as
169  *     the waveform construction. This is at the discretion of protocol
170  *     handlers, think of slave addresses, preceeding field or value
171  *     counts before their data values follow, etc.
172  * - Users may need to specify more options than expected when the file
173  *   content is "incomplete". The sequence of scanning builtin defaults,
174  *   then file content provided specs, then user specified specs, is
175  *   yet to get done. Until then it helps being explicit and thorough.
176  *
177  * TODO (arbitrary order, could partially be outdated)
178  * - Implement the most appropriate order of option scanning. Use
179  *   builtin defaults first, file content then, then user specified
180  *   options (when available). This shall be most robust and correct.
181  * - Switch to "submit one sample" in feed queue API when available.
182  *   The current implementation of this input module uses ugly ifdefs
183  *   to adjust to either feed queue API approach.
184  * - (obsoleted by the introduction of support for text format input?)
185  *   Introduce TLV support for the binary input format? u32be type,
186  *   u64be length, u8[] payload. The complexity of the implementation
187  *   in the input module, combined with the complexity of generating
188  *   the input stream which uses TLV sections, are currently considered
189  *   undesirable for this input module. Do we expect huge files where
190  *   the computational cost of text conversion causes pain?
191  * - Extend the UART protocol handler. Implement separate RX and TX
192  *   traces. Support tx-only, rx-only, and tx-then-rx input orders.
193  * - Add a 'parallel' protocol handler, which grabs a bit pattern and
194  *   derives the waveform in straight forward ways? This would be similar
195  *   to the raw binary input module, but the text format could improve
196  *   readability, and the input module could generate a clock signal
197  *   which isn't part of the input stream. That 'parallel' protocol
198  *   could be used as a vehicle to bitbang any other protocol that is
199  *   unknown to the input module. The approach is only limited by the
200  *   input stream generator's imagination.
201  * - Add other protocol variants. The binary input format was very
202  *   limiting, the text format could cover a lot of more cases:
203  *   - CAN: Pseudo comments can communicate the frame's flags (and
204  *     address type etc). The first data value can be the address. The
205  *     second data value or a pseudo comment can hold the CAN frame's
206  *     data length (bytes count). Other data values are the 0..8 data
207  *     bytes. CAN-FD might be possible with minimal adjustment?
208  *   - W1: Pseudo comments can start a frame (initiate RESET). First
209  *     value can carry frame length. Data bytes follow. Scans can get
210  *     represented as raw bytes (bit count results in full 8bit size).
211  * - Are more than 8 traces desirable? The initial implementation was
212  *   motivated by serial communication (UART). More channels were not
213  *   needed so far. Even QuadSPI and Hitachi displays fit onto 8 lines.
214  *
215  * See the sigrok.org file format wiki page for details about the syntax
216  * that is supported by this input module. Or see the top of the source
217  * file and its preprocessor symbols to quickly get an idea of known
218  * keywords in input files.
219  */
220
221 #include "config.h"
222
223 #include <ctype.h>
224 #include <libsigrok/libsigrok.h>
225 #include <string.h>
226 #include <strings.h>
227
228 #include "libsigrok-internal.h"
229
230 #define LOG_PREFIX      "input/protocoldata"
231
232 #define CHUNK_SIZE      (4 * 1024 * 1024)
233
234 /*
235  * Support optional automatic file type detection. Support optionally
236  * embedded options in a header section after the file detection magic
237  * and before the payload data (bytes or text).
238  */
239 #define MAGIC_FILE_TYPE         "# -- sigrok protocol data values file --"
240 #define TEXT_HEAD_START         "# -- sigrok protocol data header start --"
241 #define TEXT_HEAD_END           "# -- sigrok protocol data header end --"
242 #define TEXT_COMM_LEADER        "#"
243
244 #define LABEL_SAMPLERATE        "samplerate="
245 #define LABEL_BITRATE           "bitrate="
246 #define LABEL_PROTOCOL          "protocol="
247 #define LABEL_FRAMEFORMAT       "frameformat="
248 #define LABEL_TEXTINPUT         "textinput="
249
250 /*
251  * Options which are embedded in pseudo comments and are related to
252  * how the input module reads the input text stream. Universally
253  * applicable to all text inputs regardless of protocol choice.
254  */
255 #define TEXT_INPUT_PREFIX       "textinput:"
256 #define TEXT_INPUT_RADIX        "radix="
257
258 /*
259  * Protocol dependent frame formats, the default and absolute limits.
260  * Protocol dependent keywords in pseudo-comments.
261  *
262  * UART assumes 9x2 as the longest useful frameformat. Additional STOP
263  * bits let users insert idle phases between frames, until more general
264  * support for inter-frame gaps is in place. By default the protocol
265  * handler generously adds a few more idle bit times after a UART frame.
266  *
267  * SPI assumes exactly 8 bits per "word". And leaves bit slots around
268  * the byte transmission, to have space where CS asserts or releases.
269  * Including time where SCK changes to its idle level. And requires two
270  * samples per bit time (pos and neg clock phase). The "decoration" also
271  * helps users' interactive exploration of generated waveforms.
272  *
273  * I2C generously assumes six quanta per bit slot, to gracefully allow
274  * for reliable SCL and SDA transitions regardless of samples that result
275  * from prior communication. The longest waveform is a byte (with eight
276  * data bits and an ACK slot). Special symbols like START, and STOP will
277  * fit into that memory while it is not used to communicate a byte.
278  */
279 #define UART_HANDLER_NAME       "uart"
280 #define UART_DFLT_SAMPLERATE    SR_MHZ(1)
281 #define UART_DFLT_BITRATE       115200
282 #define UART_DFLT_FRAMEFMT      "8n1"
283 #define UART_MIN_DATABITS       5
284 #define UART_MAX_DATABITS       9
285 #define UART_MAX_STOPBITS       20
286 #define UART_ADD_IDLEBITS       2
287 #define UART_MAX_WAVELEN        (1 + UART_MAX_DATABITS + 1 + UART_MAX_STOPBITS \
288                                 + UART_ADD_IDLEBITS)
289 #define UART_FORMAT_INVERT      "inverted"
290 /* In addition the usual '8n1' et al are supported. */
291 #define UART_PSEUDO_BREAK       "break"
292 #define UART_PSEUDO_IDLE        "idle"
293
294 #define SPI_HANDLER_NAME        "spi"
295 #define SPI_DFLT_SAMPLERATE     SR_MHZ(10)
296 #define SPI_DFLT_BITRATE        SR_MHZ(1)
297 #define SPI_DFLT_FRAMEFMT       "cs-low,bits=8,mode=0,msb-first"
298 #define SPI_MIN_DATABITS        8
299 #define SPI_MAX_DATABITS        8
300 #define SPI_MAX_WAVELEN         (2 + 2 * SPI_MAX_DATABITS + 3)
301 #define SPI_FORMAT_CS_LOW       "cs-low"
302 #define SPI_FORMAT_CS_HIGH      "cs-high"
303 #define SPI_FORMAT_DATA_BITS    "bits="
304 #define SPI_FORMAT_SPI_MODE     "mode="
305 #define SPI_FORMAT_MODE_CPOL    "cpol="
306 #define SPI_FORMAT_MODE_CPHA    "cpha="
307 #define SPI_FORMAT_MSB_FIRST    "msb-first"
308 #define SPI_FORMAT_LSB_FIRST    "lsb-first"
309 #define SPI_PSEUDO_MOSI_ONLY    "mosi-only"
310 #define SPI_PSEUDO_MOSI_FIXED   "mosi-fixed="
311 #define SPI_PSEUDO_MISO_ONLY    "miso-only"
312 #define SPI_PSEUDO_MISO_FIXED   "miso-fixed="
313 #define SPI_PSEUDO_MOSI_MISO    "mosi-then-miso"
314 #define SPI_PSEUDO_MISO_MOSI    "miso-then-mosi"
315 #define SPI_PSEUDO_CS_ASSERT    "cs-assert"
316 #define SPI_PSEUDO_CS_RELEASE   "cs-release"
317 #define SPI_PSEUDO_CS_NEXT      "cs-auto-next="
318 #define SPI_PSEUDO_IDLE         "idle"
319
320 #define I2C_HANDLER_NAME        "i2c"
321 #define I2C_DFLT_SAMPLERATE     SR_MHZ(10)
322 #define I2C_DFLT_BITRATE        SR_KHZ(400)
323 #define I2C_DFLT_FRAMEFMT       "addr-7bit"
324 #define I2C_BITTIME_SLOTS       (1 + 8 + 1 + 1)
325 #define I2C_BITTIME_QUANTA      6
326 #define I2C_ADD_IDLESLOTS       2
327 #define I2C_MAX_WAVELEN         (I2C_BITTIME_QUANTA * I2C_BITTIME_SLOTS + I2C_ADD_IDLESLOTS)
328 #define I2C_FORMAT_ADDR_7BIT    "addr-7bit"
329 #define I2C_FORMAT_ADDR_10BIT   "addr-10bit"
330 #define I2C_PSEUDO_START        "start"
331 #define I2C_PSEUDO_REP_START    "repeat-start"
332 #define I2C_PSEUDO_STOP         "stop"
333 #define I2C_PSEUDO_ADDR_WRITE   "addr-write="
334 #define I2C_PSEUDO_ADDR_READ    "addr-read="
335 #define I2C_PSEUDO_ACK_NEXT     "ack-next="
336 #define I2C_PSEUDO_ACK_ONCE     "ack-next"
337
338 enum textinput_t {
339         INPUT_UNSPEC,
340         INPUT_BYTES,
341         INPUT_TEXT,
342 };
343
344 static const char *input_format_texts[] = {
345         [INPUT_UNSPEC] = "from-file",
346         [INPUT_BYTES] = "raw-bytes",
347         [INPUT_TEXT] = "text-format",
348 };
349
350 struct spi_proto_context_t {
351         gboolean needs_mosi, has_mosi;
352         gboolean needs_miso, has_miso;
353         gboolean mosi_first;
354         gboolean cs_active;
355         size_t auto_cs_remain;
356         uint8_t mosi_byte, miso_byte;
357         uint8_t mosi_fixed_value;
358         gboolean mosi_is_fixed;
359         uint8_t miso_fixed_value;
360         gboolean miso_is_fixed;
361 };
362
363 struct i2c_proto_context_t {
364         size_t ack_remain;
365 };
366
367 struct context;
368
369 struct proto_handler_t {
370         const char *name;
371         struct {
372                 uint64_t samplerate;
373                 uint64_t bitrate;
374                 const char *frame_format;
375                 enum textinput_t textinput;
376         } dflt;
377         struct {
378                 size_t count;
379                 const char **names;
380         } chans;
381         size_t priv_size;
382         int (*check_opts)(struct context *inc);
383         int (*config_frame)(struct context *inc);
384         int (*proc_pseudo)(struct sr_input *in, char *text);
385         int (*proc_value)(struct context *inc, uint32_t value);
386         int (*get_idle_capture)(struct context *inc,
387                 size_t *bits, uint8_t *lvls);
388         int (*get_idle_interframe)(struct context *inc,
389                 size_t *samples, uint8_t *lvls);
390 };
391
392 struct context {
393         /* User provided options. */
394         struct user_opts_t {
395                 uint64_t samplerate;
396                 uint64_t bitrate;
397                 const char *proto_name;
398                 const char *fmt_text;
399                 enum textinput_t textinput;
400         } user_opts;
401         /* Derived at runtime. */
402         struct {
403                 uint64_t samplerate;
404                 uint64_t bitrate;
405                 uint64_t samples_per_bit;
406                 char *proto_name;
407                 char *fmt_text;
408                 enum textinput_t textinput;
409                 enum proto_type_t {
410                         PROTO_TYPE_NONE,
411                         PROTO_TYPE_UART,
412                         PROTO_TYPE_SPI,
413                         PROTO_TYPE_I2C,
414                         PROTO_TYPE_COUNT,
415                 } protocol_type;
416                 const struct proto_handler_t *prot_hdl;
417                 void *prot_priv;
418                 union {
419                         struct uart_frame_fmt_opts {
420                                 size_t databit_count;
421                                 enum {
422                                         UART_PARITY_NONE,
423                                         UART_PARITY_ODD,
424                                         UART_PARITY_EVEN,
425                                 } parity_type;
426                                 size_t stopbit_count;
427                                 gboolean half_stopbit;
428                                 gboolean inverted;
429                         } uart;
430                         struct spi_frame_fmt_opts {
431                                 uint8_t cs_polarity;
432                                 size_t databit_count;
433                                 gboolean msb_first;
434                                 gboolean spi_mode_cpol;
435                                 gboolean spi_mode_cpha;
436                         } spi;
437                         struct i2c_frame_fmt_opts {
438                                 gboolean addr_10bit;
439                         } i2c;
440                 } frame_format;
441         } curr_opts;
442         /* Module stage. Logic output channels. Session feed. */
443         gboolean scanned_magic;
444         gboolean has_magic;
445         gboolean has_header;
446         gboolean got_header;
447         gboolean started;
448         gboolean meta_sent;
449         size_t channel_count;
450         const char **channel_names;
451         struct feed_queue_logic *feed_logic;
452         /*
453          * Internal state: Allocated space for a theoretical maximum
454          * bit count. Filled in bit pattern for the current data value.
455          * (Stuffing can result in varying bit counts across frames.)
456          *
457          * Keep the bits' width in sample numbers, as well as the bits'
458          * boundaries relative to the start of the protocol frame's
459          * start. Support a number of logic bits per bit time.
460          *
461          * Implementor's note: Due to development history terminology
462          * might slip here. Strictly speaking it's "waveform sections"
463          * that hold samples for a given number of cycles. "A bit" in
464          * the protocol can occupy multiple of these slots to e.g. have
465          * a synchronous clock, or to present setup and hold phases,
466          * etc. Sample data spans several logic signal traces. You get
467          * the idea ...
468          */
469         size_t max_frame_bits;  /* Reserved. */
470         size_t top_frame_bits;  /* Currently filled. */
471         struct {
472                 size_t mul;
473                 size_t div;
474         } *bit_scale;           /* Quanta scaling. */
475         size_t *sample_edges;
476         size_t *sample_widths;
477         uint8_t *sample_levels; /* Sample data, logic traces. */
478         /* Common support for samples updating by manipulation. */
479         struct {
480                 uint8_t idle_levels;
481                 uint8_t curr_levels;
482         } samples;
483         /* Internal state of the input text reader. */
484         struct {
485                 int base;
486         } read_text;
487         /* Manage state across .reset() calls. Robustness. */
488         struct proto_prev {
489                 GSList *sr_channels;
490                 GSList *sr_groups;
491         } prev;
492 };
493
494 /* {{{ frame bits manipulation, waveform construction */
495
496 /*
497  * Primitives to construct waveforms for a protocol frame, by sequencing
498  * samples after data values were seen in the input stream. Individual
499  * protocol handlers will use these common routines.
500  *
501  * The general idea is: The protocol handler's options parser determines
502  * the frame format, and derives the maximum number of time slots needed
503  * to represent the waveform. Slots can scale differintly, proportions
504  * get configured once during initialization. All remaining operation
505  * receives arbitrarily interleaved data values and pseudo comments, uses
506  * the pre-allocated and pre-scaled time slots to construct waveforms,
507  * which then get sent to the session bus as if an acquisition device
508  * had captured wire traffic. For clocked signals the "coarse" timing
509  * should never be an issue. Protocol handlers are free to use as many
510  * time slots per bit time as they please or feel necessary.
511  */
512
513 static int alloc_frame_storage(struct context *inc)
514 {
515         size_t bits, alloc;
516
517         if (!inc)
518                 return SR_ERR_ARG;
519
520         if (!inc->max_frame_bits)
521                 return SR_ERR_DATA;
522
523         inc->top_frame_bits = 0;
524         bits = inc->max_frame_bits;
525
526         alloc = bits * sizeof(inc->sample_edges[0]);
527         inc->sample_edges = g_malloc0(alloc);
528         alloc = bits * sizeof(inc->sample_widths[0]);
529         inc->sample_widths = g_malloc0(alloc);
530         alloc = bits * sizeof(inc->sample_levels[0]);
531         inc->sample_levels = g_malloc0(alloc);
532         if (!inc->sample_edges || !inc->sample_widths || !inc->sample_levels)
533                 return SR_ERR_MALLOC;
534
535         alloc = bits * sizeof(inc->bit_scale[0]);
536         inc->bit_scale = g_malloc0(alloc);
537         if (!inc->bit_scale)
538                 return SR_ERR_MALLOC;
539
540         return SR_OK;
541 }
542
543 /*
544  * Assign an equal bit width to all bits in the frame. Derive the width
545  * from the bitrate and the sampelrate. Protocol handlers optionally can
546  * arrange for "odd bit widths" (either fractions, or multiples, or when
547  * desired any rational at all). Think half-bits, or think quanta within
548  * a bit time, depends on the protocol handler really.
549  *
550  * Implementation note: The input module assumes that the position of
551  * odd length bits will never vary during frame construction. The total
552  * length may vary, 'top' can be smaller than 'max' in every iteration.
553  * It is assumed that frames with odd-length bits have constant layout,
554  * and that stuffing protocols have same-width bits. Odd lengths also
555  * can support bit time quanta, while it's assumed that these always use
556  * the same layout for all generated frames. This constraint is kept in
557  * the implementation, until one of the supported protocols genuinely
558  * requires higher flexibility and the involved complexity and runtime
559  * cost of per-samplepoint adjustment.
560  */
561 static int assign_bit_widths(struct context *inc)
562 {
563         const struct proto_handler_t *handler;
564         int ret;
565         double bit_edge, bit_time, this_bit_time;
566         uint64_t bit_time_int, bit_time_prev, bit_times_total;
567         size_t idx;
568
569         if (!inc)
570                 return SR_ERR_ARG;
571
572         /*
573          * Run the protocol handler's optional configure routine.
574          * It derives the maximum number of "bit slots" that are needed
575          * to represent a protocol frame's waveform.
576          */
577         handler = inc->curr_opts.prot_hdl;
578         if (handler && handler->config_frame) {
579                 ret = handler->config_frame(inc);
580                 if (ret != SR_OK)
581                         return ret;
582         }
583
584         /* Assign bit widths to the protocol frame's bit positions. */
585         bit_time = inc->curr_opts.samplerate;
586         bit_time /= inc->curr_opts.bitrate;
587         inc->curr_opts.samples_per_bit = bit_time + 0.5;
588         sr_dbg("Samplerate %" PRIu64 ", bitrate %" PRIu64 ".",
589                 inc->curr_opts.samplerate, inc->curr_opts.bitrate);
590         sr_dbg("Resulting bit width %.2f samples, int %" PRIu64 ".",
591                 bit_time, inc->curr_opts.samples_per_bit);
592         bit_edge = 0.0;
593         bit_time_prev = 0;
594         bit_times_total = 0;
595         for (idx = 0; idx < inc->max_frame_bits; idx++) {
596                 this_bit_time = bit_time;
597                 if (inc->bit_scale[idx].mul)
598                         this_bit_time *= inc->bit_scale[idx].mul;
599                 if (inc->bit_scale[idx].div)
600                         this_bit_time /= inc->bit_scale[idx].div;
601                 bit_edge += this_bit_time;
602                 bit_time_int = (uint64_t)(bit_edge + 0.5);
603                 inc->sample_edges[idx] = bit_time_int;
604                 bit_time_int -= bit_time_prev;
605                 inc->sample_widths[idx] = bit_time_int;
606                 bit_time_prev = inc->sample_edges[idx];
607                 bit_times_total += bit_time_int;
608                 sr_spew("Bit %zu, width %" PRIu64 ".", idx, bit_time_int);
609         }
610         sr_dbg("Maximum waveform width: %zu slots, %.2f / %zu samples.",
611                 inc->max_frame_bits, bit_edge, bit_times_total);
612
613         return SR_OK;
614 }
615
616 /* Start accumulating the samples for a new part of the waveform. */
617 static int wave_clear_sequence(struct context *inc)
618 {
619
620         if (!inc)
621                 return SR_ERR_ARG;
622
623         inc->top_frame_bits = 0;
624
625         return SR_OK;
626 }
627
628 /* Append channels' levels to the waveform for another period of samples. */
629 static int wave_append_pattern(struct context *inc, uint8_t sample)
630 {
631
632         if (!inc)
633                 return SR_ERR_ARG;
634
635         if (inc->top_frame_bits >= inc->max_frame_bits)
636                 return SR_ERR_DATA;
637
638         inc->sample_levels[inc->top_frame_bits++] = sample;
639
640         return SR_OK;
641 }
642
643 /* Initially assign idle levels, start the buffer from idle state. */
644 static void sample_buffer_preset(struct context *inc, uint8_t idle_sample)
645 {
646         inc->samples.idle_levels = idle_sample;
647         inc->samples.curr_levels = idle_sample;
648 }
649
650 /* Modify the samples buffer by assigning a given traces state. */
651 static void sample_buffer_assign(struct context *inc, uint8_t sample)
652 {
653         inc->samples.curr_levels = sample;
654 }
655
656 /* Modify the samples buffer by changing individual traces. */
657 static void sample_buffer_modify(struct context *inc,
658         uint8_t set_mask, uint8_t clr_mask)
659 {
660         inc->samples.curr_levels |= set_mask;
661         inc->samples.curr_levels &= ~clr_mask;
662 }
663
664 static void sample_buffer_raise(struct context *inc, uint8_t bits)
665 {
666         return sample_buffer_modify(inc, bits, 0);
667 }
668
669 static void sample_buffer_clear(struct context *inc, uint8_t bits)
670 {
671         return sample_buffer_modify(inc, 0, bits);
672 }
673
674 static void sample_buffer_setclr(struct context *inc,
675         gboolean level, uint8_t mask)
676 {
677         if (level)
678                 sample_buffer_raise(inc, mask);
679         else
680                 sample_buffer_clear(inc, mask);
681 }
682
683 static void sample_buffer_toggle(struct context *inc, uint8_t mask)
684 {
685         inc->samples.curr_levels ^= mask;
686 }
687
688 /* Reset current sample buffer to idle state. */
689 static void sample_buffer_toidle(struct context *inc)
690 {
691         inc->samples.curr_levels = inc->samples.idle_levels;
692 }
693
694 /* Append the buffered samples to the waveform memory. */
695 static int wave_append_buffer(struct context *inc)
696 {
697         return wave_append_pattern(inc, inc->samples.curr_levels);
698 }
699
700 /* Send idle level before the first generated frame and at end of capture. */
701 static int send_idle_capture(struct context *inc)
702 {
703         const struct proto_handler_t *handler;
704         size_t count;
705         uint8_t data;
706         int ret;
707
708         handler = inc->curr_opts.prot_hdl;
709         if (!handler->get_idle_capture)
710                 return SR_OK;
711
712         ret = handler->get_idle_capture(inc, &count, &data);
713         if (ret != SR_OK)
714                 return ret;
715         count *= inc->curr_opts.samples_per_bit;
716         while (count--) {
717                 ret = feed_queue_logic_submit_one(inc->feed_logic,
718                         &data, sizeof(data));
719                 if (ret != SR_OK)
720                         return ret;
721         }
722
723         return SR_OK;
724 }
725
726 /* Optionally send idle level between protocol frames. */
727 static int send_idle_interframe(struct context *inc)
728 {
729         const struct proto_handler_t *handler;
730         size_t count;
731         uint8_t data;
732         int ret;
733
734         handler = inc->curr_opts.prot_hdl;
735         if (!handler->get_idle_interframe)
736                 return SR_OK;
737
738         ret = handler->get_idle_interframe(inc, &count, &data);
739         if (ret != SR_OK)
740                 return ret;
741         while (count--) {
742                 ret = feed_queue_logic_submit_one(inc->feed_logic,
743                         &data, sizeof(data));
744                 if (ret != SR_OK)
745                         return ret;
746         }
747
748         return SR_OK;
749 }
750
751 /* Forward the previously accumulated samples of the waveform. */
752 static int send_frame(struct sr_input *in)
753 {
754         struct context *inc;
755         size_t count, index;
756         uint8_t data;
757
758         inc = in->priv;
759
760         for (index = 0; index < inc->top_frame_bits; index++) {
761                 data = inc->sample_levels[index];
762                 count = inc->sample_widths[index];
763                 while (count--) {
764                         feed_queue_logic_submit_one(inc->feed_logic,
765                                 &data, sizeof(data));
766                 }
767         }
768
769         return SR_OK;
770 }
771
772 /* }}} frame bits manipulation */
773 /* {{{ UART protocol handler */
774
775 enum uart_pin_t {
776         UART_PIN_RXTX,
777 };
778
779 #define UART_PINMASK_RXTX       (1UL << UART_PIN_RXTX)
780
781 /* UART specific options and frame format check. */
782 static int uart_check_opts(struct context *inc)
783 {
784         struct uart_frame_fmt_opts *fmt_opts;
785         const char *fmt_text;
786         char **opts, *opt;
787         size_t opt_count, opt_idx;
788         int ret;
789         unsigned long v;
790         char par_text;
791         char *endp;
792         size_t total_bits;
793
794         if (!inc)
795                 return SR_ERR_ARG;
796         fmt_opts = &inc->curr_opts.frame_format.uart;
797
798         /* Apply defaults before reading external spec. */
799         memset(fmt_opts, 0, sizeof(*fmt_opts));
800         fmt_opts->databit_count = 8;
801         fmt_opts->parity_type = UART_PARITY_NONE;
802         fmt_opts->stopbit_count = 1;
803         fmt_opts->half_stopbit = FALSE;
804         fmt_opts->inverted = FALSE;
805
806         /* Provide a default UART frame format. */
807         fmt_text = inc->curr_opts.fmt_text;
808         if (!fmt_text || !*fmt_text)
809                 fmt_text = UART_DFLT_FRAMEFMT;
810         sr_dbg("UART frame format: %s.", fmt_text);
811
812         /* Parse the comma separated list of user provided options. */
813         opts = g_strsplit_set(fmt_text, ", ", 0);
814         opt_count = g_strv_length(opts);
815         for (opt_idx = 0; opt_idx < opt_count; opt_idx++) {
816                 opt = opts[opt_idx];
817                 if (!opt || !*opt)
818                         continue;
819                 sr_spew("UART format option: %s", opt);
820                 /*
821                  * Check for specific keywords. Before falling back to
822                  * attempting the "8n1" et al interpretation.
823                  */
824                 if (strcmp(opt, UART_FORMAT_INVERT) == 0) {
825                         fmt_opts->inverted = TRUE;
826                         continue;
827                 }
828                 /* Parse an "8n1", "8e2", "7o1", or similar input spec. */
829                 /* Get the data bits count. */
830                 endp = NULL;
831                 ret = sr_atoul_base(opt, &v, &endp, 10);
832                 if (ret != SR_OK || !endp)
833                         return SR_ERR_DATA;
834                 opt = endp;
835                 if (v < UART_MIN_DATABITS || v > UART_MAX_DATABITS)
836                         return SR_ERR_DATA;
837                 fmt_opts->databit_count = v;
838                 /* Get the parity type. */
839                 par_text = tolower((int)*opt++);
840                 switch (par_text) {
841                 case 'n':
842                         fmt_opts->parity_type = UART_PARITY_NONE;
843                         break;
844                 case 'o':
845                         fmt_opts->parity_type = UART_PARITY_ODD;
846                         break;
847                 case 'e':
848                         fmt_opts->parity_type = UART_PARITY_EVEN;
849                         break;
850                 default:
851                         return SR_ERR_DATA;
852                 }
853                 /* Get the stop bits count. Supports half bits too. */
854                 endp = NULL;
855                 ret = sr_atoul_base(opt, &v, &endp, 10);
856                 if (ret != SR_OK || !endp)
857                         return SR_ERR_DATA;
858                 opt = endp;
859                 if (v > UART_MAX_STOPBITS)
860                         return SR_ERR_DATA;
861                 fmt_opts->stopbit_count = v;
862                 if (g_ascii_strcasecmp(opt, ".5") == 0) {
863                         opt += strlen(".5");
864                         fmt_opts->half_stopbit = TRUE;
865                 }
866                 /* Incomplete consumption of input text is fatal. */
867                 if (*opt) {
868                         sr_err("Unprocessed frame format remainder: %s.", opt);
869                         return SR_ERR_DATA;
870                 }
871                 continue;
872         }
873         g_strfreev(opts);
874
875         /*
876          * Calculate the total number of bit times in the UART frame.
877          * Add a few more bit times to the reserved space. They usually
878          * are not occupied during data transmission, but are useful to
879          * have for special symbols (BREAK, IDLE).
880          */
881         total_bits = 1; /* START bit, unconditional. */
882         total_bits += fmt_opts->databit_count;
883         total_bits += (fmt_opts->parity_type != UART_PARITY_NONE) ? 1 : 0;
884         total_bits += fmt_opts->stopbit_count;
885         total_bits += fmt_opts->half_stopbit ? 1 : 0;
886         total_bits += UART_ADD_IDLEBITS;
887         sr_dbg("UART frame: total bits %lu.", total_bits);
888         if (total_bits > UART_MAX_WAVELEN)
889                 return SR_ERR_DATA;
890         inc->max_frame_bits = total_bits;
891
892         return SR_OK;
893 }
894
895 /*
896  * Configure the frame's bit widths when not identical across the
897  * complete frame. Think half STOP bits.
898  * Preset the sample data for an idle bus.
899  */
900 static int uart_config_frame(struct context *inc)
901 {
902         struct uart_frame_fmt_opts *fmt_opts;
903         size_t bit_idx;
904         uint8_t sample;
905
906         if (!inc)
907                 return SR_ERR_ARG;
908         fmt_opts = &inc->curr_opts.frame_format.uart;
909
910         /*
911          * Position after the START bit. Advance over DATA, PARITY and
912          * (full) STOP bits. Then set the trailing STOP bit to half if
913          * needed. Make the trailing IDLE period after a UART frame
914          * wider than regular bit times. Add an even wider IDLE period
915          * which is used for special symbols.
916          */
917         bit_idx = 1;
918         bit_idx += fmt_opts->databit_count;
919         bit_idx += (fmt_opts->parity_type == UART_PARITY_NONE) ? 0 : 1;
920         bit_idx += fmt_opts->stopbit_count;
921         if (fmt_opts->half_stopbit) {
922                 sr_dbg("Setting bit index %zu to half width.", bit_idx);
923                 inc->bit_scale[bit_idx].div = 2;
924                 bit_idx++;
925         }
926         inc->bit_scale[bit_idx++].mul = 2;
927         inc->bit_scale[bit_idx++].mul = 4;
928
929         /* Start from idle signal levels (high when not inverted). */
930         sample = 0;
931         if (!fmt_opts->inverted)
932                 sample |= UART_PINMASK_RXTX;
933         sample_buffer_preset(inc, sample);
934
935         return SR_OK;
936 }
937
938 /* Create samples for a special UART frame (IDLE, BREAK). */
939 static int uart_write_special(struct context *inc, uint8_t level)
940 {
941         struct uart_frame_fmt_opts *fmt_opts;
942         int ret;
943         size_t bits;
944
945         if (!inc)
946                 return SR_ERR_ARG;
947         fmt_opts = &inc->curr_opts.frame_format.uart;
948
949         ret = wave_clear_sequence(inc);
950         if (ret != SR_OK)
951                 return ret;
952
953         /*
954          * Set the same level for all bit slots, covering all of
955          * START and DATA (and PARITY) and STOP. This allows the
956          * simulation of BREAK and IDLE phases.
957          */
958         if (fmt_opts->inverted)
959                 level = !level;
960         sample_buffer_setclr(inc, level, UART_PINMASK_RXTX);
961         bits = 1; /* START */
962         bits += fmt_opts->databit_count;
963         bits += (fmt_opts->parity_type != UART_PARITY_NONE) ? 1 : 0;
964         bits += fmt_opts->stopbit_count;
965         bits += fmt_opts->half_stopbit ? 1 : 0;
966         while (bits--) {
967                 ret = wave_append_buffer(inc);
968                 if (ret != SR_OK)
969                         return ret;
970         }
971
972         /*
973          * Force a few more idle bit times. This does not affect a
974          * caller requested IDLE symbol. But helps separate (i.e.
975          * robustly detect) several caller requested BREAK symbols.
976          * Also separates those specials from subsequent data bytes.
977          */
978         sample_buffer_toidle(inc);
979         bits = UART_ADD_IDLEBITS;
980         while (bits--) {
981                 ret = wave_append_buffer(inc);
982                 if (ret != SR_OK)
983                         return ret;
984         }
985
986         return SR_OK;
987 }
988
989 /* Process UART protocol specific pseudo comments. */
990 static int uart_proc_pseudo(struct sr_input *in, char *line)
991 {
992         struct context *inc;
993         char *word;
994         int ret;
995
996         inc = in->priv;
997
998         while (line) {
999                 word = sr_text_next_word(line, &line);
1000                 if (!word)
1001                         break;
1002                 if (!*word)
1003                         continue;
1004                 if (strcmp(word, UART_PSEUDO_BREAK) == 0) {
1005                         ret = uart_write_special(inc, 0);
1006                         if (ret != SR_OK)
1007                                 return ret;
1008                         ret = send_frame(in);
1009                         if (ret != SR_OK)
1010                                 return ret;
1011                         continue;
1012                 }
1013                 if (strcmp(word, UART_PSEUDO_IDLE) == 0) {
1014                         ret = uart_write_special(inc, 1);
1015                         if (ret != SR_OK)
1016                                 return ret;
1017                         ret = send_frame(in);
1018                         if (ret != SR_OK)
1019                                 return ret;
1020                         continue;
1021                 }
1022                 return SR_ERR_DATA;
1023         }
1024
1025         return SR_OK;
1026 }
1027
1028 /*
1029  * Create the UART frame's waveform for the given data value.
1030  *
1031  * In theory the protocol handler could setup START and STOP once during
1032  * initialization. But the overhead compares to DATA and PARITY is small.
1033  * And unconditional START/STOP would break the creation of BREAK and
1034  * IDLE frames, or complicate their construction and recovery afterwards.
1035  * A future implementation might as well support UART traffic on multiple
1036  * traces, including interleaved bidirectional communication. So let's
1037  * keep the implementation simple. Execution time is not a priority.
1038  */
1039 static int uart_proc_value(struct context *inc, uint32_t value)
1040 {
1041         struct uart_frame_fmt_opts *fmt_opts;
1042         int ret;
1043         size_t bits;
1044         int par_bit, data_bit;
1045
1046         if (!inc)
1047                 return SR_ERR_ARG;
1048         fmt_opts = &inc->curr_opts.frame_format.uart;
1049
1050         ret = wave_clear_sequence(inc);
1051         if (ret != SR_OK)
1052                 return ret;
1053
1054         /* START bit, unconditional, always 0. */
1055         sample_buffer_clear(inc, UART_PINMASK_RXTX);
1056         if (fmt_opts->inverted)
1057                 sample_buffer_toggle(inc, UART_PINMASK_RXTX);
1058         ret = wave_append_buffer(inc);
1059
1060         /* DATA bits. Track parity here (unconditionally). */
1061         par_bit = 0;
1062         bits = fmt_opts->databit_count;
1063         while (bits--) {
1064                 data_bit = value & 0x01;
1065                 value >>= 1;
1066                 par_bit ^= data_bit;
1067                 if (fmt_opts->inverted)
1068                         data_bit = !data_bit;
1069                 sample_buffer_setclr(inc, data_bit, UART_PINMASK_RXTX);
1070                 ret = wave_append_buffer(inc);
1071                 if (ret != SR_OK)
1072                         return ret;
1073         }
1074
1075         /* PARITY bit. Emission is optional. */
1076         switch (fmt_opts->parity_type) {
1077         case UART_PARITY_ODD:
1078                 data_bit = par_bit ? 0 : 1;
1079                 bits = 1;
1080                 break;
1081         case UART_PARITY_EVEN:
1082                 data_bit = par_bit ? 1 : 0;
1083                 bits = 1;
1084                 break;
1085         default:
1086                 data_bit = 0;
1087                 bits = 0;
1088                 break;
1089         }
1090         if (bits) {
1091                 if (fmt_opts->inverted)
1092                         data_bit = !data_bit;
1093                 sample_buffer_setclr(inc, data_bit, UART_PINMASK_RXTX);
1094                 ret = wave_append_buffer(inc);
1095                 if (ret != SR_OK)
1096                         return ret;
1097         }
1098
1099         /* STOP bits. Optional. */
1100         sample_buffer_raise(inc, UART_PINMASK_RXTX);
1101         if (fmt_opts->inverted)
1102                 sample_buffer_toggle(inc, UART_PINMASK_RXTX);
1103         bits = fmt_opts->stopbit_count;
1104         bits += fmt_opts->half_stopbit ? 1 : 0;
1105         while (bits--) {
1106                 ret = wave_append_buffer(inc);
1107                 if (ret != SR_OK)
1108                         return ret;
1109         }
1110
1111         /*
1112          * Force some idle time after the UART frame.
1113          * A little shorter than for special symbols.
1114          */
1115         sample_buffer_toidle(inc);
1116         bits = UART_ADD_IDLEBITS - 1;
1117         while (bits--) {
1118                 ret = wave_append_buffer(inc);
1119                 if (ret != SR_OK)
1120                         return ret;
1121         }
1122
1123         return SR_OK;
1124 }
1125
1126 /* Start/end the logic trace with a few bit times of idle level. */
1127 static int uart_get_idle_capture(struct context *inc,
1128         size_t *bitcount, uint8_t *sample)
1129 {
1130
1131         /* Describe a UART frame's length of idle level. */
1132         if (bitcount)
1133                 *bitcount = inc->max_frame_bits;
1134         if (sample)
1135                 *sample = inc->samples.idle_levels;
1136         return SR_OK;
1137 }
1138
1139 /* Arrange for a few samples of idle level between UART frames. */
1140 static int uart_get_idle_interframe(struct context *inc,
1141         size_t *samplecount, uint8_t *sample)
1142 {
1143
1144         (void)inc;
1145
1146         /*
1147          * Regular waveform creation for UART frames already includes
1148          * padding between UART frames. That is why we don't need to
1149          * add extra inter-frame samples. Yet prepare the implementation
1150          * for when we need or want to add a few more idle samples.
1151          */
1152         if (samplecount) {
1153                 *samplecount = inc->curr_opts.samples_per_bit;
1154                 *samplecount *= 0;
1155         }
1156         if (sample)
1157                 *sample = inc->samples.idle_levels;
1158         return SR_OK;
1159 }
1160
1161 /* }}} UART protocol handler */
1162 /* {{{ SPI protocol handler */
1163
1164 enum spi_pin_t {
1165         SPI_PIN_SCK,
1166         SPI_PIN_MISO,
1167         SPI_PIN_MOSI,
1168         SPI_PIN_CS,
1169         SPI_PIN_COUNT,
1170 };
1171
1172 #define SPI_PINMASK_SCK         (1UL << SPI_PIN_SCK)
1173 #define SPI_PINMASK_MISO        (1UL << SPI_PIN_MISO)
1174 #define SPI_PINMASK_MOSI        (1UL << SPI_PIN_MOSI)
1175 #define SPI_PINMASK_CS          (1UL << SPI_PIN_CS)
1176
1177 /* "Forget" data which was seen before. */
1178 static void spi_value_discard_prev_data(struct context *inc)
1179 {
1180         struct spi_proto_context_t *incs;
1181
1182         incs = inc->curr_opts.prot_priv;
1183         incs->has_mosi = !incs->needs_mosi;
1184         incs->has_miso = !incs->needs_miso;
1185         incs->mosi_byte = 0;
1186         incs->miso_byte = 0;
1187 }
1188
1189 /* Check whether all required values for the byte time were seen. */
1190 static gboolean spi_value_is_bytes_complete(struct context *inc)
1191 {
1192         struct spi_proto_context_t *incs;
1193
1194         incs = inc->curr_opts.prot_priv;
1195
1196         return incs->has_mosi && incs->has_miso;
1197 }
1198
1199 /* Arrange for data reception before waveform emission. */
1200 static void spi_pseudo_data_order(struct context *inc,
1201         gboolean needs_mosi, gboolean needs_miso, gboolean mosi_first)
1202 {
1203         struct spi_proto_context_t *incs;
1204
1205         incs = inc->curr_opts.prot_priv;
1206
1207         incs->needs_mosi = needs_mosi;
1208         incs->needs_miso = needs_miso;
1209         incs->mosi_first = mosi_first;
1210         if (needs_mosi)
1211                 incs->mosi_is_fixed = FALSE;
1212         if (needs_miso)
1213                 incs->miso_is_fixed = FALSE;
1214         spi_value_discard_prev_data(inc);
1215 }
1216
1217 static void spi_pseudo_mosi_fixed(struct context *inc, uint8_t v)
1218 {
1219         struct spi_proto_context_t *incs;
1220
1221         incs = inc->curr_opts.prot_priv;
1222
1223         incs->mosi_fixed_value = v;
1224         incs->mosi_is_fixed = TRUE;
1225 }
1226
1227 static void spi_pseudo_miso_fixed(struct context *inc, uint8_t v)
1228 {
1229         struct spi_proto_context_t *incs;
1230
1231         incs = inc->curr_opts.prot_priv;
1232
1233         incs->miso_fixed_value = v;
1234         incs->miso_is_fixed = TRUE;
1235 }
1236
1237 /* Explicit CS control. Arrange for next CS level, track state to keep it. */
1238 static void spi_pseudo_select_control(struct context *inc, gboolean cs_active)
1239 {
1240         struct spi_frame_fmt_opts *fmt_opts;
1241         struct spi_proto_context_t *incs;
1242         uint8_t cs_level, sck_level;
1243
1244         fmt_opts = &inc->curr_opts.frame_format.spi;
1245         incs = inc->curr_opts.prot_priv;
1246
1247         /* Track current "CS active" state. */
1248         incs->cs_active = cs_active;
1249         incs->auto_cs_remain = 0;
1250
1251         /* Derive current "CS pin level". Update sample data buffer. */
1252         cs_level = 1 - fmt_opts->cs_polarity;
1253         if (incs->cs_active)
1254                 cs_level = fmt_opts->cs_polarity;
1255         sample_buffer_setclr(inc, cs_level, SPI_PINMASK_CS);
1256
1257         /* Derive the idle "SCK level" from the SPI mode's CPOL. */
1258         sck_level = fmt_opts->spi_mode_cpol ? 1 : 0;
1259         sample_buffer_setclr(inc, sck_level, SPI_PINMASK_SCK);
1260 }
1261
1262 /* Arrange for automatic CS release after transfer length. Starts the phase. */
1263 static void spi_pseudo_auto_select(struct context *inc, size_t length)
1264 {
1265         struct spi_frame_fmt_opts *fmt_opts;
1266         struct spi_proto_context_t *incs;
1267         uint8_t cs_level;
1268
1269         fmt_opts = &inc->curr_opts.frame_format.spi;
1270         incs = inc->curr_opts.prot_priv;
1271
1272         /* Track current "CS active" state. */
1273         incs->cs_active = TRUE;
1274         incs->auto_cs_remain = length;
1275
1276         /* Derive current "CS pin level". Update sample data buffer. */
1277         cs_level = 1 - fmt_opts->cs_polarity;
1278         if (incs->cs_active)
1279                 cs_level = fmt_opts->cs_polarity;
1280         sample_buffer_setclr(inc, cs_level, SPI_PINMASK_CS);
1281 }
1282
1283 /* Check for automatic CS release. Decrements, yields result. No action here. */
1284 static gboolean spi_auto_select_ends(struct context *inc)
1285 {
1286         struct spi_proto_context_t *incs;
1287
1288         incs = inc->curr_opts.prot_priv;
1289         if (!incs->auto_cs_remain)
1290                 return FALSE;
1291
1292         incs->auto_cs_remain--;
1293         if (incs->auto_cs_remain)
1294                 return FALSE;
1295
1296         /*
1297          * DON'T release CS yet. The last data is yet to get sent.
1298          * Keep the current "CS pin level", but tell the caller that
1299          * CS will be released after transmission of that last data.
1300          */
1301         return TRUE;
1302 }
1303
1304 /* Update for automatic CS release after last data was sent. */
1305 static void spi_auto_select_update(struct context *inc)
1306 {
1307         struct spi_frame_fmt_opts *fmt_opts;
1308         struct spi_proto_context_t *incs;
1309         uint8_t cs_level;
1310
1311         fmt_opts = &inc->curr_opts.frame_format.spi;
1312         incs = inc->curr_opts.prot_priv;
1313
1314         /* Track current "CS active" state. */
1315         incs->cs_active = FALSE;
1316         incs->auto_cs_remain = 0;
1317
1318         /* Derive current "CS pin level". Map to bits pattern. */
1319         cs_level = 1 - fmt_opts->cs_polarity;
1320         sample_buffer_setclr(inc, cs_level, SPI_PINMASK_CS);
1321 }
1322
1323 /*
1324  * Create the waveforms for one SPI byte. Also cover idle periods:
1325  * Dummy/padding bytes within a frame with clock. Idle lines outside
1326  * of frames without clock edges. Optional automatic CS release with
1327  * resulting inter-frame gap.
1328  */
1329 static int spi_write_frame_patterns(struct context *inc,
1330         gboolean idle, gboolean cs_release)
1331 {
1332         struct spi_proto_context_t *incs;
1333         struct spi_frame_fmt_opts *fmt_opts;
1334         int ret;
1335         uint8_t mosi_bit, miso_bit;
1336         size_t bits;
1337
1338         if (!inc)
1339                 return SR_ERR_ARG;
1340         incs = inc->curr_opts.prot_priv;
1341         fmt_opts = &inc->curr_opts.frame_format.spi;
1342
1343         /* Apply fixed values before drawing the waveform. */
1344         if (incs->mosi_is_fixed)
1345                 incs->mosi_byte = incs->mosi_fixed_value;
1346         if (incs->miso_is_fixed)
1347                 incs->miso_byte = incs->miso_fixed_value;
1348
1349         ret = wave_clear_sequence(inc);
1350         if (ret != SR_OK)
1351                 return ret;
1352
1353         /* Provide two samples with idle SCK and current CS. */
1354         ret = wave_append_buffer(inc);
1355         if (ret != SR_OK)
1356                 return ret;
1357         ret = wave_append_buffer(inc);
1358         if (ret != SR_OK)
1359                 return ret;
1360
1361         /*
1362          * Provide two samples per DATABIT time slot. Keep CS as is.
1363          * Toggle SCK according to CPHA specs. Shift out MOSI and MISO
1364          * in the configured order.
1365          *
1366          * Force dummy MOSI/MISO bits for idle bytes within a frame.
1367          * Skip SCK toggling for idle "frames" outside of active CS.
1368          */
1369         bits = fmt_opts->databit_count;
1370         while (bits--) {
1371                 /*
1372                  * First half-period. Provide next DATABIT values.
1373                  * Toggle SCK here when CPHA is set.
1374                  */
1375                 if (fmt_opts->msb_first) {
1376                         mosi_bit = incs->mosi_byte & 0x80;
1377                         miso_bit = incs->miso_byte & 0x80;
1378                         incs->mosi_byte <<= 1;
1379                         incs->miso_byte <<= 1;
1380                 } else {
1381                         mosi_bit = incs->mosi_byte & 0x01;
1382                         miso_bit = incs->miso_byte & 0x01;
1383                         incs->mosi_byte >>= 1;
1384                         incs->miso_byte >>= 1;
1385                 }
1386                 if (incs->cs_active && !idle) {
1387                         sample_buffer_setclr(inc, mosi_bit, SPI_PINMASK_MOSI);
1388                         sample_buffer_setclr(inc, miso_bit, SPI_PINMASK_MISO);
1389                 }
1390                 if (fmt_opts->spi_mode_cpha && incs->cs_active)
1391                         sample_buffer_toggle(inc, SPI_PINMASK_SCK);
1392                 ret = wave_append_buffer(inc);
1393                 if (ret != SR_OK)
1394                         return ret;
1395                 /* Second half-period. Keep DATABIT, toggle SCK. */
1396                 if (incs->cs_active)
1397                         sample_buffer_toggle(inc, SPI_PINMASK_SCK);
1398                 ret = wave_append_buffer(inc);
1399                 if (ret != SR_OK)
1400                         return ret;
1401                 /* Toggle SCK again unless done above due to CPHA. */
1402                 if (!fmt_opts->spi_mode_cpha && incs->cs_active)
1403                         sample_buffer_toggle(inc, SPI_PINMASK_SCK);
1404         }
1405
1406         /*
1407          * Hold the waveform for another sample period. Happens to
1408          * also communicate the most recent SCK pin level.
1409          *
1410          * Optionally auto-release the CS signal after sending the
1411          * last data byte. Update the CS trace's level. Add another
1412          * (long) bit slot to present an inter-frame gap.
1413          */
1414         ret = wave_append_buffer(inc);
1415         if (ret != SR_OK)
1416                 return ret;
1417         if (cs_release)
1418                 spi_auto_select_update(inc);
1419         ret = wave_append_buffer(inc);
1420         if (ret != SR_OK)
1421                 return ret;
1422         if (cs_release) {
1423                 ret = wave_append_buffer(inc);
1424                 if (ret != SR_OK)
1425                         return ret;
1426         }
1427
1428         return SR_OK;
1429 }
1430
1431 /* SPI specific options and frame format check. */
1432 static int spi_check_opts(struct context *inc)
1433 {
1434         struct spi_frame_fmt_opts *fmt_opts;
1435         const char *fmt_text;
1436         char **opts, *opt;
1437         size_t opt_count, opt_idx;
1438         int ret;
1439         unsigned long v;
1440         char *endp;
1441         size_t total_bits;
1442
1443         if (!inc)
1444                 return SR_ERR_ARG;
1445         fmt_opts = &inc->curr_opts.frame_format.spi;
1446
1447         /* Setup defaults before reading external specs. */
1448         fmt_opts->cs_polarity = 0;
1449         fmt_opts->databit_count = SPI_MIN_DATABITS;
1450         fmt_opts->msb_first = TRUE;
1451         fmt_opts->spi_mode_cpol = FALSE;
1452         fmt_opts->spi_mode_cpha = FALSE;
1453
1454         /* Provide a default SPI frame format. */
1455         fmt_text = inc->curr_opts.fmt_text;
1456         if (!fmt_text || !*fmt_text)
1457                 fmt_text = SPI_DFLT_FRAMEFMT;
1458         sr_dbg("SPI frame format: %s.", fmt_text);
1459
1460         /* Accept comma separated key=value pairs of specs. */
1461         opts = g_strsplit_set(fmt_text, ", ", 0);
1462         opt_count = g_strv_length(opts);
1463         for (opt_idx = 0; opt_idx < opt_count; opt_idx++) {
1464                 opt = opts[opt_idx];
1465                 if (!opt || !*opt)
1466                         continue;
1467                 sr_spew("SPI format option: %s.", opt);
1468                 if (strcmp(opt, SPI_FORMAT_CS_LOW) == 0) {
1469                         sr_spew("SPI chip select: low.");
1470                         fmt_opts->cs_polarity = 0;
1471                         continue;
1472                 }
1473                 if (strcmp(opt, SPI_FORMAT_CS_HIGH) == 0) {
1474                         sr_spew("SPI chip select: high.");
1475                         fmt_opts->cs_polarity = 1;
1476                         continue;
1477                 }
1478                 if (g_str_has_prefix(opt, SPI_FORMAT_DATA_BITS)) {
1479                         opt += strlen(SPI_FORMAT_DATA_BITS);
1480                         endp = NULL;
1481                         ret = sr_atoul_base(opt, &v, &endp, 10);
1482                         if (ret != SR_OK)
1483                                 return ret;
1484                         if (!endp || *endp)
1485                                 return SR_ERR_ARG;
1486                         sr_spew("SPI word size: %lu.", v);
1487                         if (v < SPI_MIN_DATABITS || v > SPI_MAX_DATABITS)
1488                                 return SR_ERR_ARG;
1489                         fmt_opts->databit_count = v;
1490                         continue;
1491                 }
1492                 if (g_str_has_prefix(opt, SPI_FORMAT_SPI_MODE)) {
1493                         opt += strlen(SPI_FORMAT_SPI_MODE);
1494                         endp = NULL;
1495                         ret = sr_atoul_base(opt, &v, &endp, 10);
1496                         if (ret != SR_OK)
1497                                 return ret;
1498                         if (!endp || *endp)
1499                                 return SR_ERR_ARG;
1500                         sr_spew("SPI mode: %lu.", v);
1501                         if (v > 3)
1502                                 return SR_ERR_ARG;
1503                         fmt_opts->spi_mode_cpol = v & (1UL << 1);
1504                         fmt_opts->spi_mode_cpha = v & (1UL << 0);
1505                         continue;
1506                 }
1507                 if (g_str_has_prefix(opt, SPI_FORMAT_MODE_CPOL)) {
1508                         opt += strlen(SPI_FORMAT_MODE_CPOL);
1509                         endp = NULL;
1510                         ret = sr_atoul_base(opt, &v, &endp, 10);
1511                         if (ret != SR_OK)
1512                                 return ret;
1513                         if (!endp || *endp)
1514                                 return SR_ERR_ARG;
1515                         sr_spew("SPI cpol: %lu.", v);
1516                         if (v > 1)
1517                                 return SR_ERR_ARG;
1518                         fmt_opts->spi_mode_cpol = !!v;
1519                         continue;
1520                 }
1521                 if (g_str_has_prefix(opt, SPI_FORMAT_MODE_CPHA)) {
1522                         opt += strlen(SPI_FORMAT_MODE_CPHA);
1523                         endp = NULL;
1524                         ret = sr_atoul_base(opt, &v, &endp, 10);
1525                         if (ret != SR_OK)
1526                                 return ret;
1527                         if (!endp || *endp)
1528                                 return SR_ERR_ARG;
1529                         sr_spew("SPI cpha: %lu.", v);
1530                         if (v > 1)
1531                                 return SR_ERR_ARG;
1532                         fmt_opts->spi_mode_cpha = !!v;
1533                         continue;
1534                 }
1535                 if (strcmp(opt, SPI_FORMAT_MSB_FIRST) == 0) {
1536                         sr_spew("SPI endianess: MSB first.");
1537                         fmt_opts->msb_first = 1;
1538                         continue;
1539                 }
1540                 if (strcmp(opt, SPI_FORMAT_LSB_FIRST) == 0) {
1541                         sr_spew("SPI endianess: LSB first.");
1542                         fmt_opts->msb_first = 0;
1543                         continue;
1544                 }
1545                 return SR_ERR_ARG;
1546         }
1547         g_strfreev(opts);
1548
1549         /*
1550          * Get the total bit count. Add slack for CS control, and to
1551          * visually separate bytes in frames. Multiply data bit count
1552          * for the creation of two clock half-periods.
1553          */
1554         total_bits = 2;
1555         total_bits += 2 * fmt_opts->databit_count;
1556         total_bits += 3;
1557
1558         sr_dbg("SPI frame: total bits %lu.", total_bits);
1559         if (total_bits > SPI_MAX_WAVELEN)
1560                 return SR_ERR_DATA;
1561         inc->max_frame_bits = total_bits;
1562
1563         return SR_OK;
1564 }
1565
1566 /*
1567  * Setup half-width slots for the two halves of a DATABIT time. Keep
1568  * the "decoration" (CS control) at full width. Setup a rather long
1569  * last slot for potential inter-frame gaps.
1570  *
1571  * Preset CS and SCK from their idle levels according to the frame format
1572  * configuration. So that idle times outside of SPI transfers are covered
1573  * with simple logic despite the protocol's flexibility.
1574  */
1575 static int spi_config_frame(struct context *inc)
1576 {
1577         struct spi_frame_fmt_opts *fmt_opts;
1578         size_t bit_idx, bit_count;
1579
1580         if (!inc)
1581                 return SR_ERR_ARG;
1582         fmt_opts = &inc->curr_opts.frame_format.spi;
1583
1584         /* Configure DATABIT positions for half width (for clock period). */
1585         bit_idx = 2;
1586         bit_count = fmt_opts->databit_count;
1587         while (bit_count--) {
1588                 inc->bit_scale[bit_idx + 0].div = 2;
1589                 inc->bit_scale[bit_idx + 1].div = 2;
1590                 bit_idx += 2;
1591         }
1592         bit_idx += 2;
1593         inc->bit_scale[bit_idx].mul = fmt_opts->databit_count;
1594
1595         /*
1596          * Seed the protocol handler's internal state before seeing
1597          * first data values. To properly cover idle periods, and to
1598          * operate correctly in the absence of pseudo comments.
1599          *
1600          * Use internal helpers for sample data initialization. Then
1601          * grab the resulting pin levels as the idle state.
1602          */
1603         spi_value_discard_prev_data(inc);
1604         spi_pseudo_data_order(inc, TRUE, TRUE, TRUE);
1605         spi_pseudo_select_control(inc, FALSE);
1606         sample_buffer_preset(inc, inc->samples.curr_levels);
1607
1608         return SR_OK;
1609 }
1610
1611 /*
1612  * Process protocol dependent pseudo comments. Can affect future frame
1613  * construction and submission, or can immediately emit "inter frame"
1614  * bit patterns like chip select control.
1615  */
1616 static int spi_proc_pseudo(struct sr_input *in, char *line)
1617 {
1618         struct context *inc;
1619         char *word, *endp;
1620         int ret;
1621         unsigned long v;
1622
1623         inc = in->priv;
1624
1625         while (line) {
1626                 word = sr_text_next_word(line, &line);
1627                 if (!word)
1628                         break;
1629                 if (!*word)
1630                         continue;
1631                 if (strcmp(word, SPI_PSEUDO_MOSI_ONLY) == 0) {
1632                         sr_spew("SPI pseudo: MOSI only");
1633                         spi_pseudo_data_order(inc, TRUE, FALSE, TRUE);
1634                         continue;
1635                 }
1636                 if (g_str_has_prefix(word, SPI_PSEUDO_MOSI_FIXED)) {
1637                         word += strlen(SPI_PSEUDO_MOSI_FIXED);
1638                         endp = NULL;
1639                         ret = sr_atoul_base(word, &v, &endp, inc->read_text.base);
1640                         if (ret != SR_OK)
1641                                 return ret;
1642                         if (!endp || *endp)
1643                                 return SR_ERR_ARG;
1644                         sr_spew("SPI pseudo: MOSI fixed %lu", v);
1645                         spi_pseudo_mosi_fixed(inc, v);
1646                         continue;
1647                 }
1648                 if (strcmp(word, SPI_PSEUDO_MISO_ONLY) == 0) {
1649                         sr_spew("SPI pseudo: MISO only");
1650                         spi_pseudo_data_order(inc, FALSE, TRUE, FALSE);
1651                         continue;
1652                 }
1653                 if (g_str_has_prefix(word, SPI_PSEUDO_MISO_FIXED)) {
1654                         word += strlen(SPI_PSEUDO_MISO_FIXED);
1655                         endp = NULL;
1656                         ret = sr_atoul_base(word, &v, &endp, inc->read_text.base);
1657                         if (ret != SR_OK)
1658                                 return ret;
1659                         if (!endp || *endp)
1660                                 return SR_ERR_ARG;
1661                         sr_spew("SPI pseudo: MISO fixed %lu", v);
1662                         spi_pseudo_miso_fixed(inc, v);
1663                         continue;
1664                 }
1665                 if (strcmp(word, SPI_PSEUDO_MOSI_MISO) == 0) {
1666                         sr_spew("SPI pseudo: MOSI then MISO");
1667                         spi_pseudo_data_order(inc, TRUE, TRUE, TRUE);
1668                         continue;
1669                 }
1670                 if (strcmp(word, SPI_PSEUDO_MISO_MOSI) == 0) {
1671                         sr_spew("SPI pseudo: MISO then MOSI");
1672                         spi_pseudo_data_order(inc, TRUE, TRUE, FALSE);
1673                         continue;
1674                 }
1675                 if (strcmp(word, SPI_PSEUDO_CS_ASSERT) == 0) {
1676                         sr_spew("SPI pseudo: CS assert");
1677                         spi_pseudo_select_control(inc, TRUE);
1678                         continue;
1679                 }
1680                 if (strcmp(word, SPI_PSEUDO_CS_RELEASE) == 0) {
1681                         sr_spew("SPI pseudo: CS release");
1682                         /* Release CS. Force IDLE to display the pin change. */
1683                         spi_pseudo_select_control(inc, FALSE);
1684                         ret = spi_write_frame_patterns(inc, TRUE, FALSE);
1685                         if (ret != SR_OK)
1686                                 return ret;
1687                         ret = send_frame(in);
1688                         if (ret != SR_OK)
1689                                 return ret;
1690                         continue;
1691                 }
1692                 if (g_str_has_prefix(word, SPI_PSEUDO_CS_NEXT)) {
1693                         word += strlen(SPI_PSEUDO_CS_NEXT);
1694                         endp = NULL;
1695                         ret = sr_atoul_base(word, &v, &endp, 0);
1696                         if (ret != SR_OK)
1697                                 return ret;
1698                         if (!endp || *endp)
1699                                 return SR_ERR_ARG;
1700                         sr_spew("SPI pseudo: CS auto next %lu", v);
1701                         spi_pseudo_auto_select(inc, v);
1702                         continue;
1703                 }
1704                 if (strcmp(word, SPI_PSEUDO_IDLE) == 0) {
1705                         sr_spew("SPI pseudo: idle");
1706                         ret = spi_write_frame_patterns(inc, TRUE, FALSE);
1707                         if (ret != SR_OK)
1708                                 return ret;
1709                         ret = send_frame(in);
1710                         if (ret != SR_OK)
1711                                 return ret;
1712                         continue;
1713                 }
1714                 return SR_ERR_DATA;
1715         }
1716
1717         return SR_OK;
1718 }
1719
1720 /*
1721  * Create the frame's waveform for the given data value. For bidirectional
1722  * communication multiple routine invocations accumulate data bits, while
1723  * the last invocation completes the frame preparation.
1724  */
1725 static int spi_proc_value(struct context *inc, uint32_t value)
1726 {
1727         struct spi_proto_context_t *incs;
1728         gboolean taken;
1729         int ret;
1730         gboolean auto_cs_end;
1731
1732         if (!inc)
1733                 return SR_ERR_ARG;
1734         incs = inc->curr_opts.prot_priv;
1735
1736         /*
1737          * Discard previous data when we get here after having completed
1738          * a previous frame. This roundtrip from filling in to clearing
1739          * is required to have the caller emit the waveform that we have
1740          * constructed after receiving data values.
1741          */
1742         if (spi_value_is_bytes_complete(inc)) {
1743                 sr_spew("SPI value: discarding previous data");
1744                 spi_value_discard_prev_data(inc);
1745         }
1746
1747         /*
1748          * Consume the caller provided value. Apply data in the order
1749          * that was configured before.
1750          */
1751         taken = FALSE;
1752         if (!taken && incs->mosi_first && !incs->has_mosi) {
1753                 sr_spew("SPI value: grabbing MOSI value");
1754                 incs->mosi_byte = value & 0xff;
1755                 incs->has_mosi = TRUE;
1756                 taken = TRUE;
1757         }
1758         if (!taken && !incs->has_miso) {
1759                 sr_spew("SPI value: grabbing MISO value");
1760                 incs->miso_byte = value & 0xff;
1761                 incs->has_miso = TRUE;
1762         }
1763         if (!taken && !incs->mosi_first && !incs->has_mosi) {
1764                 sr_spew("SPI value: grabbing MOSI value");
1765                 incs->mosi_byte = value & 0xff;
1766                 incs->has_mosi = TRUE;
1767                 taken = TRUE;
1768         }
1769
1770         /*
1771          * Generate the waveform when all data values in a byte time
1772          * were seen (all MOSI and MISO including their being optional
1773          * or fixed values).
1774          *
1775          * Optionally automatically release CS after a given number of
1776          * data bytes, when requested by the input stream.
1777          */
1778         if (!spi_value_is_bytes_complete(inc)) {
1779                 sr_spew("SPI value: need more values");
1780                 return +1;
1781         }
1782         auto_cs_end = spi_auto_select_ends(inc);
1783         sr_spew("SPI value: frame complete, drawing, auto CS %d", auto_cs_end);
1784         ret = spi_write_frame_patterns(inc, FALSE, auto_cs_end);
1785         if (ret != SR_OK)
1786                 return ret;
1787         return 0;
1788 }
1789
1790 /* Start/end the logic trace with a few bit times of idle level. */
1791 static int spi_get_idle_capture(struct context *inc,
1792         size_t *bitcount, uint8_t *sample)
1793 {
1794
1795         /* Describe one byte time of idle level. */
1796         if (bitcount)
1797                 *bitcount = inc->max_frame_bits;
1798         if (sample)
1799                 *sample = inc->samples.idle_levels;
1800         return SR_OK;
1801 }
1802
1803 /* Arrange for a few samples of idle level between UART frames. */
1804 static int spi_get_idle_interframe(struct context *inc,
1805         size_t *samplecount, uint8_t *sample)
1806 {
1807
1808         /* Describe four bit times, re-use most recent pin levels. */
1809         if (samplecount) {
1810                 *samplecount = inc->curr_opts.samples_per_bit;
1811                 *samplecount *= 4;
1812         }
1813         if (sample)
1814                 *sample = inc->samples.curr_levels;
1815         return SR_OK;
1816 }
1817
1818 /* }}} SPI protocol handler */
1819 /* {{{ I2C protocol handler */
1820
1821 enum i2c_pin_t {
1822         I2C_PIN_SCL,
1823         I2C_PIN_SDA,
1824         I2C_PIN_COUNT,
1825 };
1826
1827 #define I2C_PINMASK_SCL         (1UL << I2C_PIN_SCL)
1828 #define I2C_PINMASK_SDA         (1UL << I2C_PIN_SDA)
1829
1830 /* Arrange for automatic ACK for a given number of data bytes. */
1831 static void i2c_auto_ack_start(struct context *inc, size_t count)
1832 {
1833         struct i2c_proto_context_t *incs;
1834
1835         incs = inc->curr_opts.prot_priv;
1836         incs->ack_remain = count;
1837 }
1838
1839 /* Check whether automatic ACK is still applicable. Decrements. */
1840 static gboolean i2c_auto_ack_avail(struct context *inc)
1841 {
1842         struct i2c_proto_context_t *incs;
1843
1844         incs = inc->curr_opts.prot_priv;
1845         if (!incs->ack_remain)
1846                 return FALSE;
1847
1848         if (incs->ack_remain--)
1849                 return TRUE;
1850         return FALSE;
1851 }
1852
1853 /* Occupy the slots where START/STOP would be. Keep current levels. */
1854 static int i2c_write_nothing(struct context *inc)
1855 {
1856         size_t reps;
1857         int ret;
1858
1859         reps = I2C_BITTIME_QUANTA;
1860         while (reps--) {
1861                 ret = wave_append_buffer(inc);
1862                 if (ret != SR_OK)
1863                         return ret;
1864         }
1865
1866         return SR_OK;
1867 }
1868
1869 /*
1870  * Construct a START symbol. Occupy a full bit time in the waveform.
1871  * Can also be used as REPEAT START due to its conservative signalling.
1872  *
1873  * Definition of START: Falling SDA while SCL is high.
1874  * Repeated START: A START without a preceeding STOP.
1875  */
1876 static int i2c_write_start(struct context *inc)
1877 {
1878         int ret;
1879
1880         /*
1881          * Important! Assumes that either SDA and SCL already are
1882          * high (true when we come here from an idle bus). Or that
1883          * SCL already is low before SDA potentially changes (this
1884          * is true for preceeding START or REPEAT START or DATA BIT
1885          * symbols).
1886          *
1887          * Implementation detail: This START implementation can be
1888          * used for REPEAT START as well. The signalling sequence is
1889          * conservatively done.
1890          */
1891
1892         /* Enforce SDA high. */
1893         sample_buffer_raise(inc, I2C_PINMASK_SDA);
1894         ret = wave_append_buffer(inc);
1895         if (ret != SR_OK)
1896                 return ret;
1897
1898         /* Enforce SCL high. */
1899         sample_buffer_raise(inc, I2C_PINMASK_SCL);
1900         ret = wave_append_buffer(inc);
1901         if (ret != SR_OK)
1902                 return ret;
1903
1904         /* Keep high SCL and high SDA for another period. */
1905         ret = wave_append_buffer(inc);
1906         if (ret != SR_OK)
1907                 return ret;
1908
1909         /* Falling SDA while SCL is high. */
1910         sample_buffer_clear(inc, I2C_PINMASK_SDA);
1911         ret = wave_append_buffer(inc);
1912         if (ret != SR_OK)
1913                 return ret;
1914
1915         /* Keep high SCL and low SDA for one more period. */
1916         ret = wave_append_buffer(inc);
1917         if (ret != SR_OK)
1918                 return ret;
1919
1920         /*
1921          * Lower SCL here already. Which kind of prepares DATA BIT
1922          * times (fits a data bit's start condition, does not harm).
1923          * Improves back to back START and (repeated) START as well
1924          * as STOP without preceeding DATA BIT.
1925          */
1926         sample_buffer_clear(inc, I2C_PINMASK_SCL);
1927         ret = wave_append_buffer(inc);
1928         if (ret != SR_OK)
1929                 return ret;
1930
1931         return SR_OK;
1932 }
1933
1934 /*
1935  * Construct a STOP symbol. Occupy a full bit time in the waveform.
1936  *
1937  * Definition of STOP: Rising SDA while SCL is high.
1938  */
1939 static int i2c_write_stop(struct context *inc)
1940 {
1941         int ret;
1942
1943         /* Enforce SCL low before SDA changes. */
1944         sample_buffer_clear(inc, I2C_PINMASK_SCL);
1945         ret = wave_append_buffer(inc);
1946         if (ret != SR_OK)
1947                 return ret;
1948
1949         /* Enforce SDA low (can change while SCL is low). */
1950         sample_buffer_clear(inc, I2C_PINMASK_SDA);
1951         ret = wave_append_buffer(inc);
1952         if (ret != SR_OK)
1953                 return ret;
1954
1955         /* Rise SCL high while SDA is low. */
1956         sample_buffer_raise(inc, I2C_PINMASK_SCL);
1957         ret = wave_append_buffer(inc);
1958         if (ret != SR_OK)
1959                 return ret;
1960
1961         /* Keep high SCL and low SDA for another period. */
1962         ret = wave_append_buffer(inc);
1963         if (ret != SR_OK)
1964                 return ret;
1965
1966         /* Rising SDA. */
1967         sample_buffer_raise(inc, I2C_PINMASK_SDA);
1968         ret = wave_append_buffer(inc);
1969         if (ret != SR_OK)
1970                 return ret;
1971
1972         /* Keep high SCL and high SDA for one more periods. */
1973         ret = wave_append_buffer(inc);
1974         if (ret != SR_OK)
1975                 return ret;
1976
1977         return SR_OK;
1978 }
1979
1980 /*
1981  * Construct a DATA BIT symbol. Occupy a full bit time in the waveform.
1982  *
1983  * SDA can change while SCL is low. SDA must be kept while SCL is high.
1984  */
1985 static int i2c_write_bit(struct context *inc, uint8_t value)
1986 {
1987         int ret;
1988
1989         /* Enforce SCL low before SDA changes. */
1990         sample_buffer_clear(inc, I2C_PINMASK_SCL);
1991         ret = wave_append_buffer(inc);
1992         if (ret != SR_OK)
1993                 return ret;
1994
1995         /* Setup SDA pin level while SCL is low. */
1996         sample_buffer_setclr(inc, value, I2C_PINMASK_SDA);
1997         ret = wave_append_buffer(inc);
1998         if (ret != SR_OK)
1999                 return ret;
2000
2001         /* Rising SCL, starting SDA validity. */
2002         sample_buffer_raise(inc, I2C_PINMASK_SCL);
2003         ret = wave_append_buffer(inc);
2004         if (ret != SR_OK)
2005                 return ret;
2006
2007         /* Keep SDA level with high SCL for two more periods. */
2008         ret = wave_append_buffer(inc);
2009         if (ret != SR_OK)
2010                 return ret;
2011         ret = wave_append_buffer(inc);
2012         if (ret != SR_OK)
2013                 return ret;
2014
2015         /* Falling SCL, terminates SDA validity. */
2016         sample_buffer_clear(inc, I2C_PINMASK_SCL);
2017         ret = wave_append_buffer(inc);
2018         if (ret != SR_OK)
2019                 return ret;
2020
2021         return SR_OK;
2022 }
2023
2024 /* Create a waveform for the eight data bits and the ACK/NAK slot. */
2025 static int i2c_write_byte(struct context *inc, uint8_t value, uint8_t ack)
2026 {
2027         size_t bit_mask, bit_value;
2028         int ret;
2029
2030         /* Keep an empty bit time before the data byte. */
2031         ret = i2c_write_nothing(inc);
2032         if (ret != SR_OK)
2033                 return ret;
2034
2035         /* Send 8 data bits, MSB first. */
2036         bit_mask = 0x80;
2037         while (bit_mask) {
2038                 bit_value = value & bit_mask;
2039                 bit_mask >>= 1;
2040                 ret = i2c_write_bit(inc, bit_value);
2041                 if (ret != SR_OK)
2042                         return ret;
2043         }
2044
2045         /* Send ACK, which is low active. NAK is recessive, high. */
2046         bit_value = !ack;
2047         ret = i2c_write_bit(inc, bit_value);
2048         if (ret != SR_OK)
2049                 return ret;
2050
2051         /* Keep an empty bit time after the data byte. */
2052         ret = i2c_write_nothing(inc);
2053         if (ret != SR_OK)
2054                 return ret;
2055
2056         return SR_OK;
2057 }
2058
2059 /* Send slave address (7bit or 10bit, 1 or 2 bytes). Consumes one ACK. */
2060 static int i2c_send_address(struct sr_input *in, uint16_t addr, gboolean read)
2061 {
2062         struct context *inc;
2063         struct i2c_frame_fmt_opts *fmt_opts;
2064         gboolean with_ack;
2065         uint8_t addr_byte, rw_bit;
2066         int ret;
2067
2068         inc = in->priv;
2069         fmt_opts = &inc->curr_opts.frame_format.i2c;
2070
2071         addr &= 0x3ff;
2072         rw_bit = read ? 1 : 0;
2073         with_ack = i2c_auto_ack_avail(inc);
2074
2075         if (!fmt_opts->addr_10bit) {
2076                 /* 7 bit address, the simple case. */
2077                 addr_byte = addr & 0x7f;
2078                 addr_byte <<= 1;
2079                 addr_byte |= rw_bit;
2080                 sr_spew("I2C 7bit address, byte 0x%" PRIx8, addr_byte);
2081                 ret = wave_clear_sequence(inc);
2082                 if (ret != SR_OK)
2083                         return ret;
2084                 ret = i2c_write_byte(inc, addr_byte, with_ack);
2085                 if (ret != SR_OK)
2086                         return ret;
2087                 ret = send_frame(in);
2088                 if (ret != SR_OK)
2089                         return ret;
2090         } else {
2091                 /*
2092                  * 10 bit address, need to write two bytes: First byte
2093                  * with prefix 0xf0, upper most 2 address bits, and R/W.
2094                  * Second byte with lower 8 address bits.
2095                  */
2096                 addr_byte = addr >> 8;
2097                 addr_byte <<= 1;
2098                 addr_byte |= 0xf0;
2099                 addr_byte |= rw_bit;
2100                 sr_spew("I2C 10bit address, byte 0x%" PRIx8, addr_byte);
2101                 ret = wave_clear_sequence(inc);
2102                 if (ret != SR_OK)
2103                         return ret;
2104                 ret = i2c_write_byte(inc, addr_byte, with_ack);
2105                 if (ret != SR_OK)
2106                         return ret;
2107                 ret = send_frame(in);
2108                 if (ret != SR_OK)
2109                         return ret;
2110
2111                 addr_byte = addr & 0xff;
2112                 sr_spew("I2C 10bit address, byte 0x%" PRIx8, addr_byte);
2113                 ret = wave_clear_sequence(inc);
2114                 if (ret != SR_OK)
2115                         return ret;
2116                 ret = i2c_write_byte(inc, addr_byte, with_ack);
2117                 if (ret != SR_OK)
2118                         return ret;
2119                 ret = send_frame(in);
2120                 if (ret != SR_OK)
2121                         return ret;
2122         }
2123
2124         return SR_OK;
2125 }
2126
2127 /* I2C specific options and frame format check. */
2128 static int i2c_check_opts(struct context *inc)
2129 {
2130         struct i2c_frame_fmt_opts *fmt_opts;
2131         const char *fmt_text;
2132         char **opts, *opt;
2133         size_t opt_count, opt_idx;
2134         size_t total_bits;
2135
2136         if (!inc)
2137                 return SR_ERR_ARG;
2138         fmt_opts = &inc->curr_opts.frame_format.i2c;
2139
2140         /* Apply defaults before reading external specs. */
2141         memset(fmt_opts, 0, sizeof(*fmt_opts));
2142         fmt_opts->addr_10bit = FALSE;
2143
2144         /* Provide a default I2C frame format. */
2145         fmt_text = inc->curr_opts.fmt_text;
2146         if (!fmt_text || !*fmt_text)
2147                 fmt_text = I2C_DFLT_FRAMEFMT;
2148         sr_dbg("I2C frame format: %s.", fmt_text);
2149
2150         /* Accept comma separated key=value pairs of specs. */
2151         opts = g_strsplit_set(fmt_text, ", ", 0);
2152         opt_count = g_strv_length(opts);
2153         for (opt_idx = 0; opt_idx < opt_count; opt_idx++) {
2154                 opt = opts[opt_idx];
2155                 if (!opt || !*opt)
2156                         continue;
2157                 sr_spew("I2C format option: %s.", opt);
2158                 if (strcmp(opt, I2C_FORMAT_ADDR_7BIT) == 0) {
2159                         sr_spew("I2C address: 7 bit");
2160                         fmt_opts->addr_10bit = FALSE;
2161                         continue;
2162                 }
2163                 if (strcmp(opt, I2C_FORMAT_ADDR_10BIT) == 0) {
2164                         sr_spew("I2C address: 10 bit");
2165                         fmt_opts->addr_10bit = TRUE;
2166                         continue;
2167                 }
2168                 return SR_ERR_ARG;
2169         }
2170         g_strfreev(opts);
2171
2172         /* Get the total slot count. Leave plenty room for convenience. */
2173         total_bits = 0;
2174         total_bits += I2C_BITTIME_SLOTS;
2175         total_bits *= I2C_BITTIME_QUANTA;
2176         total_bits += I2C_ADD_IDLESLOTS;
2177
2178         sr_dbg("I2C frame: total bits %lu.", total_bits);
2179         if (total_bits > I2C_MAX_WAVELEN)
2180                 return SR_ERR_DATA;
2181         inc->max_frame_bits = total_bits;
2182
2183         return SR_OK;
2184 }
2185
2186 /*
2187  * Don't bother with wide and narrow slots, just assume equal size for
2188  * them all. Edges will occupy exactly one sample, then levels are kept.
2189  * This protocol handler's oversampling should be sufficient for decoders
2190  * to extract the content from generated waveforms.
2191  *
2192  * Start with high levels on SCL and SDA for an idle bus condition.
2193  */
2194 static int i2c_config_frame(struct context *inc)
2195 {
2196         struct i2c_proto_context_t *incs;
2197         size_t bit_idx;
2198         uint8_t sample;
2199
2200         if (!inc)
2201                 return SR_ERR_ARG;
2202         incs = inc->curr_opts.prot_priv;
2203
2204         memset(incs, 0, sizeof(*incs));
2205         incs->ack_remain = 0;
2206
2207         /*
2208          * Adjust all time slots since they represent a smaller quanta
2209          * of an I2C bit time.
2210          */
2211         for (bit_idx = 0; bit_idx < inc->max_frame_bits; bit_idx++) {
2212                 inc->bit_scale[bit_idx].div = I2C_BITTIME_QUANTA;
2213         }
2214
2215         sample = 0;
2216         sample |= I2C_PINMASK_SCL;
2217         sample |= I2C_PINMASK_SDA;
2218         sample_buffer_preset(inc, sample);
2219
2220         return SR_OK;
2221 }
2222
2223 /*
2224  * Process protocol dependent pseudo comments. Can affect future frame
2225  * construction and submission, or can immediately emit "inter frame"
2226  * bit patterns like START/STOP control. Use wide waveforms for these
2227  * transfer controls, put the special symbol nicely centered. Supports
2228  * users during interactive exploration of generated waveforms.
2229  */
2230 static int i2c_proc_pseudo(struct sr_input *in, char *line)
2231 {
2232         struct context *inc;
2233         char *word, *endp;
2234         int ret;
2235         unsigned long v;
2236         size_t bits;
2237
2238         inc = in->priv;
2239
2240         while (line) {
2241                 word = sr_text_next_word(line, &line);
2242                 if (!word)
2243                         break;
2244                 if (!*word)
2245                         continue;
2246                 sr_spew("I2C pseudo: word %s", word);
2247                 if (strcmp(word, I2C_PSEUDO_START) == 0) {
2248                         sr_spew("I2C pseudo: send START");
2249                         ret = wave_clear_sequence(inc);
2250                         if (ret != SR_OK)
2251                                 return ret;
2252                         bits = I2C_BITTIME_SLOTS / 2;
2253                         while (bits--) {
2254                                 ret = i2c_write_nothing(inc);
2255                                 if (ret != SR_OK)
2256                                         return ret;
2257                         }
2258                         ret = i2c_write_start(inc);
2259                         if (ret != SR_OK)
2260                                 return ret;
2261                         bits = I2C_BITTIME_SLOTS / 2;
2262                         while (bits--) {
2263                                 ret = i2c_write_nothing(inc);
2264                                 if (ret != SR_OK)
2265                                         return ret;
2266                         }
2267                         ret = send_frame(in);
2268                         if (ret != SR_OK)
2269                                 return ret;
2270                         continue;
2271                 }
2272                 if (strcmp(word, I2C_PSEUDO_REP_START) == 0) {
2273                         sr_spew("I2C pseudo: send REPEAT START");
2274                         ret = wave_clear_sequence(inc);
2275                         if (ret != SR_OK)
2276                                 return ret;
2277                         bits = I2C_BITTIME_SLOTS / 2;
2278                         while (bits--) {
2279                                 ret = i2c_write_nothing(inc);
2280                                 if (ret != SR_OK)
2281                                         return ret;
2282                         }
2283                         ret = i2c_write_start(inc);
2284                         if (ret != SR_OK)
2285                                 return ret;
2286                         bits = I2C_BITTIME_SLOTS / 2;
2287                         while (bits--) {
2288                                 ret = i2c_write_nothing(inc);
2289                                 if (ret != SR_OK)
2290                                         return ret;
2291                         }
2292                         ret = send_frame(in);
2293                         if (ret != SR_OK)
2294                                 return ret;
2295                         continue;
2296                 }
2297                 if (strcmp(word, I2C_PSEUDO_STOP) == 0) {
2298                         sr_spew("I2C pseudo: send STOP");
2299                         ret = wave_clear_sequence(inc);
2300                         if (ret != SR_OK)
2301                                 return ret;
2302                         bits = I2C_BITTIME_SLOTS / 2;
2303                         while (bits--) {
2304                                 ret = i2c_write_nothing(inc);
2305                                 if (ret != SR_OK)
2306                                         return ret;
2307                         }
2308                         ret = i2c_write_stop(inc);
2309                         if (ret != SR_OK)
2310                                 return ret;
2311                         bits = I2C_BITTIME_SLOTS / 2;
2312                         while (bits--) {
2313                                 ret = i2c_write_nothing(inc);
2314                                 if (ret != SR_OK)
2315                                         return ret;
2316                         }
2317                         ret = send_frame(in);
2318                         if (ret != SR_OK)
2319                                 return ret;
2320                         continue;
2321                 }
2322                 if (g_str_has_prefix(word, I2C_PSEUDO_ADDR_WRITE)) {
2323                         word += strlen(I2C_PSEUDO_ADDR_WRITE);
2324                         endp = NULL;
2325                         ret = sr_atoul_base(word, &v, &endp, 0);
2326                         if (ret != SR_OK)
2327                                 return ret;
2328                         if (!endp || *endp)
2329                                 return SR_ERR_ARG;
2330                         sr_spew("I2C pseudo: addr write %lu", v);
2331                         ret = i2c_send_address(in, v, FALSE);
2332                         if (ret != SR_OK)
2333                                 return ret;
2334                         continue;
2335                 }
2336                 if (g_str_has_prefix(word, I2C_PSEUDO_ADDR_READ)) {
2337                         word += strlen(I2C_PSEUDO_ADDR_READ);
2338                         endp = NULL;
2339                         ret = sr_atoul_base(word, &v, &endp, 0);
2340                         if (ret != SR_OK)
2341                                 return ret;
2342                         if (!endp || *endp)
2343                                 return SR_ERR_ARG;
2344                         sr_spew("I2C pseudo: addr read %lu", v);
2345                         ret = i2c_send_address(in, v, TRUE);
2346                         if (ret != SR_OK)
2347                                 return ret;
2348                         continue;
2349                 }
2350                 if (g_str_has_prefix(word, I2C_PSEUDO_ACK_NEXT)) {
2351                         word += strlen(I2C_PSEUDO_ACK_NEXT);
2352                         endp = NULL;
2353                         ret = sr_atoul_base(word, &v, &endp, 0);
2354                         if (ret != SR_OK)
2355                                 return ret;
2356                         if (!endp || *endp)
2357                                 return SR_ERR_ARG;
2358                         sr_spew("i2c pseudo: ack next %lu", v);
2359                         i2c_auto_ack_start(inc, v);
2360                         continue;
2361                 }
2362                 if (strcmp(word, I2C_PSEUDO_ACK_ONCE) == 0) {
2363                         sr_spew("i2c pseudo: ack once");
2364                         i2c_auto_ack_start(inc, 1);
2365                         continue;
2366                 }
2367                 return SR_ERR_DATA;
2368         }
2369
2370         return SR_OK;
2371 }
2372
2373 /*
2374  * Create the frame's waveform for the given data value. Automatically
2375  * track ACK bits, Fallback to NAK when externally specified ACK counts
2376  * have expired. The caller sends the waveform that we created.
2377  */
2378 static int i2c_proc_value(struct context *inc, uint32_t value)
2379 {
2380         gboolean with_ack;
2381         int ret;
2382
2383         if (!inc)
2384                 return SR_ERR_ARG;
2385
2386         with_ack = i2c_auto_ack_avail(inc);
2387
2388         ret = wave_clear_sequence(inc);
2389         if (ret != SR_OK)
2390                 return ret;
2391         ret = i2c_write_byte(inc, value, with_ack);
2392         if (ret != SR_OK)
2393                 return ret;
2394
2395         return 0;
2396 }
2397
2398 /* Start/end the logic trace with a few bit times of idle level. */
2399 static int i2c_get_idle_capture(struct context *inc,
2400         size_t *bitcount, uint8_t *sample)
2401 {
2402
2403         /* Describe a byte's time of idle level. */
2404         if (bitcount)
2405                 *bitcount = I2C_BITTIME_SLOTS;
2406         if (sample)
2407                 *sample = inc->samples.idle_levels;
2408         return SR_OK;
2409 }
2410
2411 /* Arrange for a few samples of idle level between UART frames. */
2412 static int i2c_get_idle_interframe(struct context *inc,
2413         size_t *samplecount, uint8_t *sample)
2414 {
2415
2416         /*
2417          * The space around regular bytes already is sufficient. We
2418          * don't need to generate an inter-frame gap, but the code is
2419          * prepared to in case we want to in the future.
2420          */
2421         if (samplecount) {
2422                 *samplecount = inc->curr_opts.samples_per_bit;
2423                 *samplecount *= 0;
2424         }
2425         if (sample)
2426                 *sample = inc->samples.curr_levels;
2427         return SR_OK;
2428 }
2429
2430 /* }}} I2C protocol handler */
2431 /* {{{ protocol dispatching */
2432
2433 /*
2434  * The list of supported protocols and their handlers, including
2435  * protocol specific defaults. The first item after the NONE slot
2436  * is the default protocol, and takes effect in the absence of any
2437  * user provided or file content provided spec.
2438  */
2439 static const struct proto_handler_t protocols[PROTO_TYPE_COUNT] = {
2440         [PROTO_TYPE_UART] = {
2441                 UART_HANDLER_NAME,
2442                 {
2443                         UART_DFLT_SAMPLERATE,
2444                         UART_DFLT_BITRATE, UART_DFLT_FRAMEFMT,
2445                         INPUT_BYTES,
2446                 },
2447                 {
2448                         1, (const char *[]){
2449                                 [UART_PIN_RXTX] = "rxtx",
2450                         },
2451                 },
2452                 0,
2453                 uart_check_opts,
2454                 uart_config_frame,
2455                 uart_proc_pseudo,
2456                 uart_proc_value,
2457                 uart_get_idle_capture,
2458                 uart_get_idle_interframe,
2459         },
2460         [PROTO_TYPE_SPI] = {
2461                 SPI_HANDLER_NAME,
2462                 {
2463                         SPI_DFLT_SAMPLERATE,
2464                         SPI_DFLT_BITRATE, SPI_DFLT_FRAMEFMT,
2465                         INPUT_TEXT,
2466                 },
2467                 {
2468                         4, (const char *[]){
2469                                 [SPI_PIN_SCK] = "sck",
2470                                 [SPI_PIN_MISO] = "miso",
2471                                 [SPI_PIN_MOSI] = "mosi",
2472                                 [SPI_PIN_CS] = "cs",
2473                         },
2474                 },
2475                 sizeof(struct spi_proto_context_t),
2476                 spi_check_opts,
2477                 spi_config_frame,
2478                 spi_proc_pseudo,
2479                 spi_proc_value,
2480                 spi_get_idle_capture,
2481                 spi_get_idle_interframe,
2482         },
2483         [PROTO_TYPE_I2C] = {
2484                 I2C_HANDLER_NAME,
2485                 {
2486                         I2C_DFLT_SAMPLERATE,
2487                         I2C_DFLT_BITRATE, I2C_DFLT_FRAMEFMT,
2488                         INPUT_TEXT,
2489                 },
2490                 {
2491                         2, (const char *[]){
2492                                 [I2C_PIN_SCL] = "scl",
2493                                 [I2C_PIN_SDA] = "sda",
2494                         },
2495                 },
2496                 sizeof(struct i2c_proto_context_t),
2497                 i2c_check_opts,
2498                 i2c_config_frame,
2499                 i2c_proc_pseudo,
2500                 i2c_proc_value,
2501                 i2c_get_idle_capture,
2502                 i2c_get_idle_interframe,
2503         },
2504 };
2505
2506 static int lookup_protocol_name(struct context *inc)
2507 {
2508         const char *name;
2509         const struct proto_handler_t *handler;
2510         size_t idx;
2511         void *priv;
2512
2513         /*
2514          * Silence compiler warnings. Protocol handlers are free to use
2515          * several alternative sets of primitives for their operation.
2516          * Not using part of the API is nothing worth warning about.
2517          */
2518         (void)sample_buffer_assign;
2519
2520         if (!inc)
2521                 return SR_ERR_ARG;
2522         inc->curr_opts.protocol_type = PROTO_TYPE_NONE;
2523         inc->curr_opts.prot_hdl = NULL;
2524
2525         name = inc->curr_opts.proto_name;
2526         if (!name || !*name) {
2527                 /* Fallback to first item after NONE slot. */
2528                 handler = &protocols[PROTO_TYPE_NONE + 1];
2529                 name = handler->name;
2530         }
2531
2532         for (idx = 0; idx < ARRAY_SIZE(protocols); idx++) {
2533                 if (idx == PROTO_TYPE_NONE)
2534                         continue;
2535                 handler = &protocols[idx];
2536                 if (!handler->name || !*handler->name)
2537                         continue;
2538                 if (strcmp(name, handler->name) != 0)
2539                         continue;
2540                 inc->curr_opts.protocol_type = idx;
2541                 inc->curr_opts.prot_hdl = handler;
2542                 if (handler->priv_size) {
2543                         priv = g_malloc0(handler->priv_size);
2544                         if (!priv)
2545                                 return SR_ERR_MALLOC;
2546                         inc->curr_opts.prot_priv = priv;
2547                 }
2548                 return SR_OK;
2549         }
2550
2551         return SR_ERR_DATA;
2552 }
2553
2554 /* }}} protocol dispatching */
2555 /* {{{ text/binary input file reader */
2556
2557 /**
2558  * Checks for UTF BOM, removes it when found at the start of the buffer.
2559  *
2560  * @param[in] buf The accumulated input buffer.
2561  */
2562 static void check_remove_bom(GString *buf)
2563 {
2564         static const char *bom_text = "\xef\xbb\xbf";
2565
2566         if (buf->len < strlen(bom_text))
2567                 return;
2568         if (strncmp(buf->str, bom_text, strlen(bom_text)) != 0)
2569                 return;
2570         g_string_erase(buf, 0, strlen(bom_text));
2571 }
2572
2573 /**
2574  * Checks for presence of a caption, yields the position after its text line.
2575  *
2576  * @param[in] buf The accumulated input buffer.
2577  * @param[in] caption The text to search for (NUL terminated ASCII literal).
2578  * @param[in] max_pos The maximum length to search for.
2579  *
2580  * @returns The position after the text line which contains the caption.
2581  *   Or #NULL when either the caption or the end-of-line was not found.
2582  */
2583 static char *have_text_line(GString *buf, const char *caption, size_t max_pos)
2584 {
2585         size_t cap_len, rem_len;
2586         char *p_read, *p_found;
2587
2588         cap_len = strlen(caption);
2589         rem_len = buf->len;
2590         p_read = buf->str;
2591
2592         /* Search for the occurance of the caption itself. */
2593         if (!max_pos) {
2594                 /* Caption must be at the start of the buffer. */
2595                 if (rem_len < cap_len)
2596                         return NULL;
2597                 if (strncmp(p_read, caption, cap_len) != 0)
2598                         return NULL;
2599         } else {
2600                 /* Caption can be anywhere up to a max position. */
2601                 p_found = g_strstr_len(p_read, rem_len, caption);
2602                 if (!p_found)
2603                         return NULL;
2604                 /* Pretend that caption had been rather long. */
2605                 cap_len += p_found - p_read;
2606         }
2607
2608         /*
2609          * Advance over the caption. Advance over end-of-line. Supports
2610          * several end-of-line conditions, but rejects unexpected trailer
2611          * after the caption and before the end-of-line. Always wants LF.
2612          */
2613         p_read += cap_len;
2614         rem_len -= cap_len;
2615         while (rem_len && *p_read != '\n' && g_ascii_isspace(*p_read)) {
2616                 p_read++;
2617                 rem_len--;
2618         }
2619         if (rem_len && *p_read != '\n' && *p_read == '\r') {
2620                 p_read++;
2621                 rem_len--;
2622         }
2623         if (rem_len && *p_read == '\n') {
2624                 p_read++;
2625                 rem_len--;
2626                 return p_read;
2627         }
2628
2629         return NULL;
2630 }
2631
2632 /**
2633  * Checks for the presence of the magic string at the start of the file.
2634  *
2635  * @param[in] buf The accumulated input buffer.
2636  * @param[out] next_pos The text after the magic text line.
2637  *
2638  * @returns Boolean whether the magic was found.
2639  *
2640  * This implementation assumes that the magic file type marker never gets
2641  * split across receive chunks.
2642  */
2643 static gboolean have_magic(GString *buf, char **next_pos)
2644 {
2645         char *next_line;
2646
2647         if (next_pos)
2648                 *next_pos = NULL;
2649
2650         next_line = have_text_line(buf, MAGIC_FILE_TYPE, 0);
2651         if (!next_line)
2652                 return FALSE;
2653
2654         if (next_pos)
2655                 *next_pos = next_line;
2656
2657         return TRUE;
2658 }
2659
2660 /**
2661  * Checks for the presence of the header section at the start of the file.
2662  *
2663  * @param[in] buf The accumulated input buffer.
2664  * @param[out] next_pos The text after the header section.
2665  *
2666  * @returns A negative value when the answer is yet unknown (insufficient
2667  *   input data). Or boolean 0/1 when the header was found absent/present.
2668  *
2669  * The caller is supposed to have checked for and removed the magic text
2670  * for the file type. This routine expects to find the header section
2671  * boundaries right at the start of the input buffer.
2672  *
2673  * This implementation assumes that the header start marker never gets
2674  * split across receive chunks.
2675  */
2676 static int have_header(GString *buf, char **next_pos)
2677 {
2678         char *after_start, *after_end;
2679
2680         if (next_pos)
2681                 *next_pos = NULL;
2682
2683         after_start = have_text_line(buf, TEXT_HEAD_START, 0);
2684         if (!after_start)
2685                 return 0;
2686
2687         after_end = have_text_line(buf, TEXT_HEAD_END, buf->len);
2688         if (!after_end)
2689                 return -1;
2690
2691         if (next_pos)
2692                 *next_pos = after_end;
2693         return 1;
2694 }
2695
2696 /*
2697  * Implementation detail: Most parse routines merely accept an input
2698  * string or at most convert text to numbers. Actual processing of the
2699  * values or constraints checks are done later when the header section
2700  * ended and all data was seen, regardless of order of appearance.
2701  */
2702
2703 static int parse_samplerate(struct context *inc, const char *text)
2704 {
2705         uint64_t rate;
2706         int ret;
2707
2708         ret = sr_parse_sizestring(text, &rate);
2709         if (ret != SR_OK)
2710                 return SR_ERR_DATA;
2711
2712         inc->curr_opts.samplerate = rate;
2713
2714         return SR_OK;
2715 }
2716
2717 static int parse_bitrate(struct context *inc, const char *text)
2718 {
2719         uint64_t rate;
2720         int ret;
2721
2722         ret = sr_parse_sizestring(text, &rate);
2723         if (ret != SR_OK)
2724                 return SR_ERR_DATA;
2725
2726         inc->curr_opts.bitrate = rate;
2727
2728         return SR_OK;
2729 }
2730
2731 static int parse_protocol(struct context *inc, const char *line)
2732 {
2733
2734         if (!line || !*line)
2735                 return SR_ERR_DATA;
2736
2737         if (inc->curr_opts.proto_name) {
2738                 free(inc->curr_opts.proto_name);
2739                 inc->curr_opts.proto_name = NULL;
2740         }
2741         inc->curr_opts.proto_name = g_strdup(line);
2742         if (!inc->curr_opts.proto_name)
2743                 return SR_ERR_MALLOC;
2744         line = inc->curr_opts.proto_name;
2745
2746         return SR_OK;
2747 }
2748
2749 static int parse_frameformat(struct context *inc, const char *line)
2750 {
2751
2752         if (!line || !*line)
2753                 return SR_ERR_DATA;
2754
2755         if (inc->curr_opts.fmt_text) {
2756                 free(inc->curr_opts.fmt_text);
2757                 inc->curr_opts.fmt_text = NULL;
2758         }
2759         inc->curr_opts.fmt_text = g_strdup(line);
2760         if (!inc->curr_opts.fmt_text)
2761                 return SR_ERR_MALLOC;
2762         line = inc->curr_opts.fmt_text;
2763
2764         return SR_OK;
2765 }
2766
2767 static int parse_textinput(struct context *inc, const char *text)
2768 {
2769         gboolean is_text;
2770
2771         if (!text || !*text)
2772                 return SR_ERR_ARG;
2773
2774         is_text = sr_parse_boolstring(text);
2775         inc->curr_opts.textinput = is_text ? INPUT_TEXT : INPUT_BYTES;
2776         return SR_OK;
2777 }
2778
2779 static int parse_header_line(struct context *inc, const char *line)
2780 {
2781
2782         /* Silently ignore comment lines. Also covers start/end markers. */
2783         if (strncmp(line, TEXT_COMM_LEADER, strlen(TEXT_COMM_LEADER)) == 0)
2784                 return SR_OK;
2785
2786         if (strncmp(line, LABEL_SAMPLERATE, strlen(LABEL_SAMPLERATE)) == 0) {
2787                 line += strlen(LABEL_SAMPLERATE);
2788                 return parse_samplerate(inc, line);
2789         }
2790         if (strncmp(line, LABEL_BITRATE, strlen(LABEL_BITRATE)) == 0) {
2791                 line += strlen(LABEL_BITRATE);
2792                 return parse_bitrate(inc, line);
2793         }
2794         if (strncmp(line, LABEL_PROTOCOL, strlen(LABEL_PROTOCOL)) == 0) {
2795                 line += strlen(LABEL_PROTOCOL);
2796                 return parse_protocol(inc, line);
2797         }
2798         if (strncmp(line, LABEL_FRAMEFORMAT, strlen(LABEL_FRAMEFORMAT)) == 0) {
2799                 line += strlen(LABEL_FRAMEFORMAT);
2800                 return parse_frameformat(inc, line);
2801         }
2802         if (strncmp(line, LABEL_TEXTINPUT, strlen(LABEL_TEXTINPUT)) == 0) {
2803                 line += strlen(LABEL_TEXTINPUT);
2804                 return parse_textinput(inc, line);
2805         }
2806
2807         /* Unsupported directive. */
2808         sr_err("Unsupported header directive: %s.", line);
2809
2810         return SR_ERR_DATA;
2811 }
2812
2813 static int parse_header(struct context *inc, GString *buf, size_t hdr_len)
2814 {
2815         size_t remain;
2816         char *curr, *next, *line;
2817         int ret;
2818
2819         ret = SR_OK;
2820
2821         /* The caller determined where the header ends. Read up to there. */
2822         remain = hdr_len;
2823         curr = buf->str;
2824         while (curr && remain) {
2825                 /* Get another text line. Skip empty lines. */
2826                 line = sr_text_next_line(curr, remain, &next, NULL);
2827                 if (!line)
2828                         break;
2829                 if (next)
2830                         remain -= next - curr;
2831                 else
2832                         remain = 0;
2833                 curr = next;
2834                 if (!*line)
2835                         continue;
2836                 /* Process the non-empty file header text line. */
2837                 sr_dbg("Header line: %s", line);
2838                 ret = parse_header_line(inc, line);
2839                 if (ret != SR_OK)
2840                         break;
2841         }
2842
2843         return ret;
2844 }
2845
2846 /* Process input text reader specific pseudo comment. */
2847 static int process_pseudo_textinput(struct sr_input *in, char *line)
2848 {
2849         struct context *inc;
2850         char *word;
2851         unsigned long v;
2852         char *endp;
2853         int ret;
2854
2855         inc = in->priv;
2856         while (line) {
2857                 word = sr_text_next_word(line, &line);
2858                 if (!word)
2859                         break;
2860                 if (!*word)
2861                         continue;
2862                 if (g_str_has_prefix(word, TEXT_INPUT_RADIX)) {
2863                         word += strlen(TEXT_INPUT_RADIX);
2864                         endp = NULL;
2865                         ret = sr_atoul_base(word, &v, &endp, 10);
2866                         if (ret != SR_OK)
2867                                 return ret;
2868                         inc->read_text.base = v;
2869                         continue;
2870                 }
2871                 return SR_ERR_DATA;
2872         }
2873
2874         return SR_OK;
2875 }
2876
2877 /* Process a line of input text. */
2878 static int process_textline(struct sr_input *in, char *line)
2879 {
2880         struct context *inc;
2881         const struct proto_handler_t *handler;
2882         gboolean is_comm, is_pseudo;
2883         char *p, *word, *endp;
2884         unsigned long value;
2885         int ret;
2886
2887         inc = in->priv;
2888         handler = inc->curr_opts.prot_hdl;
2889
2890         /*
2891          * Check for comments, including pseudo-comments with protocol
2892          * specific or text reader specific instructions. It's essential
2893          * to check for "# ${PROTO}:" last, because the implementation
2894          * of the check advances the read position, cannot rewind when
2895          * detection fails. But we know that it is a comment and was not
2896          * a pseudo-comment. So any non-matching data just gets discarded.
2897          * Matching data gets processed (when handlers exist).
2898          */
2899         is_comm = g_str_has_prefix(line, TEXT_COMM_LEADER);
2900         if (is_comm) {
2901                 line += strlen(TEXT_COMM_LEADER);
2902                 while (isspace(*line))
2903                         line++;
2904                 is_pseudo = g_str_has_prefix(line, TEXT_INPUT_PREFIX);
2905                 if (is_pseudo) {
2906                         line += strlen(TEXT_INPUT_PREFIX);
2907                         while (isspace(*line))
2908                                 line++;
2909                         sr_dbg("pseudo comment, textinput: %s", line);
2910                         line = sr_text_trim_spaces(line);
2911                         return process_pseudo_textinput(in, line);
2912                 }
2913                 is_pseudo = g_str_has_prefix(line, handler->name);
2914                 if (is_pseudo) {
2915                         line += strlen(handler->name);
2916                         is_pseudo = *line == ':';
2917                         if (is_pseudo)
2918                                 line++;
2919                 }
2920                 if (is_pseudo) {
2921                         while (isspace(*line))
2922                                 line++;
2923                         sr_dbg("pseudo comment, protocol: %s", line);
2924                         if (!handler->proc_pseudo)
2925                                 return SR_OK;
2926                         return handler->proc_pseudo(in, line);
2927                 }
2928                 sr_spew("comment, skipping: %s", line);
2929                 return SR_OK;
2930         }
2931
2932         /*
2933          * Non-empty non-comment lines carry protocol values.
2934          * (Empty lines are handled transparently when they get here.)
2935          * Accept comma and semicolon separators for user convenience.
2936          * Convert text according to previously received instructions.
2937          * Pass the values to the protocol handler. Flush waveforms
2938          * when handlers state that their construction has completed.
2939          */
2940         sr_spew("got values line: %s", line);
2941         for (p = line; *p; p++) {
2942                 if (*p == ',' || *p == ';')
2943                         *p = ' ';
2944         }
2945         while (line) {
2946                 word = sr_text_next_word(line, &line);
2947                 if (!word)
2948                         break;
2949                 if (!*word)
2950                         continue;
2951                 /* Get another numeric value. */
2952                 endp = NULL;
2953                 ret = sr_atoul_base(word, &value, &endp, inc->read_text.base);
2954                 if (ret != SR_OK)
2955                         return ret;
2956                 if (!endp || *endp)
2957                         return SR_ERR_DATA;
2958                 sr_spew("got a value, text [%s] -> number [%lu]", word, value);
2959                 /* Forward the value to the protocol handler. */
2960                 ret = 0;
2961                 if (handler->proc_value)
2962                         ret = handler->proc_value(inc, value);
2963                 if (ret < 0)
2964                         return ret;
2965                 /* Flush the waveform when handler signals completion. */
2966                 if (ret > 0)
2967                         continue;
2968                 ret = send_frame(in);
2969                 if (ret != SR_OK)
2970                         return ret;
2971                 ret = send_idle_interframe(inc);
2972                 if (ret != SR_OK)
2973                         return ret;
2974         }
2975
2976         return SR_OK;
2977 }
2978
2979 /* }}} text/binary input file reader */
2980
2981 /*
2982  * Consistency check of all previously received information. Combines
2983  * the data file's optional header section, as well as user provided
2984  * options that were specified during input module creation. User specs
2985  * take precedence over file content.
2986  */
2987 static int check_header_user_options(struct context *inc)
2988 {
2989         int ret;
2990         const struct proto_handler_t *handler;
2991         uint64_t rate;
2992         const char *text;
2993         enum textinput_t is_text;
2994
2995         if (!inc)
2996                 return SR_ERR_ARG;
2997
2998         /* Prefer user specs over file content. */
2999         rate = inc->user_opts.samplerate;
3000         if (rate) {
3001                 sr_dbg("Using user samplerate %" PRIu64 ".", rate);
3002                 inc->curr_opts.samplerate = rate;
3003         }
3004         rate = inc->user_opts.bitrate;
3005         if (rate) {
3006                 sr_dbg("Using user bitrate %" PRIu64 ".", rate);
3007                 inc->curr_opts.bitrate = rate;
3008         }
3009         text = inc->user_opts.proto_name;
3010         if (text && *text) {
3011                 sr_dbg("Using user protocol %s.", text);
3012                 ret = parse_protocol(inc, text);
3013                 if (ret != SR_OK)
3014                         return SR_ERR_DATA;
3015         }
3016         text = inc->user_opts.fmt_text;
3017         if (text && *text) {
3018                 sr_dbg("Using user frame format %s.", text);
3019                 ret = parse_frameformat(inc, text);
3020                 if (ret != SR_OK)
3021                         return SR_ERR_DATA;
3022         }
3023         is_text = inc->user_opts.textinput;
3024         if (is_text) {
3025                 sr_dbg("Using user textinput %d.", is_text);
3026                 inc->curr_opts.textinput = is_text;
3027         }
3028
3029         /* Lookup the protocol (with fallback). Use protocol's defaults. */
3030         text = inc->curr_opts.proto_name;
3031         ret = lookup_protocol_name(inc);
3032         handler = inc->curr_opts.prot_hdl;
3033         if (ret != SR_OK || !handler) {
3034                 sr_err("Unsupported protocol: %s.", text);
3035                 return SR_ERR_DATA;
3036         }
3037         text = handler->name;
3038         if (!inc->curr_opts.proto_name && text) {
3039                 sr_dbg("Using protocol handler name %s.", text);
3040                 ret = parse_protocol(inc, text);
3041                 if (ret != SR_OK)
3042                         return SR_ERR_DATA;
3043         }
3044         rate = handler->dflt.samplerate;
3045         if (!inc->curr_opts.samplerate && rate) {
3046                 sr_dbg("Using protocol handler samplerate %" PRIu64 ".", rate);
3047                 inc->curr_opts.samplerate = rate;
3048         }
3049         rate = handler->dflt.bitrate;
3050         if (!inc->curr_opts.bitrate && rate) {
3051                 sr_dbg("Using protocol handler bitrate %" PRIu64 ".", rate);
3052                 inc->curr_opts.bitrate = rate;
3053         }
3054         text = handler->dflt.frame_format;
3055         if (!inc->curr_opts.fmt_text && text && *text) {
3056                 sr_dbg("Using protocol handler frame format %s.", text);
3057                 ret = parse_frameformat(inc, text);
3058                 if (ret != SR_OK)
3059                         return SR_ERR_DATA;
3060         }
3061         is_text = handler->dflt.textinput;
3062         if (!inc->curr_opts.textinput && is_text) {
3063                 sr_dbg("Using protocol handler text format %d.", is_text);
3064                 inc->curr_opts.textinput = is_text;
3065         }
3066
3067         if (!inc->curr_opts.samplerate) {
3068                 sr_err("Need a samplerate.");
3069                 return SR_ERR_DATA;
3070         }
3071         if (!inc->curr_opts.bitrate) {
3072                 sr_err("Need a protocol bitrate.");
3073                 return SR_ERR_DATA;
3074         }
3075
3076         if (inc->curr_opts.samplerate < inc->curr_opts.bitrate) {
3077                 sr_err("Bitrate cannot exceed samplerate.");
3078                 return SR_ERR_DATA;
3079         }
3080         if (inc->curr_opts.samplerate / inc->curr_opts.bitrate < 3)
3081                 sr_warn("Low oversampling, consider higher samplerate.");
3082         if (inc->curr_opts.prot_hdl->check_opts) {
3083                 ret = inc->curr_opts.prot_hdl->check_opts(inc);
3084                 if (ret != SR_OK) {
3085                         sr_err("Options failed the protocol's check.");
3086                         return SR_ERR_DATA;
3087                 }
3088         }
3089
3090         return SR_OK;
3091 }
3092
3093 static int create_channels(struct sr_input *in)
3094 {
3095         struct context *inc;
3096         struct sr_dev_inst *sdi;
3097         const struct proto_handler_t *handler;
3098         size_t index;
3099         const char *name;
3100
3101         if (!in)
3102                 return SR_ERR_ARG;
3103         inc = in->priv;
3104         if (!inc)
3105                 return SR_ERR_ARG;
3106         sdi = in->sdi;
3107         handler = inc->curr_opts.prot_hdl;
3108
3109         for (index = 0; index < handler->chans.count; index++) {
3110                 name = handler->chans.names[index];
3111                 sr_dbg("Channel %zu name %s.", index, name);
3112                 sr_channel_new(sdi, index, SR_CHANNEL_LOGIC, TRUE, name);
3113         }
3114
3115         inc->feed_logic = feed_queue_logic_alloc(in->sdi,
3116                 CHUNK_SIZE, sizeof(uint8_t));
3117         if (!inc->feed_logic) {
3118                 sr_err("Cannot create session feed.");
3119                 return SR_ERR_MALLOC;
3120         }
3121
3122         return SR_OK;
3123 }
3124
3125 /*
3126  * Keep track of a previously created channel list, in preparation of
3127  * re-reading the input file. Gets called from reset()/cleanup() paths.
3128  */
3129 static void keep_header_for_reread(const struct sr_input *in)
3130 {
3131         struct context *inc;
3132
3133         inc = in->priv;
3134
3135         g_slist_free_full(inc->prev.sr_groups, sr_channel_group_free_cb);
3136         inc->prev.sr_groups = in->sdi->channel_groups;
3137         in->sdi->channel_groups = NULL;
3138
3139         g_slist_free_full(inc->prev.sr_channels, sr_channel_free_cb);
3140         inc->prev.sr_channels = in->sdi->channels;
3141         in->sdi->channels = NULL;
3142 }
3143
3144 /*
3145  * Check whether the input file is being re-read, and refuse operation
3146  * when essential parameters of the acquisition have changed in ways
3147  * that are unexpected to calling applications. Gets called after the
3148  * file header got parsed (again).
3149  *
3150  * Changing the channel list across re-imports of the same file is not
3151  * supported, by design and for valid reasons, see bug #1215 for details.
3152  * Users are expected to start new sessions when they change these
3153  * essential parameters in the acquisition's setup. When we accept the
3154  * re-read file, then make sure to keep using the previous channel list,
3155  * applications may still reference them.
3156  */
3157 static gboolean check_header_in_reread(const struct sr_input *in)
3158 {
3159         struct context *inc;
3160
3161         if (!in)
3162                 return FALSE;
3163         inc = in->priv;
3164         if (!inc)
3165                 return FALSE;
3166         if (!inc->prev.sr_channels)
3167                 return TRUE;
3168
3169         if (sr_channel_lists_differ(inc->prev.sr_channels, in->sdi->channels)) {
3170                 sr_err("Channel list change not supported for file re-read.");
3171                 return FALSE;
3172         }
3173
3174         g_slist_free_full(in->sdi->channel_groups, sr_channel_group_free_cb);
3175         in->sdi->channel_groups = inc->prev.sr_groups;
3176         inc->prev.sr_groups = NULL;
3177
3178         g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
3179         in->sdi->channels = inc->prev.sr_channels;
3180         inc->prev.sr_channels = NULL;
3181
3182         return TRUE;
3183 }
3184
3185 /* Process another chunk of accumulated input data. */
3186 static int process_buffer(struct sr_input *in, gboolean is_eof)
3187 {
3188         struct context *inc;
3189         GVariant *gvar;
3190         int ret;
3191         GString *buf;
3192         const struct proto_handler_t *handler;
3193         size_t seen;
3194         char *line, *next;
3195         uint8_t sample;
3196
3197         inc = in->priv;
3198         buf = in->buf;
3199         handler = inc->curr_opts.prot_hdl;
3200
3201         /*
3202          * Send feed header and samplerate once before any sample data.
3203          * Communicate an idle period before the first generated frame.
3204          */
3205         if (!inc->started) {
3206                 std_session_send_df_header(in->sdi);
3207                 gvar = g_variant_new_uint64(inc->curr_opts.samplerate);
3208                 ret = sr_session_send_meta(in->sdi, SR_CONF_SAMPLERATE, gvar);
3209                 inc->started = TRUE;
3210                 if (ret != SR_OK)
3211                         return ret;
3212
3213                 ret = send_idle_capture(inc);
3214                 if (ret != SR_OK)
3215                         return ret;
3216         }
3217
3218         /*
3219          * Force proper line termination when EOF is seen and the data
3220          * is in text format. This does not affect binary input, while
3221          * properly terminated text input does not suffer from another
3222          * line feed, because empty lines are considered acceptable.
3223          * Increases robustness for text input from broken generators
3224          * (popular editors which don't terminate the last line).
3225          */
3226         if (inc->curr_opts.textinput == INPUT_TEXT && is_eof) {
3227                 g_string_append_c(buf, '\n');
3228         }
3229
3230         /*
3231          * For text input: Scan for the completion of another text line.
3232          * Process its values (or pseudo comments). Skip comment lines.
3233          */
3234         if (inc->curr_opts.textinput == INPUT_TEXT) do {
3235                 /* Get another line of text. */
3236                 seen = 0;
3237                 line = sr_text_next_line(buf->str, buf->len, &next, &seen);
3238                 if (!line)
3239                         break;
3240                 /* Process non-empty input lines. */
3241                 ret = *line ? process_textline(in, line) : 0;
3242                 if (ret < 0)
3243                         return ret;
3244                 /* Discard processed input text. */
3245                 g_string_erase(buf, 0, seen);
3246         } while (buf->len);
3247
3248         /*
3249          * For binary input: Pass data values (individual bytes) to the
3250          * creation of protocol frames. Send the frame's waveform to
3251          * logic channels in the session feed when the protocol handler
3252          * signals the completion of another waveform (zero return value).
3253          * Non-zero positive values translate to "need more input data".
3254          * Negative values signal fatal errors. Remove processed input
3255          * data from the receive buffer.
3256          */
3257         if (inc->curr_opts.textinput == INPUT_BYTES) {
3258                 seen = 0;
3259                 while (seen < buf->len) {
3260                         sample = buf->str[seen++];
3261                         ret = 0;
3262                         if (handler->proc_value)
3263                                 ret = handler->proc_value(inc, sample);
3264                         if (ret < 0)
3265                                 return ret;
3266                         if (ret > 0)
3267                                 continue;
3268                         ret = send_frame(in);
3269                         if (ret != SR_OK)
3270                                 return ret;
3271                         ret = send_idle_interframe(inc);
3272                         if (ret != SR_OK)
3273                                 return ret;
3274                 }
3275                 g_string_erase(buf, 0, seen);
3276         }
3277
3278         /* Send idle level, and flush when end of input data is seen. */
3279         if (is_eof) {
3280                 if (buf->len)
3281                         sr_warn("Unprocessed input data remains.");
3282
3283                 ret = send_idle_capture(inc);
3284                 if (ret != SR_OK)
3285                         return ret;
3286
3287                 ret = feed_queue_logic_flush(inc->feed_logic);
3288                 if (ret != SR_OK)
3289                         return ret;
3290         }
3291
3292         return SR_OK;
3293 }
3294
3295 static int format_match(GHashTable *metadata, unsigned int *confidence)
3296 {
3297         GString *buf, *tmpbuf;
3298         gboolean has_magic;
3299
3300         buf = g_hash_table_lookup(metadata,
3301                 GINT_TO_POINTER(SR_INPUT_META_HEADER));
3302         tmpbuf = g_string_new_len(buf->str, buf->len);
3303
3304         check_remove_bom(tmpbuf);
3305         has_magic = have_magic(tmpbuf, NULL);
3306         g_string_free(tmpbuf, TRUE);
3307
3308         if (!has_magic)
3309                 return SR_ERR;
3310
3311         *confidence = 1;
3312         return SR_OK;
3313 }
3314
3315 static int init(struct sr_input *in, GHashTable *options)
3316 {
3317         struct context *inc;
3318         GVariant *gvar;
3319         uint64_t rate;
3320         char *copy;
3321         const char *text;
3322
3323         in->sdi = g_malloc0(sizeof(*in->sdi));
3324         inc = g_malloc0(sizeof(*inc));
3325         in->priv = inc;
3326
3327         /*
3328          * Store user specified options for later reference.
3329          *
3330          * TODO How to most appropriately hook up size strings with the
3331          * input module's defaults, and applications and their input
3332          * dialogs?
3333          */
3334         gvar = g_hash_table_lookup(options, "samplerate");
3335         if (gvar) {
3336                 rate = g_variant_get_uint64(gvar);
3337                 if (rate)
3338                         sr_dbg("User samplerate %" PRIu64 ".", rate);
3339                 inc->user_opts.samplerate = rate;
3340         }
3341
3342         gvar = g_hash_table_lookup(options, "bitrate");
3343         if (gvar) {
3344                 rate = g_variant_get_uint64(gvar);
3345                 if (rate)
3346                         sr_dbg("User bitrate %" PRIu64 ".", rate);
3347                 inc->user_opts.bitrate = rate;
3348         }
3349
3350         gvar = g_hash_table_lookup(options, "protocol");
3351         if (gvar) {
3352                 copy = g_strdup(g_variant_get_string(gvar, NULL));
3353                 if (!copy)
3354                         return SR_ERR_MALLOC;
3355                 if (*copy)
3356                         sr_dbg("User protocol %s.", copy);
3357                 inc->user_opts.proto_name = copy;
3358         }
3359
3360         gvar = g_hash_table_lookup(options, "frameformat");
3361         if (gvar) {
3362                 copy = g_strdup(g_variant_get_string(gvar, NULL));
3363                 if (!copy)
3364                         return SR_ERR_MALLOC;
3365                 if (*copy)
3366                         sr_dbg("User frame format %s.", copy);
3367                 inc->user_opts.fmt_text = copy;
3368         }
3369
3370         inc->user_opts.textinput = INPUT_UNSPEC;
3371         gvar = g_hash_table_lookup(options, "textinput");
3372         if (gvar) {
3373                 text = g_variant_get_string(gvar, NULL);
3374                 if (!text)
3375                         return SR_ERR_DATA;
3376                 if (!*text)
3377                         return SR_ERR_DATA;
3378                 sr_dbg("User text input %s.", text);
3379                 if (strcmp(text, input_format_texts[INPUT_UNSPEC]) == 0) {
3380                         inc->user_opts.textinput = INPUT_UNSPEC;
3381                 } else if (strcmp(text, input_format_texts[INPUT_BYTES]) == 0) {
3382                         inc->user_opts.textinput = INPUT_BYTES;
3383                 } else if (strcmp(text, input_format_texts[INPUT_TEXT]) == 0) {
3384                         inc->user_opts.textinput = INPUT_TEXT;
3385                 } else {
3386                         return SR_ERR_DATA;
3387                 }
3388         }
3389
3390         return SR_OK;
3391 }
3392
3393 static int receive(struct sr_input *in, GString *buf)
3394 {
3395         struct context *inc;
3396         char *after_magic, *after_header;
3397         size_t consumed;
3398         int ret;
3399
3400         inc = in->priv;
3401
3402         /*
3403          * Accumulate all input chunks, potential deferred processing.
3404          *
3405          * Remove an optional BOM at the very start of the input stream.
3406          * BEWARE! This may affect binary input, and we cannot tell if
3407          * the input is text or binary at this stage. Though probability
3408          * for this issue is rather low. Workarounds are available (put
3409          * another values before the first data which happens to match
3410          * the BOM pattern, provide text input instead).
3411          */
3412         g_string_append_len(in->buf, buf->str, buf->len);
3413         if (!inc->scanned_magic)
3414                 check_remove_bom(in->buf);
3415
3416         /*
3417          * Must complete reception of the (optional) header first. Both
3418          * end of header and absence of header will: Check options that
3419          * were seen so far, then start processing the data part.
3420          */
3421         if (!inc->got_header) {
3422                 /* Check for magic file type marker. */
3423                 if (!inc->scanned_magic) {
3424                         inc->has_magic = have_magic(in->buf, &after_magic);
3425                         inc->scanned_magic = TRUE;
3426                         if (inc->has_magic) {
3427                                 consumed = after_magic - in->buf->str;
3428                                 sr_dbg("File format magic found (%zu).", consumed);
3429                                 g_string_erase(in->buf, 0, consumed);
3430                         }
3431                 }
3432
3433                 /* Complete header reception and processing. */
3434                 if (inc->has_magic) {
3435                         ret = have_header(in->buf, &after_header);
3436                         if (ret < 0)
3437                                 return SR_OK;
3438                         inc->has_header = ret;
3439                         if (inc->has_header) {
3440                                 consumed = after_header - in->buf->str;
3441                                 sr_dbg("File header found (%zu), processing.", consumed);
3442                                 ret = parse_header(inc, in->buf, consumed);
3443                                 if (ret != SR_OK)
3444                                         return ret;
3445                                 g_string_erase(in->buf, 0, consumed);
3446                         }
3447                 }
3448                 inc->got_header = TRUE;
3449
3450                 /*
3451                  * Postprocess the combination of all options. Create
3452                  * logic channels, prepare resources for data processing.
3453                  */
3454                 ret = check_header_user_options(inc);
3455                 if (ret != SR_OK)
3456                         return ret;
3457                 ret = create_channels(in);
3458                 if (ret != SR_OK)
3459                         return ret;
3460                 if (!check_header_in_reread(in))
3461                         return SR_ERR_DATA;
3462                 ret = alloc_frame_storage(inc);
3463                 if (ret != SR_OK)
3464                         return ret;
3465                 ret = assign_bit_widths(inc);
3466                 if (ret != SR_OK)
3467                         return ret;
3468
3469                 /* Notify the frontend that sdi is ready. */
3470                 in->sdi_ready = TRUE;
3471                 return SR_OK;
3472         }
3473
3474         /*
3475          * Process the input file's data section after the header section
3476          * was received and processed.
3477          */
3478         ret = process_buffer(in, FALSE);
3479
3480         return ret;
3481 }
3482
3483 static int end(struct sr_input *in)
3484 {
3485         struct context *inc;
3486         int ret;
3487
3488         inc = in->priv;
3489
3490         /* Must complete processing of previously received chunks. */
3491         if (in->sdi_ready) {
3492                 ret = process_buffer(in, TRUE);
3493                 if (ret != SR_OK)
3494                         return ret;
3495         }
3496
3497         /* Must send DF_END when DF_HEADER was sent before. */
3498         if (inc->started) {
3499                 ret = std_session_send_df_end(in->sdi);
3500                 if (ret != SR_OK)
3501                         return ret;
3502         }
3503
3504         return SR_OK;
3505 }
3506
3507 static void cleanup(struct sr_input *in)
3508 {
3509         struct context *inc;
3510
3511         inc = in->priv;
3512
3513         keep_header_for_reread(in);
3514
3515         g_free(inc->curr_opts.proto_name);
3516         inc->curr_opts.proto_name = NULL;
3517         g_free(inc->curr_opts.fmt_text);
3518         inc->curr_opts.fmt_text = NULL;
3519         g_free(inc->curr_opts.prot_priv);
3520         inc->curr_opts.prot_priv = NULL;
3521         feed_queue_logic_free(inc->feed_logic);
3522         inc->feed_logic = NULL;
3523         g_free(inc->sample_edges);
3524         inc->sample_edges = NULL;
3525         g_free(inc->sample_widths);
3526         inc->sample_widths = NULL;
3527         g_free(inc->sample_levels);
3528         inc->sample_levels = NULL;
3529         g_free(inc->bit_scale);
3530         inc->bit_scale = NULL;
3531 }
3532
3533 static int reset(struct sr_input *in)
3534 {
3535         struct context *inc;
3536         struct user_opts_t save_user_opts;
3537         struct proto_prev save_chans;
3538
3539         inc = in->priv;
3540
3541         /* Release previously allocated resources. */
3542         cleanup(in);
3543         g_string_truncate(in->buf, 0);
3544
3545         /* Restore part of the context, init() won't run again. */
3546         save_user_opts = inc->user_opts;
3547         save_chans = inc->prev;
3548         memset(inc, 0, sizeof(*inc));
3549         inc->user_opts = save_user_opts;
3550         inc->prev = save_chans;
3551
3552         return SR_OK;
3553 }
3554
3555 enum proto_option_t {
3556         OPT_SAMPLERATE,
3557         OPT_BITRATE,
3558         OPT_PROTOCOL,
3559         OPT_FRAME_FORMAT,
3560         OPT_TEXTINPUT,
3561         OPT_MAX,
3562 };
3563
3564 static struct sr_option options[] = {
3565         [OPT_SAMPLERATE] = {
3566                 "samplerate", "Logic data samplerate",
3567                 "Samplerate of generated logic traces",
3568                 NULL, NULL,
3569         },
3570         [OPT_BITRATE] = {
3571                 "bitrate", "Protocol bitrate",
3572                 "Bitrate used in protocol's communication",
3573                 NULL, NULL,
3574         },
3575         [OPT_PROTOCOL] = {
3576                 "protocol", "Protocol type",
3577                 "The type of protocol to generate waveforms for",
3578                 NULL, NULL,
3579         },
3580         [OPT_FRAME_FORMAT] = {
3581                 "frameformat", "Protocol frame format",
3582                 "Textual description of the protocol's frame format",
3583                 NULL, NULL,
3584         },
3585         [OPT_TEXTINPUT] = {
3586                 "textinput", "Input data is in text format",
3587                 "Input is not data bytes, but text formatted values",
3588                 NULL, NULL,
3589         },
3590         [OPT_MAX] = ALL_ZERO,
3591 };
3592
3593 static const struct sr_option *get_options(void)
3594 {
3595         GSList *l;
3596         enum proto_type_t p_idx;
3597         enum textinput_t t_idx;
3598         const char *s;
3599
3600         if (options[0].def)
3601                 return options;
3602
3603         options[OPT_SAMPLERATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
3604         options[OPT_BITRATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
3605         options[OPT_PROTOCOL].def = g_variant_ref_sink(g_variant_new_string(""));
3606         l = NULL;
3607         for (p_idx = 0; p_idx < ARRAY_SIZE(protocols); p_idx++) {
3608                 s = protocols[p_idx].name;
3609                 if (!s || !*s)
3610                         continue;
3611                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string(s)));
3612         }
3613         options[OPT_PROTOCOL].values = l;
3614         options[OPT_FRAME_FORMAT].def = g_variant_ref_sink(g_variant_new_string(""));
3615         l = NULL;
3616         for (t_idx = INPUT_UNSPEC; t_idx <= INPUT_TEXT; t_idx++) {
3617                 s = input_format_texts[t_idx];
3618                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string(s)));
3619         }
3620         options[OPT_TEXTINPUT].values = l;
3621         options[OPT_TEXTINPUT].def = g_variant_ref_sink(g_variant_new_string(
3622                 input_format_texts[INPUT_UNSPEC]));
3623         return options;
3624 }
3625
3626 SR_PRIV struct sr_input_module input_protocoldata = {
3627         .id = "protocoldata",
3628         .name = "Protocol data",
3629         .desc = "Generate logic traces from protocol's data values",
3630         .exts = (const char *[]){ "sr-protocol", "protocol", "bin", NULL, },
3631         .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
3632         .options = get_options,
3633         .format_match = format_match,
3634         .init = init,
3635         .receive = receive,
3636         .end = end,
3637         .reset = reset,
3638 };