summaryrefslogtreecommitdiffstats
path: root/drivers/usb/storage/usb.c
blob: fa3691af159daeef05ee4c9d82be7b15097d1289 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/*
 * Most of this source has been derived from the Linux and
 * U-Boot USB Mass Storage driver implementations.
 *
 * Adapted for barebox:
 * Copyright (c) 2011, AMK Drives & Controls Ltd.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 *
 */

#include <common.h>
#include <init.h>
#include <malloc.h>
#include <errno.h>
#include <scsi.h>
#include <usb/usb.h>
#include <usb/usb_defs.h>

#undef USB_STOR_DEBUG

#include "usb.h"
#include "transport.h"


static LIST_HEAD(us_blkdev_list);


/***********************************************************************
 * USB Storage routines
 ***********************************************************************/

static int usb_stor_inquiry(ccb *srb, struct us_data *us)
{
	int retries, result;

	srb->datalen = min(128UL, srb->datalen);
	if (srb->datalen < 5) {
		US_DEBUGP("SCSI_INQUIRY: invalid data buffer size\n");
		return -EINVAL;
	}

	retries = 3;
	do {
		US_DEBUGP("SCSI_INQUIRY\n");
		memset(&srb->cmd[0], 0, 6);
		srb->cmdlen = 6;
		srb->cmd[0] = SCSI_INQUIRY;
		srb->cmd[3] = (u8)(srb->datalen >> 8);
		srb->cmd[4] = (u8)(srb->datalen >> 0);
		result = us->transport(srb, us);
		US_DEBUGP("SCSI_INQUIRY returns %d\n", result);
	} while ((result != USB_STOR_TRANSPORT_GOOD) && retries--);

	return (result != USB_STOR_TRANSPORT_GOOD) ? -EIO : 0;
}

static int usb_stor_request_sense(ccb *srb, struct us_data *us)
{
	unsigned char *pdata = srb->pdata;
	unsigned long datalen = srb->datalen;

	US_DEBUGP("SCSI_REQ_SENSE\n");
	srb->pdata = &srb->sense_buf[0];
	srb->datalen = 18;
	memset(&srb->cmd[0], 0, 6);
	srb->cmdlen = 6;
	srb->cmd[0] = SCSI_REQ_SENSE;
	srb->cmd[4] = (u8)(srb->datalen >> 0);
	us->transport(srb, us);
	US_DEBUGP("Request Sense returned %02X %02X %02X\n",
	          srb->sense_buf[2], srb->sense_buf[12], srb->sense_buf[13]);
	srb->pdata = pdata;
	srb->datalen = datalen;

	return 0;
}

static int usb_stor_test_unit_ready(ccb *srb, struct us_data *us)
{
	int retries, result;

	retries = 10;
	do {
		US_DEBUGP("SCSI_TST_U_RDY\n");
		memset(&srb->cmd[0], 0, 12);
		srb->cmdlen = 12;
		srb->cmd[0] = SCSI_TST_U_RDY;
		srb->datalen = 0;
		result = us->transport(srb, us);
		US_DEBUGP("SCSI_TST_U_RDY returns %d\n", result);
		if (result == USB_STOR_TRANSPORT_GOOD)
			return 0;
		usb_stor_request_sense(srb, us);
		wait_ms(100);
	} while (retries--);

	return -1;
}

static int usb_stor_read_capacity(ccb *srb, struct us_data *us)
{
	int retries, result;

	if (srb->datalen < 8) {
		US_DEBUGP("SCSI_RD_CAPAC: invalid data buffer size\n");
		return -EINVAL;
	}

	retries = 3;
	do {
		US_DEBUGP("SCSI_RD_CAPAC\n");
		memset(&srb->cmd[0], 0, 10);
		srb->cmdlen = 10;
		srb->cmd[0] = SCSI_RD_CAPAC;
		srb->datalen = 8;
		result = us->transport(srb, us);
		US_DEBUGP("SCSI_RD_CAPAC returns %d\n", result);
	} while ((result != USB_STOR_TRANSPORT_GOOD) && retries--);

	return (result != USB_STOR_TRANSPORT_GOOD) ? -EIO : 0;
}

static int usb_stor_read_10(ccb *srb, struct us_data *us,
                            unsigned long start, unsigned short blocks)
{
	int retries, result;

	retries = 2;
	do {
		US_DEBUGP("SCSI_READ10: start %lx blocks %x\n", start, blocks);
		memset(&srb->cmd[0], 0, 10);
		srb->cmdlen = 10;
		srb->cmd[0] = SCSI_READ10;
		srb->cmd[2] = (u8)(start >> 24);
		srb->cmd[3] = (u8)(start >> 16);
		srb->cmd[4] = (u8)(start >> 8);
		srb->cmd[5] = (u8)(start >> 0);
		srb->cmd[7] = (u8)(blocks >> 8);
		srb->cmd[8] = (u8)(blocks >> 0);
		result = us->transport(srb, us);
		US_DEBUGP("SCSI_READ10 returns %d\n", result);
		if (result == USB_STOR_TRANSPORT_GOOD)
			return 0;
		usb_stor_request_sense(srb, us);
	} while (retries--);

	return -EIO;
}

static int usb_stor_write_10(ccb *srb, struct us_data *us,
                             unsigned long start, unsigned short blocks)
{
	int retries, result;

	retries = 2;
	do {
		US_DEBUGP("SCSI_WRITE10: start %lx blocks %x\n", start, blocks);
		memset(&srb->cmd[0], 0, 10);
		srb->cmdlen = 10;
		srb->cmd[0] = SCSI_WRITE10;
		srb->cmd[2] = (u8)(start >> 24);
		srb->cmd[3] = (u8)(start >> 16);
		srb->cmd[4] = (u8)(start >> 8);
		srb->cmd[5] = (u8)(start >> 0);
		srb->cmd[7] = (u8)(blocks >> 8);
		srb->cmd[8] = (u8)(blocks >> 0);
		result = us->transport(srb, us);
		US_DEBUGP("SCSI_WRITE10 returns %d\n", result);
		if (result == USB_STOR_TRANSPORT_GOOD)
			return 0;
		usb_stor_request_sense(srb, us);
	} while (retries--);

	return us->transport(srb, us);
}


/***********************************************************************
 * Disk driver interface
 ***********************************************************************/

#define US_MAX_IO_BLK 32

#define to_usb_mass_storage(x) container_of((x), struct us_blk_dev, blk)

enum { io_rd, io_wr };

/* Read / write a chunk of sectors on media */
static int usb_stor_blk_io(int io_op, struct block_device *disk_dev,
			int sector_start, int sector_count, void *buffer)
{
	struct us_blk_dev *pblk_dev = to_usb_mass_storage(disk_dev);
	struct us_data *us = pblk_dev->us;
	ccb us_ccb;
	unsigned sectors_done;

	if (sector_count == 0)
		return 0;

	/* check for unsupported block size */
	if (pblk_dev->blk.blockbits != SECTOR_SHIFT) {
		US_DEBUGP("%s: unsupported block shift %d\n",
		          __func__, pblk_dev->blk.blockbits);
		return -EINVAL;
	}

	/* check for invalid sector_start */
	if (sector_start >= pblk_dev->blk.num_blocks || sector_start > (ulong)-1) {
		US_DEBUGP("%s: start sector %d too large\n",
		          __func__, sector_start);
		return -EINVAL;
	}

	us_ccb.lun = pblk_dev->lun;
	usb_disable_asynch(1);

	/* ensure unit ready */
	US_DEBUGP("Testing for unit ready\n");
	if (usb_stor_test_unit_ready(&us_ccb, us)) {
		US_DEBUGP("Device NOT ready\n");
		usb_disable_asynch(0);
		return -EIO;
	}

	/* possibly limit the amount of I/O data */
	if (sector_count > INT_MAX) {
		sector_count = INT_MAX;
		US_DEBUGP("Restricting I/O to %u blocks\n", sector_count);
	}
	if (sector_start + sector_count > pblk_dev->blk.num_blocks) {
		sector_count = pblk_dev->blk.num_blocks - sector_start;
		US_DEBUGP("Restricting I/O to %u blocks\n", sector_count);
	}

	/* read / write the requested data */
	US_DEBUGP("%s %u block(s), starting from %d\n",
	          ((io_op == io_rd) ? "Read" : "Write"),
	          sector_count, sector_start);
	sectors_done = 0;
	while (sector_count > 0) {
		int result;
		unsigned n = min(sector_count, US_MAX_IO_BLK);
		us_ccb.pdata = buffer + (sectors_done * SECTOR_SIZE);
		us_ccb.datalen = n * SECTOR_SIZE;
		if (io_op == io_rd)
			result = usb_stor_read_10(&us_ccb, us,
			                          (ulong)sector_start, n);
		else
			result = usb_stor_write_10(&us_ccb, us,
			                           (ulong)sector_start, n);
		if (result != 0) {
			US_DEBUGP("I/O error at sector %d\n", sector_start);
			break;
		}
		sector_start += n;
		sector_count -= n;
		sectors_done += n;
	}

	usb_disable_asynch(0);

	US_DEBUGP("Successful I/O of %d blocks\n", sectors_done);

	return (sector_count != 0) ? -EIO : 0;
}

/* Write a chunk of sectors to media */
static int __maybe_unused usb_stor_blk_write(struct block_device *blk,
				const void *buffer, int block, int num_blocks)
{
	return usb_stor_blk_io(io_wr, blk, block, num_blocks, (void *)buffer);
}

/* Read a chunk of sectors from media */
static int usb_stor_blk_read(struct block_device *blk, void *buffer, int block,
				int num_blocks)
{
	return usb_stor_blk_io(io_rd, blk, block, num_blocks, buffer);
}

static struct block_device_ops usb_mass_storage_ops = {
	.read = usb_stor_blk_read,
#ifdef CONFIG_BLOCK_WRITE
	.write = usb_stor_blk_write,
#endif
};

/***********************************************************************
 * Block device routines
 ***********************************************************************/

static unsigned char us_io_buf[512];

static int usb_limit_blk_cnt(unsigned cnt)
{
	if (cnt > 0x7fffffff) {
		pr_warn("Limiting device size due to 31 bit contraints\n");
		return 0x7fffffff;
	}

	return (int)cnt;
}

/* Prepare a disk device */
static int usb_stor_init_blkdev(struct us_blk_dev *pblk_dev)
{
	struct us_data *us = pblk_dev->us;
	ccb us_ccb;
	unsigned long *pcap;
	int result = 0;

	us_ccb.pdata = us_io_buf;
	us_ccb.lun = pblk_dev->lun;

	pblk_dev->blk.num_blocks = 0;
	usb_disable_asynch(1);

	/* get device info */
	US_DEBUGP("Reading device info\n");
	us_ccb.datalen = 36;
	if (usb_stor_inquiry(&us_ccb, us)) {
		US_DEBUGP("Cannot read device info\n");
		result = -ENODEV;
		goto Exit;
	}
	US_DEBUGP("Peripheral type: %x, removable: %x\n",
	          us_io_buf[0], (us_io_buf[1] >> 7));
	US_DEBUGP("ISO ver: %x, resp format: %x\n", us_io_buf[2], us_io_buf[3]);
	US_DEBUGP("Vendor/product/rev: %28s\n", &us_io_buf[8]);
	// TODO:  process and store device info

	/* ensure unit ready */
	US_DEBUGP("Testing for unit ready\n");
	us_ccb.datalen = 0;
	if (usb_stor_test_unit_ready(&us_ccb, us)) {
		US_DEBUGP("Device NOT ready\n");
		result = -ENODEV;
		goto Exit;
	}

	/* read capacity */
	US_DEBUGP("Reading capacity\n");
	memset(us_ccb.pdata, 0, 8);
	us_ccb.datalen = sizeof(us_io_buf);
	if (usb_stor_read_capacity(&us_ccb, us) != 0) {
		US_DEBUGP("Cannot read device capacity\n");
		result = -EIO;
		goto Exit;
	}
	pcap = (unsigned long *)us_ccb.pdata;
	US_DEBUGP("Read Capacity returns: 0x%lx, 0x%lx\n", pcap[0], pcap[1]);
	pblk_dev->blk.num_blocks = usb_limit_blk_cnt(be32_to_cpu(pcap[0]) + 1);
	if (be32_to_cpu(pcap[1]) != SECTOR_SIZE)
		pr_warn("Support only %d bytes sectors\n", SECTOR_SIZE);
	pblk_dev->blk.blockbits = SECTOR_SHIFT;
	US_DEBUGP("Capacity = 0x%x, blockshift = 0x%x\n",
	          pblk_dev->blk.num_blocks, pblk_dev->blk.blockbits);

Exit:
	usb_disable_asynch(0);
	return result;
}

/* Create and register a disk device for the specified LUN */
static int usb_stor_add_blkdev(struct us_data *us, struct device_d *dev,
							unsigned char lun)
{
	struct us_blk_dev *pblk_dev;
	int result;

	/* allocate a new USB block device */
	pblk_dev = xzalloc(sizeof(struct us_blk_dev));

	/* initialize blk dev data */
	pblk_dev->blk.dev = dev;
	pblk_dev->blk.ops = &usb_mass_storage_ops;
	pblk_dev->us = us;
	pblk_dev->lun = lun;

	/* read some info and get the unit ready */
	result = usb_stor_init_blkdev(pblk_dev);
	if (result < 0)
		goto BadDevice;

	result = cdev_find_free_index("disk");
	if (result == -1)
		pr_err("Cannot find a free number for the disk node\n");
	pr_info("Using index %d for the new disk\n", result);

	pblk_dev->blk.cdev.name = asprintf("disk%d", result);
	pblk_dev->blk.blockbits = SECTOR_SHIFT;

	result = blockdevice_register(&pblk_dev->blk);
	if (result != 0) {
		dev_err(dev, "Failed to register blockdevice\n");
		goto BadDevice;
	}

	/* create partitions on demand */
	result = parse_partition_table(&pblk_dev->blk);
	if (result != 0)
		dev_warn(dev, "No partition table found\n");

	list_add_tail(&pblk_dev->list, &us->blk_dev_list);
	US_DEBUGP("USB disk device successfully added\n");

	return 0;

BadDevice:
	US_DEBUGP("%s failed with %d\n", __func__, result);
	free(pblk_dev);
	return result;
}

/***********************************************************************
 * USB Mass Storage device probe and initialization
 ***********************************************************************/

/* Get the transport settings */
static void get_transport(struct us_data *us)
{
	switch (us->protocol) {
	case US_PR_BULK:
		us->transport_name = "Bulk";
		us->transport = &usb_stor_Bulk_transport;
		us->transport_reset = &usb_stor_Bulk_reset;
		break;
	}

	US_DEBUGP("Transport: %s\n", us->transport_name);
}

/* Get the endpoint settings */
static int get_pipes(struct us_data *us, struct usb_interface_descriptor *intf)
{
	unsigned int i;
	struct usb_endpoint_descriptor *ep;
	struct usb_endpoint_descriptor *ep_in = NULL;
	struct usb_endpoint_descriptor *ep_out = NULL;
	struct usb_endpoint_descriptor *ep_int = NULL;

	/*
	 * Find the first endpoint of each type we need.
	 * We are expecting a minimum of 2 endpoints - in and out (bulk).
	 * An optional interrupt-in is OK (necessary for CBI protocol).
	 * We will ignore any others.
	 */
	for (i = 0; i < intf->bNumEndpoints; i++) {
		ep = &intf->ep_desc[i];

		if (USB_EP_IS_XFER_BULK(ep)) {
			if (USB_EP_IS_DIR_IN(ep)) {
				if ( !ep_in )
					ep_in = ep;
			}
			else {
				if ( !ep_out )
					ep_out = ep;
			}
		}
		else if (USB_EP_IS_INT_IN(ep)) {
			if (!ep_int)
				ep_int = ep;
		}
	}
	if (!ep_in || !ep_out || (us->protocol == US_PR_CBI && !ep_int)) {
		US_DEBUGP("Endpoint sanity check failed! Rejecting dev.\n");
		return -EIO;
	}

	/* Store the pipe values */
	us->send_bulk_ep = USB_EP_NUM(ep_out);
	us->recv_bulk_ep = USB_EP_NUM(ep_in);
	if (ep_int) {
		us->recv_intr_ep = USB_EP_NUM(ep_int);
		us->ep_bInterval = ep_int->bInterval;
	}
	return 0;
}

/* Scan device's LUNs, registering a disk device for each LUN */
static int usb_stor_scan(struct usb_device *usbdev, struct us_data *us)
{
	unsigned char lun;
	int num_devs = 0;

	/* obtain the max LUN */
	us->max_lun = 0;
	if (us->protocol == US_PR_BULK)
		us->max_lun = usb_stor_Bulk_max_lun(us);

	/* register a disk device for each active LUN */
	for (lun=0; lun<=us->max_lun; lun++) {
		if (usb_stor_add_blkdev(us, &usbdev->dev, lun) == 0)
			num_devs++;
	}

	US_DEBUGP("Found %d block devices on %s\n", num_devs, usbdev->dev.name);

	return  num_devs ? 0 : -ENODEV;
}

/* Probe routine for standard devices */
static int usb_stor_probe(struct usb_device *usbdev,
			 const struct usb_device_id *id)
{
	struct us_data *us;
	int result;
	int ifno;
	struct usb_interface_descriptor *intf;

	US_DEBUGP("Supported USB Mass Storage device detected\n");

	/* scan usbdev interfaces again to find one that we can handle */
	for (ifno=0; ifno<usbdev->config.no_of_if; ifno++) {
		intf = &usbdev->config.if_desc[ifno];

		if (intf->bInterfaceClass    == USB_CLASS_MASS_STORAGE &&
		    intf->bInterfaceSubClass == US_SC_SCSI &&
		    intf->bInterfaceProtocol == US_PR_BULK)
			break;
	}
	if (ifno >= usbdev->config.no_of_if)
		return -ENXIO;

	/* select the right interface */
	result = usb_set_interface(usbdev, intf->bInterfaceNumber, 0);
	if (result)
		return result;

	US_DEBUGP("Selected interface %d\n", (int)intf->bInterfaceNumber);

	/* allocate us_data structure */
	us = (struct us_data *)malloc(sizeof(struct us_data));
	if (!us)
		return -ENOMEM;
	memset(us, 0, sizeof(struct us_data));

	/* initialize the us_data structure */
	us->pusb_dev = usbdev;
	us->flags = 0;
	us->ifnum = intf->bInterfaceNumber;
	us->subclass = intf->bInterfaceSubClass;
	us->protocol = intf->bInterfaceProtocol;
	INIT_LIST_HEAD(&us->blk_dev_list);

	/* get standard transport and protocol settings */
	get_transport(us);

	/* find the endpoints needed by the transport */
	result = get_pipes(us, intf);
	if (result)
		goto BadDevice;

	/* register a disk device for each LUN */
	usb_stor_scan(usbdev, us);

	/* associate the us_data structure with the usb_device */
	usbdev->drv_data = us;

	return 0;

BadDevice:
	US_DEBUGP("%s failed with %d\n", __func__, result);
	free(us);
	return result;
}

/* Handle a USB mass-storage disconnect */
static void usb_stor_disconnect(struct usb_device *usbdev)
{
	struct us_data *us = (struct us_data *)usbdev->drv_data;
	struct us_blk_dev *bdev, *bdev_tmp;

	list_for_each_entry_safe(bdev, bdev_tmp, &us->blk_dev_list, list) {
		list_del(&bdev->list);
		blockdevice_unregister(&bdev->blk);
		free(bdev);
	}

	/* release device's private data */
	usbdev->drv_data = 0;
	free(us);
}

#define USUAL_DEV(use_proto, use_trans, drv_info) \
{	USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, use_proto, use_trans), \
	.driver_info = (drv_info) }

/* Table with supported devices, most specific first. */
static struct usb_device_id usb_storage_usb_ids[] = {
	USUAL_DEV(US_SC_SCSI, US_PR_BULK, 0),	// SCSI intf, BBB proto
	{ }
};


/***********************************************************************
 * USB Storage driver initialization and registration
 ***********************************************************************/

static struct usb_driver usb_storage_driver = {
	.driver.name =	"usb-storage",
	.id_table =	usb_storage_usb_ids,
	.probe =	usb_stor_probe,
	.disconnect =	usb_stor_disconnect,
};

static int __init usb_stor_init(void)
{
	return usb_driver_register(&usb_storage_driver);
}
device_initcall(usb_stor_init);