1 /*
2  * (C) Copyright 2015 Google, Inc
3  * Written by Simon Glass <sjg@chromium.org>
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  */
7 
8 #include <common.h>
9 #include <dm.h>
10 #include <os.h>
11 #include <scsi.h>
12 #include <usb.h>
13 
14 DECLARE_GLOBAL_DATA_PTR;
15 
16 /*
17  * This driver emulates a flash stick using the UFI command specification and
18  * the BBB (bulk/bulk/bulk) protocol. It supports only a single logical unit
19  * number (LUN 0).
20  */
21 
22 enum {
23 	SANDBOX_FLASH_EP_OUT		= 1,	/* endpoints */
24 	SANDBOX_FLASH_EP_IN		= 2,
25 	SANDBOX_FLASH_BLOCK_LEN		= 512,
26 };
27 
28 enum cmd_phase {
29 	PHASE_START,
30 	PHASE_DATA,
31 	PHASE_STATUS,
32 };
33 
34 enum {
35 	STRINGID_MANUFACTURER = 1,
36 	STRINGID_PRODUCT,
37 	STRINGID_SERIAL,
38 
39 	STRINGID_COUNT,
40 };
41 
42 /**
43  * struct sandbox_flash_priv - private state for this driver
44  *
45  * @error:	true if there is an error condition
46  * @alloc_len:	Allocation length from the last incoming command
47  * @transfer_len: Transfer length from CBW header
48  * @read_len:	Number of blocks of data left in the current read command
49  * @tag:	Tag value from last command
50  * @fd:		File descriptor of backing file
51  * @file_size:	Size of file in bytes
52  * @status_buff:	Data buffer for outgoing status
53  * @buff_used:	Number of bytes ready to transfer back to host
54  * @buff:	Data buffer for outgoing data
55  */
56 struct sandbox_flash_priv {
57 	bool error;
58 	int alloc_len;
59 	int transfer_len;
60 	int read_len;
61 	enum cmd_phase phase;
62 	u32 tag;
63 	int fd;
64 	loff_t file_size;
65 	struct umass_bbb_csw status;
66 	int buff_used;
67 	u8 buff[512];
68 };
69 
70 struct sandbox_flash_plat {
71 	const char *pathname;
72 	struct usb_string flash_strings[STRINGID_COUNT];
73 };
74 
75 struct scsi_inquiry_resp {
76 	u8 type;
77 	u8 flags;
78 	u8 version;
79 	u8 data_format;
80 	u8 additional_len;
81 	u8 spare[3];
82 	char vendor[8];
83 	char product[16];
84 	char revision[4];
85 };
86 
87 struct scsi_read_capacity_resp {
88 	u32 last_block_addr;
89 	u32 block_len;
90 };
91 
92 struct __packed scsi_read10_req {
93 	u8 cmd;
94 	u8 lun_flags;
95 	u32 lba;
96 	u8 spare;
97 	u16 transfer_len;
98 	u8 spare2[3];
99 };
100 
101 static struct usb_device_descriptor flash_device_desc = {
102 	.bLength =		sizeof(flash_device_desc),
103 	.bDescriptorType =	USB_DT_DEVICE,
104 
105 	.bcdUSB =		__constant_cpu_to_le16(0x0200),
106 
107 	.bDeviceClass =		0,
108 	.bDeviceSubClass =	0,
109 	.bDeviceProtocol =	0,
110 
111 	.idVendor =		__constant_cpu_to_le16(0x1234),
112 	.idProduct =		__constant_cpu_to_le16(0x5678),
113 	.iManufacturer =	STRINGID_MANUFACTURER,
114 	.iProduct =		STRINGID_PRODUCT,
115 	.iSerialNumber =	STRINGID_SERIAL,
116 	.bNumConfigurations =	1,
117 };
118 
119 static struct usb_config_descriptor flash_config0 = {
120 	.bLength		= sizeof(flash_config0),
121 	.bDescriptorType	= USB_DT_CONFIG,
122 
123 	/* wTotalLength is set up by usb-emul-uclass */
124 	.bNumInterfaces		= 1,
125 	.bConfigurationValue	= 0,
126 	.iConfiguration		= 0,
127 	.bmAttributes		= 1 << 7,
128 	.bMaxPower		= 50,
129 };
130 
131 static struct usb_interface_descriptor flash_interface0 = {
132 	.bLength		= sizeof(flash_interface0),
133 	.bDescriptorType	= USB_DT_INTERFACE,
134 
135 	.bInterfaceNumber	= 0,
136 	.bAlternateSetting	= 0,
137 	.bNumEndpoints		= 2,
138 	.bInterfaceClass	= USB_CLASS_MASS_STORAGE,
139 	.bInterfaceSubClass	= US_SC_UFI,
140 	.bInterfaceProtocol	= US_PR_BULK,
141 	.iInterface		= 0,
142 };
143 
144 static struct usb_endpoint_descriptor flash_endpoint0_out = {
145 	.bLength		= USB_DT_ENDPOINT_SIZE,
146 	.bDescriptorType	= USB_DT_ENDPOINT,
147 
148 	.bEndpointAddress	= SANDBOX_FLASH_EP_OUT,
149 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
150 	.wMaxPacketSize		= __constant_cpu_to_le16(1024),
151 	.bInterval		= 0,
152 };
153 
154 static struct usb_endpoint_descriptor flash_endpoint1_in = {
155 	.bLength		= USB_DT_ENDPOINT_SIZE,
156 	.bDescriptorType	= USB_DT_ENDPOINT,
157 
158 	.bEndpointAddress	= SANDBOX_FLASH_EP_IN | USB_ENDPOINT_DIR_MASK,
159 	.bmAttributes		= USB_ENDPOINT_XFER_BULK,
160 	.wMaxPacketSize		= __constant_cpu_to_le16(1024),
161 	.bInterval		= 0,
162 };
163 
164 static void *flash_desc_list[] = {
165 	&flash_device_desc,
166 	&flash_config0,
167 	&flash_interface0,
168 	&flash_endpoint0_out,
169 	&flash_endpoint1_in,
170 	NULL,
171 };
172 
173 static int sandbox_flash_control(struct udevice *dev, struct usb_device *udev,
174 				 unsigned long pipe, void *buff, int len,
175 				 struct devrequest *setup)
176 {
177 	struct sandbox_flash_priv *priv = dev_get_priv(dev);
178 
179 	if (pipe == usb_rcvctrlpipe(udev, 0)) {
180 		switch (setup->request) {
181 		case US_BBB_RESET:
182 			priv->error = false;
183 			return 0;
184 		case US_BBB_GET_MAX_LUN:
185 			*(char *)buff = '\0';
186 			return 1;
187 		default:
188 			debug("request=%x\n", setup->request);
189 			break;
190 		}
191 	}
192 	debug("pipe=%lx\n", pipe);
193 
194 	return -EIO;
195 }
196 
197 static void setup_fail_response(struct sandbox_flash_priv *priv)
198 {
199 	struct umass_bbb_csw *csw = &priv->status;
200 
201 	csw->dCSWSignature = CSWSIGNATURE;
202 	csw->dCSWTag = priv->tag;
203 	csw->dCSWDataResidue = 0;
204 	csw->bCSWStatus = CSWSTATUS_FAILED;
205 	priv->buff_used = 0;
206 }
207 
208 /**
209  * setup_response() - set up a response to send back to the host
210  *
211  * @priv:	Sandbox flash private data
212  * @resp:	Response to send, or NULL if none
213  * @size:	Size of response
214  */
215 static void setup_response(struct sandbox_flash_priv *priv, void *resp,
216 			   int size)
217 {
218 	struct umass_bbb_csw *csw = &priv->status;
219 
220 	csw->dCSWSignature = CSWSIGNATURE;
221 	csw->dCSWTag = priv->tag;
222 	csw->dCSWDataResidue = 0;
223 	csw->bCSWStatus = CSWSTATUS_GOOD;
224 
225 	assert(!resp || resp == priv->buff);
226 	priv->buff_used = size;
227 }
228 
229 static void handle_read(struct sandbox_flash_priv *priv, ulong lba,
230 			ulong transfer_len)
231 {
232 	debug("%s: lba=%lx, transfer_len=%lx\n", __func__, lba, transfer_len);
233 	if (priv->fd != -1) {
234 		os_lseek(priv->fd, lba * SANDBOX_FLASH_BLOCK_LEN, OS_SEEK_SET);
235 		priv->read_len = transfer_len;
236 		setup_response(priv, priv->buff,
237 			       transfer_len * SANDBOX_FLASH_BLOCK_LEN);
238 	} else {
239 		setup_fail_response(priv);
240 	}
241 }
242 
243 static int handle_ufi_command(struct sandbox_flash_plat *plat,
244 			      struct sandbox_flash_priv *priv, const void *buff,
245 			      int len)
246 {
247 	const struct SCSI_cmd_block *req = buff;
248 
249 	switch (*req->cmd) {
250 	case SCSI_INQUIRY: {
251 		struct scsi_inquiry_resp *resp = (void *)priv->buff;
252 
253 		priv->alloc_len = req->cmd[4];
254 		memset(resp, '\0', sizeof(*resp));
255 		resp->data_format = 1;
256 		resp->additional_len = 0x1f;
257 		strncpy(resp->vendor,
258 			plat->flash_strings[STRINGID_MANUFACTURER -  1].s,
259 			sizeof(resp->vendor));
260 		strncpy(resp->product,
261 			plat->flash_strings[STRINGID_PRODUCT - 1].s,
262 			sizeof(resp->product));
263 		strncpy(resp->revision, "1.0", sizeof(resp->revision));
264 		setup_response(priv, resp, sizeof(*resp));
265 		break;
266 	}
267 	case SCSI_TST_U_RDY:
268 		setup_response(priv, NULL, 0);
269 		break;
270 	case SCSI_RD_CAPAC: {
271 		struct scsi_read_capacity_resp *resp = (void *)priv->buff;
272 		uint blocks;
273 
274 		if (priv->file_size)
275 			blocks = priv->file_size / SANDBOX_FLASH_BLOCK_LEN - 1;
276 		else
277 			blocks = 0;
278 		resp->last_block_addr = cpu_to_be32(blocks);
279 		resp->block_len = cpu_to_be32(SANDBOX_FLASH_BLOCK_LEN);
280 		setup_response(priv, resp, sizeof(*resp));
281 		break;
282 	}
283 	case SCSI_READ10: {
284 		struct scsi_read10_req *req = (void *)buff;
285 
286 		handle_read(priv, be32_to_cpu(req->lba),
287 			    be16_to_cpu(req->transfer_len));
288 		break;
289 	}
290 	default:
291 		debug("Command not supported: %x\n", req->cmd[0]);
292 		return -EPROTONOSUPPORT;
293 	}
294 
295 	priv->phase = priv->transfer_len ? PHASE_DATA : PHASE_STATUS;
296 	return 0;
297 }
298 
299 static int sandbox_flash_bulk(struct udevice *dev, struct usb_device *udev,
300 			      unsigned long pipe, void *buff, int len)
301 {
302 	struct sandbox_flash_plat *plat = dev_get_platdata(dev);
303 	struct sandbox_flash_priv *priv = dev_get_priv(dev);
304 	int ep = usb_pipeendpoint(pipe);
305 	struct umass_bbb_cbw *cbw = buff;
306 
307 	debug("%s: dev=%s, pipe=%lx, ep=%x, len=%x, phase=%d\n", __func__,
308 	      dev->name, pipe, ep, len, priv->phase);
309 	switch (ep) {
310 	case SANDBOX_FLASH_EP_OUT:
311 		switch (priv->phase) {
312 		case PHASE_START:
313 			priv->alloc_len = 0;
314 			priv->read_len = 0;
315 			if (priv->error || len != UMASS_BBB_CBW_SIZE ||
316 			    cbw->dCBWSignature != CBWSIGNATURE)
317 				goto err;
318 			if ((cbw->bCBWFlags & CBWFLAGS_SBZ) ||
319 			    cbw->bCBWLUN != 0)
320 				goto err;
321 			if (cbw->bCDBLength < 1 || cbw->bCDBLength >= 0x10)
322 				goto err;
323 			priv->transfer_len = cbw->dCBWDataTransferLength;
324 			priv->tag = cbw->dCBWTag;
325 			return handle_ufi_command(plat, priv, cbw->CBWCDB,
326 						  cbw->bCDBLength);
327 		case PHASE_DATA:
328 			debug("data out\n");
329 			break;
330 		default:
331 			break;
332 		}
333 	case SANDBOX_FLASH_EP_IN:
334 		switch (priv->phase) {
335 		case PHASE_DATA:
336 			debug("data in, len=%x, alloc_len=%x, priv->read_len=%x\n",
337 			      len, priv->alloc_len, priv->read_len);
338 			if (priv->read_len) {
339 				ulong bytes_read;
340 
341 				bytes_read = os_read(priv->fd, buff, len);
342 				if (bytes_read != len)
343 					return -EIO;
344 				priv->read_len -= len / SANDBOX_FLASH_BLOCK_LEN;
345 				if (!priv->read_len)
346 					priv->phase = PHASE_STATUS;
347 			} else {
348 				if (priv->alloc_len && len > priv->alloc_len)
349 					len = priv->alloc_len;
350 				memcpy(buff, priv->buff, len);
351 				priv->phase = PHASE_STATUS;
352 			}
353 			return len;
354 		case PHASE_STATUS:
355 			debug("status in, len=%x\n", len);
356 			if (len > sizeof(priv->status))
357 				len = sizeof(priv->status);
358 			memcpy(buff, &priv->status, len);
359 			priv->phase = PHASE_START;
360 			return len;
361 		default:
362 			break;
363 		}
364 	}
365 err:
366 	priv->error = true;
367 	debug("%s: Detected transfer error\n", __func__);
368 	return 0;
369 }
370 
371 static int sandbox_flash_ofdata_to_platdata(struct udevice *dev)
372 {
373 	struct sandbox_flash_plat *plat = dev_get_platdata(dev);
374 
375 	plat->pathname = dev_read_string(dev, "sandbox,filepath");
376 
377 	return 0;
378 }
379 
380 static int sandbox_flash_bind(struct udevice *dev)
381 {
382 	struct sandbox_flash_plat *plat = dev_get_platdata(dev);
383 	struct usb_string *fs;
384 
385 	fs = plat->flash_strings;
386 	fs[0].id = STRINGID_MANUFACTURER;
387 	fs[0].s = "sandbox";
388 	fs[1].id = STRINGID_PRODUCT;
389 	fs[1].s = "flash";
390 	fs[2].id = STRINGID_SERIAL;
391 	fs[2].s = dev->name;
392 
393 	return usb_emul_setup_device(dev, PACKET_SIZE_64, plat->flash_strings,
394 				     flash_desc_list);
395 }
396 
397 static int sandbox_flash_probe(struct udevice *dev)
398 {
399 	struct sandbox_flash_plat *plat = dev_get_platdata(dev);
400 	struct sandbox_flash_priv *priv = dev_get_priv(dev);
401 
402 	priv->fd = os_open(plat->pathname, OS_O_RDONLY);
403 	if (priv->fd != -1)
404 		return os_get_filesize(plat->pathname, &priv->file_size);
405 
406 	return 0;
407 }
408 
409 static const struct dm_usb_ops sandbox_usb_flash_ops = {
410 	.control	= sandbox_flash_control,
411 	.bulk		= sandbox_flash_bulk,
412 };
413 
414 static const struct udevice_id sandbox_usb_flash_ids[] = {
415 	{ .compatible = "sandbox,usb-flash" },
416 	{ }
417 };
418 
419 U_BOOT_DRIVER(usb_sandbox_flash) = {
420 	.name	= "usb_sandbox_flash",
421 	.id	= UCLASS_USB_EMUL,
422 	.of_match = sandbox_usb_flash_ids,
423 	.bind	= sandbox_flash_bind,
424 	.probe	= sandbox_flash_probe,
425 	.ofdata_to_platdata = sandbox_flash_ofdata_to_platdata,
426 	.ops	= &sandbox_usb_flash_ops,
427 	.priv_auto_alloc_size = sizeof(struct sandbox_flash_priv),
428 	.platdata_auto_alloc_size = sizeof(struct sandbox_flash_plat),
429 };
430