]> sigrok.org Git - libsigrok.git/blob - src/input/protocoldata.c
e8591b22296cec68b53ae6e2884fff3dbe0a0b10
[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(inc->feed_logic, &data, sizeof(data));
718                 if (ret != SR_OK)
719                         return ret;
720         }
721
722         return SR_OK;
723 }
724
725 /* Optionally send idle level between protocol frames. */
726 static int send_idle_interframe(struct context *inc)
727 {
728         const struct proto_handler_t *handler;
729         size_t count;
730         uint8_t data;
731         int ret;
732
733         handler = inc->curr_opts.prot_hdl;
734         if (!handler->get_idle_interframe)
735                 return SR_OK;
736
737         ret = handler->get_idle_interframe(inc, &count, &data);
738         if (ret != SR_OK)
739                 return ret;
740         while (count--) {
741                 ret = feed_queue_logic_submit(inc->feed_logic, &data, sizeof(data));
742                 if (ret != SR_OK)
743                         return ret;
744         }
745
746         return SR_OK;
747 }
748
749 /* Forward the previously accumulated samples of the waveform. */
750 static int send_frame(struct sr_input *in)
751 {
752         struct context *inc;
753         size_t count, index;
754         uint8_t data;
755
756         inc = in->priv;
757
758         for (index = 0; index < inc->top_frame_bits; index++) {
759                 data = inc->sample_levels[index];
760                 count = inc->sample_widths[index];
761                 while (count--) {
762                         feed_queue_logic_submit(inc->feed_logic,
763                                 &data, sizeof(data));
764                 }
765         }
766
767         return SR_OK;
768 }
769
770 /* }}} frame bits manipulation */
771 /* {{{ UART protocol handler */
772
773 enum uart_pin_t {
774         UART_PIN_RXTX,
775 };
776
777 #define UART_PINMASK_RXTX       (1UL << UART_PIN_RXTX)
778
779 /* UART specific options and frame format check. */
780 static int uart_check_opts(struct context *inc)
781 {
782         struct uart_frame_fmt_opts *fmt_opts;
783         const char *fmt_text;
784         char **opts, *opt;
785         size_t opt_count, opt_idx;
786         int ret;
787         unsigned long v;
788         char par_text;
789         char *endp;
790         size_t total_bits;
791
792         if (!inc)
793                 return SR_ERR_ARG;
794         fmt_opts = &inc->curr_opts.frame_format.uart;
795
796         /* Apply defaults before reading external spec. */
797         memset(fmt_opts, 0, sizeof(*fmt_opts));
798         fmt_opts->databit_count = 8;
799         fmt_opts->parity_type = UART_PARITY_NONE;
800         fmt_opts->stopbit_count = 1;
801         fmt_opts->half_stopbit = FALSE;
802         fmt_opts->inverted = FALSE;
803
804         /* Provide a default UART frame format. */
805         fmt_text = inc->curr_opts.fmt_text;
806         if (!fmt_text || !*fmt_text)
807                 fmt_text = UART_DFLT_FRAMEFMT;
808         sr_dbg("UART frame format: %s.", fmt_text);
809
810         /* Parse the comma separated list of user provided options. */
811         opts = g_strsplit_set(fmt_text, ", ", 0);
812         opt_count = g_strv_length(opts);
813         for (opt_idx = 0; opt_idx < opt_count; opt_idx++) {
814                 opt = opts[opt_idx];
815                 if (!opt || !*opt)
816                         continue;
817                 sr_spew("UART format option: %s", opt);
818                 /*
819                  * Check for specific keywords. Before falling back to
820                  * attempting the "8n1" et al interpretation.
821                  */
822                 if (strcmp(opt, UART_FORMAT_INVERT) == 0) {
823                         fmt_opts->inverted = TRUE;
824                         continue;
825                 }
826                 /* Parse an "8n1", "8e2", "7o1", or similar input spec. */
827                 /* Get the data bits count. */
828                 endp = NULL;
829                 ret = sr_atoul_base(opt, &v, &endp, 10);
830                 if (ret != SR_OK || !endp)
831                         return SR_ERR_DATA;
832                 opt = endp;
833                 if (v < UART_MIN_DATABITS || v > UART_MAX_DATABITS)
834                         return SR_ERR_DATA;
835                 fmt_opts->databit_count = v;
836                 /* Get the parity type. */
837                 par_text = tolower((int)*opt++);
838                 switch (par_text) {
839                 case 'n':
840                         fmt_opts->parity_type = UART_PARITY_NONE;
841                         break;
842                 case 'o':
843                         fmt_opts->parity_type = UART_PARITY_ODD;
844                         break;
845                 case 'e':
846                         fmt_opts->parity_type = UART_PARITY_EVEN;
847                         break;
848                 default:
849                         return SR_ERR_DATA;
850                 }
851                 /* Get the stop bits count. Supports half bits too. */
852                 endp = NULL;
853                 ret = sr_atoul_base(opt, &v, &endp, 10);
854                 if (ret != SR_OK || !endp)
855                         return SR_ERR_DATA;
856                 opt = endp;
857                 if (v > UART_MAX_STOPBITS)
858                         return SR_ERR_DATA;
859                 fmt_opts->stopbit_count = v;
860                 if (g_ascii_strcasecmp(opt, ".5") == 0) {
861                         opt += strlen(".5");
862                         fmt_opts->half_stopbit = TRUE;
863                 }
864                 /* Incomplete consumption of input text is fatal. */
865                 if (*opt) {
866                         sr_err("Unprocessed frame format remainder: %s.", opt);
867                         return SR_ERR_DATA;
868                 }
869                 continue;
870         }
871         g_strfreev(opts);
872
873         /*
874          * Calculate the total number of bit times in the UART frame.
875          * Add a few more bit times to the reserved space. They usually
876          * are not occupied during data transmission, but are useful to
877          * have for special symbols (BREAK, IDLE).
878          */
879         total_bits = 1; /* START bit, unconditional. */
880         total_bits += fmt_opts->databit_count;
881         total_bits += (fmt_opts->parity_type != UART_PARITY_NONE) ? 1 : 0;
882         total_bits += fmt_opts->stopbit_count;
883         total_bits += fmt_opts->half_stopbit ? 1 : 0;
884         total_bits += UART_ADD_IDLEBITS;
885         sr_dbg("UART frame: total bits %lu.", total_bits);
886         if (total_bits > UART_MAX_WAVELEN)
887                 return SR_ERR_DATA;
888         inc->max_frame_bits = total_bits;
889
890         return SR_OK;
891 }
892
893 /*
894  * Configure the frame's bit widths when not identical across the
895  * complete frame. Think half STOP bits.
896  * Preset the sample data for an idle bus.
897  */
898 static int uart_config_frame(struct context *inc)
899 {
900         struct uart_frame_fmt_opts *fmt_opts;
901         size_t bit_idx;
902         uint8_t sample;
903
904         if (!inc)
905                 return SR_ERR_ARG;
906         fmt_opts = &inc->curr_opts.frame_format.uart;
907
908         /*
909          * Position after the START bit. Advance over DATA, PARITY and
910          * (full) STOP bits. Then set the trailing STOP bit to half if
911          * needed. Make the trailing IDLE period after a UART frame
912          * wider than regular bit times. Add an even wider IDLE period
913          * which is used for special symbols.
914          */
915         bit_idx = 1;
916         bit_idx += fmt_opts->databit_count;
917         bit_idx += (fmt_opts->parity_type == UART_PARITY_NONE) ? 0 : 1;
918         bit_idx += fmt_opts->stopbit_count;
919         if (fmt_opts->half_stopbit) {
920                 sr_dbg("Setting bit index %zu to half width.", bit_idx);
921                 inc->bit_scale[bit_idx].div = 2;
922                 bit_idx++;
923         }
924         inc->bit_scale[bit_idx++].mul = 2;
925         inc->bit_scale[bit_idx++].mul = 4;
926
927         /* Start from idle signal levels (high when not inverted). */
928         sample = 0;
929         if (!fmt_opts->inverted)
930                 sample |= UART_PINMASK_RXTX;
931         sample_buffer_preset(inc, sample);
932
933         return SR_OK;
934 }
935
936 /* Create samples for a special UART frame (IDLE, BREAK). */
937 static int uart_write_special(struct context *inc, uint8_t level)
938 {
939         struct uart_frame_fmt_opts *fmt_opts;
940         int ret;
941         size_t bits;
942
943         if (!inc)
944                 return SR_ERR_ARG;
945         fmt_opts = &inc->curr_opts.frame_format.uart;
946
947         ret = wave_clear_sequence(inc);
948         if (ret != SR_OK)
949                 return ret;
950
951         /*
952          * Set the same level for all bit slots, covering all of
953          * START and DATA (and PARITY) and STOP. This allows the
954          * simulation of BREAK and IDLE phases.
955          */
956         if (fmt_opts->inverted)
957                 level = !level;
958         sample_buffer_setclr(inc, level, UART_PINMASK_RXTX);
959         bits = 1; /* START */
960         bits += fmt_opts->databit_count;
961         bits += (fmt_opts->parity_type != UART_PARITY_NONE) ? 1 : 0;
962         bits += fmt_opts->stopbit_count;
963         bits += fmt_opts->half_stopbit ? 1 : 0;
964         while (bits--) {
965                 ret = wave_append_buffer(inc);
966                 if (ret != SR_OK)
967                         return ret;
968         }
969
970         /*
971          * Force a few more idle bit times. This does not affect a
972          * caller requested IDLE symbol. But helps separate (i.e.
973          * robustly detect) several caller requested BREAK symbols.
974          * Also separates those specials from subsequent data bytes.
975          */
976         sample_buffer_toidle(inc);
977         bits = UART_ADD_IDLEBITS;
978         while (bits--) {
979                 ret = wave_append_buffer(inc);
980                 if (ret != SR_OK)
981                         return ret;
982         }
983
984         return SR_OK;
985 }
986
987 /* Process UART protocol specific pseudo comments. */
988 static int uart_proc_pseudo(struct sr_input *in, char *line)
989 {
990         struct context *inc;
991         char *word;
992         int ret;
993
994         inc = in->priv;
995
996         while (line) {
997                 word = sr_text_next_word(line, &line);
998                 if (!word)
999                         break;
1000                 if (!*word)
1001                         continue;
1002                 if (strcmp(word, UART_PSEUDO_BREAK) == 0) {
1003                         ret = uart_write_special(inc, 0);
1004                         if (ret != SR_OK)
1005                                 return ret;
1006                         ret = send_frame(in);
1007                         if (ret != SR_OK)
1008                                 return ret;
1009                         continue;
1010                 }
1011                 if (strcmp(word, UART_PSEUDO_IDLE) == 0) {
1012                         ret = uart_write_special(inc, 1);
1013                         if (ret != SR_OK)
1014                                 return ret;
1015                         ret = send_frame(in);
1016                         if (ret != SR_OK)
1017                                 return ret;
1018                         continue;
1019                 }
1020                 return SR_ERR_DATA;
1021         }
1022
1023         return SR_OK;
1024 }
1025
1026 /*
1027  * Create the UART frame's waveform for the given data value.
1028  *
1029  * In theory the protocol handler could setup START and STOP once during
1030  * initialization. But the overhead compares to DATA and PARITY is small.
1031  * And unconditional START/STOP would break the creation of BREAK and
1032  * IDLE frames, or complicate their construction and recovery afterwards.
1033  * A future implementation might as well support UART traffic on multiple
1034  * traces, including interleaved bidirectional communication. So let's
1035  * keep the implementation simple. Execution time is not a priority.
1036  */
1037 static int uart_proc_value(struct context *inc, uint32_t value)
1038 {
1039         struct uart_frame_fmt_opts *fmt_opts;
1040         int ret;
1041         size_t bits;
1042         int par_bit, data_bit;
1043
1044         if (!inc)
1045                 return SR_ERR_ARG;
1046         fmt_opts = &inc->curr_opts.frame_format.uart;
1047
1048         ret = wave_clear_sequence(inc);
1049         if (ret != SR_OK)
1050                 return ret;
1051
1052         /* START bit, unconditional, always 0. */
1053         sample_buffer_clear(inc, UART_PINMASK_RXTX);
1054         if (fmt_opts->inverted)
1055                 sample_buffer_toggle(inc, UART_PINMASK_RXTX);
1056         ret = wave_append_buffer(inc);
1057
1058         /* DATA bits. Track parity here (unconditionally). */
1059         par_bit = 0;
1060         bits = fmt_opts->databit_count;
1061         while (bits--) {
1062                 data_bit = value & 0x01;
1063                 value >>= 1;
1064                 par_bit ^= data_bit;
1065                 if (fmt_opts->inverted)
1066                         data_bit = !data_bit;
1067                 sample_buffer_setclr(inc, data_bit, UART_PINMASK_RXTX);
1068                 ret = wave_append_buffer(inc);
1069                 if (ret != SR_OK)
1070                         return ret;
1071         }
1072
1073         /* PARITY bit. Emission is optional. */
1074         switch (fmt_opts->parity_type) {
1075         case UART_PARITY_ODD:
1076                 data_bit = par_bit ? 0 : 1;
1077                 bits = 1;
1078                 break;
1079         case UART_PARITY_EVEN:
1080                 data_bit = par_bit ? 1 : 0;
1081                 bits = 1;
1082                 break;
1083         default:
1084                 data_bit = 0;
1085                 bits = 0;
1086                 break;
1087         }
1088         if (bits) {
1089                 if (fmt_opts->inverted)
1090                         data_bit = !data_bit;
1091                 sample_buffer_setclr(inc, data_bit, UART_PINMASK_RXTX);
1092                 ret = wave_append_buffer(inc);
1093                 if (ret != SR_OK)
1094                         return ret;
1095         }
1096
1097         /* STOP bits. Optional. */
1098         sample_buffer_raise(inc, UART_PINMASK_RXTX);
1099         if (fmt_opts->inverted)
1100                 sample_buffer_toggle(inc, UART_PINMASK_RXTX);
1101         bits = fmt_opts->stopbit_count;
1102         bits += fmt_opts->half_stopbit ? 1 : 0;
1103         while (bits--) {
1104                 ret = wave_append_buffer(inc);
1105                 if (ret != SR_OK)
1106                         return ret;
1107         }
1108
1109         /*
1110          * Force some idle time after the UART frame.
1111          * A little shorter than for special symbols.
1112          */
1113         sample_buffer_toidle(inc);
1114         bits = UART_ADD_IDLEBITS - 1;
1115         while (bits--) {
1116                 ret = wave_append_buffer(inc);
1117                 if (ret != SR_OK)
1118                         return ret;
1119         }
1120
1121         return SR_OK;
1122 }
1123
1124 /* Start/end the logic trace with a few bit times of idle level. */
1125 static int uart_get_idle_capture(struct context *inc,
1126         size_t *bitcount, uint8_t *sample)
1127 {
1128
1129         /* Describe a UART frame's length of idle level. */
1130         if (bitcount)
1131                 *bitcount = inc->max_frame_bits;
1132         if (sample)
1133                 *sample = inc->samples.idle_levels;
1134         return SR_OK;
1135 }
1136
1137 /* Arrange for a few samples of idle level between UART frames. */
1138 static int uart_get_idle_interframe(struct context *inc,
1139         size_t *samplecount, uint8_t *sample)
1140 {
1141
1142         (void)inc;
1143
1144         /*
1145          * Regular waveform creation for UART frames already includes
1146          * padding between UART frames. That is why we don't need to
1147          * add extra inter-frame samples. Yet prepare the implementation
1148          * for when we need or want to add a few more idle samples.
1149          */
1150         if (samplecount) {
1151                 *samplecount = inc->curr_opts.samples_per_bit;
1152                 *samplecount *= 0;
1153         }
1154         if (sample)
1155                 *sample = inc->samples.idle_levels;
1156         return SR_OK;
1157 }
1158
1159 /* }}} UART protocol handler */
1160 /* {{{ SPI protocol handler */
1161
1162 enum spi_pin_t {
1163         SPI_PIN_SCK,
1164         SPI_PIN_MISO,
1165         SPI_PIN_MOSI,
1166         SPI_PIN_CS,
1167         SPI_PIN_COUNT,
1168 };
1169
1170 #define SPI_PINMASK_SCK         (1UL << SPI_PIN_SCK)
1171 #define SPI_PINMASK_MISO        (1UL << SPI_PIN_MISO)
1172 #define SPI_PINMASK_MOSI        (1UL << SPI_PIN_MOSI)
1173 #define SPI_PINMASK_CS          (1UL << SPI_PIN_CS)
1174
1175 /* "Forget" data which was seen before. */
1176 static void spi_value_discard_prev_data(struct context *inc)
1177 {
1178         struct spi_proto_context_t *incs;
1179
1180         incs = inc->curr_opts.prot_priv;
1181         incs->has_mosi = !incs->needs_mosi;
1182         incs->has_miso = !incs->needs_miso;
1183         incs->mosi_byte = 0;
1184         incs->miso_byte = 0;
1185 }
1186
1187 /* Check whether all required values for the byte time were seen. */
1188 static gboolean spi_value_is_bytes_complete(struct context *inc)
1189 {
1190         struct spi_proto_context_t *incs;
1191
1192         incs = inc->curr_opts.prot_priv;
1193
1194         return incs->has_mosi && incs->has_miso;
1195 }
1196
1197 /* Arrange for data reception before waveform emission. */
1198 static void spi_pseudo_data_order(struct context *inc,
1199         gboolean needs_mosi, gboolean needs_miso, gboolean mosi_first)
1200 {
1201         struct spi_proto_context_t *incs;
1202
1203         incs = inc->curr_opts.prot_priv;
1204
1205         incs->needs_mosi = needs_mosi;
1206         incs->needs_miso = needs_miso;
1207         incs->mosi_first = mosi_first;
1208         if (needs_mosi)
1209                 incs->mosi_is_fixed = FALSE;
1210         if (needs_miso)
1211                 incs->miso_is_fixed = FALSE;
1212         spi_value_discard_prev_data(inc);
1213 }
1214
1215 static void spi_pseudo_mosi_fixed(struct context *inc, uint8_t v)
1216 {
1217         struct spi_proto_context_t *incs;
1218
1219         incs = inc->curr_opts.prot_priv;
1220
1221         incs->mosi_fixed_value = v;
1222         incs->mosi_is_fixed = TRUE;
1223 }
1224
1225 static void spi_pseudo_miso_fixed(struct context *inc, uint8_t v)
1226 {
1227         struct spi_proto_context_t *incs;
1228
1229         incs = inc->curr_opts.prot_priv;
1230
1231         incs->miso_fixed_value = v;
1232         incs->miso_is_fixed = TRUE;
1233 }
1234
1235 /* Explicit CS control. Arrange for next CS level, track state to keep it. */
1236 static void spi_pseudo_select_control(struct context *inc, gboolean cs_active)
1237 {
1238         struct spi_frame_fmt_opts *fmt_opts;
1239         struct spi_proto_context_t *incs;
1240         uint8_t cs_level, sck_level;
1241
1242         fmt_opts = &inc->curr_opts.frame_format.spi;
1243         incs = inc->curr_opts.prot_priv;
1244
1245         /* Track current "CS active" state. */
1246         incs->cs_active = cs_active;
1247         incs->auto_cs_remain = 0;
1248
1249         /* Derive current "CS pin level". Update sample data buffer. */
1250         cs_level = 1 - fmt_opts->cs_polarity;
1251         if (incs->cs_active)
1252                 cs_level = fmt_opts->cs_polarity;
1253         sample_buffer_setclr(inc, cs_level, SPI_PINMASK_CS);
1254
1255         /* Derive the idle "SCK level" from the SPI mode's CPOL. */
1256         sck_level = fmt_opts->spi_mode_cpol ? 1 : 0;
1257         sample_buffer_setclr(inc, sck_level, SPI_PINMASK_SCK);
1258 }
1259
1260 /* Arrange for automatic CS release after transfer length. Starts the phase. */
1261 static void spi_pseudo_auto_select(struct context *inc, size_t length)
1262 {
1263         struct spi_frame_fmt_opts *fmt_opts;
1264         struct spi_proto_context_t *incs;
1265         uint8_t cs_level;
1266
1267         fmt_opts = &inc->curr_opts.frame_format.spi;
1268         incs = inc->curr_opts.prot_priv;
1269
1270         /* Track current "CS active" state. */
1271         incs->cs_active = TRUE;
1272         incs->auto_cs_remain = length;
1273
1274         /* Derive current "CS pin level". Update sample data buffer. */
1275         cs_level = 1 - fmt_opts->cs_polarity;
1276         if (incs->cs_active)
1277                 cs_level = fmt_opts->cs_polarity;
1278         sample_buffer_setclr(inc, cs_level, SPI_PINMASK_CS);
1279 }
1280
1281 /* Check for automatic CS release. Decrements, yields result. No action here. */
1282 static gboolean spi_auto_select_ends(struct context *inc)
1283 {
1284         struct spi_proto_context_t *incs;
1285
1286         incs = inc->curr_opts.prot_priv;
1287         if (!incs->auto_cs_remain)
1288                 return FALSE;
1289
1290         incs->auto_cs_remain--;
1291         if (incs->auto_cs_remain)
1292                 return FALSE;
1293
1294         /*
1295          * DON'T release CS yet. The last data is yet to get sent.
1296          * Keep the current "CS pin level", but tell the caller that
1297          * CS will be released after transmission of that last data.
1298          */
1299         return TRUE;
1300 }
1301
1302 /* Update for automatic CS release after last data was sent. */
1303 static void spi_auto_select_update(struct context *inc)
1304 {
1305         struct spi_frame_fmt_opts *fmt_opts;
1306         struct spi_proto_context_t *incs;
1307         uint8_t cs_level;
1308
1309         fmt_opts = &inc->curr_opts.frame_format.spi;
1310         incs = inc->curr_opts.prot_priv;
1311
1312         /* Track current "CS active" state. */
1313         incs->cs_active = FALSE;
1314         incs->auto_cs_remain = 0;
1315
1316         /* Derive current "CS pin level". Map to bits pattern. */
1317         cs_level = 1 - fmt_opts->cs_polarity;
1318         sample_buffer_setclr(inc, cs_level, SPI_PINMASK_CS);
1319 }
1320
1321 /*
1322  * Create the waveforms for one SPI byte. Also cover idle periods:
1323  * Dummy/padding bytes within a frame with clock. Idle lines outside
1324  * of frames without clock edges. Optional automatic CS release with
1325  * resulting inter-frame gap.
1326  */
1327 static int spi_write_frame_patterns(struct context *inc,
1328         gboolean idle, gboolean cs_release)
1329 {
1330         struct spi_proto_context_t *incs;
1331         struct spi_frame_fmt_opts *fmt_opts;
1332         int ret;
1333         uint8_t mosi_bit, miso_bit;
1334         size_t bits;
1335
1336         if (!inc)
1337                 return SR_ERR_ARG;
1338         incs = inc->curr_opts.prot_priv;
1339         fmt_opts = &inc->curr_opts.frame_format.spi;
1340
1341         /* Apply fixed values before drawing the waveform. */
1342         if (incs->mosi_is_fixed)
1343                 incs->mosi_byte = incs->mosi_fixed_value;
1344         if (incs->miso_is_fixed)
1345                 incs->miso_byte = incs->miso_fixed_value;
1346
1347         ret = wave_clear_sequence(inc);
1348         if (ret != SR_OK)
1349                 return ret;
1350
1351         /* Provide two samples with idle SCK and current CS. */
1352         ret = wave_append_buffer(inc);
1353         if (ret != SR_OK)
1354                 return ret;
1355         ret = wave_append_buffer(inc);
1356         if (ret != SR_OK)
1357                 return ret;
1358
1359         /*
1360          * Provide two samples per DATABIT time slot. Keep CS as is.
1361          * Toggle SCK according to CPHA specs. Shift out MOSI and MISO
1362          * in the configured order.
1363          *
1364          * Force dummy MOSI/MISO bits for idle bytes within a frame.
1365          * Skip SCK toggling for idle "frames" outside of active CS.
1366          */
1367         bits = fmt_opts->databit_count;
1368         while (bits--) {
1369                 /*
1370                  * First half-period. Provide next DATABIT values.
1371                  * Toggle SCK here when CPHA is set.
1372                  */
1373                 if (fmt_opts->msb_first) {
1374                         mosi_bit = incs->mosi_byte & 0x80;
1375                         miso_bit = incs->miso_byte & 0x80;
1376                         incs->mosi_byte <<= 1;
1377                         incs->miso_byte <<= 1;
1378                 } else {
1379                         mosi_bit = incs->mosi_byte & 0x01;
1380                         miso_bit = incs->miso_byte & 0x01;
1381                         incs->mosi_byte >>= 1;
1382                         incs->miso_byte >>= 1;
1383                 }
1384                 if (incs->cs_active && !idle) {
1385                         sample_buffer_setclr(inc, mosi_bit, SPI_PINMASK_MOSI);
1386                         sample_buffer_setclr(inc, miso_bit, SPI_PINMASK_MISO);
1387                 }
1388                 if (fmt_opts->spi_mode_cpha && incs->cs_active)
1389                         sample_buffer_toggle(inc, SPI_PINMASK_SCK);
1390                 ret = wave_append_buffer(inc);
1391                 if (ret != SR_OK)
1392                         return ret;
1393                 /* Second half-period. Keep DATABIT, toggle SCK. */
1394                 if (incs->cs_active)
1395                         sample_buffer_toggle(inc, SPI_PINMASK_SCK);
1396                 ret = wave_append_buffer(inc);
1397                 if (ret != SR_OK)
1398                         return ret;
1399                 /* Toggle SCK again unless done above due to CPHA. */
1400                 if (!fmt_opts->spi_mode_cpha && incs->cs_active)
1401                         sample_buffer_toggle(inc, SPI_PINMASK_SCK);
1402         }
1403
1404         /*
1405          * Hold the waveform for another sample period. Happens to
1406          * also communicate the most recent SCK pin level.
1407          *
1408          * Optionally auto-release the CS signal after sending the
1409          * last data byte. Update the CS trace's level. Add another
1410          * (long) bit slot to present an inter-frame gap.
1411          */
1412         ret = wave_append_buffer(inc);
1413         if (ret != SR_OK)
1414                 return ret;
1415         if (cs_release)
1416                 spi_auto_select_update(inc);
1417         ret = wave_append_buffer(inc);
1418         if (ret != SR_OK)
1419                 return ret;
1420         if (cs_release) {
1421                 ret = wave_append_buffer(inc);
1422                 if (ret != SR_OK)
1423                         return ret;
1424         }
1425
1426         return SR_OK;
1427 }
1428
1429 /* SPI specific options and frame format check. */
1430 static int spi_check_opts(struct context *inc)
1431 {
1432         struct spi_frame_fmt_opts *fmt_opts;
1433         const char *fmt_text;
1434         char **opts, *opt;
1435         size_t opt_count, opt_idx;
1436         int ret;
1437         unsigned long v;
1438         char *endp;
1439         size_t total_bits;
1440
1441         if (!inc)
1442                 return SR_ERR_ARG;
1443         fmt_opts = &inc->curr_opts.frame_format.spi;
1444
1445         /* Setup defaults before reading external specs. */
1446         fmt_opts->cs_polarity = 0;
1447         fmt_opts->databit_count = SPI_MIN_DATABITS;
1448         fmt_opts->msb_first = TRUE;
1449         fmt_opts->spi_mode_cpol = FALSE;
1450         fmt_opts->spi_mode_cpha = FALSE;
1451
1452         /* Provide a default SPI frame format. */
1453         fmt_text = inc->curr_opts.fmt_text;
1454         if (!fmt_text || !*fmt_text)
1455                 fmt_text = SPI_DFLT_FRAMEFMT;
1456         sr_dbg("SPI frame format: %s.", fmt_text);
1457
1458         /* Accept comma separated key=value pairs of specs. */
1459         opts = g_strsplit_set(fmt_text, ", ", 0);
1460         opt_count = g_strv_length(opts);
1461         for (opt_idx = 0; opt_idx < opt_count; opt_idx++) {
1462                 opt = opts[opt_idx];
1463                 if (!opt || !*opt)
1464                         continue;
1465                 sr_spew("SPI format option: %s.", opt);
1466                 if (strcmp(opt, SPI_FORMAT_CS_LOW) == 0) {
1467                         sr_spew("SPI chip select: low.");
1468                         fmt_opts->cs_polarity = 0;
1469                         continue;
1470                 }
1471                 if (strcmp(opt, SPI_FORMAT_CS_HIGH) == 0) {
1472                         sr_spew("SPI chip select: high.");
1473                         fmt_opts->cs_polarity = 1;
1474                         continue;
1475                 }
1476                 if (g_str_has_prefix(opt, SPI_FORMAT_DATA_BITS)) {
1477                         opt += strlen(SPI_FORMAT_DATA_BITS);
1478                         endp = NULL;
1479                         ret = sr_atoul_base(opt, &v, &endp, 10);
1480                         if (ret != SR_OK)
1481                                 return ret;
1482                         if (!endp || *endp)
1483                                 return SR_ERR_ARG;
1484                         sr_spew("SPI word size: %lu.", v);
1485                         if (v < SPI_MIN_DATABITS || v > SPI_MAX_DATABITS)
1486                                 return SR_ERR_ARG;
1487                         fmt_opts->databit_count = v;
1488                         continue;
1489                 }
1490                 if (g_str_has_prefix(opt, SPI_FORMAT_SPI_MODE)) {
1491                         opt += strlen(SPI_FORMAT_SPI_MODE);
1492                         endp = NULL;
1493                         ret = sr_atoul_base(opt, &v, &endp, 10);
1494                         if (ret != SR_OK)
1495                                 return ret;
1496                         if (!endp || *endp)
1497                                 return SR_ERR_ARG;
1498                         sr_spew("SPI mode: %lu.", v);
1499                         if (v > 3)
1500                                 return SR_ERR_ARG;
1501                         fmt_opts->spi_mode_cpol = v & (1UL << 1);
1502                         fmt_opts->spi_mode_cpha = v & (1UL << 0);
1503                         continue;
1504                 }
1505                 if (g_str_has_prefix(opt, SPI_FORMAT_MODE_CPOL)) {
1506                         opt += strlen(SPI_FORMAT_MODE_CPOL);
1507                         endp = NULL;
1508                         ret = sr_atoul_base(opt, &v, &endp, 10);
1509                         if (ret != SR_OK)
1510                                 return ret;
1511                         if (!endp || *endp)
1512                                 return SR_ERR_ARG;
1513                         sr_spew("SPI cpol: %lu.", v);
1514                         if (v > 1)
1515                                 return SR_ERR_ARG;
1516                         fmt_opts->spi_mode_cpol = !!v;
1517                         continue;
1518                 }
1519                 if (g_str_has_prefix(opt, SPI_FORMAT_MODE_CPHA)) {
1520                         opt += strlen(SPI_FORMAT_MODE_CPHA);
1521                         endp = NULL;
1522                         ret = sr_atoul_base(opt, &v, &endp, 10);
1523                         if (ret != SR_OK)
1524                                 return ret;
1525                         if (!endp || *endp)
1526                                 return SR_ERR_ARG;
1527                         sr_spew("SPI cpha: %lu.", v);
1528                         if (v > 1)
1529                                 return SR_ERR_ARG;
1530                         fmt_opts->spi_mode_cpha = !!v;
1531                         continue;
1532                 }
1533                 if (strcmp(opt, SPI_FORMAT_MSB_FIRST) == 0) {
1534                         sr_spew("SPI endianess: MSB first.");
1535                         fmt_opts->msb_first = 1;
1536                         continue;
1537                 }
1538                 if (strcmp(opt, SPI_FORMAT_LSB_FIRST) == 0) {
1539                         sr_spew("SPI endianess: LSB first.");
1540                         fmt_opts->msb_first = 0;
1541                         continue;
1542                 }
1543                 return SR_ERR_ARG;
1544         }
1545         g_strfreev(opts);
1546
1547         /*
1548          * Get the total bit count. Add slack for CS control, and to
1549          * visually separate bytes in frames. Multiply data bit count
1550          * for the creation of two clock half-periods.
1551          */
1552         total_bits = 2;
1553         total_bits += 2 * fmt_opts->databit_count;
1554         total_bits += 3;
1555
1556         sr_dbg("SPI frame: total bits %lu.", total_bits);
1557         if (total_bits > SPI_MAX_WAVELEN)
1558                 return SR_ERR_DATA;
1559         inc->max_frame_bits = total_bits;
1560
1561         return SR_OK;
1562 }
1563
1564 /*
1565  * Setup half-width slots for the two halves of a DATABIT time. Keep
1566  * the "decoration" (CS control) at full width. Setup a rather long
1567  * last slot for potential inter-frame gaps.
1568  *
1569  * Preset CS and SCK from their idle levels according to the frame format
1570  * configuration. So that idle times outside of SPI transfers are covered
1571  * with simple logic despite the protocol's flexibility.
1572  */
1573 static int spi_config_frame(struct context *inc)
1574 {
1575         struct spi_frame_fmt_opts *fmt_opts;
1576         size_t bit_idx, bit_count;
1577
1578         if (!inc)
1579                 return SR_ERR_ARG;
1580         fmt_opts = &inc->curr_opts.frame_format.spi;
1581
1582         /* Configure DATABIT positions for half width (for clock period). */
1583         bit_idx = 2;
1584         bit_count = fmt_opts->databit_count;
1585         while (bit_count--) {
1586                 inc->bit_scale[bit_idx + 0].div = 2;
1587                 inc->bit_scale[bit_idx + 1].div = 2;
1588                 bit_idx += 2;
1589         }
1590         bit_idx += 2;
1591         inc->bit_scale[bit_idx].mul = fmt_opts->databit_count;
1592
1593         /*
1594          * Seed the protocol handler's internal state before seeing
1595          * first data values. To properly cover idle periods, and to
1596          * operate correctly in the absence of pseudo comments.
1597          *
1598          * Use internal helpers for sample data initialization. Then
1599          * grab the resulting pin levels as the idle state.
1600          */
1601         spi_value_discard_prev_data(inc);
1602         spi_pseudo_data_order(inc, TRUE, TRUE, TRUE);
1603         spi_pseudo_select_control(inc, FALSE);
1604         sample_buffer_preset(inc, inc->samples.curr_levels);
1605
1606         return SR_OK;
1607 }
1608
1609 /*
1610  * Process protocol dependent pseudo comments. Can affect future frame
1611  * construction and submission, or can immediately emit "inter frame"
1612  * bit patterns like chip select control.
1613  */
1614 static int spi_proc_pseudo(struct sr_input *in, char *line)
1615 {
1616         struct context *inc;
1617         char *word, *endp;
1618         int ret;
1619         unsigned long v;
1620
1621         inc = in->priv;
1622
1623         while (line) {
1624                 word = sr_text_next_word(line, &line);
1625                 if (!word)
1626                         break;
1627                 if (!*word)
1628                         continue;
1629                 if (strcmp(word, SPI_PSEUDO_MOSI_ONLY) == 0) {
1630                         sr_spew("SPI pseudo: MOSI only");
1631                         spi_pseudo_data_order(inc, TRUE, FALSE, TRUE);
1632                         continue;
1633                 }
1634                 if (g_str_has_prefix(word, SPI_PSEUDO_MOSI_FIXED)) {
1635                         word += strlen(SPI_PSEUDO_MOSI_FIXED);
1636                         endp = NULL;
1637                         ret = sr_atoul_base(word, &v, &endp, inc->read_text.base);
1638                         if (ret != SR_OK)
1639                                 return ret;
1640                         if (!endp || *endp)
1641                                 return SR_ERR_ARG;
1642                         sr_spew("SPI pseudo: MOSI fixed %lu", v);
1643                         spi_pseudo_mosi_fixed(inc, v);
1644                         continue;
1645                 }
1646                 if (strcmp(word, SPI_PSEUDO_MISO_ONLY) == 0) {
1647                         sr_spew("SPI pseudo: MISO only");
1648                         spi_pseudo_data_order(inc, FALSE, TRUE, FALSE);
1649                         continue;
1650                 }
1651                 if (g_str_has_prefix(word, SPI_PSEUDO_MISO_FIXED)) {
1652                         word += strlen(SPI_PSEUDO_MISO_FIXED);
1653                         endp = NULL;
1654                         ret = sr_atoul_base(word, &v, &endp, inc->read_text.base);
1655                         if (ret != SR_OK)
1656                                 return ret;
1657                         if (!endp || *endp)
1658                                 return SR_ERR_ARG;
1659                         sr_spew("SPI pseudo: MISO fixed %lu", v);
1660                         spi_pseudo_miso_fixed(inc, v);
1661                         continue;
1662                 }
1663                 if (strcmp(word, SPI_PSEUDO_MOSI_MISO) == 0) {
1664                         sr_spew("SPI pseudo: MOSI then MISO");
1665                         spi_pseudo_data_order(inc, TRUE, TRUE, TRUE);
1666                         continue;
1667                 }
1668                 if (strcmp(word, SPI_PSEUDO_MISO_MOSI) == 0) {
1669                         sr_spew("SPI pseudo: MISO then MOSI");
1670                         spi_pseudo_data_order(inc, TRUE, TRUE, FALSE);
1671                         continue;
1672                 }
1673                 if (strcmp(word, SPI_PSEUDO_CS_ASSERT) == 0) {
1674                         sr_spew("SPI pseudo: CS assert");
1675                         spi_pseudo_select_control(inc, TRUE);
1676                         continue;
1677                 }
1678                 if (strcmp(word, SPI_PSEUDO_CS_RELEASE) == 0) {
1679                         sr_spew("SPI pseudo: CS release");
1680                         /* Release CS. Force IDLE to display the pin change. */
1681                         spi_pseudo_select_control(inc, FALSE);
1682                         ret = spi_write_frame_patterns(inc, TRUE, FALSE);
1683                         if (ret != SR_OK)
1684                                 return ret;
1685                         ret = send_frame(in);
1686                         if (ret != SR_OK)
1687                                 return ret;
1688                         continue;
1689                 }
1690                 if (g_str_has_prefix(word, SPI_PSEUDO_CS_NEXT)) {
1691                         word += strlen(SPI_PSEUDO_CS_NEXT);
1692                         endp = NULL;
1693                         ret = sr_atoul_base(word, &v, &endp, 0);
1694                         if (ret != SR_OK)
1695                                 return ret;
1696                         if (!endp || *endp)
1697                                 return SR_ERR_ARG;
1698                         sr_spew("SPI pseudo: CS auto next %lu", v);
1699                         spi_pseudo_auto_select(inc, v);
1700                         continue;
1701                 }
1702                 if (strcmp(word, SPI_PSEUDO_IDLE) == 0) {
1703                         sr_spew("SPI pseudo: idle");
1704                         ret = spi_write_frame_patterns(inc, TRUE, FALSE);
1705                         if (ret != SR_OK)
1706                                 return ret;
1707                         ret = send_frame(in);
1708                         if (ret != SR_OK)
1709                                 return ret;
1710                         continue;
1711                 }
1712                 return SR_ERR_DATA;
1713         }
1714
1715         return SR_OK;
1716 }
1717
1718 /*
1719  * Create the frame's waveform for the given data value. For bidirectional
1720  * communication multiple routine invocations accumulate data bits, while
1721  * the last invocation completes the frame preparation.
1722  */
1723 static int spi_proc_value(struct context *inc, uint32_t value)
1724 {
1725         struct spi_proto_context_t *incs;
1726         gboolean taken;
1727         int ret;
1728         gboolean auto_cs_end;
1729
1730         if (!inc)
1731                 return SR_ERR_ARG;
1732         incs = inc->curr_opts.prot_priv;
1733
1734         /*
1735          * Discard previous data when we get here after having completed
1736          * a previous frame. This roundtrip from filling in to clearing
1737          * is required to have the caller emit the waveform that we have
1738          * constructed after receiving data values.
1739          */
1740         if (spi_value_is_bytes_complete(inc)) {
1741                 sr_spew("SPI value: discarding previous data");
1742                 spi_value_discard_prev_data(inc);
1743         }
1744
1745         /*
1746          * Consume the caller provided value. Apply data in the order
1747          * that was configured before.
1748          */
1749         taken = FALSE;
1750         if (!taken && incs->mosi_first && !incs->has_mosi) {
1751                 sr_spew("SPI value: grabbing MOSI value");
1752                 incs->mosi_byte = value & 0xff;
1753                 incs->has_mosi = TRUE;
1754                 taken = TRUE;
1755         }
1756         if (!taken && !incs->has_miso) {
1757                 sr_spew("SPI value: grabbing MISO value");
1758                 incs->miso_byte = value & 0xff;
1759                 incs->has_miso = TRUE;
1760         }
1761         if (!taken && !incs->mosi_first && !incs->has_mosi) {
1762                 sr_spew("SPI value: grabbing MOSI value");
1763                 incs->mosi_byte = value & 0xff;
1764                 incs->has_mosi = TRUE;
1765                 taken = TRUE;
1766         }
1767
1768         /*
1769          * Generate the waveform when all data values in a byte time
1770          * were seen (all MOSI and MISO including their being optional
1771          * or fixed values).
1772          *
1773          * Optionally automatically release CS after a given number of
1774          * data bytes, when requested by the input stream.
1775          */
1776         if (!spi_value_is_bytes_complete(inc)) {
1777                 sr_spew("SPI value: need more values");
1778                 return +1;
1779         }
1780         auto_cs_end = spi_auto_select_ends(inc);
1781         sr_spew("SPI value: frame complete, drawing, auto CS %d", auto_cs_end);
1782         ret = spi_write_frame_patterns(inc, FALSE, auto_cs_end);
1783         if (ret != SR_OK)
1784                 return ret;
1785         return 0;
1786 }
1787
1788 /* Start/end the logic trace with a few bit times of idle level. */
1789 static int spi_get_idle_capture(struct context *inc,
1790         size_t *bitcount, uint8_t *sample)
1791 {
1792
1793         /* Describe one byte time of idle level. */
1794         if (bitcount)
1795                 *bitcount = inc->max_frame_bits;
1796         if (sample)
1797                 *sample = inc->samples.idle_levels;
1798         return SR_OK;
1799 }
1800
1801 /* Arrange for a few samples of idle level between UART frames. */
1802 static int spi_get_idle_interframe(struct context *inc,
1803         size_t *samplecount, uint8_t *sample)
1804 {
1805
1806         /* Describe four bit times, re-use most recent pin levels. */
1807         if (samplecount) {
1808                 *samplecount = inc->curr_opts.samples_per_bit;
1809                 *samplecount *= 4;
1810         }
1811         if (sample)
1812                 *sample = inc->samples.curr_levels;
1813         return SR_OK;
1814 }
1815
1816 /* }}} SPI protocol handler */
1817 /* {{{ I2C protocol handler */
1818
1819 enum i2c_pin_t {
1820         I2C_PIN_SCL,
1821         I2C_PIN_SDA,
1822         I2C_PIN_COUNT,
1823 };
1824
1825 #define I2C_PINMASK_SCL         (1UL << I2C_PIN_SCL)
1826 #define I2C_PINMASK_SDA         (1UL << I2C_PIN_SDA)
1827
1828 /* Arrange for automatic ACK for a given number of data bytes. */
1829 static void i2c_auto_ack_start(struct context *inc, size_t count)
1830 {
1831         struct i2c_proto_context_t *incs;
1832
1833         incs = inc->curr_opts.prot_priv;
1834         incs->ack_remain = count;
1835 }
1836
1837 /* Check whether automatic ACK is still applicable. Decrements. */
1838 static gboolean i2c_auto_ack_avail(struct context *inc)
1839 {
1840         struct i2c_proto_context_t *incs;
1841
1842         incs = inc->curr_opts.prot_priv;
1843         if (!incs->ack_remain)
1844                 return FALSE;
1845
1846         if (incs->ack_remain--)
1847                 return TRUE;
1848         return FALSE;
1849 }
1850
1851 /* Occupy the slots where START/STOP would be. Keep current levels. */
1852 static int i2c_write_nothing(struct context *inc)
1853 {
1854         size_t reps;
1855         int ret;
1856
1857         reps = I2C_BITTIME_QUANTA;
1858         while (reps--) {
1859                 ret = wave_append_buffer(inc);
1860                 if (ret != SR_OK)
1861                         return ret;
1862         }
1863
1864         return SR_OK;
1865 }
1866
1867 /*
1868  * Construct a START symbol. Occupy a full bit time in the waveform.
1869  * Can also be used as REPEAT START due to its conservative signalling.
1870  *
1871  * Definition of START: Falling SDA while SCL is high.
1872  * Repeated START: A START without a preceeding STOP.
1873  */
1874 static int i2c_write_start(struct context *inc)
1875 {
1876         int ret;
1877
1878         /*
1879          * Important! Assumes that either SDA and SCL already are
1880          * high (true when we come here from an idle bus). Or that
1881          * SCL already is low before SDA potentially changes (this
1882          * is true for preceeding START or REPEAT START or DATA BIT
1883          * symbols).
1884          *
1885          * Implementation detail: This START implementation can be
1886          * used for REPEAT START as well. The signalling sequence is
1887          * conservatively done.
1888          */
1889
1890         /* Enforce SDA high. */
1891         sample_buffer_raise(inc, I2C_PINMASK_SDA);
1892         ret = wave_append_buffer(inc);
1893         if (ret != SR_OK)
1894                 return ret;
1895
1896         /* Enforce SCL high. */
1897         sample_buffer_raise(inc, I2C_PINMASK_SCL);
1898         ret = wave_append_buffer(inc);
1899         if (ret != SR_OK)
1900                 return ret;
1901
1902         /* Keep high SCL and high SDA for another period. */
1903         ret = wave_append_buffer(inc);
1904         if (ret != SR_OK)
1905                 return ret;
1906
1907         /* Falling SDA while SCL is high. */
1908         sample_buffer_clear(inc, I2C_PINMASK_SDA);
1909         ret = wave_append_buffer(inc);
1910         if (ret != SR_OK)
1911                 return ret;
1912
1913         /* Keep high SCL and low SDA for one more period. */
1914         ret = wave_append_buffer(inc);
1915         if (ret != SR_OK)
1916                 return ret;
1917
1918         /*
1919          * Lower SCL here already. Which kind of prepares DATA BIT
1920          * times (fits a data bit's start condition, does not harm).
1921          * Improves back to back START and (repeated) START as well
1922          * as STOP without preceeding DATA BIT.
1923          */
1924         sample_buffer_clear(inc, I2C_PINMASK_SCL);
1925         ret = wave_append_buffer(inc);
1926         if (ret != SR_OK)
1927                 return ret;
1928
1929         return SR_OK;
1930 }
1931
1932 /*
1933  * Construct a STOP symbol. Occupy a full bit time in the waveform.
1934  *
1935  * Definition of STOP: Rising SDA while SCL is high.
1936  */
1937 static int i2c_write_stop(struct context *inc)
1938 {
1939         int ret;
1940
1941         /* Enforce SCL low before SDA changes. */
1942         sample_buffer_clear(inc, I2C_PINMASK_SCL);
1943         ret = wave_append_buffer(inc);
1944         if (ret != SR_OK)
1945                 return ret;
1946
1947         /* Enforce SDA low (can change while SCL is low). */
1948         sample_buffer_clear(inc, I2C_PINMASK_SDA);
1949         ret = wave_append_buffer(inc);
1950         if (ret != SR_OK)
1951                 return ret;
1952
1953         /* Rise SCL high while SDA is low. */
1954         sample_buffer_raise(inc, I2C_PINMASK_SCL);
1955         ret = wave_append_buffer(inc);
1956         if (ret != SR_OK)
1957                 return ret;
1958
1959         /* Keep high SCL and low SDA for another period. */
1960         ret = wave_append_buffer(inc);
1961         if (ret != SR_OK)
1962                 return ret;
1963
1964         /* Rising SDA. */
1965         sample_buffer_raise(inc, I2C_PINMASK_SDA);
1966         ret = wave_append_buffer(inc);
1967         if (ret != SR_OK)
1968                 return ret;
1969
1970         /* Keep high SCL and high SDA for one more periods. */
1971         ret = wave_append_buffer(inc);
1972         if (ret != SR_OK)
1973                 return ret;
1974
1975         return SR_OK;
1976 }
1977
1978 /*
1979  * Construct a DATA BIT symbol. Occupy a full bit time in the waveform.
1980  *
1981  * SDA can change while SCL is low. SDA must be kept while SCL is high.
1982  */
1983 static int i2c_write_bit(struct context *inc, uint8_t value)
1984 {
1985         int ret;
1986
1987         /* Enforce SCL low before SDA changes. */
1988         sample_buffer_clear(inc, I2C_PINMASK_SCL);
1989         ret = wave_append_buffer(inc);
1990         if (ret != SR_OK)
1991                 return ret;
1992
1993         /* Setup SDA pin level while SCL is low. */
1994         sample_buffer_setclr(inc, value, I2C_PINMASK_SDA);
1995         ret = wave_append_buffer(inc);
1996         if (ret != SR_OK)
1997                 return ret;
1998
1999         /* Rising SCL, starting SDA validity. */
2000         sample_buffer_raise(inc, I2C_PINMASK_SCL);
2001         ret = wave_append_buffer(inc);
2002         if (ret != SR_OK)
2003                 return ret;
2004
2005         /* Keep SDA level with high SCL for two more periods. */
2006         ret = wave_append_buffer(inc);
2007         if (ret != SR_OK)
2008                 return ret;
2009         ret = wave_append_buffer(inc);
2010         if (ret != SR_OK)
2011                 return ret;
2012
2013         /* Falling SCL, terminates SDA validity. */
2014         sample_buffer_clear(inc, I2C_PINMASK_SCL);
2015         ret = wave_append_buffer(inc);
2016         if (ret != SR_OK)
2017                 return ret;
2018
2019         return SR_OK;
2020 }
2021
2022 /* Create a waveform for the eight data bits and the ACK/NAK slot. */
2023 static int i2c_write_byte(struct context *inc, uint8_t value, uint8_t ack)
2024 {
2025         size_t bit_mask, bit_value;
2026         int ret;
2027
2028         /* Keep an empty bit time before the data byte. */
2029         ret = i2c_write_nothing(inc);
2030         if (ret != SR_OK)
2031                 return ret;
2032
2033         /* Send 8 data bits, MSB first. */
2034         bit_mask = 0x80;
2035         while (bit_mask) {
2036                 bit_value = value & bit_mask;
2037                 bit_mask >>= 1;
2038                 ret = i2c_write_bit(inc, bit_value);
2039                 if (ret != SR_OK)
2040                         return ret;
2041         }
2042
2043         /* Send ACK, which is low active. NAK is recessive, high. */
2044         bit_value = !ack;
2045         ret = i2c_write_bit(inc, bit_value);
2046         if (ret != SR_OK)
2047                 return ret;
2048
2049         /* Keep an empty bit time after the data byte. */
2050         ret = i2c_write_nothing(inc);
2051         if (ret != SR_OK)
2052                 return ret;
2053
2054         return SR_OK;
2055 }
2056
2057 /* Send slave address (7bit or 10bit, 1 or 2 bytes). Consumes one ACK. */
2058 static int i2c_send_address(struct sr_input *in, uint16_t addr, gboolean read)
2059 {
2060         struct context *inc;
2061         struct i2c_frame_fmt_opts *fmt_opts;
2062         gboolean with_ack;
2063         uint8_t addr_byte, rw_bit;
2064         int ret;
2065
2066         inc = in->priv;
2067         fmt_opts = &inc->curr_opts.frame_format.i2c;
2068
2069         addr &= 0x3ff;
2070         rw_bit = read ? 1 : 0;
2071         with_ack = i2c_auto_ack_avail(inc);
2072
2073         if (!fmt_opts->addr_10bit) {
2074                 /* 7 bit address, the simple case. */
2075                 addr_byte = addr & 0x7f;
2076                 addr_byte <<= 1;
2077                 addr_byte |= rw_bit;
2078                 sr_spew("I2C 7bit address, byte 0x%" PRIx8, addr_byte);
2079                 ret = wave_clear_sequence(inc);
2080                 if (ret != SR_OK)
2081                         return ret;
2082                 ret = i2c_write_byte(inc, addr_byte, with_ack);
2083                 if (ret != SR_OK)
2084                         return ret;
2085                 ret = send_frame(in);
2086                 if (ret != SR_OK)
2087                         return ret;
2088         } else {
2089                 /*
2090                  * 10 bit address, need to write two bytes: First byte
2091                  * with prefix 0xf0, upper most 2 address bits, and R/W.
2092                  * Second byte with lower 8 address bits.
2093                  */
2094                 addr_byte = addr >> 8;
2095                 addr_byte <<= 1;
2096                 addr_byte |= 0xf0;
2097                 addr_byte |= rw_bit;
2098                 sr_spew("I2C 10bit address, byte 0x%" PRIx8, addr_byte);
2099                 ret = wave_clear_sequence(inc);
2100                 if (ret != SR_OK)
2101                         return ret;
2102                 ret = i2c_write_byte(inc, addr_byte, with_ack);
2103                 if (ret != SR_OK)
2104                         return ret;
2105                 ret = send_frame(in);
2106                 if (ret != SR_OK)
2107                         return ret;
2108
2109                 addr_byte = addr & 0xff;
2110                 sr_spew("I2C 10bit address, byte 0x%" PRIx8, addr_byte);
2111                 ret = wave_clear_sequence(inc);
2112                 if (ret != SR_OK)
2113                         return ret;
2114                 ret = i2c_write_byte(inc, addr_byte, with_ack);
2115                 if (ret != SR_OK)
2116                         return ret;
2117                 ret = send_frame(in);
2118                 if (ret != SR_OK)
2119                         return ret;
2120         }
2121
2122         return SR_OK;
2123 }
2124
2125 /* I2C specific options and frame format check. */
2126 static int i2c_check_opts(struct context *inc)
2127 {
2128         struct i2c_frame_fmt_opts *fmt_opts;
2129         const char *fmt_text;
2130         char **opts, *opt;
2131         size_t opt_count, opt_idx;
2132         size_t total_bits;
2133
2134         if (!inc)
2135                 return SR_ERR_ARG;
2136         fmt_opts = &inc->curr_opts.frame_format.i2c;
2137
2138         /* Apply defaults before reading external specs. */
2139         memset(fmt_opts, 0, sizeof(*fmt_opts));
2140         fmt_opts->addr_10bit = FALSE;
2141
2142         /* Provide a default I2C frame format. */
2143         fmt_text = inc->curr_opts.fmt_text;
2144         if (!fmt_text || !*fmt_text)
2145                 fmt_text = I2C_DFLT_FRAMEFMT;
2146         sr_dbg("I2C frame format: %s.", fmt_text);
2147
2148         /* Accept comma separated key=value pairs of specs. */
2149         opts = g_strsplit_set(fmt_text, ", ", 0);
2150         opt_count = g_strv_length(opts);
2151         for (opt_idx = 0; opt_idx < opt_count; opt_idx++) {
2152                 opt = opts[opt_idx];
2153                 if (!opt || !*opt)
2154                         continue;
2155                 sr_spew("I2C format option: %s.", opt);
2156                 if (strcmp(opt, I2C_FORMAT_ADDR_7BIT) == 0) {
2157                         sr_spew("I2C address: 7 bit");
2158                         fmt_opts->addr_10bit = FALSE;
2159                         continue;
2160                 }
2161                 if (strcmp(opt, I2C_FORMAT_ADDR_10BIT) == 0) {
2162                         sr_spew("I2C address: 10 bit");
2163                         fmt_opts->addr_10bit = TRUE;
2164                         continue;
2165                 }
2166                 return SR_ERR_ARG;
2167         }
2168         g_strfreev(opts);
2169
2170         /* Get the total slot count. Leave plenty room for convenience. */
2171         total_bits = 0;
2172         total_bits += I2C_BITTIME_SLOTS;
2173         total_bits *= I2C_BITTIME_QUANTA;
2174         total_bits += I2C_ADD_IDLESLOTS;
2175
2176         sr_dbg("I2C frame: total bits %lu.", total_bits);
2177         if (total_bits > I2C_MAX_WAVELEN)
2178                 return SR_ERR_DATA;
2179         inc->max_frame_bits = total_bits;
2180
2181         return SR_OK;
2182 }
2183
2184 /*
2185  * Don't bother with wide and narrow slots, just assume equal size for
2186  * them all. Edges will occupy exactly one sample, then levels are kept.
2187  * This protocol handler's oversampling should be sufficient for decoders
2188  * to extract the content from generated waveforms.
2189  *
2190  * Start with high levels on SCL and SDA for an idle bus condition.
2191  */
2192 static int i2c_config_frame(struct context *inc)
2193 {
2194         struct i2c_proto_context_t *incs;
2195         size_t bit_idx;
2196         uint8_t sample;
2197
2198         if (!inc)
2199                 return SR_ERR_ARG;
2200         incs = inc->curr_opts.prot_priv;
2201
2202         memset(incs, 0, sizeof(*incs));
2203         incs->ack_remain = 0;
2204
2205         /*
2206          * Adjust all time slots since they represent a smaller quanta
2207          * of an I2C bit time.
2208          */
2209         for (bit_idx = 0; bit_idx < inc->max_frame_bits; bit_idx++) {
2210                 inc->bit_scale[bit_idx].div = I2C_BITTIME_QUANTA;
2211         }
2212
2213         sample = 0;
2214         sample |= I2C_PINMASK_SCL;
2215         sample |= I2C_PINMASK_SDA;
2216         sample_buffer_preset(inc, sample);
2217
2218         return SR_OK;
2219 }
2220
2221 /*
2222  * Process protocol dependent pseudo comments. Can affect future frame
2223  * construction and submission, or can immediately emit "inter frame"
2224  * bit patterns like START/STOP control. Use wide waveforms for these
2225  * transfer controls, put the special symbol nicely centered. Supports
2226  * users during interactive exploration of generated waveforms.
2227  */
2228 static int i2c_proc_pseudo(struct sr_input *in, char *line)
2229 {
2230         struct context *inc;
2231         char *word, *endp;
2232         int ret;
2233         unsigned long v;
2234         size_t bits;
2235
2236         inc = in->priv;
2237
2238         while (line) {
2239                 word = sr_text_next_word(line, &line);
2240                 if (!word)
2241                         break;
2242                 if (!*word)
2243                         continue;
2244                 sr_spew("I2C pseudo: word %s", word);
2245                 if (strcmp(word, I2C_PSEUDO_START) == 0) {
2246                         sr_spew("I2C pseudo: send START");
2247                         ret = wave_clear_sequence(inc);
2248                         if (ret != SR_OK)
2249                                 return ret;
2250                         bits = I2C_BITTIME_SLOTS / 2;
2251                         while (bits--) {
2252                                 ret = i2c_write_nothing(inc);
2253                                 if (ret != SR_OK)
2254                                         return ret;
2255                         }
2256                         ret = i2c_write_start(inc);
2257                         if (ret != SR_OK)
2258                                 return ret;
2259                         bits = I2C_BITTIME_SLOTS / 2;
2260                         while (bits--) {
2261                                 ret = i2c_write_nothing(inc);
2262                                 if (ret != SR_OK)
2263                                         return ret;
2264                         }
2265                         ret = send_frame(in);
2266                         if (ret != SR_OK)
2267                                 return ret;
2268                         continue;
2269                 }
2270                 if (strcmp(word, I2C_PSEUDO_REP_START) == 0) {
2271                         sr_spew("I2C pseudo: send REPEAT START");
2272                         ret = wave_clear_sequence(inc);
2273                         if (ret != SR_OK)
2274                                 return ret;
2275                         bits = I2C_BITTIME_SLOTS / 2;
2276                         while (bits--) {
2277                                 ret = i2c_write_nothing(inc);
2278                                 if (ret != SR_OK)
2279                                         return ret;
2280                         }
2281                         ret = i2c_write_start(inc);
2282                         if (ret != SR_OK)
2283                                 return ret;
2284                         bits = I2C_BITTIME_SLOTS / 2;
2285                         while (bits--) {
2286                                 ret = i2c_write_nothing(inc);
2287                                 if (ret != SR_OK)
2288                                         return ret;
2289                         }
2290                         ret = send_frame(in);
2291                         if (ret != SR_OK)
2292                                 return ret;
2293                         continue;
2294                 }
2295                 if (strcmp(word, I2C_PSEUDO_STOP) == 0) {
2296                         sr_spew("I2C pseudo: send STOP");
2297                         ret = wave_clear_sequence(inc);
2298                         if (ret != SR_OK)
2299                                 return ret;
2300                         bits = I2C_BITTIME_SLOTS / 2;
2301                         while (bits--) {
2302                                 ret = i2c_write_nothing(inc);
2303                                 if (ret != SR_OK)
2304                                         return ret;
2305                         }
2306                         ret = i2c_write_stop(inc);
2307                         if (ret != SR_OK)
2308                                 return ret;
2309                         bits = I2C_BITTIME_SLOTS / 2;
2310                         while (bits--) {
2311                                 ret = i2c_write_nothing(inc);
2312                                 if (ret != SR_OK)
2313                                         return ret;
2314                         }
2315                         ret = send_frame(in);
2316                         if (ret != SR_OK)
2317                                 return ret;
2318                         continue;
2319                 }
2320                 if (g_str_has_prefix(word, I2C_PSEUDO_ADDR_WRITE)) {
2321                         word += strlen(I2C_PSEUDO_ADDR_WRITE);
2322                         endp = NULL;
2323                         ret = sr_atoul_base(word, &v, &endp, 0);
2324                         if (ret != SR_OK)
2325                                 return ret;
2326                         if (!endp || *endp)
2327                                 return SR_ERR_ARG;
2328                         sr_spew("I2C pseudo: addr write %lu", v);
2329                         ret = i2c_send_address(in, v, FALSE);
2330                         if (ret != SR_OK)
2331                                 return ret;
2332                         continue;
2333                 }
2334                 if (g_str_has_prefix(word, I2C_PSEUDO_ADDR_READ)) {
2335                         word += strlen(I2C_PSEUDO_ADDR_READ);
2336                         endp = NULL;
2337                         ret = sr_atoul_base(word, &v, &endp, 0);
2338                         if (ret != SR_OK)
2339                                 return ret;
2340                         if (!endp || *endp)
2341                                 return SR_ERR_ARG;
2342                         sr_spew("I2C pseudo: addr read %lu", v);
2343                         ret = i2c_send_address(in, v, TRUE);
2344                         if (ret != SR_OK)
2345                                 return ret;
2346                         continue;
2347                 }
2348                 if (g_str_has_prefix(word, I2C_PSEUDO_ACK_NEXT)) {
2349                         word += strlen(I2C_PSEUDO_ACK_NEXT);
2350                         endp = NULL;
2351                         ret = sr_atoul_base(word, &v, &endp, 0);
2352                         if (ret != SR_OK)
2353                                 return ret;
2354                         if (!endp || *endp)
2355                                 return SR_ERR_ARG;
2356                         sr_spew("i2c pseudo: ack next %lu", v);
2357                         i2c_auto_ack_start(inc, v);
2358                         continue;
2359                 }
2360                 if (strcmp(word, I2C_PSEUDO_ACK_ONCE) == 0) {
2361                         sr_spew("i2c pseudo: ack once");
2362                         i2c_auto_ack_start(inc, 1);
2363                         continue;
2364                 }
2365                 return SR_ERR_DATA;
2366         }
2367
2368         return SR_OK;
2369 }
2370
2371 /*
2372  * Create the frame's waveform for the given data value. Automatically
2373  * track ACK bits, Fallback to NAK when externally specified ACK counts
2374  * have expired. The caller sends the waveform that we created.
2375  */
2376 static int i2c_proc_value(struct context *inc, uint32_t value)
2377 {
2378         gboolean with_ack;
2379         int ret;
2380
2381         if (!inc)
2382                 return SR_ERR_ARG;
2383
2384         with_ack = i2c_auto_ack_avail(inc);
2385
2386         ret = wave_clear_sequence(inc);
2387         if (ret != SR_OK)
2388                 return ret;
2389         ret = i2c_write_byte(inc, value, with_ack);
2390         if (ret != SR_OK)
2391                 return ret;
2392
2393         return 0;
2394 }
2395
2396 /* Start/end the logic trace with a few bit times of idle level. */
2397 static int i2c_get_idle_capture(struct context *inc,
2398         size_t *bitcount, uint8_t *sample)
2399 {
2400
2401         /* Describe a byte's time of idle level. */
2402         if (bitcount)
2403                 *bitcount = I2C_BITTIME_SLOTS;
2404         if (sample)
2405                 *sample = inc->samples.idle_levels;
2406         return SR_OK;
2407 }
2408
2409 /* Arrange for a few samples of idle level between UART frames. */
2410 static int i2c_get_idle_interframe(struct context *inc,
2411         size_t *samplecount, uint8_t *sample)
2412 {
2413
2414         /*
2415          * The space around regular bytes already is sufficient. We
2416          * don't need to generate an inter-frame gap, but the code is
2417          * prepared to in case we want to in the future.
2418          */
2419         if (samplecount) {
2420                 *samplecount = inc->curr_opts.samples_per_bit;
2421                 *samplecount *= 0;
2422         }
2423         if (sample)
2424                 *sample = inc->samples.curr_levels;
2425         return SR_OK;
2426 }
2427
2428 /* }}} I2C protocol handler */
2429 /* {{{ protocol dispatching */
2430
2431 /*
2432  * The list of supported protocols and their handlers, including
2433  * protocol specific defaults. The first item after the NONE slot
2434  * is the default protocol, and takes effect in the absence of any
2435  * user provided or file content provided spec.
2436  */
2437 static const struct proto_handler_t protocols[PROTO_TYPE_COUNT] = {
2438         [PROTO_TYPE_UART] = {
2439                 UART_HANDLER_NAME,
2440                 {
2441                         UART_DFLT_SAMPLERATE,
2442                         UART_DFLT_BITRATE, UART_DFLT_FRAMEFMT,
2443                         INPUT_BYTES,
2444                 },
2445                 {
2446                         1, (const char *[]){
2447                                 [UART_PIN_RXTX] = "rxtx",
2448                         },
2449                 },
2450                 0,
2451                 uart_check_opts,
2452                 uart_config_frame,
2453                 uart_proc_pseudo,
2454                 uart_proc_value,
2455                 uart_get_idle_capture,
2456                 uart_get_idle_interframe,
2457         },
2458         [PROTO_TYPE_SPI] = {
2459                 SPI_HANDLER_NAME,
2460                 {
2461                         SPI_DFLT_SAMPLERATE,
2462                         SPI_DFLT_BITRATE, SPI_DFLT_FRAMEFMT,
2463                         INPUT_TEXT,
2464                 },
2465                 {
2466                         4, (const char *[]){
2467                                 [SPI_PIN_SCK] = "sck",
2468                                 [SPI_PIN_MISO] = "miso",
2469                                 [SPI_PIN_MOSI] = "mosi",
2470                                 [SPI_PIN_CS] = "cs",
2471                         },
2472                 },
2473                 sizeof(struct spi_proto_context_t),
2474                 spi_check_opts,
2475                 spi_config_frame,
2476                 spi_proc_pseudo,
2477                 spi_proc_value,
2478                 spi_get_idle_capture,
2479                 spi_get_idle_interframe,
2480         },
2481         [PROTO_TYPE_I2C] = {
2482                 I2C_HANDLER_NAME,
2483                 {
2484                         I2C_DFLT_SAMPLERATE,
2485                         I2C_DFLT_BITRATE, I2C_DFLT_FRAMEFMT,
2486                         INPUT_TEXT,
2487                 },
2488                 {
2489                         2, (const char *[]){
2490                                 [I2C_PIN_SCL] = "scl",
2491                                 [I2C_PIN_SDA] = "sda",
2492                         },
2493                 },
2494                 sizeof(struct i2c_proto_context_t),
2495                 i2c_check_opts,
2496                 i2c_config_frame,
2497                 i2c_proc_pseudo,
2498                 i2c_proc_value,
2499                 i2c_get_idle_capture,
2500                 i2c_get_idle_interframe,
2501         },
2502 };
2503
2504 static int lookup_protocol_name(struct context *inc)
2505 {
2506         const char *name;
2507         const struct proto_handler_t *handler;
2508         size_t idx;
2509         void *priv;
2510
2511         /*
2512          * Silence compiler warnings. Protocol handlers are free to use
2513          * several alternative sets of primitives for their operation.
2514          * Not using part of the API is nothing worth warning about.
2515          */
2516         (void)sample_buffer_assign;
2517
2518         if (!inc)
2519                 return SR_ERR_ARG;
2520         inc->curr_opts.protocol_type = PROTO_TYPE_NONE;
2521         inc->curr_opts.prot_hdl = NULL;
2522
2523         name = inc->curr_opts.proto_name;
2524         if (!name || !*name) {
2525                 /* Fallback to first item after NONE slot. */
2526                 handler = &protocols[PROTO_TYPE_NONE + 1];
2527                 name = handler->name;
2528         }
2529
2530         for (idx = 0; idx < ARRAY_SIZE(protocols); idx++) {
2531                 if (idx == PROTO_TYPE_NONE)
2532                         continue;
2533                 handler = &protocols[idx];
2534                 if (!handler->name || !*handler->name)
2535                         continue;
2536                 if (strcmp(name, handler->name) != 0)
2537                         continue;
2538                 inc->curr_opts.protocol_type = idx;
2539                 inc->curr_opts.prot_hdl = handler;
2540                 if (handler->priv_size) {
2541                         priv = g_malloc0(handler->priv_size);
2542                         if (!priv)
2543                                 return SR_ERR_MALLOC;
2544                         inc->curr_opts.prot_priv = priv;
2545                 }
2546                 return SR_OK;
2547         }
2548
2549         return SR_ERR_DATA;
2550 }
2551
2552 /* }}} protocol dispatching */
2553 /* {{{ text/binary input file reader */
2554
2555 /**
2556  * Checks for UTF BOM, removes it when found at the start of the buffer.
2557  *
2558  * @param[in] buf The accumulated input buffer.
2559  */
2560 static void check_remove_bom(GString *buf)
2561 {
2562         static const char *bom_text = "\xef\xbb\xbf";
2563
2564         if (buf->len < strlen(bom_text))
2565                 return;
2566         if (strncmp(buf->str, bom_text, strlen(bom_text)) != 0)
2567                 return;
2568         g_string_erase(buf, 0, strlen(bom_text));
2569 }
2570
2571 /**
2572  * Checks for presence of a caption, yields the position after its text line.
2573  *
2574  * @param[in] buf The accumulated input buffer.
2575  * @param[in] caption The text to search for (NUL terminated ASCII literal).
2576  * @param[in] max_pos The maximum length to search for.
2577  *
2578  * @returns The position after the text line which contains the caption.
2579  *   Or #NULL when either the caption or the end-of-line was not found.
2580  */
2581 static char *have_text_line(GString *buf, const char *caption, size_t max_pos)
2582 {
2583         size_t cap_len, rem_len;
2584         char *p_read, *p_found;
2585
2586         cap_len = strlen(caption);
2587         rem_len = buf->len;
2588         p_read = buf->str;
2589
2590         /* Search for the occurance of the caption itself. */
2591         if (!max_pos) {
2592                 /* Caption must be at the start of the buffer. */
2593                 if (rem_len < cap_len)
2594                         return NULL;
2595                 if (strncmp(p_read, caption, cap_len) != 0)
2596                         return NULL;
2597         } else {
2598                 /* Caption can be anywhere up to a max position. */
2599                 p_found = g_strstr_len(p_read, rem_len, caption);
2600                 if (!p_found)
2601                         return NULL;
2602                 /* Pretend that caption had been rather long. */
2603                 cap_len += p_found - p_read;
2604         }
2605
2606         /*
2607          * Advance over the caption. Advance over end-of-line. Supports
2608          * several end-of-line conditions, but rejects unexpected trailer
2609          * after the caption and before the end-of-line. Always wants LF.
2610          */
2611         p_read += cap_len;
2612         rem_len -= cap_len;
2613         while (rem_len && *p_read != '\n' && g_ascii_isspace(*p_read)) {
2614                 p_read++;
2615                 rem_len--;
2616         }
2617         if (rem_len && *p_read != '\n' && *p_read == '\r') {
2618                 p_read++;
2619                 rem_len--;
2620         }
2621         if (rem_len && *p_read == '\n') {
2622                 p_read++;
2623                 rem_len--;
2624                 return p_read;
2625         }
2626
2627         return NULL;
2628 }
2629
2630 /**
2631  * Checks for the presence of the magic string at the start of the file.
2632  *
2633  * @param[in] buf The accumulated input buffer.
2634  * @param[out] next_pos The text after the magic text line.
2635  *
2636  * @returns Boolean whether the magic was found.
2637  *
2638  * This implementation assumes that the magic file type marker never gets
2639  * split across receive chunks.
2640  */
2641 static gboolean have_magic(GString *buf, char **next_pos)
2642 {
2643         char *next_line;
2644
2645         if (next_pos)
2646                 *next_pos = NULL;
2647
2648         next_line = have_text_line(buf, MAGIC_FILE_TYPE, 0);
2649         if (!next_line)
2650                 return FALSE;
2651
2652         if (next_pos)
2653                 *next_pos = next_line;
2654
2655         return TRUE;
2656 }
2657
2658 /**
2659  * Checks for the presence of the header section at the start of the file.
2660  *
2661  * @param[in] buf The accumulated input buffer.
2662  * @param[out] next_pos The text after the header section.
2663  *
2664  * @returns A negative value when the answer is yet unknown (insufficient
2665  *   input data). Or boolean 0/1 when the header was found absent/present.
2666  *
2667  * The caller is supposed to have checked for and removed the magic text
2668  * for the file type. This routine expects to find the header section
2669  * boundaries right at the start of the input buffer.
2670  *
2671  * This implementation assumes that the header start marker never gets
2672  * split across receive chunks.
2673  */
2674 static int have_header(GString *buf, char **next_pos)
2675 {
2676         char *after_start, *after_end;
2677
2678         if (next_pos)
2679                 *next_pos = NULL;
2680
2681         after_start = have_text_line(buf, TEXT_HEAD_START, 0);
2682         if (!after_start)
2683                 return 0;
2684
2685         after_end = have_text_line(buf, TEXT_HEAD_END, buf->len);
2686         if (!after_end)
2687                 return -1;
2688
2689         if (next_pos)
2690                 *next_pos = after_end;
2691         return 1;
2692 }
2693
2694 /*
2695  * Implementation detail: Most parse routines merely accept an input
2696  * string or at most convert text to numbers. Actual processing of the
2697  * values or constraints checks are done later when the header section
2698  * ended and all data was seen, regardless of order of appearance.
2699  */
2700
2701 static int parse_samplerate(struct context *inc, const char *text)
2702 {
2703         uint64_t rate;
2704         int ret;
2705
2706         ret = sr_parse_sizestring(text, &rate);
2707         if (ret != SR_OK)
2708                 return SR_ERR_DATA;
2709
2710         inc->curr_opts.samplerate = rate;
2711
2712         return SR_OK;
2713 }
2714
2715 static int parse_bitrate(struct context *inc, const char *text)
2716 {
2717         uint64_t rate;
2718         int ret;
2719
2720         ret = sr_parse_sizestring(text, &rate);
2721         if (ret != SR_OK)
2722                 return SR_ERR_DATA;
2723
2724         inc->curr_opts.bitrate = rate;
2725
2726         return SR_OK;
2727 }
2728
2729 static int parse_protocol(struct context *inc, const char *line)
2730 {
2731
2732         if (!line || !*line)
2733                 return SR_ERR_DATA;
2734
2735         if (inc->curr_opts.proto_name) {
2736                 free(inc->curr_opts.proto_name);
2737                 inc->curr_opts.proto_name = NULL;
2738         }
2739         inc->curr_opts.proto_name = g_strdup(line);
2740         if (!inc->curr_opts.proto_name)
2741                 return SR_ERR_MALLOC;
2742         line = inc->curr_opts.proto_name;
2743
2744         return SR_OK;
2745 }
2746
2747 static int parse_frameformat(struct context *inc, const char *line)
2748 {
2749
2750         if (!line || !*line)
2751                 return SR_ERR_DATA;
2752
2753         if (inc->curr_opts.fmt_text) {
2754                 free(inc->curr_opts.fmt_text);
2755                 inc->curr_opts.fmt_text = NULL;
2756         }
2757         inc->curr_opts.fmt_text = g_strdup(line);
2758         if (!inc->curr_opts.fmt_text)
2759                 return SR_ERR_MALLOC;
2760         line = inc->curr_opts.fmt_text;
2761
2762         return SR_OK;
2763 }
2764
2765 static int parse_textinput(struct context *inc, const char *text)
2766 {
2767         gboolean is_text;
2768
2769         if (!text || !*text)
2770                 return SR_ERR_ARG;
2771
2772         is_text = sr_parse_boolstring(text);
2773         inc->curr_opts.textinput = is_text ? INPUT_TEXT : INPUT_BYTES;
2774         return SR_OK;
2775 }
2776
2777 static int parse_header_line(struct context *inc, const char *line)
2778 {
2779
2780         /* Silently ignore comment lines. Also covers start/end markers. */
2781         if (strncmp(line, TEXT_COMM_LEADER, strlen(TEXT_COMM_LEADER)) == 0)
2782                 return SR_OK;
2783
2784         if (strncmp(line, LABEL_SAMPLERATE, strlen(LABEL_SAMPLERATE)) == 0) {
2785                 line += strlen(LABEL_SAMPLERATE);
2786                 return parse_samplerate(inc, line);
2787         }
2788         if (strncmp(line, LABEL_BITRATE, strlen(LABEL_BITRATE)) == 0) {
2789                 line += strlen(LABEL_BITRATE);
2790                 return parse_bitrate(inc, line);
2791         }
2792         if (strncmp(line, LABEL_PROTOCOL, strlen(LABEL_PROTOCOL)) == 0) {
2793                 line += strlen(LABEL_PROTOCOL);
2794                 return parse_protocol(inc, line);
2795         }
2796         if (strncmp(line, LABEL_FRAMEFORMAT, strlen(LABEL_FRAMEFORMAT)) == 0) {
2797                 line += strlen(LABEL_FRAMEFORMAT);
2798                 return parse_frameformat(inc, line);
2799         }
2800         if (strncmp(line, LABEL_TEXTINPUT, strlen(LABEL_TEXTINPUT)) == 0) {
2801                 line += strlen(LABEL_TEXTINPUT);
2802                 return parse_textinput(inc, line);
2803         }
2804
2805         /* Unsupported directive. */
2806         sr_err("Unsupported header directive: %s.", line);
2807
2808         return SR_ERR_DATA;
2809 }
2810
2811 static int parse_header(struct context *inc, GString *buf, size_t hdr_len)
2812 {
2813         size_t remain;
2814         char *curr, *next, *line;
2815         int ret;
2816
2817         ret = SR_OK;
2818
2819         /* The caller determined where the header ends. Read up to there. */
2820         remain = hdr_len;
2821         curr = buf->str;
2822         while (curr && remain) {
2823                 /* Get another text line. Skip empty lines. */
2824                 line = sr_text_next_line(curr, remain, &next, NULL);
2825                 if (!line)
2826                         break;
2827                 if (next)
2828                         remain -= next - curr;
2829                 else
2830                         remain = 0;
2831                 curr = next;
2832                 if (!*line)
2833                         continue;
2834                 /* Process the non-empty file header text line. */
2835                 sr_dbg("Header line: %s", line);
2836                 ret = parse_header_line(inc, line);
2837                 if (ret != SR_OK)
2838                         break;
2839         }
2840
2841         return ret;
2842 }
2843
2844 /* Process input text reader specific pseudo comment. */
2845 static int process_pseudo_textinput(struct sr_input *in, char *line)
2846 {
2847         struct context *inc;
2848         char *word;
2849         unsigned long v;
2850         char *endp;
2851         int ret;
2852
2853         inc = in->priv;
2854         while (line) {
2855                 word = sr_text_next_word(line, &line);
2856                 if (!word)
2857                         break;
2858                 if (!*word)
2859                         continue;
2860                 if (g_str_has_prefix(word, TEXT_INPUT_RADIX)) {
2861                         word += strlen(TEXT_INPUT_RADIX);
2862                         endp = NULL;
2863                         ret = sr_atoul_base(word, &v, &endp, 10);
2864                         if (ret != SR_OK)
2865                                 return ret;
2866                         inc->read_text.base = v;
2867                         continue;
2868                 }
2869                 return SR_ERR_DATA;
2870         }
2871
2872         return SR_OK;
2873 }
2874
2875 /* Process a line of input text. */
2876 static int process_textline(struct sr_input *in, char *line)
2877 {
2878         struct context *inc;
2879         const struct proto_handler_t *handler;
2880         gboolean is_comm, is_pseudo;
2881         char *p, *word, *endp;
2882         unsigned long value;
2883         int ret;
2884
2885         inc = in->priv;
2886         handler = inc->curr_opts.prot_hdl;
2887
2888         /*
2889          * Check for comments, including pseudo-comments with protocol
2890          * specific or text reader specific instructions. It's essential
2891          * to check for "# ${PROTO}:" last, because the implementation
2892          * of the check advances the read position, cannot rewind when
2893          * detection fails. But we know that it is a comment and was not
2894          * a pseudo-comment. So any non-matching data just gets discarded.
2895          * Matching data gets processed (when handlers exist).
2896          */
2897         is_comm = g_str_has_prefix(line, TEXT_COMM_LEADER);
2898         if (is_comm) {
2899                 line += strlen(TEXT_COMM_LEADER);
2900                 while (isspace(*line))
2901                         line++;
2902                 is_pseudo = g_str_has_prefix(line, TEXT_INPUT_PREFIX);
2903                 if (is_pseudo) {
2904                         line += strlen(TEXT_INPUT_PREFIX);
2905                         while (isspace(*line))
2906                                 line++;
2907                         sr_dbg("pseudo comment, textinput: %s", line);
2908                         line = sr_text_trim_spaces(line);
2909                         return process_pseudo_textinput(in, line);
2910                 }
2911                 is_pseudo = g_str_has_prefix(line, handler->name);
2912                 if (is_pseudo) {
2913                         line += strlen(handler->name);
2914                         is_pseudo = *line == ':';
2915                         if (is_pseudo)
2916                                 line++;
2917                 }
2918                 if (is_pseudo) {
2919                         while (isspace(*line))
2920                                 line++;
2921                         sr_dbg("pseudo comment, protocol: %s", line);
2922                         if (!handler->proc_pseudo)
2923                                 return SR_OK;
2924                         return handler->proc_pseudo(in, line);
2925                 }
2926                 sr_spew("comment, skipping: %s", line);
2927                 return SR_OK;
2928         }
2929
2930         /*
2931          * Non-empty non-comment lines carry protocol values.
2932          * (Empty lines are handled transparently when they get here.)
2933          * Accept comma and semicolon separators for user convenience.
2934          * Convert text according to previously received instructions.
2935          * Pass the values to the protocol handler. Flush waveforms
2936          * when handlers state that their construction has completed.
2937          */
2938         sr_spew("got values line: %s", line);
2939         for (p = line; *p; p++) {
2940                 if (*p == ',' || *p == ';')
2941                         *p = ' ';
2942         }
2943         while (line) {
2944                 word = sr_text_next_word(line, &line);
2945                 if (!word)
2946                         break;
2947                 if (!*word)
2948                         continue;
2949                 /* Get another numeric value. */
2950                 endp = NULL;
2951                 ret = sr_atoul_base(word, &value, &endp, inc->read_text.base);
2952                 if (ret != SR_OK)
2953                         return ret;
2954                 if (!endp || *endp)
2955                         return SR_ERR_DATA;
2956                 sr_spew("got a value, text [%s] -> number [%lu]", word, value);
2957                 /* Forward the value to the protocol handler. */
2958                 ret = 0;
2959                 if (handler->proc_value)
2960                         ret = handler->proc_value(inc, value);
2961                 if (ret < 0)
2962                         return ret;
2963                 /* Flush the waveform when handler signals completion. */
2964                 if (ret > 0)
2965                         continue;
2966                 ret = send_frame(in);
2967                 if (ret != SR_OK)
2968                         return ret;
2969                 ret = send_idle_interframe(inc);
2970                 if (ret != SR_OK)
2971                         return ret;
2972         }
2973
2974         return SR_OK;
2975 }
2976
2977 /* }}} text/binary input file reader */
2978
2979 /*
2980  * Consistency check of all previously received information. Combines
2981  * the data file's optional header section, as well as user provided
2982  * options that were specified during input module creation. User specs
2983  * take precedence over file content.
2984  */
2985 static int check_header_user_options(struct context *inc)
2986 {
2987         int ret;
2988         const struct proto_handler_t *handler;
2989         uint64_t rate;
2990         const char *text;
2991         enum textinput_t is_text;
2992
2993         if (!inc)
2994                 return SR_ERR_ARG;
2995
2996         /* Prefer user specs over file content. */
2997         rate = inc->user_opts.samplerate;
2998         if (rate) {
2999                 sr_dbg("Using user samplerate %" PRIu64 ".", rate);
3000                 inc->curr_opts.samplerate = rate;
3001         }
3002         rate = inc->user_opts.bitrate;
3003         if (rate) {
3004                 sr_dbg("Using user bitrate %" PRIu64 ".", rate);
3005                 inc->curr_opts.bitrate = rate;
3006         }
3007         text = inc->user_opts.proto_name;
3008         if (text && *text) {
3009                 sr_dbg("Using user protocol %s.", text);
3010                 ret = parse_protocol(inc, text);
3011                 if (ret != SR_OK)
3012                         return SR_ERR_DATA;
3013         }
3014         text = inc->user_opts.fmt_text;
3015         if (text && *text) {
3016                 sr_dbg("Using user frame format %s.", text);
3017                 ret = parse_frameformat(inc, text);
3018                 if (ret != SR_OK)
3019                         return SR_ERR_DATA;
3020         }
3021         is_text = inc->user_opts.textinput;
3022         if (is_text) {
3023                 sr_dbg("Using user textinput %d.", is_text);
3024                 inc->curr_opts.textinput = is_text;
3025         }
3026
3027         /* Lookup the protocol (with fallback). Use protocol's defaults. */
3028         text = inc->curr_opts.proto_name;
3029         ret = lookup_protocol_name(inc);
3030         handler = inc->curr_opts.prot_hdl;
3031         if (ret != SR_OK || !handler) {
3032                 sr_err("Unsupported protocol: %s.", text);
3033                 return SR_ERR_DATA;
3034         }
3035         text = handler->name;
3036         if (!inc->curr_opts.proto_name && text) {
3037                 sr_dbg("Using protocol handler name %s.", text);
3038                 ret = parse_protocol(inc, text);
3039                 if (ret != SR_OK)
3040                         return SR_ERR_DATA;
3041         }
3042         rate = handler->dflt.samplerate;
3043         if (!inc->curr_opts.samplerate && rate) {
3044                 sr_dbg("Using protocol handler samplerate %" PRIu64 ".", rate);
3045                 inc->curr_opts.samplerate = rate;
3046         }
3047         rate = handler->dflt.bitrate;
3048         if (!inc->curr_opts.bitrate && rate) {
3049                 sr_dbg("Using protocol handler bitrate %" PRIu64 ".", rate);
3050                 inc->curr_opts.bitrate = rate;
3051         }
3052         text = handler->dflt.frame_format;
3053         if (!inc->curr_opts.fmt_text && text && *text) {
3054                 sr_dbg("Using protocol handler frame format %s.", text);
3055                 ret = parse_frameformat(inc, text);
3056                 if (ret != SR_OK)
3057                         return SR_ERR_DATA;
3058         }
3059         is_text = handler->dflt.textinput;
3060         if (!inc->curr_opts.textinput && is_text) {
3061                 sr_dbg("Using protocol handler text format %d.", is_text);
3062                 inc->curr_opts.textinput = is_text;
3063         }
3064
3065         if (!inc->curr_opts.samplerate) {
3066                 sr_err("Need a samplerate.");
3067                 return SR_ERR_DATA;
3068         }
3069         if (!inc->curr_opts.bitrate) {
3070                 sr_err("Need a protocol bitrate.");
3071                 return SR_ERR_DATA;
3072         }
3073
3074         if (inc->curr_opts.samplerate < inc->curr_opts.bitrate) {
3075                 sr_err("Bitrate cannot exceed samplerate.");
3076                 return SR_ERR_DATA;
3077         }
3078         if (inc->curr_opts.samplerate / inc->curr_opts.bitrate < 3)
3079                 sr_warn("Low oversampling, consider higher samplerate.");
3080         if (inc->curr_opts.prot_hdl->check_opts) {
3081                 ret = inc->curr_opts.prot_hdl->check_opts(inc);
3082                 if (ret != SR_OK) {
3083                         sr_err("Options failed the protocol's check.");
3084                         return SR_ERR_DATA;
3085                 }
3086         }
3087
3088         return SR_OK;
3089 }
3090
3091 static int create_channels(struct sr_input *in)
3092 {
3093         struct context *inc;
3094         struct sr_dev_inst *sdi;
3095         const struct proto_handler_t *handler;
3096         size_t index;
3097         const char *name;
3098
3099         if (!in)
3100                 return SR_ERR_ARG;
3101         inc = in->priv;
3102         if (!inc)
3103                 return SR_ERR_ARG;
3104         sdi = in->sdi;
3105         handler = inc->curr_opts.prot_hdl;
3106
3107         for (index = 0; index < handler->chans.count; index++) {
3108                 name = handler->chans.names[index];
3109                 sr_dbg("Channel %zu name %s.", index, name);
3110                 sr_channel_new(sdi, index, SR_CHANNEL_LOGIC, TRUE, name);
3111         }
3112
3113         inc->feed_logic = feed_queue_logic_alloc(in->sdi,
3114                 CHUNK_SIZE, sizeof(uint8_t));
3115         if (!inc->feed_logic) {
3116                 sr_err("Cannot create session feed.");
3117                 return SR_ERR_MALLOC;
3118         }
3119
3120         return SR_OK;
3121 }
3122
3123 /*
3124  * Keep track of a previously created channel list, in preparation of
3125  * re-reading the input file. Gets called from reset()/cleanup() paths.
3126  */
3127 static void keep_header_for_reread(const struct sr_input *in)
3128 {
3129         struct context *inc;
3130
3131         inc = in->priv;
3132
3133         g_slist_free_full(inc->prev.sr_groups, sr_channel_group_free_cb);
3134         inc->prev.sr_groups = in->sdi->channel_groups;
3135         in->sdi->channel_groups = NULL;
3136
3137         g_slist_free_full(inc->prev.sr_channels, sr_channel_free_cb);
3138         inc->prev.sr_channels = in->sdi->channels;
3139         in->sdi->channels = NULL;
3140 }
3141
3142 /*
3143  * Check whether the input file is being re-read, and refuse operation
3144  * when essential parameters of the acquisition have changed in ways
3145  * that are unexpected to calling applications. Gets called after the
3146  * file header got parsed (again).
3147  *
3148  * Changing the channel list across re-imports of the same file is not
3149  * supported, by design and for valid reasons, see bug #1215 for details.
3150  * Users are expected to start new sessions when they change these
3151  * essential parameters in the acquisition's setup. When we accept the
3152  * re-read file, then make sure to keep using the previous channel list,
3153  * applications may still reference them.
3154  */
3155 static gboolean check_header_in_reread(const struct sr_input *in)
3156 {
3157         struct context *inc;
3158
3159         if (!in)
3160                 return FALSE;
3161         inc = in->priv;
3162         if (!inc)
3163                 return FALSE;
3164         if (!inc->prev.sr_channels)
3165                 return TRUE;
3166
3167         if (sr_channel_lists_differ(inc->prev.sr_channels, in->sdi->channels)) {
3168                 sr_err("Channel list change not supported for file re-read.");
3169                 return FALSE;
3170         }
3171
3172         g_slist_free_full(in->sdi->channel_groups, sr_channel_group_free_cb);
3173         in->sdi->channel_groups = inc->prev.sr_groups;
3174         inc->prev.sr_groups = NULL;
3175
3176         g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
3177         in->sdi->channels = inc->prev.sr_channels;
3178         inc->prev.sr_channels = NULL;
3179
3180         return TRUE;
3181 }
3182
3183 /* Process another chunk of accumulated input data. */
3184 static int process_buffer(struct sr_input *in, gboolean is_eof)
3185 {
3186         struct context *inc;
3187         GVariant *gvar;
3188         int ret;
3189         GString *buf;
3190         const struct proto_handler_t *handler;
3191         size_t seen;
3192         char *line, *next;
3193         uint8_t sample;
3194
3195         inc = in->priv;
3196         buf = in->buf;
3197         handler = inc->curr_opts.prot_hdl;
3198
3199         /*
3200          * Send feed header and samplerate once before any sample data.
3201          * Communicate an idle period before the first generated frame.
3202          */
3203         if (!inc->started) {
3204                 std_session_send_df_header(in->sdi);
3205                 gvar = g_variant_new_uint64(inc->curr_opts.samplerate);
3206                 ret = sr_session_send_meta(in->sdi, SR_CONF_SAMPLERATE, gvar);
3207                 inc->started = TRUE;
3208                 if (ret != SR_OK)
3209                         return ret;
3210
3211                 ret = send_idle_capture(inc);
3212                 if (ret != SR_OK)
3213                         return ret;
3214         }
3215
3216         /*
3217          * Force proper line termination when EOF is seen and the data
3218          * is in text format. This does not affect binary input, while
3219          * properly terminated text input does not suffer from another
3220          * line feed, because empty lines are considered acceptable.
3221          * Increases robustness for text input from broken generators
3222          * (popular editors which don't terminate the last line).
3223          */
3224         if (inc->curr_opts.textinput == INPUT_TEXT && is_eof) {
3225                 g_string_append_c(buf, '\n');
3226         }
3227
3228         /*
3229          * For text input: Scan for the completion of another text line.
3230          * Process its values (or pseudo comments). Skip comment lines.
3231          */
3232         if (inc->curr_opts.textinput == INPUT_TEXT) do {
3233                 /* Get another line of text. */
3234                 seen = 0;
3235                 line = sr_text_next_line(buf->str, buf->len, &next, &seen);
3236                 if (!line)
3237                         break;
3238                 /* Process non-empty input lines. */
3239                 ret = *line ? process_textline(in, line) : 0;
3240                 if (ret < 0)
3241                         return ret;
3242                 /* Discard processed input text. */
3243                 g_string_erase(buf, 0, seen);
3244         } while (buf->len);
3245
3246         /*
3247          * For binary input: Pass data values (individual bytes) to the
3248          * creation of protocol frames. Send the frame's waveform to
3249          * logic channels in the session feed when the protocol handler
3250          * signals the completion of another waveform (zero return value).
3251          * Non-zero positive values translate to "need more input data".
3252          * Negative values signal fatal errors. Remove processed input
3253          * data from the receive buffer.
3254          */
3255         if (inc->curr_opts.textinput == INPUT_BYTES) {
3256                 seen = 0;
3257                 while (seen < buf->len) {
3258                         sample = buf->str[seen++];
3259                         ret = 0;
3260                         if (handler->proc_value)
3261                                 ret = handler->proc_value(inc, sample);
3262                         if (ret < 0)
3263                                 return ret;
3264                         if (ret > 0)
3265                                 continue;
3266                         ret = send_frame(in);
3267                         if (ret != SR_OK)
3268                                 return ret;
3269                         ret = send_idle_interframe(inc);
3270                         if (ret != SR_OK)
3271                                 return ret;
3272                 }
3273                 g_string_erase(buf, 0, seen);
3274         }
3275
3276         /* Send idle level, and flush when end of input data is seen. */
3277         if (is_eof) {
3278                 if (buf->len)
3279                         sr_warn("Unprocessed input data remains.");
3280
3281                 ret = send_idle_capture(inc);
3282                 if (ret != SR_OK)
3283                         return ret;
3284
3285                 ret = feed_queue_logic_flush(inc->feed_logic);
3286                 if (ret != SR_OK)
3287                         return ret;
3288         }
3289
3290         return SR_OK;
3291 }
3292
3293 static int format_match(GHashTable *metadata, unsigned int *confidence)
3294 {
3295         GString *buf, *tmpbuf;
3296         gboolean has_magic;
3297
3298         buf = g_hash_table_lookup(metadata,
3299                 GINT_TO_POINTER(SR_INPUT_META_HEADER));
3300         tmpbuf = g_string_new_len(buf->str, buf->len);
3301
3302         check_remove_bom(tmpbuf);
3303         has_magic = have_magic(tmpbuf, NULL);
3304         g_string_free(tmpbuf, TRUE);
3305
3306         if (!has_magic)
3307                 return SR_ERR;
3308
3309         *confidence = 1;
3310         return SR_OK;
3311 }
3312
3313 static int init(struct sr_input *in, GHashTable *options)
3314 {
3315         struct context *inc;
3316         GVariant *gvar;
3317         uint64_t rate;
3318         char *copy;
3319         const char *text;
3320
3321         in->sdi = g_malloc0(sizeof(*in->sdi));
3322         inc = g_malloc0(sizeof(*inc));
3323         in->priv = inc;
3324
3325         /*
3326          * Store user specified options for later reference.
3327          *
3328          * TODO How to most appropriately hook up size strings with the
3329          * input module's defaults, and applications and their input
3330          * dialogs?
3331          */
3332         gvar = g_hash_table_lookup(options, "samplerate");
3333         if (gvar) {
3334                 rate = g_variant_get_uint64(gvar);
3335                 if (rate)
3336                         sr_dbg("User samplerate %" PRIu64 ".", rate);
3337                 inc->user_opts.samplerate = rate;
3338         }
3339
3340         gvar = g_hash_table_lookup(options, "bitrate");
3341         if (gvar) {
3342                 rate = g_variant_get_uint64(gvar);
3343                 if (rate)
3344                         sr_dbg("User bitrate %" PRIu64 ".", rate);
3345                 inc->user_opts.bitrate = rate;
3346         }
3347
3348         gvar = g_hash_table_lookup(options, "protocol");
3349         if (gvar) {
3350                 copy = g_strdup(g_variant_get_string(gvar, NULL));
3351                 if (!copy)
3352                         return SR_ERR_MALLOC;
3353                 if (*copy)
3354                         sr_dbg("User protocol %s.", copy);
3355                 inc->user_opts.proto_name = copy;
3356         }
3357
3358         gvar = g_hash_table_lookup(options, "frameformat");
3359         if (gvar) {
3360                 copy = g_strdup(g_variant_get_string(gvar, NULL));
3361                 if (!copy)
3362                         return SR_ERR_MALLOC;
3363                 if (*copy)
3364                         sr_dbg("User frame format %s.", copy);
3365                 inc->user_opts.fmt_text = copy;
3366         }
3367
3368         inc->user_opts.textinput = INPUT_UNSPEC;
3369         gvar = g_hash_table_lookup(options, "textinput");
3370         if (gvar) {
3371                 text = g_variant_get_string(gvar, NULL);
3372                 if (!text)
3373                         return SR_ERR_DATA;
3374                 if (!*text)
3375                         return SR_ERR_DATA;
3376                 sr_dbg("User text input %s.", text);
3377                 if (strcmp(text, input_format_texts[INPUT_UNSPEC]) == 0) {
3378                         inc->user_opts.textinput = INPUT_UNSPEC;
3379                 } else if (strcmp(text, input_format_texts[INPUT_BYTES]) == 0) {
3380                         inc->user_opts.textinput = INPUT_BYTES;
3381                 } else if (strcmp(text, input_format_texts[INPUT_TEXT]) == 0) {
3382                         inc->user_opts.textinput = INPUT_TEXT;
3383                 } else {
3384                         return SR_ERR_DATA;
3385                 }
3386         }
3387
3388         return SR_OK;
3389 }
3390
3391 static int receive(struct sr_input *in, GString *buf)
3392 {
3393         struct context *inc;
3394         char *after_magic, *after_header;
3395         size_t consumed;
3396         int ret;
3397
3398         inc = in->priv;
3399
3400         /*
3401          * Accumulate all input chunks, potential deferred processing.
3402          *
3403          * Remove an optional BOM at the very start of the input stream.
3404          * BEWARE! This may affect binary input, and we cannot tell if
3405          * the input is text or binary at this stage. Though probability
3406          * for this issue is rather low. Workarounds are available (put
3407          * another values before the first data which happens to match
3408          * the BOM pattern, provide text input instead).
3409          */
3410         g_string_append_len(in->buf, buf->str, buf->len);
3411         if (!inc->scanned_magic)
3412                 check_remove_bom(in->buf);
3413
3414         /*
3415          * Must complete reception of the (optional) header first. Both
3416          * end of header and absence of header will: Check options that
3417          * were seen so far, then start processing the data part.
3418          */
3419         if (!inc->got_header) {
3420                 /* Check for magic file type marker. */
3421                 if (!inc->scanned_magic) {
3422                         inc->has_magic = have_magic(in->buf, &after_magic);
3423                         inc->scanned_magic = TRUE;
3424                         if (inc->has_magic) {
3425                                 consumed = after_magic - in->buf->str;
3426                                 sr_dbg("File format magic found (%zu).", consumed);
3427                                 g_string_erase(in->buf, 0, consumed);
3428                         }
3429                 }
3430
3431                 /* Complete header reception and processing. */
3432                 if (inc->has_magic) {
3433                         ret = have_header(in->buf, &after_header);
3434                         if (ret < 0)
3435                                 return SR_OK;
3436                         inc->has_header = ret;
3437                         if (inc->has_header) {
3438                                 consumed = after_header - in->buf->str;
3439                                 sr_dbg("File header found (%zu), processing.", consumed);
3440                                 ret = parse_header(inc, in->buf, consumed);
3441                                 if (ret != SR_OK)
3442                                         return ret;
3443                                 g_string_erase(in->buf, 0, consumed);
3444                         }
3445                 }
3446                 inc->got_header = TRUE;
3447
3448                 /*
3449                  * Postprocess the combination of all options. Create
3450                  * logic channels, prepare resources for data processing.
3451                  */
3452                 ret = check_header_user_options(inc);
3453                 if (ret != SR_OK)
3454                         return ret;
3455                 ret = create_channels(in);
3456                 if (ret != SR_OK)
3457                         return ret;
3458                 if (!check_header_in_reread(in))
3459                         return SR_ERR_DATA;
3460                 ret = alloc_frame_storage(inc);
3461                 if (ret != SR_OK)
3462                         return ret;
3463                 ret = assign_bit_widths(inc);
3464                 if (ret != SR_OK)
3465                         return ret;
3466
3467                 /* Notify the frontend that sdi is ready. */
3468                 in->sdi_ready = TRUE;
3469                 return SR_OK;
3470         }
3471
3472         /*
3473          * Process the input file's data section after the header section
3474          * was received and processed.
3475          */
3476         ret = process_buffer(in, FALSE);
3477
3478         return ret;
3479 }
3480
3481 static int end(struct sr_input *in)
3482 {
3483         struct context *inc;
3484         int ret;
3485
3486         inc = in->priv;
3487
3488         /* Must complete processing of previously received chunks. */
3489         if (in->sdi_ready) {
3490                 ret = process_buffer(in, TRUE);
3491                 if (ret != SR_OK)
3492                         return ret;
3493         }
3494
3495         /* Must send DF_END when DF_HEADER was sent before. */
3496         if (inc->started) {
3497                 ret = std_session_send_df_end(in->sdi);
3498                 if (ret != SR_OK)
3499                         return ret;
3500         }
3501
3502         return SR_OK;
3503 }
3504
3505 static void cleanup(struct sr_input *in)
3506 {
3507         struct context *inc;
3508
3509         inc = in->priv;
3510
3511         keep_header_for_reread(in);
3512
3513         g_free(inc->curr_opts.proto_name);
3514         inc->curr_opts.proto_name = NULL;
3515         g_free(inc->curr_opts.fmt_text);
3516         inc->curr_opts.fmt_text = NULL;
3517         g_free(inc->curr_opts.prot_priv);
3518         inc->curr_opts.prot_priv = NULL;
3519         feed_queue_logic_free(inc->feed_logic);
3520         inc->feed_logic = NULL;
3521         g_free(inc->sample_edges);
3522         inc->sample_edges = NULL;
3523         g_free(inc->sample_widths);
3524         inc->sample_widths = NULL;
3525         g_free(inc->sample_levels);
3526         inc->sample_levels = NULL;
3527         g_free(inc->bit_scale);
3528         inc->bit_scale = NULL;
3529 }
3530
3531 static int reset(struct sr_input *in)
3532 {
3533         struct context *inc;
3534         struct user_opts_t save_user_opts;
3535         struct proto_prev save_chans;
3536
3537         inc = in->priv;
3538
3539         /* Release previously allocated resources. */
3540         cleanup(in);
3541         g_string_truncate(in->buf, 0);
3542
3543         /* Restore part of the context, init() won't run again. */
3544         save_user_opts = inc->user_opts;
3545         save_chans = inc->prev;
3546         memset(inc, 0, sizeof(*inc));
3547         inc->user_opts = save_user_opts;
3548         inc->prev = save_chans;
3549
3550         return SR_OK;
3551 }
3552
3553 enum proto_option_t {
3554         OPT_SAMPLERATE,
3555         OPT_BITRATE,
3556         OPT_PROTOCOL,
3557         OPT_FRAME_FORMAT,
3558         OPT_TEXTINPUT,
3559         OPT_MAX,
3560 };
3561
3562 static struct sr_option options[] = {
3563         [OPT_SAMPLERATE] = {
3564                 "samplerate", "Logic data samplerate",
3565                 "Samplerate of generated logic traces",
3566                 NULL, NULL,
3567         },
3568         [OPT_BITRATE] = {
3569                 "bitrate", "Protocol bitrate",
3570                 "Bitrate used in protocol's communication",
3571                 NULL, NULL,
3572         },
3573         [OPT_PROTOCOL] = {
3574                 "protocol", "Protocol type",
3575                 "The type of protocol to generate waveforms for",
3576                 NULL, NULL,
3577         },
3578         [OPT_FRAME_FORMAT] = {
3579                 "frameformat", "Protocol frame format",
3580                 "Textual description of the protocol's frame format",
3581                 NULL, NULL,
3582         },
3583         [OPT_TEXTINPUT] = {
3584                 "textinput", "Input data is in text format",
3585                 "Input is not data bytes, but text formatted values",
3586                 NULL, NULL,
3587         },
3588         [OPT_MAX] = ALL_ZERO,
3589 };
3590
3591 static const struct sr_option *get_options(void)
3592 {
3593         GSList *l;
3594         enum proto_type_t p_idx;
3595         enum textinput_t t_idx;
3596         const char *s;
3597
3598         if (options[0].def)
3599                 return options;
3600
3601         options[OPT_SAMPLERATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
3602         options[OPT_BITRATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
3603         options[OPT_PROTOCOL].def = g_variant_ref_sink(g_variant_new_string(""));
3604         l = NULL;
3605         for (p_idx = 0; p_idx < ARRAY_SIZE(protocols); p_idx++) {
3606                 s = protocols[p_idx].name;
3607                 if (!s || !*s)
3608                         continue;
3609                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string(s)));
3610         }
3611         options[OPT_PROTOCOL].values = l;
3612         options[OPT_FRAME_FORMAT].def = g_variant_ref_sink(g_variant_new_string(""));
3613         l = NULL;
3614         for (t_idx = INPUT_UNSPEC; t_idx <= INPUT_TEXT; t_idx++) {
3615                 s = input_format_texts[t_idx];
3616                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string(s)));
3617         }
3618         options[OPT_TEXTINPUT].values = l;
3619         options[OPT_TEXTINPUT].def = g_variant_ref_sink(g_variant_new_string(
3620                 input_format_texts[INPUT_UNSPEC]));
3621         return options;
3622 }
3623
3624 SR_PRIV struct sr_input_module input_protocoldata = {
3625         .id = "protocoldata",
3626         .name = "Protocol data",
3627         .desc = "Generate logic traces from protocol's data values",
3628         .exts = (const char *[]){ "sr-protocol", "protocol", "bin", NULL, },
3629         .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
3630         .options = get_options,
3631         .format_match = format_match,
3632         .init = init,
3633         .receive = receive,
3634         .end = end,
3635         .reset = reset,
3636 };