mpsse.c revision 9caf492818a4cc51ba471534d3fcaa84c9ce0278
1/*
2 *Copyright (C) 2015 The Android Open Source Project
3 *
4 *Licensed under the Apache License, Version 2.0 (the "License");
5 *you may not use this file except in compliance with the License.
6 *You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *Unless required by applicable law or agreed to in writing, software
11 *distributed under the License is distributed on an "AS IS" BASIS,
12 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *See the License for the specific language governing permissions and
14 *limitations under the License.
15 *
16 * This file was copied from https://github.com/devttys0/libmpsse.git (sha1
17 * f1a6744b), and modified to suite the Chromium OS project.
18 *
19 * Main libmpsse source file.
20 *
21 * Craig Heffner
22 * 27 December 2011
23 */
24
25#include <stdlib.h>
26#include <string.h>
27#include <stdint.h>
28#include <unistd.h>
29
30#include "trunks/ftdi/support.h"
31
32/* List of known FT2232-based devices */
33struct vid_pid supported_devices[] = {
34    {0x0403, 0x6010, "FT2232 Future Technology Devices International, Ltd"},
35    {0x0403, 0x6011, "FT4232 Future Technology Devices International, Ltd"},
36    {0x0403, 0x6014, "FT232H Future Technology Devices International, Ltd"},
37
38    /* These devices are based on FT2232 chips, but have not been tested. */
39    {0x0403, 0x8878, "Bus Blaster v2 (channel A)"},
40    {0x0403, 0x8879, "Bus Blaster v2 (channel B)"},
41    {0x0403, 0xBDC8, "Turtelizer JTAG/RS232 Adapter A"},
42    {0x0403, 0xCFF8, "Amontec JTAGkey"},
43    {0x0403, 0x8A98, "TIAO Multi Protocol Adapter"},
44    {0x15BA, 0x0003, "Olimex Ltd. OpenOCD JTAG"},
45    {0x15BA, 0x0004, "Olimex Ltd. OpenOCD JTAG TINY"},
46
47    {0, 0, NULL}};
48
49/*
50 * Opens and initializes the first FTDI device found.
51 *
52 * @mode      - Mode to open the device in. One of enum modes.
53 * @freq      - Clock frequency to use for the specified mode.
54 * @endianess - Specifies how data is clocked in/out (MSB, LSB).
55 *
56 * Returns a pointer to an MPSSE context structure if succeeded, NULL otherwise.
57 */
58struct mpsse_context* MPSSE(enum modes mode, int freq, int endianess) {
59  int i = 0;
60  struct mpsse_context* mpsse = NULL;
61
62  for (i = 0; supported_devices[i].vid != 0; i++) {
63    mpsse = Open(supported_devices[i].vid, supported_devices[i].pid, mode,
64                 freq, endianess, IFACE_A, NULL, NULL);
65    if (mpsse) {
66      mpsse->description = supported_devices[i].description;
67      return mpsse;
68    }
69  }
70
71  return NULL;
72}
73
74/*
75 * Open device by VID/PID
76 *
77 * @vid         - Device vendor ID.
78 * @pid         - Device product ID.
79 * @mode        - MPSSE mode, one of enum modes.
80 * @freq        - Clock frequency to use for the specified mode.
81 * @endianess   - Specifies how data is clocked in/out (MSB, LSB).
82 * @interface   - FTDI interface to use (IFACE_A - IFACE_D).
83 * @description - Device product description (set to NULL if not needed).
84 * @serial      - Device serial number (set to NULL if not needed).
85 *
86 * Returns a pointer to an MPSSE context structure on success.
87 */
88struct mpsse_context* Open(int vid,
89                           int pid,
90                           enum modes mode,
91                           int freq,
92                           int endianess,
93                           int interface,
94                           const char* description,
95                           const char* serial) {
96  return OpenIndex(vid, pid, mode, freq, endianess, interface, description,
97                   serial, 0);
98}
99
100/*
101 * Open device by VID/PID/index
102 *
103 * @vid         - Device vendor ID.
104 * @pid         - Device product ID.
105 * @mode        - MPSSE mode, one of enum modes.
106 * @freq        - Clock frequency to use for the specified mode.
107 * @endianess   - Specifies how data is clocked in/out (MSB, LSB).
108 * @interface   - FTDI interface to use (IFACE_A - IFACE_D).
109 * @description - Device product description (set to NULL if not needed).
110 * @serial      - Device serial number (set to NULL if not needed).
111 * @index       - Device index (set to 0 if not needed).
112 *
113 * Returns a pointer to an MPSSE context structure.
114 * On success, mpsse->open will be set to 1.
115 * On failure, mpsse->open will be set to 0.
116 */
117struct mpsse_context* OpenIndex(int vid,
118                                int pid,
119                                enum modes mode,
120                                int freq,
121                                int endianess,
122                                int interface,
123                                const char* description,
124                                const char* serial,
125                                int index) {
126  int status = 0;
127  struct mpsse_context* mpsse = NULL;
128
129  mpsse = malloc(sizeof(struct mpsse_context));
130  if (!mpsse)
131    return NULL;
132
133  memset(mpsse, 0, sizeof(struct mpsse_context));
134
135  /* Legacy; flushing is no longer needed, so disable it by default. */
136  FlushAfterRead(mpsse, 0);
137
138  /* ftdilib initialization */
139  if (ftdi_init(&mpsse->ftdi)) {
140    free(mpsse);
141    return NULL;
142  }
143
144  /* Set the FTDI interface  */
145  ftdi_set_interface(&mpsse->ftdi, interface);
146
147  /* Open the specified device */
148  if (!ftdi_usb_open_desc_index(&mpsse->ftdi, vid, pid, description, serial,
149                                index)) {
150    mpsse->mode = mode;
151    mpsse->vid = vid;
152    mpsse->pid = pid;
153    mpsse->status = STOPPED;
154    mpsse->endianess = endianess;
155
156    /* Set the appropriate transfer size for the requested protocol */
157    if (mpsse->mode == I2C)
158      mpsse->xsize = I2C_TRANSFER_SIZE;
159    else
160      mpsse->xsize = SPI_RW_SIZE;
161
162    status |= ftdi_usb_reset(&mpsse->ftdi);
163    status |= ftdi_set_latency_timer(&mpsse->ftdi, LATENCY_MS);
164    status |= ftdi_write_data_set_chunksize(&mpsse->ftdi, CHUNK_SIZE);
165    status |= ftdi_read_data_set_chunksize(&mpsse->ftdi, CHUNK_SIZE);
166    status |= ftdi_set_bitmode(&mpsse->ftdi, 0, BITMODE_RESET);
167
168    if (status == 0) {
169      /* Set the read and write timeout periods */
170      set_timeouts(mpsse, USB_TIMEOUT);
171
172      if (mpsse->mode != BITBANG) {
173        ftdi_set_bitmode(&mpsse->ftdi, 0, BITMODE_MPSSE);
174
175        if (SetClock(mpsse, freq) == MPSSE_OK) {
176          if (SetMode(mpsse, endianess) == MPSSE_OK) {
177            mpsse->opened = 1;
178
179            /* Give the chip a few mS to initialize */
180            usleep(SETUP_DELAY);
181
182            /*
183             * Not all FTDI chips support all the commands that SetMode may
184             * have sent.
185             * This clears out any errors from unsupported commands that
186             * might have been sent during set up.
187             */
188            ftdi_usb_purge_buffers(&mpsse->ftdi);
189          }
190        }
191      } else {
192        /* Skip the setup functions if we're just operating in BITBANG mode
193         */
194        if (!ftdi_set_bitmode(&mpsse->ftdi, 0xFF, BITMODE_BITBANG))
195          mpsse->opened = 1;
196      }
197    }
198  }
199
200  if (mpsse && !mpsse->opened) {
201    Close(mpsse);
202    mpsse = NULL;
203  }
204
205  return mpsse;
206}
207
208/*
209 * Closes the device, deinitializes libftdi, and frees the MPSSE context
210 *pointer.
211 *
212 * @mpsse - MPSSE context pointer.
213 *
214 * Returns void.
215 */
216void Close(struct mpsse_context* mpsse) {
217  if (!mpsse)
218    return;
219
220  if (mpsse->opened) {
221    /* Shut these down only if initialization succeeded before. */
222    ftdi_set_bitmode(&mpsse->ftdi, 0, BITMODE_RESET);
223    ftdi_usb_close(&mpsse->ftdi);
224  }
225  ftdi_deinit(&mpsse->ftdi);
226  free(mpsse);
227}
228
229/* Enables bit-wise data transfers.
230 * Must be called after MPSSE() / Open() / OpenIndex().
231 *
232 * Returns void.
233 */
234void EnableBitmode(struct mpsse_context* mpsse, int tf) {
235  if (is_valid_context(mpsse)) {
236    if (tf) {
237      mpsse->tx |= MPSSE_BITMODE;
238      mpsse->rx |= MPSSE_BITMODE;
239      mpsse->txrx |= MPSSE_BITMODE;
240    } else {
241      mpsse->tx &= ~MPSSE_BITMODE;
242      mpsse->rx &= ~MPSSE_BITMODE;
243      mpsse->txrx &= ~MPSSE_BITMODE;
244    }
245  }
246}
247
248/*
249 * Sets the appropriate transmit and receive commands based on the requested
250 *mode and byte order.
251 *
252 * @mpsse     - MPSSE context pointer.
253 * @endianess - MPSSE_MSB or MPSSE_LSB.
254 *
255 * Returns MPSSE_OK on success.
256 * Returns MPSSE_FAIL on failure.
257 */
258int SetMode(struct mpsse_context* mpsse, int endianess) {
259  int retval = MPSSE_OK, i = 0, setup_commands_size = 0;
260  uint8_t buf[CMD_SIZE] = {0};
261  uint8_t setup_commands[CMD_SIZE * MAX_SETUP_COMMANDS] = {0};
262
263  /* Do not call is_valid_context() here, as the FTDI chip may not be completely
264   * configured when SetMode is called */
265  if (mpsse) {
266    /* Read and write commands need to include endianess */
267    mpsse->tx = MPSSE_DO_WRITE | endianess;
268    mpsse->rx = MPSSE_DO_READ | endianess;
269    mpsse->txrx = MPSSE_DO_WRITE | MPSSE_DO_READ | endianess;
270
271    /* Clock, data out, chip select pins are outputs; all others are inputs. */
272    mpsse->tris = DEFAULT_TRIS;
273
274    /* Clock and chip select pins idle high; all others are low */
275    mpsse->pidle = mpsse->pstart = mpsse->pstop = DEFAULT_PORT;
276
277    /* During reads and writes the chip select pin is brought low */
278    mpsse->pstart &= ~CS;
279
280    /* Disable FTDI internal loopback */
281    SetLoopback(mpsse, 0);
282
283    /* Send ACKs by default */
284    SetAck(mpsse, ACK);
285
286    /* Ensure adaptive clock is disabled */
287    setup_commands[setup_commands_size++] = DISABLE_ADAPTIVE_CLOCK;
288
289    switch (mpsse->mode) {
290      case SPI0:
291        /* SPI mode 0 clock idles low */
292        mpsse->pidle &= ~SK;
293        mpsse->pstart &= ~SK;
294        mpsse->pstop &= ~SK;
295        /* SPI mode 0 propogates data on the falling edge and read data on the
296         * rising edge of the clock */
297        mpsse->tx |= MPSSE_WRITE_NEG;
298        mpsse->rx &= ~MPSSE_READ_NEG;
299        mpsse->txrx |= MPSSE_WRITE_NEG;
300        mpsse->txrx &= ~MPSSE_READ_NEG;
301        break;
302      case SPI3:
303        /* SPI mode 3 clock idles high */
304        mpsse->pidle |= SK;
305        mpsse->pstart |= SK;
306        /* Keep the clock low while the CS pin is brought high to ensure we
307         * don't accidentally clock out an extra bit */
308        mpsse->pstop &= ~SK;
309        /* SPI mode 3 propogates data on the falling edge and read data on the
310         * rising edge of the clock */
311        mpsse->tx |= MPSSE_WRITE_NEG;
312        mpsse->rx &= ~MPSSE_READ_NEG;
313        mpsse->txrx |= MPSSE_WRITE_NEG;
314        mpsse->txrx &= ~MPSSE_READ_NEG;
315        break;
316      case SPI1:
317        /* SPI mode 1 clock idles low */
318        mpsse->pidle &= ~SK;
319        /* Since this mode idles low, the start condition should ensure that the
320         * clock is low */
321        mpsse->pstart &= ~SK;
322        /* Even though we idle low in this mode, we need to keep the clock line
323         * high when we set the CS pin high to prevent
324         * an unintended clock cycle from being sent by the FT2232. This way,
325         * the clock goes high, but does not go low until
326         * after the CS pin goes high.
327         */
328        mpsse->pstop |= SK;
329        /* Data read on falling clock edge */
330        mpsse->rx |= MPSSE_READ_NEG;
331        mpsse->tx &= ~MPSSE_WRITE_NEG;
332        mpsse->txrx |= MPSSE_READ_NEG;
333        mpsse->txrx &= ~MPSSE_WRITE_NEG;
334        break;
335      case SPI2:
336        /* SPI 2 clock idles high */
337        mpsse->pidle |= SK;
338        mpsse->pstart |= SK;
339        mpsse->pstop |= SK;
340        /* Data read on falling clock edge */
341        mpsse->rx |= MPSSE_READ_NEG;
342        mpsse->tx &= ~MPSSE_WRITE_NEG;
343        mpsse->txrx |= MPSSE_READ_NEG;
344        mpsse->txrx &= ~MPSSE_WRITE_NEG;
345        break;
346      case I2C:
347        /* I2C propogates data on the falling clock edge and reads data on the
348         * falling (or rising) clock edge */
349        mpsse->tx |= MPSSE_WRITE_NEG;
350        mpsse->rx &= ~MPSSE_READ_NEG;
351        /* In I2C, both the clock and the data lines idle high */
352        mpsse->pidle |= DO | DI;
353        /* I2C start bit == data line goes from high to low while clock line is
354         * high */
355        mpsse->pstart &= ~DO & ~DI;
356        /* I2C stop bit == data line goes from low to high while clock line is
357         * high - set data line low here, so the transition to the idle state
358         * triggers the stop condition. */
359        mpsse->pstop &= ~DO & ~DI;
360        /* Enable three phase clock to ensure that I2C data is available on both
361         * the rising and falling clock edges */
362        setup_commands[setup_commands_size++] = ENABLE_3_PHASE_CLOCK;
363        break;
364      case GPIO:
365        break;
366      default:
367        retval = MPSSE_FAIL;
368    }
369
370    /* Send any setup commands to the chip */
371    if (retval == MPSSE_OK && setup_commands_size > 0) {
372      retval = raw_write(mpsse, setup_commands, setup_commands_size);
373    }
374
375    if (retval == MPSSE_OK) {
376      /* Set the idle pin states */
377      set_bits_low(mpsse, mpsse->pidle);
378
379      /* All GPIO pins are outputs, set low */
380      mpsse->trish = 0xFF;
381      mpsse->gpioh = 0x00;
382
383      buf[i++] = SET_BITS_HIGH;
384      buf[i++] = mpsse->gpioh;
385      buf[i++] = mpsse->trish;
386
387      retval = raw_write(mpsse, buf, i);
388    }
389  } else {
390    retval = MPSSE_FAIL;
391  }
392
393  return retval;
394}
395
396/*
397 * Sets the appropriate divisor for the desired clock frequency.
398 *
399 * @mpsse - MPSSE context pointer.
400 * @freq  - Desired clock frequency in hertz.
401 *
402 * Returns MPSSE_OK on success.
403 * Returns MPSSE_FAIL on failure.
404 */
405int SetClock(struct mpsse_context* mpsse, uint32_t freq) {
406  int retval = MPSSE_FAIL;
407  uint32_t system_clock = 0;
408  uint16_t divisor = 0;
409  uint8_t buf[CMD_SIZE] = {0};
410
411  /* Do not call is_valid_context() here, as the FTDI chip may not be completely
412   * configured when SetClock is called */
413  if (mpsse) {
414    if (freq > SIX_MHZ) {
415      buf[0] = TCK_X5;
416      system_clock = SIXTY_MHZ;
417    } else {
418      buf[0] = TCK_D5;
419      system_clock = TWELVE_MHZ;
420    }
421
422    if (raw_write(mpsse, buf, 1) == MPSSE_OK) {
423      if (freq <= 0) {
424        divisor = 0xFFFF;
425      } else {
426        divisor = freq2div(system_clock, freq);
427      }
428
429      buf[0] = TCK_DIVISOR;
430      buf[1] = (divisor & 0xFF);
431      buf[2] = ((divisor >> 8) & 0xFF);
432
433      if (raw_write(mpsse, buf, 3) == MPSSE_OK) {
434        mpsse->clock = div2freq(system_clock, divisor);
435        retval = MPSSE_OK;
436      }
437    }
438  }
439
440  return retval;
441}
442
443/*
444 * Retrieves the last error string from libftdi.
445 *
446 * @mpsse - MPSSE context pointer.
447 *
448 * Returns a pointer to the last error string.
449 */
450const char* ErrorString(struct mpsse_context* mpsse) {
451  if (mpsse != NULL) {
452    return ftdi_get_error_string(&mpsse->ftdi);
453  }
454
455  return NULL_CONTEXT_ERROR_MSG;
456}
457
458/*
459 * Gets the currently configured clock rate.
460 *
461 * @mpsse - MPSSE context pointer.
462 *
463 * Returns the existing clock rate in hertz.
464 */
465int GetClock(struct mpsse_context* mpsse) {
466  int clock = 0;
467
468  if (is_valid_context(mpsse)) {
469    clock = mpsse->clock;
470  }
471
472  return clock;
473}
474
475/*
476 * Returns the vendor ID of the FTDI chip.
477 *
478 * @mpsse - MPSSE context pointer.
479 *
480 * Returns the integer value of the vendor ID.
481 */
482int GetVid(struct mpsse_context* mpsse) {
483  int vid = 0;
484
485  if (is_valid_context(mpsse)) {
486    vid = mpsse->vid;
487  }
488
489  return vid;
490}
491
492/*
493 * Returns the product ID of the FTDI chip.
494 *
495 * @mpsse - MPSSE context pointer.
496 *
497 * Returns the integer value of the product ID.
498 */
499int GetPid(struct mpsse_context* mpsse) {
500  int pid = 0;
501
502  if (is_valid_context(mpsse)) {
503    pid = mpsse->pid;
504  }
505
506  return pid;
507}
508
509/*
510 * Returns the description of the FTDI chip, if any.
511 *
512 * @mpsse - MPSSE context pointer.
513 *
514 * Returns the description of the FTDI chip.
515 */
516const char* GetDescription(struct mpsse_context* mpsse) {
517  char* description = NULL;
518
519  if (is_valid_context(mpsse)) {
520    description = mpsse->description;
521  }
522
523  return description;
524}
525
526/*
527 * Enable / disable internal loopback.
528 *
529 * @mpsse  - MPSSE context pointer.
530 * @enable - Zero to disable loopback, 1 to enable loopback.
531 *
532 * Returns MPSSE_OK on success.
533 * Returns MPSSE_FAIL on failure.
534 */
535int SetLoopback(struct mpsse_context* mpsse, int enable) {
536  uint8_t buf[1] = {0};
537  int retval = MPSSE_FAIL;
538
539  if (is_valid_context(mpsse)) {
540    if (enable) {
541      buf[0] = LOOPBACK_START;
542    } else {
543      buf[0] = LOOPBACK_END;
544    }
545
546    retval = raw_write(mpsse, buf, 1);
547  }
548
549  return retval;
550}
551
552/*
553 * Sets the idle state of the chip select pin. CS idles high by default.
554 *
555 * @mpsse - MPSSE context pointer.
556 * @idle  - Set to 1 to idle high, 0 to idle low.
557 *
558 * Returns void.
559 */
560void SetCSIdle(struct mpsse_context* mpsse, int idle) {
561  if (is_valid_context(mpsse)) {
562    if (idle > 0) {
563      /* Chip select idles high, active low */
564      mpsse->pidle |= CS;
565      mpsse->pstop |= CS;
566      mpsse->pstart &= ~CS;
567    } else {
568      /* Chip select idles low, active high */
569      mpsse->pidle &= ~CS;
570      mpsse->pstop &= ~CS;
571      mpsse->pstart |= CS;
572    }
573  }
574
575  return;
576}
577
578/*
579 * Enables or disables flushing of the FTDI chip's RX buffers after each read
580 *operation.
581 * Flushing is disable by default.
582 *
583 * @mpsse - MPSSE context pointer.
584 * @tf    - Set to 1 to enable flushing, or 0 to disable flushing.
585 *
586 * Returns void.
587 */
588void FlushAfterRead(struct mpsse_context* mpsse, int tf) {
589  mpsse->flush_after_read = tf;
590  return;
591}
592
593/*
594 * Send data start condition.
595 *
596 * @mpsse - MPSSE context pointer.
597 *
598 * Returns MPSSE_OK on success.
599 * Returns MPSSE_FAIL on failure.
600 */
601int Start(struct mpsse_context* mpsse) {
602  int status = MPSSE_OK;
603
604  if (is_valid_context(mpsse)) {
605    if (mpsse->mode == I2C && mpsse->status == STARTED) {
606      /* Set the default pin states while the clock is low since this is an I2C
607       * repeated start condition */
608      status |= set_bits_low(mpsse, (mpsse->pidle & ~SK));
609
610      /* Make sure the pins are in their default idle state */
611      status |= set_bits_low(mpsse, mpsse->pidle);
612    }
613
614    /* Set the start condition */
615    status |= set_bits_low(mpsse, mpsse->pstart);
616
617    /*
618     * Hackish work around to properly support SPI mode 3.
619     * SPI3 clock idles high, but needs to be set low before sending out
620     * data to prevent unintenteded clock glitches from the FT2232.
621     */
622    if (mpsse->mode == SPI3) {
623      status |= set_bits_low(mpsse, (mpsse->pstart & ~SK));
624    }
625    /*
626     * Hackish work around to properly support SPI mode 1.
627     * SPI1 clock idles low, but needs to be set high before sending out
628     * data to preven unintended clock glitches from the FT2232.
629     */
630    else if (mpsse->mode == SPI1) {
631      status |= set_bits_low(mpsse, (mpsse->pstart | SK));
632    }
633
634    mpsse->status = STARTED;
635  } else {
636    status = MPSSE_FAIL;
637    mpsse->status = STOPPED;
638  }
639
640  return status;
641}
642
643/*
644 * Performs a bit-wise write of up to 8 bits at a time.
645 *
646 * @mpsse - MPSSE context pointer.
647 * @bits  - A byte containing the desired bits to write.
648 * @size  - The number of bits from the 'bits' byte to write.
649 *
650 * Returns MPSSE_OK on success, MPSSE_FAIL on failure.
651 */
652int WriteBits(struct mpsse_context* mpsse, char bits, size_t size) {
653  uint8_t data[8] = {0};
654  size_t i = 0;
655  int retval = MPSSE_OK;
656
657  if (size > sizeof(data)) {
658    size = sizeof(data);
659  }
660
661  /* Convert each bit in bits to an array of bytes */
662  for (i = 0; i < size; i++) {
663    if (bits & (1 << i)) {
664      /* Be sure to honor endianess */
665      if (mpsse->endianess == LSB) {
666        data[i] = '\xFF';
667      } else {
668        data[size - i - 1] = '\xFF';
669      }
670    }
671  }
672
673  /* Enable bit mode before writing, then disable it afterwards. */
674  EnableBitmode(mpsse, 1);
675  retval = Write(mpsse, data, size);
676  EnableBitmode(mpsse, 0);
677
678  return retval;
679}
680
681/*
682 * Send data out via the selected serial protocol.
683 *
684 * @mpsse - MPSSE context pointer.
685 * @data  - Buffer of data to send.
686 * @size  - Size of data.
687 *
688 * Returns MPSSE_OK on success.
689 * Returns MPSSE_FAIL on failure.
690 */
691int Write(struct mpsse_context* mpsse, const void* vdata, int size) {
692  const uint8_t* data = vdata;
693  uint8_t* buf = NULL;
694  int retval = MPSSE_FAIL, buf_size = 0, txsize = 0, n = 0;
695
696  if (is_valid_context(mpsse)) {
697    if (mpsse->mode) {
698      while (n < size) {
699        txsize = size - n;
700        if (txsize > mpsse->xsize) {
701          txsize = mpsse->xsize;
702        }
703
704        /*
705         * For I2C we need to send each byte individually so that we can
706         * read back each individual ACK bit, so set the transmit size to 1.
707         */
708        if (mpsse->mode == I2C) {
709          txsize = 1;
710        }
711
712        buf = build_block_buffer(mpsse, mpsse->tx, data + n, txsize, &buf_size);
713        if (buf) {
714          retval = raw_write(mpsse, buf, buf_size);
715          n += txsize;
716          free(buf);
717
718          if (retval == MPSSE_FAIL) {
719            break;
720          }
721
722          /* Read in the ACK bit and store it in mpsse->rack */
723          if (mpsse->mode == I2C) {
724            raw_read(mpsse, (uint8_t*)&mpsse->rack, 1);
725          }
726        } else {
727          break;
728        }
729      }
730    }
731
732    if (retval == MPSSE_OK && n == size) {
733      retval = MPSSE_OK;
734    }
735  }
736
737  return retval;
738}
739
740/* Performs a read. For internal use only; see Read() and ReadBits(). */
741static uint8_t* InternalRead(struct mpsse_context* mpsse, int size) {
742  uint8_t *data = NULL, *buf = NULL;
743  uint8_t sbuf[SPI_RW_SIZE] = {0};
744  int n = 0, rxsize = 0, data_size = 0, retval = 0;
745
746  if (is_valid_context(mpsse)) {
747    if (mpsse->mode) {
748      buf = malloc(size);
749      if (buf) {
750        memset(buf, 0, size);
751
752        while (n < size) {
753          rxsize = size - n;
754          if (rxsize > mpsse->xsize) {
755            rxsize = mpsse->xsize;
756          }
757
758          data = build_block_buffer(mpsse, mpsse->rx, sbuf, rxsize, &data_size);
759          if (data) {
760            retval = raw_write(mpsse, data, data_size);
761            free(data);
762
763            if (retval == MPSSE_OK) {
764              n += raw_read(mpsse, buf + n, rxsize);
765            } else {
766              break;
767            }
768          } else {
769            break;
770          }
771        }
772      }
773    }
774  }
775
776  return buf;
777}
778
779/*
780 * Reads data over the selected serial protocol.
781 *
782 * @mpsse - MPSSE context pointer.
783 * @size  - Number of bytes to read.
784 *
785 * Returns a pointer to the read data on success.
786 * Returns NULL on failure.
787 */
788#ifdef SWIGPYTHON
789swig_string_data Read(struct mpsse_context* mpsse, int size)
790#else
791uint8_t* Read(struct mpsse_context* mpsse, int size)
792#endif
793{
794  uint8_t* buf = NULL;
795
796  buf = InternalRead(mpsse, size);
797
798#ifdef SWIGPYTHON
799  swig_string_data sdata = {0};
800  sdata.size = size;
801  sdata.data = buf;
802  return sdata;
803#else
804  return buf;
805#endif
806}
807
808/*
809 * Performs a bit-wise read of up to 8 bits.
810 *
811 * @mpsse - MPSSE context pointer.
812 * @size  - Number of bits to read.
813 *
814 * Returns an 8-bit byte containing the read bits.
815 */
816char ReadBits(struct mpsse_context* mpsse, int size) {
817  char bits = 0;
818  uint8_t* rdata = NULL;
819
820  if (size > 8) {
821    size = 8;
822  }
823
824  EnableBitmode(mpsse, 1);
825  rdata = InternalRead(mpsse, size);
826  EnableBitmode(mpsse, 0);
827
828  if (rdata) {
829    /* The last byte in rdata will have all the read bits set or unset as
830     * needed. */
831    bits = rdata[size - 1];
832
833    if (mpsse->endianess == MSB) {
834      /*
835       * In MSB mode, bits are sifted in from the left. If less than 8 bits were
836       * read, we need to shift them left accordingly.
837       */
838      bits = bits << (8 - size);
839    } else if (mpsse->endianess == LSB) {
840      /*
841       * In LSB mode, bits are shifted in from the right. If less than 8 bits
842       * were
843       * read, we need to shift them right accordingly.
844       */
845      bits = bits >> (8 - size);
846    }
847
848    free(rdata);
849  }
850
851  return bits;
852}
853
854/*
855 * Reads and writes data over the selected serial protocol (SPI only).
856 *
857 * @mpsse - MPSSE context pointer.
858 * @data  - Buffer containing bytes to write.
859 * @size  - Number of bytes to transfer.
860 *
861 * Returns a pointer to the read data on success.
862 * Returns NULL on failure.
863 */
864#ifdef SWIGPYTHON
865swig_string_data Transfer(struct mpsse_context* mpsse, char* data, int size)
866#else
867uint8_t* Transfer(struct mpsse_context* mpsse, uint8_t* data, int size)
868#endif
869{
870  uint8_t *txdata = NULL, *buf = NULL;
871  int n = 0, data_size = 0, rxsize = 0, retval = 0;
872
873  if (is_valid_context(mpsse)) {
874    /* Make sure we're configured for one of the SPI modes */
875    if (mpsse->mode >= SPI0 && mpsse->mode <= SPI3) {
876      buf = malloc(size);
877      if (buf) {
878        memset(buf, 0, size);
879
880        while (n < size) {
881          /* When sending and recieving, FTDI chips don't seem to like large
882           * data blocks. Limit the size of each block to SPI_TRANSFER_SIZE */
883          rxsize = size - n;
884          if (rxsize > SPI_TRANSFER_SIZE) {
885            rxsize = SPI_TRANSFER_SIZE;
886          }
887
888          txdata =
889              build_block_buffer(mpsse, mpsse->txrx, data + n,
890                                 rxsize, &data_size);
891          if (txdata) {
892            retval = raw_write(mpsse, txdata, data_size);
893            free(txdata);
894
895            if (retval == MPSSE_OK) {
896              n += raw_read(mpsse, (buf + n), rxsize);
897            } else {
898              break;
899            }
900          } else {
901            break;
902          }
903        }
904      }
905    }
906  }
907
908#ifdef SWIGPYTHON
909  swig_string_data sdata = {0};
910  sdata.size = n;
911  sdata.data = (char*)buf;
912  return sdata;
913#else
914  return buf;
915#endif
916}
917
918/*
919 * Returns the last received ACK bit.
920 *
921 * @mpsse - MPSSE context pointer.
922 *
923 * Returns either an ACK (0) or a NACK (1).
924 */
925int GetAck(struct mpsse_context* mpsse) {
926  int ack = 0;
927
928  if (is_valid_context(mpsse)) {
929    ack = (mpsse->rack & 0x01);
930  }
931
932  return ack;
933}
934
935/*
936 * Sets the transmitted ACK bit.
937 *
938 * @mpsse - MPSSE context pointer.
939 * @ack   - 0 to send ACKs, 1 to send NACKs.
940 *
941 * Returns void.
942 */
943void SetAck(struct mpsse_context* mpsse, int ack) {
944  if (is_valid_context(mpsse)) {
945    if (ack == NACK) {
946      mpsse->tack = 0xFF;
947    } else {
948      mpsse->tack = 0x00;
949    }
950  }
951
952  return;
953}
954
955/*
956 * Causes libmpsse to send ACKs after each read byte in I2C mode.
957 *
958 * @mpsse - MPSSE context pointer.
959 *
960 * Returns void.
961 */
962void SendAcks(struct mpsse_context* mpsse) {
963  return SetAck(mpsse, ACK);
964}
965
966/*
967 * Causes libmpsse to send NACKs after each read byte in I2C mode.
968 *
969 * @mpsse - MPSSE context pointer.
970 *
971 * Returns void.
972 */
973void SendNacks(struct mpsse_context* mpsse) {
974  return SetAck(mpsse, NACK);
975}
976
977/*
978 * Send data stop condition.
979 *
980 * @mpsse - MPSSE context pointer.
981 *
982 * Returns MPSSE_OK on success.
983 * Returns MPSSE_FAIL on failure.
984 */
985int Stop(struct mpsse_context* mpsse) {
986  int retval = MPSSE_OK;
987
988  if (is_valid_context(mpsse)) {
989    /* In I2C mode, we need to ensure that the data line goes low while the
990     * clock line is low to avoid sending an inadvertent start condition */
991    if (mpsse->mode == I2C) {
992      retval |= set_bits_low(mpsse, (mpsse->pidle & ~DO & ~SK));
993    }
994
995    /* Send the stop condition */
996    retval |= set_bits_low(mpsse, mpsse->pstop);
997
998    if (retval == MPSSE_OK) {
999      /* Restore the pins to their idle states */
1000      retval |= set_bits_low(mpsse, mpsse->pidle);
1001    }
1002
1003    mpsse->status = STOPPED;
1004  } else {
1005    retval = MPSSE_FAIL;
1006    mpsse->status = STOPPED;
1007  }
1008
1009  return retval;
1010}
1011
1012/*
1013 * Sets the specified pin high.
1014 *
1015 * @mpsse - MPSSE context pointer.
1016 * @pin   - Pin number to set high.
1017 *
1018 * Returns MPSSE_OK on success.
1019 * Returns MPSSE_FAIL on failure.
1020 */
1021int PinHigh(struct mpsse_context* mpsse, int pin) {
1022  int retval = MPSSE_FAIL;
1023
1024  if (is_valid_context(mpsse)) {
1025    retval = gpio_write(mpsse, pin, HIGH);
1026  }
1027
1028  return retval;
1029}
1030
1031/*
1032 * Sets the specified pin low.
1033 *
1034 * @mpsse - MPSSE context pointer.
1035 * @pin   - Pin number to set low.
1036 *
1037 * Returns MPSSE_OK on success.
1038 * Returns MPSSE_FAIL on failure.
1039 */
1040int PinLow(struct mpsse_context* mpsse, int pin) {
1041  int retval = MPSSE_FAIL;
1042
1043  if (is_valid_context(mpsse)) {
1044    retval = gpio_write(mpsse, pin, LOW);
1045  }
1046
1047  return retval;
1048}
1049
1050/*
1051 * Sets the input/output direction of all pins. For use in BITBANG mode only.
1052 *
1053 * @mpsse     - MPSSE context pointer.
1054 * @direction - Byte indicating input/output direction of each bit.  1 is out.
1055 *
1056 * Returns MPSSE_OK if direction could be set, MPSSE_FAIL otherwise.
1057 */
1058int SetDirection(struct mpsse_context* mpsse, uint8_t direction) {
1059  int retval = MPSSE_FAIL;
1060
1061  if (is_valid_context(mpsse)) {
1062    if (mpsse->mode == BITBANG) {
1063      if (ftdi_set_bitmode(&mpsse->ftdi, direction, BITMODE_BITBANG) == 0) {
1064        retval = MPSSE_OK;
1065      }
1066    }
1067  }
1068
1069  return retval;
1070}
1071
1072/*
1073 * Sets the input/output value of all pins. For use in BITBANG mode only.
1074 *
1075 * @mpsse - MPSSE context pointer.
1076 * @data  - Byte indicating bit hi/low value of each bit.
1077 *
1078 * Returns MPSSE_OK if direction could be set, MPSSE_FAIL otherwise.
1079 */
1080int WritePins(struct mpsse_context* mpsse, uint8_t data) {
1081  int retval = MPSSE_FAIL;
1082
1083  if (is_valid_context(mpsse)) {
1084    if (mpsse->mode == BITBANG) {
1085      if (ftdi_write_data(&mpsse->ftdi, &data, 1) == 0) {
1086        retval = MPSSE_OK;
1087      }
1088    }
1089  }
1090
1091  return retval;
1092}
1093
1094/*
1095 * Reads the state of the chip's pins. For use in BITBANG mode only.
1096 *
1097 * @mpsse - MPSSE context pointer.
1098 *
1099 * Returns a byte with the corresponding pin's bits set to 1 or 0.
1100 */
1101int ReadPins(struct mpsse_context* mpsse) {
1102  uint8_t val = 0;
1103
1104  if (is_valid_context(mpsse)) {
1105    ftdi_read_pins((struct ftdi_context*)&mpsse->ftdi, (uint8_t*)&val);
1106  }
1107
1108  return (int)val;
1109}
1110
1111/*
1112 * Checks if a specific pin is high or low. For use in BITBANG mode only.
1113 *
1114 * @mpsse - MPSSE context pointer.
1115 * @pin   - The pin number.
1116 * @state - The state of the pins, as returned by ReadPins.
1117 *          If set to -1, ReadPins will automatically be called.
1118 *
1119 * Returns a 1 if the pin is high, 0 if the pin is low.
1120 */
1121int PinState(struct mpsse_context* mpsse, int pin, int state) {
1122  if (state == -1) {
1123    state = ReadPins(mpsse);
1124  }
1125
1126  /* If not in bitbang mode, the specified pin should be one of GPIOLx. Convert
1127   * these defines into an absolute pin number. */
1128  if (mpsse->mode != BITBANG) {
1129    pin += NUM_GPIOL_PINS;
1130  }
1131
1132  return ((state & (1 << pin)) >> pin);
1133}
1134
1135/*
1136 * Places all I/O pins into a tristate mode.
1137 *
1138 * @mpsse - MPSSE context pointer.
1139 *
1140 * Returns MPSSE_OK on success, MPSSE_FAIL on failure.
1141 */
1142int Tristate(struct mpsse_context* mpsse) {
1143  uint8_t cmd[CMD_SIZE] = {0};
1144
1145  /* Tristate the all I/O pins (FT232H only) */
1146  cmd[0] = TRISTATE_IO;
1147  cmd[1] = 0xFF;
1148  cmd[2] = 0xFF;
1149
1150  return raw_write(mpsse, cmd, sizeof(cmd));
1151}
1152