• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 */
33 struct 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  */
MPSSE(enum modes mode,int freq,int endianess)58 struct 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, freq,
64                  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  */
Open(int vid,int pid,enum modes mode,int freq,int endianess,int interface,const char * description,const char * serial)88 struct 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  */
OpenIndex(int vid,int pid,enum modes mode,int freq,int endianess,int interface,const char * description,const char * serial,int index)117 struct 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  */
Close(struct mpsse_context * mpsse)216 void 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  */
EnableBitmode(struct mpsse_context * mpsse,int tf)234 void 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  */
SetMode(struct mpsse_context * mpsse,int endianess)258 int 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  */
SetClock(struct mpsse_context * mpsse,uint32_t freq)405 int 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  */
ErrorString(struct mpsse_context * mpsse)450 const 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  */
GetClock(struct mpsse_context * mpsse)465 int 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  */
GetVid(struct mpsse_context * mpsse)482 int 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  */
GetPid(struct mpsse_context * mpsse)499 int 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  */
GetDescription(struct mpsse_context * mpsse)516 const 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  */
SetLoopback(struct mpsse_context * mpsse,int enable)535 int 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  */
SetCSIdle(struct mpsse_context * mpsse,int idle)560 void 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  */
FlushAfterRead(struct mpsse_context * mpsse,int tf)588 void 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  */
Start(struct mpsse_context * mpsse)601 int 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  */
WriteBits(struct mpsse_context * mpsse,char bits,size_t size)652 int 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  */
Write(struct mpsse_context * mpsse,const void * vdata,int size)691 int 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(). */
InternalRead(struct mpsse_context * mpsse,int size)741 static 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
Read(struct mpsse_context * mpsse,int size)789 swig_string_data Read(struct mpsse_context* mpsse, int size)
790 #else
791 uint8_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  */
ReadBits(struct mpsse_context * mpsse,int size)816 char 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
Transfer(struct mpsse_context * mpsse,char * data,int size)865 swig_string_data Transfer(struct mpsse_context* mpsse, char* data, int size)
866 #else
867 uint8_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 = build_block_buffer(mpsse, mpsse->txrx, data + n, rxsize,
889                                       &data_size);
890           if (txdata) {
891             retval = raw_write(mpsse, txdata, data_size);
892             free(txdata);
893 
894             if (retval == MPSSE_OK) {
895               n += raw_read(mpsse, (buf + n), rxsize);
896             } else {
897               break;
898             }
899           } else {
900             break;
901           }
902         }
903       }
904     }
905   }
906 
907 #ifdef SWIGPYTHON
908   swig_string_data sdata = {0};
909   sdata.size = n;
910   sdata.data = (char*)buf;
911   return sdata;
912 #else
913   return buf;
914 #endif
915 }
916 
917 /*
918  * Returns the last received ACK bit.
919  *
920  * @mpsse - MPSSE context pointer.
921  *
922  * Returns either an ACK (0) or a NACK (1).
923  */
GetAck(struct mpsse_context * mpsse)924 int GetAck(struct mpsse_context* mpsse) {
925   int ack = 0;
926 
927   if (is_valid_context(mpsse)) {
928     ack = (mpsse->rack & 0x01);
929   }
930 
931   return ack;
932 }
933 
934 /*
935  * Sets the transmitted ACK bit.
936  *
937  * @mpsse - MPSSE context pointer.
938  * @ack   - 0 to send ACKs, 1 to send NACKs.
939  *
940  * Returns void.
941  */
SetAck(struct mpsse_context * mpsse,int ack)942 void SetAck(struct mpsse_context* mpsse, int ack) {
943   if (is_valid_context(mpsse)) {
944     if (ack == NACK) {
945       mpsse->tack = 0xFF;
946     } else {
947       mpsse->tack = 0x00;
948     }
949   }
950 
951   return;
952 }
953 
954 /*
955  * Causes libmpsse to send ACKs after each read byte in I2C mode.
956  *
957  * @mpsse - MPSSE context pointer.
958  *
959  * Returns void.
960  */
SendAcks(struct mpsse_context * mpsse)961 void SendAcks(struct mpsse_context* mpsse) {
962   return SetAck(mpsse, ACK);
963 }
964 
965 /*
966  * Causes libmpsse to send NACKs after each read byte in I2C mode.
967  *
968  * @mpsse - MPSSE context pointer.
969  *
970  * Returns void.
971  */
SendNacks(struct mpsse_context * mpsse)972 void SendNacks(struct mpsse_context* mpsse) {
973   return SetAck(mpsse, NACK);
974 }
975 
976 /*
977  * Send data stop condition.
978  *
979  * @mpsse - MPSSE context pointer.
980  *
981  * Returns MPSSE_OK on success.
982  * Returns MPSSE_FAIL on failure.
983  */
Stop(struct mpsse_context * mpsse)984 int Stop(struct mpsse_context* mpsse) {
985   int retval = MPSSE_OK;
986 
987   if (is_valid_context(mpsse)) {
988     /* In I2C mode, we need to ensure that the data line goes low while the
989      * clock line is low to avoid sending an inadvertent start condition */
990     if (mpsse->mode == I2C) {
991       retval |= set_bits_low(mpsse, (mpsse->pidle & ~DO & ~SK));
992     }
993 
994     /* Send the stop condition */
995     retval |= set_bits_low(mpsse, mpsse->pstop);
996 
997     if (retval == MPSSE_OK) {
998       /* Restore the pins to their idle states */
999       retval |= set_bits_low(mpsse, mpsse->pidle);
1000     }
1001 
1002     mpsse->status = STOPPED;
1003   } else {
1004     retval = MPSSE_FAIL;
1005     mpsse->status = STOPPED;
1006   }
1007 
1008   return retval;
1009 }
1010 
1011 /*
1012  * Sets the specified pin high.
1013  *
1014  * @mpsse - MPSSE context pointer.
1015  * @pin   - Pin number to set high.
1016  *
1017  * Returns MPSSE_OK on success.
1018  * Returns MPSSE_FAIL on failure.
1019  */
PinHigh(struct mpsse_context * mpsse,int pin)1020 int PinHigh(struct mpsse_context* mpsse, int pin) {
1021   int retval = MPSSE_FAIL;
1022 
1023   if (is_valid_context(mpsse)) {
1024     retval = gpio_write(mpsse, pin, HIGH);
1025   }
1026 
1027   return retval;
1028 }
1029 
1030 /*
1031  * Sets the specified pin low.
1032  *
1033  * @mpsse - MPSSE context pointer.
1034  * @pin   - Pin number to set low.
1035  *
1036  * Returns MPSSE_OK on success.
1037  * Returns MPSSE_FAIL on failure.
1038  */
PinLow(struct mpsse_context * mpsse,int pin)1039 int PinLow(struct mpsse_context* mpsse, int pin) {
1040   int retval = MPSSE_FAIL;
1041 
1042   if (is_valid_context(mpsse)) {
1043     retval = gpio_write(mpsse, pin, LOW);
1044   }
1045 
1046   return retval;
1047 }
1048 
1049 /*
1050  * Sets the input/output direction of all pins. For use in BITBANG mode only.
1051  *
1052  * @mpsse     - MPSSE context pointer.
1053  * @direction - Byte indicating input/output direction of each bit.  1 is out.
1054  *
1055  * Returns MPSSE_OK if direction could be set, MPSSE_FAIL otherwise.
1056  */
SetDirection(struct mpsse_context * mpsse,uint8_t direction)1057 int SetDirection(struct mpsse_context* mpsse, uint8_t direction) {
1058   int retval = MPSSE_FAIL;
1059 
1060   if (is_valid_context(mpsse)) {
1061     if (mpsse->mode == BITBANG) {
1062       if (ftdi_set_bitmode(&mpsse->ftdi, direction, BITMODE_BITBANG) == 0) {
1063         retval = MPSSE_OK;
1064       }
1065     }
1066   }
1067 
1068   return retval;
1069 }
1070 
1071 /*
1072  * Sets the input/output value of all pins. For use in BITBANG mode only.
1073  *
1074  * @mpsse - MPSSE context pointer.
1075  * @data  - Byte indicating bit hi/low value of each bit.
1076  *
1077  * Returns MPSSE_OK if direction could be set, MPSSE_FAIL otherwise.
1078  */
WritePins(struct mpsse_context * mpsse,uint8_t data)1079 int WritePins(struct mpsse_context* mpsse, uint8_t data) {
1080   int retval = MPSSE_FAIL;
1081 
1082   if (is_valid_context(mpsse)) {
1083     if (mpsse->mode == BITBANG) {
1084       if (ftdi_write_data(&mpsse->ftdi, &data, 1) == 0) {
1085         retval = MPSSE_OK;
1086       }
1087     }
1088   }
1089 
1090   return retval;
1091 }
1092 
1093 /*
1094  * Reads the state of the chip's pins. For use in BITBANG mode only.
1095  *
1096  * @mpsse - MPSSE context pointer.
1097  *
1098  * Returns a byte with the corresponding pin's bits set to 1 or 0.
1099  */
ReadPins(struct mpsse_context * mpsse)1100 int ReadPins(struct mpsse_context* mpsse) {
1101   uint8_t val = 0;
1102 
1103   if (is_valid_context(mpsse)) {
1104     ftdi_read_pins((struct ftdi_context*)&mpsse->ftdi, (uint8_t*)&val);
1105   }
1106 
1107   return (int)val;
1108 }
1109 
1110 /*
1111  * Checks if a specific pin is high or low. For use in BITBANG mode only.
1112  *
1113  * @mpsse - MPSSE context pointer.
1114  * @pin   - The pin number.
1115  * @state - The state of the pins, as returned by ReadPins.
1116  *          If set to -1, ReadPins will automatically be called.
1117  *
1118  * Returns a 1 if the pin is high, 0 if the pin is low.
1119  */
PinState(struct mpsse_context * mpsse,int pin,int state)1120 int PinState(struct mpsse_context* mpsse, int pin, int state) {
1121   if (state == -1) {
1122     state = ReadPins(mpsse);
1123   }
1124 
1125   /* If not in bitbang mode, the specified pin should be one of GPIOLx. Convert
1126    * these defines into an absolute pin number. */
1127   if (mpsse->mode != BITBANG) {
1128     pin += NUM_GPIOL_PINS;
1129   }
1130 
1131   return ((state & (1 << pin)) >> pin);
1132 }
1133 
1134 /*
1135  * Places all I/O pins into a tristate mode.
1136  *
1137  * @mpsse - MPSSE context pointer.
1138  *
1139  * Returns MPSSE_OK on success, MPSSE_FAIL on failure.
1140  */
Tristate(struct mpsse_context * mpsse)1141 int Tristate(struct mpsse_context* mpsse) {
1142   uint8_t cmd[CMD_SIZE] = {0};
1143 
1144   /* Tristate the all I/O pins (FT232H only) */
1145   cmd[0] = TRISTATE_IO;
1146   cmd[1] = 0xFF;
1147   cmd[2] = 0xFF;
1148 
1149   return raw_write(mpsse, cmd, sizeof(cmd));
1150 }
1151