xref: /aosp_15_r20/external/flashrom/raiden_debug_spi.c (revision 0d6140be3aa665ecc836e8907834fcd3e3b018fc)
1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright 2014, Google Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are
9  * met:
10  *
11  *    * Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *    * Redistributions in binary form must reproduce the above
14  * copyright notice, this list of conditions and the following disclaimer
15  * in the documentation and/or other materials provided with the
16  * distribution.
17  *    * Neither the name of Google Inc. nor the names of its
18  * contributors may be used to endorse or promote products derived from
19  * this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Alternatively, this software may be distributed under the terms of the
34  * GNU General Public License ("GPL") version 2 as published by the Free
35  * Software Foundation.
36  */
37 
38 /*
39  * This SPI flash programming interface is designed to talk to a Chromium OS
40  * device over a Raiden USB connection.  The USB connection is routed to a
41  * microcontroller running an image compiled from:
42  *
43  *     https://chromium.googlesource.com/chromiumos/platform/ec
44  *
45  * The protocol for the USB-SPI bridge is implemented in the following files
46  * in that repository:
47  *
48  *     chip/stm32/usb_spi.h
49  *     chip/stm32/usb_spi.c
50  *
51  * bInterfaceProtocol determines which protocol is used by the USB SPI device.
52  *
53  *
54  * USB SPI Version 1:
55  *
56  *     SPI transactions of up to 62B in each direction with every command having
57  *     a response. The initial packet from host contains a 2B header indicating
58  *     write and read counts with an optional payload length equal to the write
59  *     count. The device will respond with a message that reports the 2B status
60  *     code and an optional payload response length equal to read count.
61  *
62  *
63  * Message Packets:
64  *
65  * Command First Packet (Host to Device):
66  *
67  *      USB SPI command, containing the number of bytes to write and read
68  *      and a payload of bytes to write.
69  *
70  *     +------------------+-----------------+------------------------+
71  *     | write count : 1B | read count : 1B | write payload : <= 62B |
72  *     +------------------+-----------------+------------------------+
73  *
74  *     write count:   1 byte, zero based count of bytes to write
75  *
76  *     read count:    1 byte, zero based count of bytes to read. Full duplex
77  *                    mode is enabled with UINT8_MAX
78  *
79  *     write payload: Up to 62 bytes of data to write to SPI, the total
80  *                    length of all TX packets must match write count.
81  *                    Due to data alignment constraints, this must be an
82  *                    even number of bytes unless this is the final packet.
83  *
84  * Response Packet (Device to Host):
85  *
86  *      USB SPI response, containing the status code and any bytes of the
87  *      read payload.
88  *
89  *     +-------------+-----------------------+
90  *     | status : 2B | read payload : <= 62B |
91  *     +-------------+-----------------------+
92  *
93  *     status: 2 byte status
94  *         0x0000: Success
95  *         0x0001: SPI timeout
96  *         0x0002: Busy, try again
97  *             This can happen if someone else has acquired the shared memory
98  *             buffer that the SPI driver uses as /dev/null
99  *         0x0003: Write count invalid (over 62 bytes)
100  *         0x0004: Read count invalid (over 62 bytes)
101  *         0x0005: The SPI bridge is disabled.
102  *         0x8000: Unknown error mask
103  *             The bottom 15 bits will contain the bottom 15 bits from the EC
104  *             error code.
105  *
106  *     read payload: Up to 62 bytes of data read from SPI, the total
107  *                   length of all RX packets must match read count
108  *                   unless an error status was returned. Due to data
109  *                   alignment constraints, this must be a even number
110  *                   of bytes unless this is the final packet.
111  *
112  *
113  * USB SPI Version 2:
114  *
115  *     USB SPI version 2 adds support for larger SPI transfers and reduces the
116  *     number of USB packets transferred. This improves performance when
117  *     writing or reading large chunks of memory from a device. A packet ID
118  *     field is used to distinguish the different packet types. Additional
119  *     packets have been included to query the device for its configuration
120  *     allowing the interface to be used on platforms with different SPI
121  *     limitations. It includes validation and a packet to recover from the
122  *     situations where USB packets are lost.
123  *
124  *     The USB SPI hosts which support packet version 2 are backwards compatible
125  *     and use the bInterfaceProtocol field to identify which type of target
126  *     they are connected to.
127  *
128  *
129  * Example: USB SPI request with 128 byte write and 0 byte read.
130  *
131  *      Packet #1 Host to Device:
132  *           packet id   = USB_SPI_PKT_ID_CMD_TRANSFER_START
133  *           write count = 128
134  *           read count  = 0
135  *           payload     = First 58 bytes from the write buffer,
136  *                            starting at byte 0 in the buffer
137  *           packet size = 64 bytes
138  *
139  *      Packet #2 Host to Device:
140  *           packet id   = USB_SPI_PKT_ID_CMD_TRANSFER_CONTINUE
141  *           data index  = 58
142  *           payload     = Next 60 bytes from the write buffer,
143  *                           starting at byte 58 in the buffer
144  *           packet size = 64 bytes
145  *
146  *      Packet #3 Host to Device:
147  *           packet id   = USB_SPI_PKT_ID_CMD_TRANSFER_CONTINUE
148  *           data index  = 118
149  *           payload     = Next 10 bytes from the write buffer,
150  *                           starting at byte 118 in the buffer
151  *           packet size = 14 bytes
152  *
153  *      Packet #4 Device to Host:
154  *           packet id   = USB_SPI_PKT_ID_RSP_TRANSFER_START
155  *           status code = status code from device
156  *           payload     = 0 bytes
157  *           packet size = 4 bytes
158  *
159  * Example: USB SPI request with 2 byte write and 100 byte read.
160  *
161  *      Packet #1 Host to Device:
162  *           packet id   = USB_SPI_PKT_ID_CMD_TRANSFER_START
163  *           write count = 2
164  *           read count  = 100
165  *           payload     = The 2 byte write buffer
166  *           packet size = 8 bytes
167  *
168  *      Packet #2 Device to Host:
169  *           packet id   = USB_SPI_PKT_ID_RSP_TRANSFER_START
170  *           status code = status code from device
171  *           payload     = First 60 bytes from the read buffer,
172  *                            starting at byte 0 in the buffer
173  *           packet size = 64 bytes
174  *
175  *      Packet #3 Device to Host:
176  *           packet id   = USB_SPI_PKT_ID_RSP_TRANSFER_CONTINUE
177  *           data index  = 60
178  *           payload     = Next 40 bytes from the read buffer,
179  *                           starting at byte 60 in the buffer
180  *           packet size = 44 bytes
181  *
182  *
183  * Message Packets:
184  *
185  * Command Start Packet (Host to Device):
186  *
187  *      Start of the USB SPI command, contains the number of bytes to write
188  *      and read on SPI and up to the first 58 bytes of write payload.
189  *      Longer writes will use the continue packets with packet id
190  *      USB_SPI_PKT_ID_CMD_TRANSFER_CONTINUE to transmit the remaining data.
191  *
192  *     +----------------+------------------+-----------------+---------------+
193  *     | packet id : 2B | write count : 2B | read count : 2B | w.p. : <= 58B |
194  *     +----------------+------------------+-----------------+---------------+
195  *
196  *     packet id:     2 byte enum defined by packet_id_type
197  *                    Valid values packet id = USB_SPI_PKT_ID_CMD_TRANSFER_START
198  *
199  *     write count:   2 byte, zero based count of bytes to write
200  *
201  *     read count:    2 byte, zero based count of bytes to read
202  *                    UINT16_MAX indicates full duplex mode with a read count
203  *                    equal to the write count.
204  *
205  *     write payload: Up to 58 bytes of data to write to SPI, the total
206  *                    length of all TX packets must match write count.
207  *                    Due to data alignment constraints, this must be an
208  *                    even number of bytes unless this is the final packet.
209  *
210  *
211  * Response Start Packet (Device to Host):
212  *
213  *      Start of the USB SPI response, contains the status code and up to
214  *      the first 60 bytes of read payload. Longer reads will use the
215  *      continue packets with packet id USB_SPI_PKT_ID_RSP_TRANSFER_CONTINUE
216  *      to transmit the remaining data.
217  *
218  *     +----------------+------------------+-----------------------+
219  *     | packet id : 2B | status code : 2B | read payload : <= 60B |
220  *     +----------------+------------------+-----------------------+
221  *
222  *     packet id:     2 byte enum defined by packet_id_type
223  *                    Valid values packet id = USB_SPI_PKT_ID_RSP_TRANSFER_START
224  *
225  *     status code: 2 byte status code
226  *         0x0000: Success
227  *         0x0001: SPI timeout
228  *         0x0002: Busy, try again
229  *             This can happen if someone else has acquired the shared memory
230  *             buffer that the SPI driver uses as /dev/null
231  *         0x0003: Write count invalid. The byte limit is platform specific
232  *             and is set during the configure USB SPI response.
233  *         0x0004: Read count invalid. The byte limit is platform specific
234  *             and is set during the configure USB SPI response.
235  *         0x0005: The SPI bridge is disabled.
236  *         0x0006: The RX continue packet's data index is invalid. This
237  *             can indicate a USB transfer failure to the device.
238  *         0x0007: The RX endpoint has received more data than write count.
239  *             This can indicate a USB transfer failure to the device.
240  *         0x0008: An unexpected packet arrived that the device could not
241  *             process.
242  *         0x0009: The device does not support full duplex mode.
243  *         0x8000: Unknown error mask
244  *             The bottom 15 bits will contain the bottom 15 bits from the EC
245  *             error code.
246  *
247  *     read payload: Up to 60 bytes of data read from SPI, the total
248  *                   length of all RX packets must match read count
249  *                   unless an error status was returned. Due to data
250  *                   alignment constraints, this must be a even number
251  *                   of bytes unless this is the final packet.
252  *
253  *
254  * Continue Packet (Bidirectional):
255  *
256  *      Continuation packet for the writes and read buffers. Both packets
257  *      follow the same format, a data index counts the number of bytes
258  *      previously transferred in the USB SPI transfer and a payload of bytes.
259  *
260  *     +----------------+-----------------+-------------------------------+
261  *     | packet id : 2B | data index : 2B | write / read payload : <= 60B |
262  *     +----------------+-----------------+-------------------------------+
263  *
264  *     packet id:     2 byte enum defined by packet_id_type
265  *                    The packet id has 2 values depending on direction:
266  *                    packet id = USB_SPI_PKT_ID_CMD_TRANSFER_CONTINUE
267  *                    indicates the packet is being transmitted from the host
268  *                    to the device and contains SPI write payload.
269  *                    packet id = USB_SPI_PKT_ID_RSP_TRANSFER_CONTINUE
270  *                    indicates the packet is being transmitted from the device
271  *                    to the host and contains SPI read payload.
272  *
273  *     data index:    The data index indicates the number of bytes in the
274  *                    read or write buffers that have already been transmitted.
275  *                    It is used to validate that no packets have been dropped
276  *                    and that the prior packets have been correctly decoded.
277  *                    This value corresponds to the offset bytes in the buffer
278  *                    to start copying the payload into.
279  *
280  *     read and write payload:
281  *                    Contains up to 60 bytes of payload data to transfer to
282  *                    the SPI write buffer or from the SPI read buffer.
283  *
284  *
285  * Command Get Configuration Packet (Host to Device):
286  *
287  *      Query the device to request its USB SPI configuration indicating
288  *      the number of bytes it can write and read.
289  *
290  *     +----------------+
291  *     | packet id : 2B |
292  *     +----------------+
293  *
294  *     packet id:     2 byte enum USB_SPI_PKT_ID_CMD_GET_USB_SPI_CONFIG
295  *
296  * Response Configuration Packet (Device to Host):
297  *
298  *      Response packet form the device to report the maximum write and
299  *      read size supported by the device.
300  *
301  *     +----------------+----------------+---------------+----------------+
302  *     | packet id : 2B | max write : 2B | max read : 2B | feature bitmap |
303  *     +----------------+----------------+---------------+----------------+
304  *
305  *     packet id:         2 byte enum USB_SPI_PKT_ID_RSP_USB_SPI_CONFIG
306  *
307  *     max write count:   2 byte count of the maximum number of bytes
308  *                        the device can write to SPI in one transaction.
309  *
310  *     max read count:    2 byte count of the maximum number of bytes
311  *                        the device can read from SPI in one transaction.
312  *
313  *     feature bitmap:    Bitmap of supported features.
314  *                        BIT(0): Full duplex SPI mode is supported
315  *                        BIT(1:15): Reserved for future use
316  *
317  * Command Restart Response Packet (Host to Device):
318  *
319  *      Command to restart the response transfer from the device. This enables
320  *      the host to recover from a lost packet when reading the response
321  *      without restarting the SPI transfer.
322  *
323  *     +----------------+
324  *     | packet id : 2B |
325  *     +----------------+
326  *
327  *     packet id:         2 byte enum USB_SPI_PKT_ID_CMD_RESTART_RESPONSE
328  *
329  * USB Error Codes:
330  *
331  * send_command return codes have the following format:
332  *
333  *     0x00000:         Status code success.
334  *     0x00001-0x0FFFF: Error code returned by the USB SPI device.
335  *     0x10001-0x1FFFF: Error code returned by the USB SPI host.
336  *     0x20001-0x20063  Lower bits store the positive value representation
337  *                      of the libusb_error enum. See the libusb documentation:
338  *                      http://libusb.sourceforge.net/api-1.0/group__misc.html
339  */
340 
341 #include "programmer.h"
342 #include "spi.h"
343 #include "usb_device.h"
344 
345 #include <libusb.h>
346 #include <stdbool.h>
347 #include <stdint.h>
348 #include <stdio.h>
349 #include <stdlib.h>
350 #include <string.h>
351 #include <unistd.h>
352 
353 /*
354  * Table is empty as raiden_debug_spi matches against the class and
355  * subclass of the connected USB devices, rather than looking for a
356  * device with a specific vid:pid.
357  */
358 static const struct dev_entry devs_raiden[] = {
359 	{0},
360 };
361 
362 #define GOOGLE_VID                  (0x18D1)
363 #define GOOGLE_RAIDEN_SPI_SUBCLASS  (0x51)
364 
365 enum {
366 	GOOGLE_RAIDEN_SPI_PROTOCOL_V1 = 0x01,
367 	GOOGLE_RAIDEN_SPI_PROTOCOL_V2 = 0x02,
368 };
369 
370 enum {
371 	/* The host failed to transfer the data with no libusb error. */
372 	USB_SPI_HOST_TX_BAD_TRANSFER      = 0x10001,
373 	/* The number of bytes written did not match expected. */
374 	USB_SPI_HOST_TX_WRITE_FAILURE     = 0x10002,
375 
376 	/* We did not receive the expected USB packet. */
377 	USB_SPI_HOST_RX_UNEXPECTED_PACKET = 0x11001,
378 	/* We received a continue packet with an invalid data index. */
379 	USB_SPI_HOST_RX_BAD_DATA_INDEX    = 0x11002,
380 	/* We received too much data. */
381 	USB_SPI_HOST_RX_DATA_OVERFLOW     = 0x11003,
382 	/* The number of bytes read did not match expected. */
383 	USB_SPI_HOST_RX_READ_FAILURE      = 0x11004,
384 
385 	/* We were unable to configure the device. */
386 	USB_SPI_HOST_INIT_FAILURE         = 0x12001,
387 };
388 
389 enum usb_spi_error {
390 	USB_SPI_SUCCESS                 = 0x0000,
391 	USB_SPI_TIMEOUT                 = 0x0001,
392 	USB_SPI_BUSY                    = 0x0002,
393 	USB_SPI_WRITE_COUNT_INVALID     = 0x0003,
394 	USB_SPI_READ_COUNT_INVALID      = 0x0004,
395 	USB_SPI_DISABLED                = 0x0005,
396 	/* The RX continue packet's data index is invalid. */
397 	USB_SPI_RX_BAD_DATA_INDEX       = 0x0006,
398 	/* The RX endpoint has received more data than write count. */
399 	USB_SPI_RX_DATA_OVERFLOW        = 0x0007,
400 	/* An unexpected packet arrived on the device. */
401 	USB_SPI_RX_UNEXPECTED_PACKET    = 0x0008,
402 	/* The device does not support full duplex mode. */
403 	USB_SPI_UNSUPPORTED_FULL_DUPLEX = 0x0009,
404 	USB_SPI_UNKNOWN_ERROR           = 0x8000,
405 };
406 
407 /* Corresponds with 'enum usb_spi_request' in,
408  * platform/cr50/chip/g/usb_spi.h and,
409  * platform/ec/chip/stm32/usb_spi.h.
410  */
411 enum raiden_debug_spi_request {
412 	RAIDEN_DEBUG_SPI_REQ_ENABLE           = 0x0000,
413 	RAIDEN_DEBUG_SPI_REQ_DISABLE          = 0x0001,
414 	RAIDEN_DEBUG_SPI_REQ_ENABLE_AP        = 0x0002,
415 	RAIDEN_DEBUG_SPI_REQ_ENABLE_EC        = 0x0003,
416 	RAIDEN_DEBUG_SPI_REQ_ENABLE_H1        = 0x0004,
417 	RAIDEN_DEBUG_SPI_REQ_RESET            = 0x0005,
418 	RAIDEN_DEBUG_SPI_REQ_BOOT_CFG         = 0x0006,
419 	RAIDEN_DEBUG_SPI_REQ_SOCKET           = 0x0007,
420 	RAIDEN_DEBUG_SPI_REQ_SIGNING_START    = 0x0008,
421 	RAIDEN_DEBUG_SPI_REQ_SIGNING_SIGN     = 0x0009,
422 	RAIDEN_DEBUG_SPI_REQ_ENABLE_AP_CUSTOM = 0x000a,
423 };
424 
425 /*
426  * Servo Micro has an error where it is capable of acknowledging USB packets
427  * without loading it into the USB endpoint buffers or triggering interrupts.
428  * See crbug.com/952494. Retry mechanisms have been implemented to recover
429  * from these rare failures allowing the process to continue.
430  */
431 #define WRITE_RETRY_ATTEMPTS      (3)
432 #define READ_RETRY_ATTEMPTS       (3)
433 #define GET_CONFIG_RETRY_ATTEMPTS (3)
434 #define RETRY_INTERVAL_US         (100 * 1000)
435 
436 /*
437  * This timeout is so large because the Raiden SPI timeout is 800ms.
438  */
439 #define TRANSFER_TIMEOUT_MS     (200 + 800)
440 
441 struct raiden_debug_spi_data {
442 	struct usb_device *dev;
443 	uint8_t in_ep;
444 	uint8_t out_ep;
445 	uint8_t protocol_version;
446 	/*
447 	 * Note: Due to bugs, flashrom does not always treat the max_data_write
448 	 * and max_data_read counts as the maximum packet size. As a result, we
449 	 * have to store a local copy of the actual max packet sizes and validate
450 	 * against it when performing transfers.
451 	 */
452 	uint16_t max_spi_write_count;
453 	uint16_t max_spi_read_count;
454 	struct spi_master *spi_config;
455 };
456 /*
457  * USB permits a maximum bulk transfer of 64B.
458  */
459 #define USB_MAX_PACKET_SIZE             (64)
460 #define PACKET_HEADER_SIZE              (2)
461 
462 /*
463  * All of the USB SPI packets have size equal to the max USB packet size of 64B
464  */
465 #define PAYLOAD_SIZE_V1                 (62)
466 
467 #define SPI_TRANSFER_V1_MAX             (PAYLOAD_SIZE_V1)
468 
469 /*
470  * Version 1 protocol specific attributes
471  */
472 
473 struct usb_spi_command_v1 {
474 	uint8_t write_count;
475 	/* UINT8_MAX indicates full duplex mode on compliant devices. */
476 	uint8_t read_count;
477 	uint8_t data[PAYLOAD_SIZE_V1];
478 } __attribute__((packed));
479 
480 struct usb_spi_response_v1 {
481 	uint16_t status_code;
482 	uint8_t data[PAYLOAD_SIZE_V1];
483 } __attribute__((packed));
484 
485 union usb_spi_packet_v1 {
486 	struct usb_spi_command_v1 command;
487 	struct usb_spi_response_v1 response;
488 } __attribute__((packed));
489 
490 /*
491  * Version 2 protocol specific attributes
492  */
493 
494 #define USB_SPI_FULL_DUPLEX_ENABLED_V2      (UINT16_MAX)
495 
496 #define USB_SPI_PAYLOAD_SIZE_V2_START       (58)
497 
498 #define USB_SPI_PAYLOAD_SIZE_V2_RESPONSE    (60)
499 
500 #define USB_SPI_PAYLOAD_SIZE_V2_CONTINUE    (60)
501 
502 enum packet_id_type {
503 	/* Request USB SPI configuration data from device. */
504 	USB_SPI_PKT_ID_CMD_GET_USB_SPI_CONFIG = 0,
505 	/* USB SPI configuration data from device. */
506 	USB_SPI_PKT_ID_RSP_USB_SPI_CONFIG     = 1,
507 	/*
508 	 * Start a USB SPI transfer specifying number of bytes to write,
509 	 * read and deliver first packet of data to write.
510 	 */
511 	USB_SPI_PKT_ID_CMD_TRANSFER_START     = 2,
512 	/* Additional packets containing write payload. */
513 	USB_SPI_PKT_ID_CMD_TRANSFER_CONTINUE  = 3,
514 	/*
515 	 * Request the device restart the response enabling us to recover
516 	 * from packet loss without another SPI transfer.
517 	 */
518 	USB_SPI_PKT_ID_CMD_RESTART_RESPONSE   = 4,
519 	/*
520 	 * First packet of USB SPI response with the status code
521 	 * and read payload if it was successful.
522 	 */
523 	USB_SPI_PKT_ID_RSP_TRANSFER_START     = 5,
524 	/* Additional packets containing read payload. */
525 	USB_SPI_PKT_ID_RSP_TRANSFER_CONTINUE  = 6,
526 };
527 
528 enum feature_bitmap {
529 	/* Indicates the platform supports full duplex mode. */
530 	USB_SPI_FEATURE_FULL_DUPLEX_SUPPORTED = 0x01
531 };
532 
533 struct usb_spi_response_configuration_v2 {
534 	uint16_t packet_id;
535 	uint16_t max_write_count;
536 	uint16_t max_read_count;
537 	uint16_t feature_bitmap;
538 } __attribute__((packed));
539 
540 struct usb_spi_command_v2 {
541 	uint16_t packet_id;
542 	uint16_t write_count;
543 	/* UINT16_MAX Indicates readback all on halfduplex compliant devices. */
544 	uint16_t read_count;
545 	uint8_t data[USB_SPI_PAYLOAD_SIZE_V2_START];
546 } __attribute__((packed));
547 
548 struct usb_spi_response_v2 {
549 	uint16_t packet_id;
550 	uint16_t status_code;
551 	uint8_t data[USB_SPI_PAYLOAD_SIZE_V2_RESPONSE];
552 } __attribute__((packed));
553 
554 struct usb_spi_continue_v2 {
555 	uint16_t packet_id;
556 	uint16_t data_index;
557 	uint8_t data[USB_SPI_PAYLOAD_SIZE_V2_CONTINUE];
558 } __attribute__((packed));
559 
560 union usb_spi_packet_v2 {
561 	uint16_t packet_id;
562 	struct usb_spi_command_v2 cmd_start;
563 	struct usb_spi_continue_v2 cmd_continue;
564 	struct usb_spi_response_configuration_v2 rsp_config;
565 	struct usb_spi_response_v2 rsp_start;
566 	struct usb_spi_continue_v2 rsp_continue;
567 } __attribute__((packed));
568 
569 struct usb_spi_packet_ctx {
570 	union {
571 		uint8_t bytes[USB_MAX_PACKET_SIZE];
572 		union usb_spi_packet_v1 packet_v1;
573 		union usb_spi_packet_v2 packet_v2;
574 	};
575 	/*
576 	 * By storing the number of bytes in the header and knowing that the
577 	 * USB data packets are all 64B long, we are able to use the header
578 	 * size to store the offset of the buffer and it's size without
579 	 * duplicating variables that can go out of sync.
580 	 */
581 	size_t header_size;
582 	/* Number of bytes in the packet */
583 	size_t packet_size;
584 };
585 
586 struct usb_spi_transmit_ctx {
587 	/* Buffer we are reading data from. */
588 	const uint8_t *buffer;
589 	/* Number of bytes in the transfer. */
590 	size_t transmit_size;
591 	/* Number of bytes transferred. */
592 	size_t transmit_index;
593 };
594 
595 struct usb_spi_receive_ctx {
596 	/* Buffer we are writing data into. */
597 	uint8_t *buffer;
598 	/* Number of bytes in the transfer. */
599 	size_t receive_size;
600 	/* Number of bytes transferred. */
601 	size_t receive_index;
602 };
603 
604 /*
605  * This function will return true when an error code can potentially recover
606  * if we attempt to write SPI data to the device or read from it. We know
607  * that some conditions are not recoverable in the current state so allows us
608  * to bypass the retry logic and terminate early.
609  */
retry_recovery(int error_code)610 static bool retry_recovery(int error_code)
611 {
612 	if (error_code < 0x10000) {
613 		/*
614 		 * Handle error codes returned from the device. USB_SPI_TIMEOUT,
615 		 * USB_SPI_BUSY, and USB_SPI_WRITE_COUNT_INVALID have been observed
616 		 * during transfer errors to the device and can be recovered.
617 		 */
618 		if (USB_SPI_READ_COUNT_INVALID <= error_code &&
619 		    error_code <= USB_SPI_DISABLED) {
620 			return false;
621 		}
622 	} else if (usb_device_is_libusb_error(error_code)) {
623 		/* Handle error codes returned from libusb. */
624 		if (error_code == LIBUSB_ERROR(LIBUSB_ERROR_NO_DEVICE)) {
625 			return false;
626 		}
627 	}
628 	return true;
629 }
630 
631 static struct raiden_debug_spi_data *
get_raiden_data_from_context(const struct flashctx * flash)632 	get_raiden_data_from_context(const struct flashctx *flash)
633 {
634 	return (struct raiden_debug_spi_data *)flash->mst->spi.data;
635 }
636 
637 /*
638  * Read data into the receive buffer.
639  *
640  * @param dst       Destination receive context we are writing data to.
641  * @param src       Source packet context we are reading data from.
642  *
643  * @returns         status code 0 on success.
644  *                  USB_SPI_HOST_RX_DATA_OVERFLOW if the source packet is too
645  *                  large to fit in read buffer.
646  */
read_usb_packet(struct usb_spi_receive_ctx * dst,const struct usb_spi_packet_ctx * src)647 static int read_usb_packet(struct usb_spi_receive_ctx *dst,
648 		const struct usb_spi_packet_ctx *src)
649 {
650 	size_t max_read_length = dst->receive_size - dst->receive_index;
651 	size_t bytes_in_buffer = src->packet_size - src->header_size;
652 	const uint8_t *packet_buffer = src->bytes + src->header_size;
653 
654 	if (bytes_in_buffer > max_read_length) {
655 		/*
656 		 * An error occurred, we should not receive more data than
657 		 * the buffer can support.
658 		 */
659 		msg_perr("Raiden: Receive packet overflowed\n"
660 				"    bytes_in_buffer = %zu\n"
661 				"    max_read_length = %zu\n"
662 				"    receive_index   = %zu\n"
663 				"    receive_size    = %zu\n",
664 				bytes_in_buffer, max_read_length,
665 				dst->receive_size, dst->receive_index);
666 		return USB_SPI_HOST_RX_DATA_OVERFLOW;
667 	}
668 	memcpy(dst->buffer + dst->receive_index, packet_buffer,
669 		bytes_in_buffer);
670 
671 	dst->receive_index += bytes_in_buffer;
672 	return 0;
673 }
674 
675 /*
676  * Fill the USB packet with data from the transmit buffer.
677  *
678  * @param dst       Destination packet context we are writing data to.
679  * @param src       Source transmit context we are reading data from.
680  */
fill_usb_packet(struct usb_spi_packet_ctx * dst,struct usb_spi_transmit_ctx * src)681 static void fill_usb_packet(struct usb_spi_packet_ctx *dst,
682 		struct usb_spi_transmit_ctx *src)
683 {
684 	size_t transmit_size = src->transmit_size - src->transmit_index;
685 	size_t max_buffer_size = USB_MAX_PACKET_SIZE - dst->header_size;
686 	uint8_t *packet_buffer = dst->bytes + dst->header_size;
687 
688 	if (transmit_size > max_buffer_size)
689 		transmit_size = max_buffer_size;
690 
691 	memcpy(packet_buffer, src->buffer + src->transmit_index, transmit_size);
692 
693 	dst->packet_size = dst->header_size + transmit_size;
694 	src->transmit_index += transmit_size;
695 }
696 
697 /*
698  * Receive the data from the device USB endpoint and store in the packet.
699  *
700  * @param ctx_data      Raiden SPI config.
701  * @param packet        Destination packet used to store the endpoint data.
702  *
703  * @returns             Returns status code with 0 on success.
704  */
receive_packet(const struct raiden_debug_spi_data * ctx_data,struct usb_spi_packet_ctx * packet)705 static int receive_packet(const struct raiden_debug_spi_data *ctx_data,
706 		struct usb_spi_packet_ctx *packet)
707 {
708 	int received;
709 	int status = LIBUSB(libusb_bulk_transfer(ctx_data->dev->handle,
710 				ctx_data->in_ep,
711 				packet->bytes,
712 				USB_MAX_PACKET_SIZE,
713 				&received,
714 				TRANSFER_TIMEOUT_MS));
715 	packet->packet_size = received;
716 	if (status) {
717 		msg_perr("Raiden: IN transfer failed\n"
718 			 "    received = %d\n"
719 			 "    status   = 0x%05x\n",
720 			 received, status);
721 	}
722 	return status;
723 }
724 
725 /*
726  * Transmit data from the packet to the device's USB endpoint.
727  *
728  * @param ctx_data      Raiden SPI config.
729  * @param packet        Source packet we will write to the endpoint data.
730  *
731  * @returns             Returns status code with 0 on success.
732  */
transmit_packet(const struct raiden_debug_spi_data * ctx_data,struct usb_spi_packet_ctx * packet)733 static int transmit_packet(const struct raiden_debug_spi_data *ctx_data,
734 		struct usb_spi_packet_ctx *packet)
735 {
736 	int transferred;
737 	int status = LIBUSB(libusb_bulk_transfer(ctx_data->dev->handle,
738 				ctx_data->out_ep,
739 				packet->bytes,
740 				packet->packet_size,
741 				&transferred,
742 				TRANSFER_TIMEOUT_MS));
743 	if (status || (size_t)transferred != packet->packet_size) {
744 		if (!status) {
745 			/* No error was reported, but we didn't transmit the data expected. */
746 			status = USB_SPI_HOST_TX_BAD_TRANSFER;
747 		}
748 		msg_perr("Raiden: OUT transfer failed\n"
749 			 "    transferred = %d\n"
750 			 "    packet_size = %zu\n"
751 			 "    status      = 0x%05x\n",
752 			 transferred, packet->packet_size, status);
753 
754 	}
755 	return status;
756 }
757 
758 /*
759  * Version 1 protocol command to start a USB SPI transfer and write the payload.
760  *
761  * @param ctx_data      Raiden SPI config.
762  * @param write         Write context of data to transmit and write payload.
763  * @param read          Read context of data to receive and read buffer.
764  *
765  * @returns             Returns status code with 0 on success.
766  */
write_command_v1(const struct raiden_debug_spi_data * ctx_data,struct usb_spi_transmit_ctx * write,struct usb_spi_receive_ctx * read)767 static int write_command_v1(const struct raiden_debug_spi_data *ctx_data,
768 		struct usb_spi_transmit_ctx *write,
769 		struct usb_spi_receive_ctx *read)
770 {
771 	struct usb_spi_packet_ctx command = {
772 		.header_size = offsetof(struct usb_spi_command_v1, data),
773 		.packet_v1.command.write_count = write->transmit_size,
774 		.packet_v1.command.read_count = read->receive_size
775 	};
776 
777 	/* Reset the write context to the start. */
778 	write->transmit_index = 0;
779 
780 	fill_usb_packet(&command, write);
781 	return transmit_packet(ctx_data, &command);
782 }
783 
784 /*
785  * Version 1 Protocol: Responsible for reading the response of the USB SPI
786  * transfer. Status codes from the transfer and any read payload are copied
787  * to the read_buffer.
788  *
789  * @param ctx_data      Raiden SPI config.
790  * @param write         Write context of data to transmit and write payload.
791  * @param read          Read context of data to receive and read buffer.
792  *
793  * @returns             Returns status code with 0 on success.
794  */
read_response_v1(const struct raiden_debug_spi_data * ctx_data,struct usb_spi_transmit_ctx * write,struct usb_spi_receive_ctx * read)795 static int read_response_v1(const struct raiden_debug_spi_data *ctx_data,
796 		struct usb_spi_transmit_ctx *write,
797 		struct usb_spi_receive_ctx *read)
798 {
799 	int status;
800 	struct usb_spi_packet_ctx response;
801 
802 	/* Reset the read context to the start. */
803 	read->receive_index = 0;
804 
805 	status = receive_packet(ctx_data, &response);
806 	if (status) {
807 		/* Return the transfer error since the status_code is unreliable */
808 		return status;
809 	}
810 	if (response.packet_v1.response.status_code) {
811 		return response.packet_v1.response.status_code;
812 	}
813 	response.header_size = offsetof(struct usb_spi_response_v1, data);
814 
815 	status = read_usb_packet(read, &response);
816 	return status;
817 }
818 
819 /*
820  * Version 1 Protocol: Sets up a USB SPI transfer, transmits data to the device,
821  * reads the status code and any payload from the device. This will also handle
822  * recovery if an error has occurred.
823  *
824  * @param flash         Flash context storing SPI capabilities and USB device
825  *                      information.
826  * @param write_count   Number of bytes to write
827  * @param read_count    Number of bytes to read
828  * @param write_buffer  Address of write buffer
829  * @param read_buffer   Address of buffer to store read data
830  *
831  * @returns             Returns status code with 0 on success.
832  */
send_command_v1(const struct flashctx * flash,unsigned int write_count,unsigned int read_count,const unsigned char * write_buffer,unsigned char * read_buffer)833 static int send_command_v1(const struct flashctx *flash,
834 		unsigned int write_count,
835 		unsigned int read_count,
836 		const unsigned char *write_buffer,
837 		unsigned char *read_buffer)
838 {
839 	int status = -1;
840 
841 	struct usb_spi_transmit_ctx write_ctx = {
842 		.buffer = write_buffer,
843 		.transmit_size = write_count
844 	};
845 	struct usb_spi_receive_ctx read_ctx = {
846 		.buffer = read_buffer,
847 		.receive_size = read_count
848 	};
849 	const struct raiden_debug_spi_data *ctx_data = get_raiden_data_from_context(flash);
850 
851 	if (write_count > ctx_data->max_spi_write_count) {
852 		msg_perr("Raiden: Invalid write count\n"
853 			 "    write count = %u\n"
854 			 "    max write   = %d\n",
855 			 write_count, ctx_data->max_spi_write_count);
856 		return SPI_INVALID_LENGTH;
857 	}
858 
859 	if (read_count > ctx_data->max_spi_read_count) {
860 		msg_perr("Raiden: Invalid read count\n"
861 			 "    read count = %d\n"
862 			 "    max read   = %d\n",
863 			 read_count, ctx_data->max_spi_read_count);
864 		return SPI_INVALID_LENGTH;
865 	}
866 
867 	for (unsigned int write_attempt = 0; write_attempt < WRITE_RETRY_ATTEMPTS;
868 	         write_attempt++) {
869 
870 
871 		status = write_command_v1(ctx_data, &write_ctx, &read_ctx);
872 
873 		if (!status &&
874 			(write_ctx.transmit_index != write_ctx.transmit_size)) {
875 			/* No errors were reported, but write is incomplete. */
876 			status = USB_SPI_HOST_TX_WRITE_FAILURE;
877 		}
878 
879 		if (status) {
880 			/* Write operation failed. */
881 			msg_perr("Raiden: Write command failed\n"
882 				 "    protocol          = %u\n"
883 				 "    write count       = %u\n"
884 				 "    read count        = %u\n"
885 				 "    transmitted bytes = %zu\n"
886 				 "    write attempt     = %u\n"
887 				 "    status            = 0x%05x\n",
888 				 ctx_data->protocol_version,
889 				 write_count, read_count, write_ctx.transmit_index,
890 				 write_attempt + 1, status);
891 			if (!retry_recovery(status)) {
892 				/* Reattempting will not result in a recovery. */
893 				return status;
894 			}
895 			default_delay(RETRY_INTERVAL_US);
896 			continue;
897 		}
898 
899 		for (unsigned int read_attempt = 0; read_attempt < READ_RETRY_ATTEMPTS;
900 				read_attempt++) {
901 
902 			status = read_response_v1(ctx_data, &write_ctx, &read_ctx);
903 
904 			if (!status) {
905 				if (read_ctx.receive_size == read_ctx.receive_index) {
906 					/* Successful transfer. */
907 					return status;
908 				} else {
909 					/* Report the error from the failed read. */
910 					status = USB_SPI_HOST_RX_READ_FAILURE;
911 				}
912 			}
913 
914 			/* Read operation failed. */
915 			msg_perr("Raiden: Read response failed\n"
916 				 "    protocol       = %u\n"
917 				 "    write count    = %u\n"
918 				 "    read count     = %u\n"
919 				 "    received bytes = %zu\n"
920 				 "    write attempt  = %u\n"
921 				 "    read attempt   = %u\n"
922 				 "    status         = 0x%05x\n",
923 				 ctx_data->protocol_version,
924 				 write_count, read_count, read_ctx.receive_index,
925 				 write_attempt + 1, read_attempt + 1, status);
926 			if (!retry_recovery(status)) {
927 				/* Reattempting will not result in a recovery. */
928 				return status;
929 			}
930 			default_delay(RETRY_INTERVAL_US);
931 		}
932 	}
933 
934 	return status;
935 }
936 
937 /*
938  * Get the USB SPI configuration with the maximum write and read counts, and
939  * any enabled features.
940  *
941  * @param ctx_data      Raiden SPI config.
942  *
943  * @returns             Returns status code with 0 on success.
944  */
get_spi_config_v2(struct raiden_debug_spi_data * ctx_data)945 static int get_spi_config_v2(struct raiden_debug_spi_data *ctx_data)
946 {
947 	int status;
948 	unsigned int config_attempt;
949 	struct usb_spi_packet_ctx rsp_config;
950 
951 	struct usb_spi_packet_ctx cmd_get_config = {
952 		.header_size = PACKET_HEADER_SIZE,
953 		.packet_size = PACKET_HEADER_SIZE,
954 		.packet_v2.packet_id = USB_SPI_PKT_ID_CMD_GET_USB_SPI_CONFIG
955 	};
956 
957 	for (config_attempt = 0; config_attempt < GET_CONFIG_RETRY_ATTEMPTS; config_attempt++) {
958 
959 		status = transmit_packet(ctx_data, &cmd_get_config);
960 		if (status) {
961 			msg_perr("Raiden: Failed to transmit get config\n"
962 			         "    config attempt = %d\n"
963 			         "    status         = 0x%05x\n",
964 			         config_attempt + 1, status);
965 			default_delay(RETRY_INTERVAL_US);
966 			continue;
967 		}
968 
969 		status = receive_packet(ctx_data, &rsp_config);
970 		if (status) {
971 			msg_perr("Raiden: Failed to receive packet\n"
972 			         "    config attempt = %d\n"
973 			         "    status         = 0x%05x\n",
974 			         config_attempt + 1, status);
975 			default_delay(RETRY_INTERVAL_US);
976 			continue;
977 		}
978 
979 		/*
980 		 * Perform validation on the packet received to verify it is a valid
981 		 * configuration. If it is, we are ready to perform transfers.
982 		 */
983 		if ((rsp_config.packet_v2.packet_id ==
984 				USB_SPI_PKT_ID_RSP_USB_SPI_CONFIG) ||
985 				(rsp_config.packet_size ==
986 				sizeof(struct usb_spi_response_configuration_v2))) {
987 
988 			/* Set the parameters from the configuration. */
989 			ctx_data->max_spi_write_count =
990 				rsp_config.packet_v2.rsp_config.max_write_count;
991 			ctx_data->max_spi_read_count =
992 				rsp_config.packet_v2.rsp_config.max_read_count;
993 			return status;
994 		}
995 
996 		/*
997 		 * Check if we received an error from the device. An error will have no
998 		 * response data, just the packet_id and status_code.
999 		 */
1000 		const size_t err_packet_size = sizeof(struct usb_spi_response_v2) -
1001 			USB_SPI_PAYLOAD_SIZE_V2_RESPONSE;
1002 		if (rsp_config.packet_size == err_packet_size &&
1003 				rsp_config.packet_v2.rsp_start.status_code !=
1004 				USB_SPI_SUCCESS) {
1005 			status = rsp_config.packet_v2.rsp_start.status_code;
1006 			if (status == USB_SPI_DISABLED) {
1007 				msg_perr("Raiden: Target SPI bridge is disabled (is WP enabled?)\n");
1008 				return status;
1009 			}
1010 		}
1011 
1012 		msg_perr("Raiden: Packet is not a valid config\n"
1013 		         "    config attempt = %d\n"
1014 		         "    packet id      = %u\n"
1015 		         "    packet size    = %zu\n",
1016 		         config_attempt + 1,
1017 		         rsp_config.packet_v2.packet_id,
1018 		         rsp_config.packet_size);
1019 		default_delay(RETRY_INTERVAL_US);
1020 	}
1021 	return USB_SPI_HOST_INIT_FAILURE;
1022 }
1023 
1024 /*
1025  * Version 2 protocol restart the SPI response. This allows us to recover from
1026  * USB packet errors without restarting the SPI transfer.
1027  *
1028  * @param ctx_data      Raiden SPI config.
1029  *
1030  * @returns             Returns status code with 0 on success.
1031  */
restart_response_v2(const struct raiden_debug_spi_data * ctx_data)1032 static int restart_response_v2(const struct raiden_debug_spi_data *ctx_data)
1033 {
1034 	struct usb_spi_packet_ctx restart_response = {
1035 		.header_size = PACKET_HEADER_SIZE,
1036 		.packet_size = PACKET_HEADER_SIZE,
1037 		.packet_v2.packet_id = USB_SPI_PKT_ID_CMD_RESTART_RESPONSE
1038 	};
1039 
1040 	return transmit_packet(ctx_data, &restart_response);
1041 }
1042 
1043 /*
1044  * Version 2 Protocol: command to start a USB SPI transfer and write the payload.
1045  *
1046  * @param ctx_data      Raiden SPI config.
1047  * @param write         Write context of data to transmit and write payload.
1048  * @param read          Read context of data to receive and read buffer.
1049  *
1050  * @returns             Returns status code with 0 on success.
1051  */
write_command_v2(const struct raiden_debug_spi_data * ctx_data,struct usb_spi_transmit_ctx * write,struct usb_spi_receive_ctx * read)1052 static int write_command_v2(const struct raiden_debug_spi_data *ctx_data,
1053 		struct usb_spi_transmit_ctx *write,
1054 		struct usb_spi_receive_ctx *read)
1055 {
1056 	int status;
1057 	struct usb_spi_packet_ctx continue_packet;
1058 
1059 	struct usb_spi_packet_ctx start_usb_spi_packet = {
1060 		.header_size = offsetof(struct usb_spi_command_v2, data),
1061 		.packet_v2.cmd_start.packet_id = USB_SPI_PKT_ID_CMD_TRANSFER_START,
1062 		.packet_v2.cmd_start.write_count = write->transmit_size,
1063 		.packet_v2.cmd_start.read_count = read->receive_size
1064 	};
1065 
1066 	/* Reset the write context to the start. */
1067 	write->transmit_index = 0;
1068 
1069 	fill_usb_packet(&start_usb_spi_packet, write);
1070 	status = transmit_packet(ctx_data, &start_usb_spi_packet);
1071 	if (status) {
1072 		return status;
1073 	}
1074 
1075 	while (write->transmit_index < write->transmit_size) {
1076 		/* Transmit any continue packets. */
1077 		continue_packet.header_size = offsetof(struct usb_spi_continue_v2, data);
1078 		continue_packet.packet_v2.cmd_continue.packet_id =
1079 				USB_SPI_PKT_ID_CMD_TRANSFER_CONTINUE;
1080 		continue_packet.packet_v2.cmd_continue.data_index =
1081 				write->transmit_index;
1082 
1083 		fill_usb_packet(&continue_packet, write);
1084 
1085 		status = transmit_packet(ctx_data, &continue_packet);
1086 		if (status) {
1087 			return status;
1088 		}
1089 	}
1090 
1091 	return status;
1092 }
1093 
1094 /*
1095  * Version 2 Protocol: Command to read a USB SPI transfer response and read the payload.
1096  *
1097  * @param ctx_data      Raiden SPI config.
1098  * @param write         Write context of data to transmit and write payload.
1099  * @param read          Read context of data to receive and read buffer.
1100  *
1101  * @returns             Returns status code with 0 on success.
1102  */
read_response_v2(const struct raiden_debug_spi_data * ctx_data,struct usb_spi_transmit_ctx * write,struct usb_spi_receive_ctx * read)1103 static int read_response_v2(const struct raiden_debug_spi_data *ctx_data,
1104 		struct usb_spi_transmit_ctx *write,
1105 		struct usb_spi_receive_ctx *read)
1106 {
1107 	int status = -1;
1108 	struct usb_spi_packet_ctx response;
1109 
1110 	/* Reset the read context to the start. */
1111 	read->receive_index = 0;
1112 
1113 	/* Receive the payload to the servo micro. */
1114 	do {
1115 		status = receive_packet(ctx_data, &response);
1116 		if (status) {
1117 			/* Return the transfer error. */
1118 			return status;
1119 		}
1120 		if (response.packet_v2.packet_id == USB_SPI_PKT_ID_RSP_TRANSFER_START) {
1121 			/*
1122 			 * The host should only see this packet if an error occurs
1123 			 * on the device or if it's the first response packet.
1124 			 */
1125 			if (response.packet_v2.rsp_start.status_code) {
1126 				return response.packet_v2.rsp_start.status_code;
1127 			}
1128 			if (read->receive_index) {
1129 				msg_perr("Raiden: Unexpected start packet id = %u\n",
1130 					 response.packet_v2.rsp_start.packet_id);
1131 				return USB_SPI_HOST_RX_UNEXPECTED_PACKET;
1132 			}
1133 			response.header_size = offsetof(struct usb_spi_response_v2, data);
1134 		} else if (response.packet_v2.packet_id ==
1135 				USB_SPI_PKT_ID_RSP_TRANSFER_CONTINUE) {
1136 
1137 			/* We validate that no packets were missed. */
1138 			if (read->receive_index !=
1139 					response.packet_v2.rsp_continue.data_index) {
1140 				msg_perr("Raiden: Bad Index = %u Expected = %zu\n",
1141 					 response.packet_v2.rsp_continue.data_index,
1142 					 read->receive_index);
1143 				return USB_SPI_HOST_RX_BAD_DATA_INDEX;
1144 			}
1145 			response.header_size = offsetof(struct usb_spi_continue_v2, data);
1146 		} else {
1147 			msg_perr("Raiden: Unexpected packet id = %u\n",
1148 				 response.packet_v2.packet_id);
1149 			return USB_SPI_HOST_RX_UNEXPECTED_PACKET;
1150 		}
1151 		status = read_usb_packet(read, &response);
1152 		if (status) {
1153 			return status;
1154 		}
1155 	} while (read->receive_index < read->receive_size);
1156 
1157 	return status;
1158 }
1159 
1160 /*
1161  * Version 2 Protocol: Sets up a USB SPI transfer, transmits data to the device,
1162  * reads the status code and any payload from the device. This will also handle
1163  * recovery if an error has occurred.
1164  *
1165  * In order to avoid having the v2 protocol held back by requiring
1166  * backwards compatibility with v1 we are duplicating the send_command
1167  * function. This will allow the 2 versions to diverge in the future
1168  * so fixes in one do not need to be compatible with the legacy.
1169  *
1170  * @param flash         Flash context storing SPI capabilities and USB device
1171  *                      information.
1172  * @param write_count   Number of bytes to write
1173  * @param read_count    Number of bytes to read
1174  * @param write_buffer  Address of write buffer
1175  * @param read_buffer   Address of buffer to store read data
1176  *
1177  * @returns             Returns status code with 0 on success.
1178  */
send_command_v2(const struct flashctx * flash,unsigned int write_count,unsigned int read_count,const unsigned char * write_buffer,unsigned char * read_buffer)1179 static int send_command_v2(const struct flashctx *flash,
1180 		unsigned int write_count,
1181 		unsigned int read_count,
1182 		const unsigned char *write_buffer,
1183 		unsigned char *read_buffer)
1184 {
1185 	const struct raiden_debug_spi_data *ctx_data =
1186 		get_raiden_data_from_context(flash);
1187 	int status = -1;
1188 	unsigned int write_attempt;
1189 	unsigned int read_attempt;
1190 
1191 	struct usb_spi_transmit_ctx write_ctx = {
1192 		.buffer = write_buffer,
1193 		.transmit_size = write_count
1194 	};
1195 	struct usb_spi_receive_ctx read_ctx = {
1196 		.buffer = read_buffer,
1197 		.receive_size = read_count
1198 	};
1199 
1200 	if (write_count > ctx_data->max_spi_write_count) {
1201 		msg_perr("Raiden: Invalid write count\n"
1202 			 "    write count = %u\n"
1203 			 "    max write   = %u\n",
1204 			 write_count, ctx_data->max_spi_write_count);
1205 		return SPI_INVALID_LENGTH;
1206 	}
1207 
1208 	if (read_count > ctx_data->max_spi_read_count) {
1209 		msg_perr("Raiden: Invalid read count\n"
1210 			 "    read count = %u\n"
1211 			 "    max read   = %u\n",
1212 			 read_count, ctx_data->max_spi_read_count);
1213 		return SPI_INVALID_LENGTH;
1214 	}
1215 
1216 	for (write_attempt = 0; write_attempt < WRITE_RETRY_ATTEMPTS;
1217 			write_attempt++) {
1218 
1219 		status = write_command_v2(ctx_data, &write_ctx, &read_ctx);
1220 
1221 		if (!status &&
1222 			(write_ctx.transmit_index != write_ctx.transmit_size)) {
1223 			/* No errors were reported, but write is incomplete. */
1224 			status = USB_SPI_HOST_TX_WRITE_FAILURE;
1225 		}
1226 
1227 		if (status) {
1228 			/* Write operation failed. */
1229 			msg_perr("Raiden: Write command failed\n"
1230 				 "    protocol          = %u\n"
1231 				 "    write count       = %u\n"
1232 				 "    read count        = %u\n"
1233 				 "    transmitted bytes = %zu\n"
1234 				 "    write attempt     = %u\n"
1235 				 "    status            = 0x%05x\n",
1236 				 ctx_data->protocol_version,
1237 				 write_count, read_count, write_ctx.transmit_index,
1238 				 write_attempt + 1, status);
1239 			if (!retry_recovery(status)) {
1240 				/* Reattempting will not result in a recovery. */
1241 				return status;
1242 			}
1243 			default_delay(RETRY_INTERVAL_US);
1244 			continue;
1245 		}
1246 		for (read_attempt = 0; read_attempt < READ_RETRY_ATTEMPTS;
1247 				read_attempt++) {
1248 
1249 			status = read_response_v2(ctx_data, &write_ctx, &read_ctx);
1250 
1251 			if (!status) {
1252 				if (read_ctx.receive_size == read_ctx.receive_index) {
1253 					/* Successful transfer. */
1254 					return status;
1255 				} else {
1256 					/* Report the error from the failed read. */
1257 					status = USB_SPI_HOST_RX_READ_FAILURE;
1258 				}
1259 			}
1260 
1261 			if (status) {
1262 				/* Read operation failed. */
1263 				msg_perr("Raiden: Read response failed\n"
1264 					 "    protocol       = %u\n"
1265 					 "    write count    = %u\n"
1266 					 "    read count     = %u\n"
1267 					 "    received bytes = %zu\n"
1268 					 "    write attempt  = %u\n"
1269 					 "    read attempt   = %u\n"
1270 					 "    status         = 0x%05x\n",
1271 					 ctx_data->protocol_version,
1272 					 write_count, read_count, read_ctx.receive_index,
1273 					 write_attempt + 1, read_attempt + 1, status);
1274 				if (!retry_recovery(status)) {
1275 					/* Reattempting will not result in a recovery. */
1276 					return status;
1277 				}
1278 				/* Device needs to reset its transmit index. */
1279 				restart_response_v2(ctx_data);
1280 				default_delay(RETRY_INTERVAL_US);
1281 			}
1282 		}
1283 	}
1284 	return status;
1285 }
1286 
raiden_debug_spi_shutdown(void * data)1287 static int raiden_debug_spi_shutdown(void * data)
1288 {
1289 	struct raiden_debug_spi_data *ctx_data = (struct raiden_debug_spi_data *)data;
1290 	struct spi_master *spi_config = ctx_data->spi_config;
1291 
1292 	int ret = LIBUSB(libusb_control_transfer(
1293 				ctx_data->dev->handle,
1294 				LIBUSB_ENDPOINT_OUT |
1295 				LIBUSB_REQUEST_TYPE_VENDOR |
1296 				LIBUSB_RECIPIENT_INTERFACE,
1297 				RAIDEN_DEBUG_SPI_REQ_DISABLE,
1298 				0,
1299 				ctx_data->dev->interface_descriptor->bInterfaceNumber,
1300 				NULL,
1301 				0,
1302 				TRANSFER_TIMEOUT_MS));
1303 	if (ret != 0) {
1304 		msg_perr("Raiden: Failed to disable SPI bridge\n");
1305 		free(ctx_data);
1306 		free(spi_config);
1307 		return ret;
1308 	}
1309 
1310 	usb_device_free(ctx_data->dev);
1311 	libusb_exit(NULL);
1312 	free(ctx_data);
1313 	free(spi_config);
1314 
1315 	return 0;
1316 }
1317 
1318 static const struct spi_master spi_master_raiden_debug = {
1319 	.features	= SPI_MASTER_4BA,
1320 	.max_data_read	= 0,
1321 	.max_data_write	= 0,
1322 	.command	= NULL,
1323 	.read		= default_spi_read,
1324 	.write_256	= default_spi_write_256,
1325 	.shutdown	= raiden_debug_spi_shutdown,
1326 };
1327 
match_endpoint(struct libusb_endpoint_descriptor const * descriptor,enum libusb_endpoint_direction direction)1328 static int match_endpoint(struct libusb_endpoint_descriptor const *descriptor,
1329                           enum libusb_endpoint_direction direction)
1330 {
1331 	return (((descriptor->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ==
1332 		 direction) &&
1333 		((descriptor->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) ==
1334 		 LIBUSB_TRANSFER_TYPE_BULK));
1335 }
1336 
find_endpoints(struct usb_device * dev,uint8_t * in_ep,uint8_t * out_ep)1337 static int find_endpoints(struct usb_device *dev, uint8_t *in_ep, uint8_t *out_ep)
1338 {
1339 	int i;
1340 	int in_count  = 0;
1341 	int out_count = 0;
1342 
1343 	for (i = 0; i < dev->interface_descriptor->bNumEndpoints; i++) {
1344 		struct libusb_endpoint_descriptor const  *endpoint =
1345 			&dev->interface_descriptor->endpoint[i];
1346 
1347 		if (match_endpoint(endpoint, LIBUSB_ENDPOINT_IN)) {
1348 			in_count++;
1349 			*in_ep = endpoint->bEndpointAddress;
1350 		} else if (match_endpoint(endpoint, LIBUSB_ENDPOINT_OUT)) {
1351 			out_count++;
1352 			*out_ep = endpoint->bEndpointAddress;
1353 		}
1354 	}
1355 
1356 	if (in_count != 1 || out_count != 1) {
1357 		msg_perr("Raiden: Failed to find one IN and one OUT endpoint\n"
1358 			 "        found %d IN and %d OUT endpoints\n",
1359 			 in_count,
1360 			 out_count);
1361 		return 1;
1362 	}
1363 
1364 	msg_pdbg("Raiden: Found IN  endpoint = 0x%02x\n", *in_ep);
1365 	msg_pdbg("Raiden: Found OUT endpoint = 0x%02x\n", *out_ep);
1366 
1367 	return 0;
1368 }
1369 
1370 /*
1371  * Configure the USB SPI master based on the device we are connected to.
1372  * It will use the device's bInterfaceProtocol to identify which protocol
1373  * is being used by the device USB SPI interface and if needed query the
1374  * device for its capabilities.
1375  *
1376  * @param ctx_data Raiden SPI data, data contains pointer to config which will be modified.
1377  *
1378  * @returns	   Returns status code with 0 on success.
1379  */
configure_protocol(struct raiden_debug_spi_data * ctx_data)1380 static int configure_protocol(struct raiden_debug_spi_data *ctx_data)
1381 {
1382 	int status = 0;
1383 	struct spi_master *spi_config = ctx_data->spi_config;
1384 
1385 	ctx_data->protocol_version =
1386 		ctx_data->dev->interface_descriptor->bInterfaceProtocol;
1387 
1388 	switch (ctx_data->protocol_version) {
1389 	case GOOGLE_RAIDEN_SPI_PROTOCOL_V1:
1390 		/*
1391 		 * Protocol V1 is supported by adjusting the max data
1392 		 * read and write sizes which results in no continue packets.
1393 		 */
1394 		spi_config->command = send_command_v1;
1395 		ctx_data->max_spi_write_count = SPI_TRANSFER_V1_MAX;
1396 		ctx_data->max_spi_read_count = SPI_TRANSFER_V1_MAX;
1397 		break;
1398 	case GOOGLE_RAIDEN_SPI_PROTOCOL_V2:
1399 		/*
1400 		 * Protocol V2 requires the host to query the device for
1401 		 * its maximum read and write sizes
1402 		 */
1403 		spi_config->command = send_command_v2;
1404 		status = get_spi_config_v2(ctx_data);
1405 		if (status) {
1406 			return status;
1407 		}
1408 		break;
1409 	default:
1410 		msg_pdbg("Raiden: Unknown USB SPI protocol version = %u\n",
1411 				ctx_data->protocol_version);
1412 		return USB_SPI_HOST_INIT_FAILURE;
1413 	}
1414 
1415 	/*
1416 	 * Unfortunately there doesn't seem to be a way to specify the maximum number
1417 	 * of bytes that your SPI device can read/write, these values are the maximum
1418 	 * data chunk size that flashrom will package up with an additional five bytes
1419 	 * of command for the flash device.
1420 	 *
1421 	 * The largest command that flashrom generates is the byte program command, so
1422 	 * we use that command header maximum size here. If we didn't include the
1423 	 * offset, flashrom may request a SPI transfer that is too large for the SPI
1424 	 * device to support.
1425 	 */
1426 	spi_config->max_data_write = ctx_data->max_spi_write_count -
1427 		JEDEC_BYTE_PROGRAM_OUTSIZE;
1428 	spi_config->max_data_read = ctx_data->max_spi_read_count -
1429 		JEDEC_BYTE_PROGRAM_OUTSIZE;
1430 
1431 	return 0;
1432 }
1433 
get_ap_request_type(const struct programmer_cfg * cfg)1434 static int get_ap_request_type(const struct programmer_cfg *cfg)
1435 {
1436 	int ap_request = RAIDEN_DEBUG_SPI_REQ_ENABLE_AP;
1437 	char *custom_rst_str = extract_programmer_param_str(cfg, "custom_rst");
1438 	if (custom_rst_str) {
1439 		if (!strcasecmp(custom_rst_str, "true")) {
1440 			ap_request = RAIDEN_DEBUG_SPI_REQ_ENABLE_AP_CUSTOM;
1441 		} else if (!strcasecmp(custom_rst_str, "false")) {
1442 			ap_request = RAIDEN_DEBUG_SPI_REQ_ENABLE_AP;
1443 		} else {
1444 			msg_perr("Invalid custom rst param: %s\n",
1445 			         custom_rst_str);
1446 			ap_request = -1;
1447 		}
1448 	}
1449 	free(custom_rst_str);
1450 	return ap_request;
1451 }
1452 
decode_programmer_param(const struct programmer_cfg * cfg,uint8_t * request,uint16_t * request_parameter)1453 static int decode_programmer_param(const struct programmer_cfg *cfg, uint8_t *request,
1454                                    uint16_t *request_parameter)
1455 {
1456 	/**
1457 	 * REQ_ENABLE doesn't specify a target bus, and will be rejected
1458 	 * by adapters that support more than one target.
1459 	 */
1460 	uint8_t request_enable = RAIDEN_DEBUG_SPI_REQ_ENABLE;
1461         uint16_t parameter = 0;
1462         int ret = 0;
1463 
1464 	char *target_str = extract_programmer_param_str(cfg, "target");
1465         printf("FISK: %s\n", target_str);
1466 
1467 	if (target_str) {
1468 		char *endptr;
1469 		int index = strtol(target_str, &endptr, 0);
1470 		if (*target_str && !*endptr && index >= 0 && index < 256) {
1471 			request_enable = RAIDEN_DEBUG_SPI_REQ_ENABLE;
1472                         parameter = index;
1473 		} else if (!strcasecmp(target_str, "ap"))
1474 			request_enable = get_ap_request_type(cfg);
1475 		else if (!strcasecmp(target_str, "ec"))
1476 			request_enable = RAIDEN_DEBUG_SPI_REQ_ENABLE_EC;
1477 		else {
1478 			msg_perr("Invalid target: %s\n", target_str);
1479 			ret = 1;
1480 		}
1481 	}
1482 	free(target_str);
1483 	if (ret == 0) {
1484 		msg_pinfo("Raiden target: %d,%d\n", request_enable, parameter);
1485 
1486                 *request = request_enable;
1487                 *request_parameter = parameter;
1488         }
1489         return ret;
1490 }
1491 
free_dev_list(struct usb_device ** dev_lst)1492 static void free_dev_list(struct usb_device **dev_lst)
1493 {
1494 	struct usb_device *dev = *dev_lst;
1495 	/* free devices we don't care about */
1496 	dev = dev->next;
1497 	while (dev)
1498 		dev = usb_device_free(dev);
1499 }
1500 
raiden_debug_spi_init(const struct programmer_cfg * cfg)1501 static int raiden_debug_spi_init(const struct programmer_cfg *cfg)
1502 {
1503 	struct usb_match match;
1504 	char *serial = extract_programmer_param_str(cfg, "serial");
1505 	struct usb_device *current;
1506 	struct usb_device *device = NULL;
1507 	bool found = false;
1508 	int ret;
1509 
1510 	uint8_t request_enable;
1511         uint16_t request_parameter;
1512         ret = decode_programmer_param(cfg, &request_enable, &request_parameter);
1513 	if (ret != 0) {
1514 		free(serial);
1515 		return ret;
1516 	}
1517 
1518 	usb_match_init(cfg, &match);
1519 
1520 	usb_match_value_default(&match.vid,      GOOGLE_VID);
1521 	usb_match_value_default(&match.class,    LIBUSB_CLASS_VENDOR_SPEC);
1522 	usb_match_value_default(&match.subclass, GOOGLE_RAIDEN_SPI_SUBCLASS);
1523 
1524 	ret = LIBUSB(libusb_init(NULL));
1525 	if (ret != 0) {
1526 		msg_perr("Raiden: libusb_init failed\n");
1527 		free(serial);
1528 		return ret;
1529 	}
1530 
1531 	ret = usb_device_find(&match, &current);
1532 	if (ret != 0) {
1533 		msg_perr("Raiden: Failed to find devices\n");
1534 		free(serial);
1535 		return ret;
1536 	}
1537 
1538 	uint8_t in_endpoint  = 0;
1539 	uint8_t out_endpoint = 0;
1540 	while (current) {
1541 		device = current;
1542 
1543 		if (find_endpoints(device, &in_endpoint, &out_endpoint)) {
1544 			msg_pdbg("Raiden: Failed to find valid endpoints on device");
1545 			usb_device_show(" ", current);
1546 			goto loop_end;
1547 		}
1548 
1549 		if (usb_device_claim(device)) {
1550 			msg_pdbg("Raiden: Failed to claim USB device");
1551 			usb_device_show(" ", current);
1552 			goto loop_end;
1553 		}
1554 
1555 		if (!serial) {
1556 			found = true;
1557 			goto loop_end;
1558 		} else {
1559 			unsigned char dev_serial[32] = { 0 };
1560 			struct libusb_device_descriptor descriptor;
1561 			int rc;
1562 
1563 			if (libusb_get_device_descriptor(device->device, &descriptor)) {
1564 				msg_pdbg("USB: Failed to get device descriptor.\n");
1565 				goto loop_end;
1566 			}
1567 
1568 			rc = libusb_get_string_descriptor_ascii(device->handle,
1569 					descriptor.iSerialNumber,
1570 					dev_serial,
1571 					sizeof(dev_serial));
1572 			if (rc < 0) {
1573 				LIBUSB(rc);
1574 			} else {
1575 				if (strcmp(serial, (char *)dev_serial)) {
1576 					msg_pdbg("Raiden: Serial number %s did not match device", serial);
1577 					usb_device_show(" ", current);
1578 				} else {
1579 					msg_pinfo("Raiden: Serial number %s matched device", serial);
1580 					usb_device_show(" ", current);
1581 					found = true;
1582 				}
1583 			}
1584 		}
1585 
1586 loop_end:
1587 		if (found)
1588 			break;
1589 		else
1590 			current = usb_device_free(current);
1591 	}
1592 
1593 	if (!device || !found) {
1594 		msg_perr("Raiden: No usable device found.\n");
1595 		free(serial);
1596 		return 1;
1597 	}
1598 
1599 	free_dev_list(&current);
1600 
1601 	ret = LIBUSB(libusb_control_transfer(
1602 				device->handle,
1603 				LIBUSB_ENDPOINT_OUT |
1604 				LIBUSB_REQUEST_TYPE_VENDOR |
1605 				LIBUSB_RECIPIENT_INTERFACE,
1606 				request_enable,
1607 				request_parameter,
1608 				device->interface_descriptor->bInterfaceNumber,
1609 				NULL,
1610 				0,
1611 				TRANSFER_TIMEOUT_MS));
1612 	if (ret != 0) {
1613 		msg_perr("Raiden: Failed to enable SPI bridge\n");
1614 		return ret;
1615 	}
1616 
1617 	/*
1618 	 * Allow for power to settle on the AP and EC flash devices.
1619 	 * Load switches can have a 1-3 ms turn on time, and SPI flash devices
1620 	 * can require up to 10 ms from power on to the first write.
1621 	 */
1622 	if ((request_enable == RAIDEN_DEBUG_SPI_REQ_ENABLE_AP) ||
1623 		(request_enable == RAIDEN_DEBUG_SPI_REQ_ENABLE_EC))
1624 		usleep(50 * 1000);
1625 
1626 	struct spi_master *spi_config = calloc(1, sizeof(*spi_config));
1627 	if (!spi_config) {
1628 		msg_perr("Unable to allocate space for SPI master.\n");
1629 		return SPI_GENERIC_ERROR;
1630 	}
1631 	struct raiden_debug_spi_data *data = calloc(1, sizeof(*data));
1632 	if (!data) {
1633 		free(spi_config);
1634 		msg_perr("Unable to allocate space for extra SPI master data.\n");
1635 		return SPI_GENERIC_ERROR;
1636 	}
1637 
1638 	*spi_config = spi_master_raiden_debug;
1639 
1640 	data->dev = device;
1641 	data->in_ep = in_endpoint;
1642 	data->out_ep = out_endpoint;
1643 	data->spi_config = spi_config;
1644 
1645 	/*
1646 	 * The SPI master needs to be configured based on the device connected.
1647 	 * Using the device protocol interrogation, we will set the limits on
1648 	 * the write and read sizes and switch command functions.
1649 	 */
1650 	ret = configure_protocol(data);
1651 	if (ret) {
1652 		msg_perr("Raiden: Error configuring protocol\n"
1653 			 "    protocol       = %u\n"
1654 			 "    status         = 0x%05x\n",
1655 			 data->dev->interface_descriptor->bInterfaceProtocol, ret);
1656 		free(data);
1657 		free(spi_config);
1658 		return SPI_GENERIC_ERROR;
1659 	}
1660 
1661 	return register_spi_master(spi_config, data);
1662 }
1663 
1664 const struct programmer_entry programmer_raiden_debug_spi = {
1665 	.name			= "raiden_debug_spi",
1666 	.type			= USB,
1667 	.devs.dev		= devs_raiden,
1668 	.init			= raiden_debug_spi_init,
1669 };
1670