aba9ccb7f5b7bfd58062a6726cfd334d835ea12a
[oweals/u-boot.git] / common / usb_storage.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Most of this source has been derived from the Linux USB
4  * project:
5  *   (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
6  *   (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
7  *   (c) 1999 Michael Gee (michael@linuxspecific.com)
8  *   (c) 2000 Yggdrasil Computing, Inc.
9  *
10  *
11  * Adapted for U-Boot:
12  *   (C) Copyright 2001 Denis Peter, MPL AG Switzerland
13  * Driver model conversion:
14  *   (C) Copyright 2015 Google, Inc
15  *
16  * For BBB support (C) Copyright 2003
17  * Gary Jennejohn, DENX Software Engineering <garyj@denx.de>
18  *
19  * BBB support based on /sys/dev/usb/umass.c from
20  * FreeBSD.
21  */
22
23 /* Note:
24  * Currently only the CBI transport protocoll has been implemented, and it
25  * is only tested with a TEAC USB Floppy. Other Massstorages with CBI or CB
26  * transport protocoll may work as well.
27  */
28 /*
29  * New Note:
30  * Support for USB Mass Storage Devices (BBB) has been added. It has
31  * only been tested with USB memory sticks.
32  */
33
34
35 #include <common.h>
36 #include <blk.h>
37 #include <command.h>
38 #include <dm.h>
39 #include <errno.h>
40 #include <mapmem.h>
41 #include <memalign.h>
42 #include <asm/byteorder.h>
43 #include <asm/cache.h>
44 #include <asm/processor.h>
45 #include <dm/device-internal.h>
46 #include <dm/lists.h>
47
48 #include <part.h>
49 #include <usb.h>
50
51 #undef BBB_COMDAT_TRACE
52 #undef BBB_XPORT_TRACE
53
54 #include <scsi.h>
55 /* direction table -- this indicates the direction of the data
56  * transfer for each command code -- a 1 indicates input
57  */
58 static const unsigned char us_direction[256/8] = {
59         0x28, 0x81, 0x14, 0x14, 0x20, 0x01, 0x90, 0x77,
60         0x0C, 0x20, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,
61         0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,
62         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
63 };
64 #define US_DIRECTION(x) ((us_direction[x>>3] >> (x & 7)) & 1)
65
66 static struct scsi_cmd usb_ccb __aligned(ARCH_DMA_MINALIGN);
67 static __u32 CBWTag;
68
69 static int usb_max_devs; /* number of highest available usb device */
70
71 #if !CONFIG_IS_ENABLED(BLK)
72 static struct blk_desc usb_dev_desc[USB_MAX_STOR_DEV];
73 #endif
74
75 struct us_data;
76 typedef int (*trans_cmnd)(struct scsi_cmd *cb, struct us_data *data);
77 typedef int (*trans_reset)(struct us_data *data);
78
79 struct us_data {
80         struct usb_device *pusb_dev;     /* this usb_device */
81
82         unsigned int    flags;                  /* from filter initially */
83 #       define USB_READY        (1 << 0)
84         unsigned char   ifnum;                  /* interface number */
85         unsigned char   ep_in;                  /* in endpoint */
86         unsigned char   ep_out;                 /* out ....... */
87         unsigned char   ep_int;                 /* interrupt . */
88         unsigned char   subclass;               /* as in overview */
89         unsigned char   protocol;               /* .............. */
90         unsigned char   attention_done;         /* force attn on first cmd */
91         unsigned short  ip_data;                /* interrupt data */
92         int             action;                 /* what to do */
93         int             ip_wanted;              /* needed */
94         int             *irq_handle;            /* for USB int requests */
95         unsigned int    irqpipe;                /* pipe for release_irq */
96         unsigned char   irqmaxp;                /* max packed for irq Pipe */
97         unsigned char   irqinterval;            /* Intervall for IRQ Pipe */
98         struct scsi_cmd *srb;                   /* current srb */
99         trans_reset     transport_reset;        /* reset routine */
100         trans_cmnd      transport;              /* transport routine */
101         unsigned short  max_xfer_blk;           /* maximum transfer blocks */
102 };
103
104 #if !CONFIG_IS_ENABLED(BLK)
105 static struct us_data usb_stor[USB_MAX_STOR_DEV];
106 #endif
107
108 #define USB_STOR_TRANSPORT_GOOD    0
109 #define USB_STOR_TRANSPORT_FAILED -1
110 #define USB_STOR_TRANSPORT_ERROR  -2
111
112 int usb_stor_get_info(struct usb_device *dev, struct us_data *us,
113                       struct blk_desc *dev_desc);
114 int usb_storage_probe(struct usb_device *dev, unsigned int ifnum,
115                       struct us_data *ss);
116 #if CONFIG_IS_ENABLED(BLK)
117 static unsigned long usb_stor_read(struct udevice *dev, lbaint_t blknr,
118                                    lbaint_t blkcnt, void *buffer);
119 static unsigned long usb_stor_write(struct udevice *dev, lbaint_t blknr,
120                                     lbaint_t blkcnt, const void *buffer);
121 #else
122 static unsigned long usb_stor_read(struct blk_desc *block_dev, lbaint_t blknr,
123                                    lbaint_t blkcnt, void *buffer);
124 static unsigned long usb_stor_write(struct blk_desc *block_dev, lbaint_t blknr,
125                                     lbaint_t blkcnt, const void *buffer);
126 #endif
127 void uhci_show_temp_int_td(void);
128
129 static void usb_show_progress(void)
130 {
131         debug(".");
132 }
133
134 /*******************************************************************************
135  * show info on storage devices; 'usb start/init' must be invoked earlier
136  * as we only retrieve structures populated during devices initialization
137  */
138 int usb_stor_info(void)
139 {
140         int count = 0;
141 #if CONFIG_IS_ENABLED(BLK)
142         struct udevice *dev;
143
144         for (blk_first_device(IF_TYPE_USB, &dev);
145              dev;
146              blk_next_device(&dev)) {
147                 struct blk_desc *desc = dev_get_uclass_platdata(dev);
148
149                 printf("  Device %d: ", desc->devnum);
150                 dev_print(desc);
151                 count++;
152         }
153 #else
154         int i;
155
156         if (usb_max_devs > 0) {
157                 for (i = 0; i < usb_max_devs; i++) {
158                         printf("  Device %d: ", i);
159                         dev_print(&usb_dev_desc[i]);
160                 }
161                 return 0;
162         }
163 #endif
164         if (!count) {
165                 printf("No storage devices, perhaps not 'usb start'ed..?\n");
166                 return 1;
167         }
168
169         return 0;
170 }
171
172 static unsigned int usb_get_max_lun(struct us_data *us)
173 {
174         int len;
175         ALLOC_CACHE_ALIGN_BUFFER(unsigned char, result, 1);
176         len = usb_control_msg(us->pusb_dev,
177                               usb_rcvctrlpipe(us->pusb_dev, 0),
178                               US_BBB_GET_MAX_LUN,
179                               USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
180                               0, us->ifnum,
181                               result, sizeof(char),
182                               USB_CNTL_TIMEOUT * 5);
183         debug("Get Max LUN -> len = %i, result = %i\n", len, (int) *result);
184         return (len > 0) ? *result : 0;
185 }
186
187 static int usb_stor_probe_device(struct usb_device *udev)
188 {
189         int lun, max_lun;
190
191 #if CONFIG_IS_ENABLED(BLK)
192         struct us_data *data;
193         int ret;
194 #else
195         int start;
196
197         if (udev == NULL)
198                 return -ENOENT; /* no more devices available */
199 #endif
200
201         debug("\n\nProbing for storage\n");
202 #if CONFIG_IS_ENABLED(BLK)
203         /*
204          * We store the us_data in the mass storage device's platdata. It
205          * is shared by all LUNs (block devices) attached to this mass storage
206          * device.
207          */
208         data = dev_get_platdata(udev->dev);
209         if (!usb_storage_probe(udev, 0, data))
210                 return 0;
211         max_lun = usb_get_max_lun(data);
212         for (lun = 0; lun <= max_lun; lun++) {
213                 struct blk_desc *blkdev;
214                 struct udevice *dev;
215                 char str[10];
216
217                 snprintf(str, sizeof(str), "lun%d", lun);
218                 ret = blk_create_devicef(udev->dev, "usb_storage_blk", str,
219                                          IF_TYPE_USB, usb_max_devs, 512, 0,
220                                          &dev);
221                 if (ret) {
222                         debug("Cannot bind driver\n");
223                         return ret;
224                 }
225
226                 blkdev = dev_get_uclass_platdata(dev);
227                 blkdev->target = 0xff;
228                 blkdev->lun = lun;
229
230                 ret = usb_stor_get_info(udev, data, blkdev);
231                 if (ret == 1) {
232                         usb_max_devs++;
233                         debug("%s: Found device %p\n", __func__, udev);
234                 } else {
235                         debug("usb_stor_get_info: Invalid device\n");
236                         ret = device_unbind(dev);
237                         if (ret)
238                                 return ret;
239                 }
240         }
241 #else
242         /* We don't have space to even probe if we hit the maximum */
243         if (usb_max_devs == USB_MAX_STOR_DEV) {
244                 printf("max USB Storage Device reached: %d stopping\n",
245                        usb_max_devs);
246                 return -ENOSPC;
247         }
248
249         if (!usb_storage_probe(udev, 0, &usb_stor[usb_max_devs]))
250                 return 0;
251
252         /*
253          * OK, it's a storage device.  Iterate over its LUNs and populate
254          * usb_dev_desc'
255          */
256         start = usb_max_devs;
257
258         max_lun = usb_get_max_lun(&usb_stor[usb_max_devs]);
259         for (lun = 0; lun <= max_lun && usb_max_devs < USB_MAX_STOR_DEV;
260              lun++) {
261                 struct blk_desc *blkdev;
262
263                 blkdev = &usb_dev_desc[usb_max_devs];
264                 memset(blkdev, '\0', sizeof(struct blk_desc));
265                 blkdev->if_type = IF_TYPE_USB;
266                 blkdev->devnum = usb_max_devs;
267                 blkdev->part_type = PART_TYPE_UNKNOWN;
268                 blkdev->target = 0xff;
269                 blkdev->type = DEV_TYPE_UNKNOWN;
270                 blkdev->block_read = usb_stor_read;
271                 blkdev->block_write = usb_stor_write;
272                 blkdev->lun = lun;
273                 blkdev->priv = udev;
274
275                 if (usb_stor_get_info(udev, &usb_stor[start],
276                                       &usb_dev_desc[usb_max_devs]) == 1) {
277                         debug("partype: %d\n", blkdev->part_type);
278                         part_init(blkdev);
279                         debug("partype: %d\n", blkdev->part_type);
280                         usb_max_devs++;
281                         debug("%s: Found device %p\n", __func__, udev);
282                 }
283         }
284 #endif
285
286         return 0;
287 }
288
289 void usb_stor_reset(void)
290 {
291         usb_max_devs = 0;
292 }
293
294 /*******************************************************************************
295  * scan the usb and reports device info
296  * to the user if mode = 1
297  * returns current device or -1 if no
298  */
299 int usb_stor_scan(int mode)
300 {
301         if (mode == 1)
302                 printf("       scanning usb for storage devices... ");
303
304 #if !CONFIG_IS_ENABLED(DM_USB)
305         unsigned char i;
306
307         usb_disable_asynch(1); /* asynch transfer not allowed */
308
309         usb_stor_reset();
310         for (i = 0; i < USB_MAX_DEVICE; i++) {
311                 struct usb_device *dev;
312
313                 dev = usb_get_dev_index(i); /* get device */
314                 debug("i=%d\n", i);
315                 if (usb_stor_probe_device(dev))
316                         break;
317         } /* for */
318
319         usb_disable_asynch(0); /* asynch transfer allowed */
320 #endif
321         printf("%d Storage Device(s) found\n", usb_max_devs);
322         if (usb_max_devs > 0)
323                 return 0;
324         return -1;
325 }
326
327 static int usb_stor_irq(struct usb_device *dev)
328 {
329         struct us_data *us;
330         us = (struct us_data *)dev->privptr;
331
332         if (us->ip_wanted)
333                 us->ip_wanted = 0;
334         return 0;
335 }
336
337
338 #ifdef  DEBUG
339
340 static void usb_show_srb(struct scsi_cmd *pccb)
341 {
342         int i;
343         printf("SRB: len %d datalen 0x%lX\n ", pccb->cmdlen, pccb->datalen);
344         for (i = 0; i < 12; i++)
345                 printf("%02X ", pccb->cmd[i]);
346         printf("\n");
347 }
348
349 static void display_int_status(unsigned long tmp)
350 {
351         printf("Status: %s %s %s %s %s %s %s\n",
352                 (tmp & USB_ST_ACTIVE) ? "Active" : "",
353                 (tmp & USB_ST_STALLED) ? "Stalled" : "",
354                 (tmp & USB_ST_BUF_ERR) ? "Buffer Error" : "",
355                 (tmp & USB_ST_BABBLE_DET) ? "Babble Det" : "",
356                 (tmp & USB_ST_NAK_REC) ? "NAKed" : "",
357                 (tmp & USB_ST_CRC_ERR) ? "CRC Error" : "",
358                 (tmp & USB_ST_BIT_ERR) ? "Bitstuff Error" : "");
359 }
360 #endif
361 /***********************************************************************
362  * Data transfer routines
363  ***********************************************************************/
364
365 static int us_one_transfer(struct us_data *us, int pipe, char *buf, int length)
366 {
367         int max_size;
368         int this_xfer;
369         int result;
370         int partial;
371         int maxtry;
372         int stat;
373
374         /* determine the maximum packet size for these transfers */
375         max_size = usb_maxpacket(us->pusb_dev, pipe) * 16;
376
377         /* while we have data left to transfer */
378         while (length) {
379
380                 /* calculate how long this will be -- maximum or a remainder */
381                 this_xfer = length > max_size ? max_size : length;
382                 length -= this_xfer;
383
384                 /* setup the retry counter */
385                 maxtry = 10;
386
387                 /* set up the transfer loop */
388                 do {
389                         /* transfer the data */
390                         debug("Bulk xfer 0x%lx(%d) try #%d\n",
391                               (ulong)map_to_sysmem(buf), this_xfer,
392                               11 - maxtry);
393                         result = usb_bulk_msg(us->pusb_dev, pipe, buf,
394                                               this_xfer, &partial,
395                                               USB_CNTL_TIMEOUT * 5);
396                         debug("bulk_msg returned %d xferred %d/%d\n",
397                               result, partial, this_xfer);
398                         if (us->pusb_dev->status != 0) {
399                                 /* if we stall, we need to clear it before
400                                  * we go on
401                                  */
402 #ifdef DEBUG
403                                 display_int_status(us->pusb_dev->status);
404 #endif
405                                 if (us->pusb_dev->status & USB_ST_STALLED) {
406                                         debug("stalled ->clearing endpoint" \
407                                               "halt for pipe 0x%x\n", pipe);
408                                         stat = us->pusb_dev->status;
409                                         usb_clear_halt(us->pusb_dev, pipe);
410                                         us->pusb_dev->status = stat;
411                                         if (this_xfer == partial) {
412                                                 debug("bulk transferred" \
413                                                       "with error %lX," \
414                                                       " but data ok\n",
415                                                       us->pusb_dev->status);
416                                                 return 0;
417                                         }
418                                         else
419                                                 return result;
420                                 }
421                                 if (us->pusb_dev->status & USB_ST_NAK_REC) {
422                                         debug("Device NAKed bulk_msg\n");
423                                         return result;
424                                 }
425                                 debug("bulk transferred with error");
426                                 if (this_xfer == partial) {
427                                         debug(" %ld, but data ok\n",
428                                               us->pusb_dev->status);
429                                         return 0;
430                                 }
431                                 /* if our try counter reaches 0, bail out */
432                                         debug(" %ld, data %d\n",
433                                               us->pusb_dev->status, partial);
434                                 if (!maxtry--)
435                                                 return result;
436                         }
437                         /* update to show what data was transferred */
438                         this_xfer -= partial;
439                         buf += partial;
440                         /* continue until this transfer is done */
441                 } while (this_xfer);
442         }
443
444         /* if we get here, we're done and successful */
445         return 0;
446 }
447
448 static int usb_stor_BBB_reset(struct us_data *us)
449 {
450         int result;
451         unsigned int pipe;
452
453         /*
454          * Reset recovery (5.3.4 in Universal Serial Bus Mass Storage Class)
455          *
456          * For Reset Recovery the host shall issue in the following order:
457          * a) a Bulk-Only Mass Storage Reset
458          * b) a Clear Feature HALT to the Bulk-In endpoint
459          * c) a Clear Feature HALT to the Bulk-Out endpoint
460          *
461          * This is done in 3 steps.
462          *
463          * If the reset doesn't succeed, the device should be port reset.
464          *
465          * This comment stolen from FreeBSD's /sys/dev/usb/umass.c.
466          */
467         debug("BBB_reset\n");
468         result = usb_control_msg(us->pusb_dev, usb_sndctrlpipe(us->pusb_dev, 0),
469                                  US_BBB_RESET,
470                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
471                                  0, us->ifnum, NULL, 0, USB_CNTL_TIMEOUT * 5);
472
473         if ((result < 0) && (us->pusb_dev->status & USB_ST_STALLED)) {
474                 debug("RESET:stall\n");
475                 return -1;
476         }
477
478         /* long wait for reset */
479         mdelay(150);
480         debug("BBB_reset result %d: status %lX reset\n",
481               result, us->pusb_dev->status);
482         pipe = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
483         result = usb_clear_halt(us->pusb_dev, pipe);
484         /* long wait for reset */
485         mdelay(150);
486         debug("BBB_reset result %d: status %lX clearing IN endpoint\n",
487               result, us->pusb_dev->status);
488         /* long wait for reset */
489         pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
490         result = usb_clear_halt(us->pusb_dev, pipe);
491         mdelay(150);
492         debug("BBB_reset result %d: status %lX clearing OUT endpoint\n",
493               result, us->pusb_dev->status);
494         debug("BBB_reset done\n");
495         return 0;
496 }
497
498 /* FIXME: this reset function doesn't really reset the port, and it
499  * should. Actually it should probably do what it's doing here, and
500  * reset the port physically
501  */
502 static int usb_stor_CB_reset(struct us_data *us)
503 {
504         unsigned char cmd[12];
505         int result;
506
507         debug("CB_reset\n");
508         memset(cmd, 0xff, sizeof(cmd));
509         cmd[0] = SCSI_SEND_DIAG;
510         cmd[1] = 4;
511         result = usb_control_msg(us->pusb_dev, usb_sndctrlpipe(us->pusb_dev, 0),
512                                  US_CBI_ADSC,
513                                  USB_TYPE_CLASS | USB_RECIP_INTERFACE,
514                                  0, us->ifnum, cmd, sizeof(cmd),
515                                  USB_CNTL_TIMEOUT * 5);
516
517         /* long wait for reset */
518         mdelay(1500);
519         debug("CB_reset result %d: status %lX clearing endpoint halt\n",
520               result, us->pusb_dev->status);
521         usb_clear_halt(us->pusb_dev, usb_rcvbulkpipe(us->pusb_dev, us->ep_in));
522         usb_clear_halt(us->pusb_dev, usb_rcvbulkpipe(us->pusb_dev, us->ep_out));
523
524         debug("CB_reset done\n");
525         return 0;
526 }
527
528 /*
529  * Set up the command for a BBB device. Note that the actual SCSI
530  * command is copied into cbw.CBWCDB.
531  */
532 static int usb_stor_BBB_comdat(struct scsi_cmd *srb, struct us_data *us)
533 {
534         int result;
535         int actlen;
536         int dir_in;
537         unsigned int pipe;
538         ALLOC_CACHE_ALIGN_BUFFER(struct umass_bbb_cbw, cbw, 1);
539
540         dir_in = US_DIRECTION(srb->cmd[0]);
541
542 #ifdef BBB_COMDAT_TRACE
543         printf("dir %d lun %d cmdlen %d cmd %p datalen %lu pdata %p\n",
544                 dir_in, srb->lun, srb->cmdlen, srb->cmd, srb->datalen,
545                 srb->pdata);
546         if (srb->cmdlen) {
547                 for (result = 0; result < srb->cmdlen; result++)
548                         printf("cmd[%d] %#x ", result, srb->cmd[result]);
549                 printf("\n");
550         }
551 #endif
552         /* sanity checks */
553         if (!(srb->cmdlen <= CBWCDBLENGTH)) {
554                 debug("usb_stor_BBB_comdat:cmdlen too large\n");
555                 return -1;
556         }
557
558         /* always OUT to the ep */
559         pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
560
561         cbw->dCBWSignature = cpu_to_le32(CBWSIGNATURE);
562         cbw->dCBWTag = cpu_to_le32(CBWTag++);
563         cbw->dCBWDataTransferLength = cpu_to_le32(srb->datalen);
564         cbw->bCBWFlags = (dir_in ? CBWFLAGS_IN : CBWFLAGS_OUT);
565         cbw->bCBWLUN = srb->lun;
566         cbw->bCDBLength = srb->cmdlen;
567         /* copy the command data into the CBW command data buffer */
568         /* DST SRC LEN!!! */
569
570         memcpy(cbw->CBWCDB, srb->cmd, srb->cmdlen);
571         result = usb_bulk_msg(us->pusb_dev, pipe, cbw, UMASS_BBB_CBW_SIZE,
572                               &actlen, USB_CNTL_TIMEOUT * 5);
573         if (result < 0)
574                 debug("usb_stor_BBB_comdat:usb_bulk_msg error\n");
575         return result;
576 }
577
578 /* FIXME: we also need a CBI_command which sets up the completion
579  * interrupt, and waits for it
580  */
581 static int usb_stor_CB_comdat(struct scsi_cmd *srb, struct us_data *us)
582 {
583         int result = 0;
584         int dir_in, retry;
585         unsigned int pipe;
586         unsigned long status;
587
588         retry = 5;
589         dir_in = US_DIRECTION(srb->cmd[0]);
590
591         if (dir_in)
592                 pipe = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
593         else
594                 pipe = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
595
596         while (retry--) {
597                 debug("CBI gets a command: Try %d\n", 5 - retry);
598 #ifdef DEBUG
599                 usb_show_srb(srb);
600 #endif
601                 /* let's send the command via the control pipe */
602                 result = usb_control_msg(us->pusb_dev,
603                                          usb_sndctrlpipe(us->pusb_dev , 0),
604                                          US_CBI_ADSC,
605                                          USB_TYPE_CLASS | USB_RECIP_INTERFACE,
606                                          0, us->ifnum,
607                                          srb->cmd, srb->cmdlen,
608                                          USB_CNTL_TIMEOUT * 5);
609                 debug("CB_transport: control msg returned %d, status %lX\n",
610                       result, us->pusb_dev->status);
611                 /* check the return code for the command */
612                 if (result < 0) {
613                         if (us->pusb_dev->status & USB_ST_STALLED) {
614                                 status = us->pusb_dev->status;
615                                 debug(" stall during command found," \
616                                       " clear pipe\n");
617                                 usb_clear_halt(us->pusb_dev,
618                                               usb_sndctrlpipe(us->pusb_dev, 0));
619                                 us->pusb_dev->status = status;
620                         }
621                         debug(" error during command %02X" \
622                               " Stat = %lX\n", srb->cmd[0],
623                               us->pusb_dev->status);
624                         return result;
625                 }
626                 /* transfer the data payload for this command, if one exists*/
627
628                 debug("CB_transport: control msg returned %d," \
629                       " direction is %s to go 0x%lx\n", result,
630                       dir_in ? "IN" : "OUT", srb->datalen);
631                 if (srb->datalen) {
632                         result = us_one_transfer(us, pipe, (char *)srb->pdata,
633                                                  srb->datalen);
634                         debug("CBI attempted to transfer data," \
635                               " result is %d status %lX, len %d\n",
636                               result, us->pusb_dev->status,
637                                 us->pusb_dev->act_len);
638                         if (!(us->pusb_dev->status & USB_ST_NAK_REC))
639                                 break;
640                 } /* if (srb->datalen) */
641                 else
642                         break;
643         }
644         /* return result */
645
646         return result;
647 }
648
649
650 static int usb_stor_CBI_get_status(struct scsi_cmd *srb, struct us_data *us)
651 {
652         int timeout;
653
654         us->ip_wanted = 1;
655         usb_int_msg(us->pusb_dev, us->irqpipe,
656                     (void *)&us->ip_data, us->irqmaxp, us->irqinterval, false);
657         timeout = 1000;
658         while (timeout--) {
659                 if (us->ip_wanted == 0)
660                         break;
661                 mdelay(10);
662         }
663         if (us->ip_wanted) {
664                 printf("        Did not get interrupt on CBI\n");
665                 us->ip_wanted = 0;
666                 return USB_STOR_TRANSPORT_ERROR;
667         }
668         debug("Got interrupt data 0x%x, transferred %d status 0x%lX\n",
669               us->ip_data, us->pusb_dev->irq_act_len,
670               us->pusb_dev->irq_status);
671         /* UFI gives us ASC and ASCQ, like a request sense */
672         if (us->subclass == US_SC_UFI) {
673                 if (srb->cmd[0] == SCSI_REQ_SENSE ||
674                     srb->cmd[0] == SCSI_INQUIRY)
675                         return USB_STOR_TRANSPORT_GOOD; /* Good */
676                 else if (us->ip_data)
677                         return USB_STOR_TRANSPORT_FAILED;
678                 else
679                         return USB_STOR_TRANSPORT_GOOD;
680         }
681         /* otherwise, we interpret the data normally */
682         switch (us->ip_data) {
683         case 0x0001:
684                 return USB_STOR_TRANSPORT_GOOD;
685         case 0x0002:
686                 return USB_STOR_TRANSPORT_FAILED;
687         default:
688                 return USB_STOR_TRANSPORT_ERROR;
689         }                       /* switch */
690         return USB_STOR_TRANSPORT_ERROR;
691 }
692
693 #define USB_TRANSPORT_UNKNOWN_RETRY 5
694 #define USB_TRANSPORT_NOT_READY_RETRY 10
695
696 /* clear a stall on an endpoint - special for BBB devices */
697 static int usb_stor_BBB_clear_endpt_stall(struct us_data *us, __u8 endpt)
698 {
699         /* ENDPOINT_HALT = 0, so set value to 0 */
700         return usb_control_msg(us->pusb_dev, usb_sndctrlpipe(us->pusb_dev, 0),
701                                USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0,
702                                endpt, NULL, 0, USB_CNTL_TIMEOUT * 5);
703 }
704
705 static int usb_stor_BBB_transport(struct scsi_cmd *srb, struct us_data *us)
706 {
707         int result, retry;
708         int dir_in;
709         int actlen, data_actlen;
710         unsigned int pipe, pipein, pipeout;
711         ALLOC_CACHE_ALIGN_BUFFER(struct umass_bbb_csw, csw, 1);
712 #ifdef BBB_XPORT_TRACE
713         unsigned char *ptr;
714         int index;
715 #endif
716
717         dir_in = US_DIRECTION(srb->cmd[0]);
718
719         /* COMMAND phase */
720         debug("COMMAND phase\n");
721         result = usb_stor_BBB_comdat(srb, us);
722         if (result < 0) {
723                 debug("failed to send CBW status %ld\n",
724                       us->pusb_dev->status);
725                 usb_stor_BBB_reset(us);
726                 return USB_STOR_TRANSPORT_FAILED;
727         }
728         if (!(us->flags & USB_READY))
729                 mdelay(5);
730         pipein = usb_rcvbulkpipe(us->pusb_dev, us->ep_in);
731         pipeout = usb_sndbulkpipe(us->pusb_dev, us->ep_out);
732         /* DATA phase + error handling */
733         data_actlen = 0;
734         /* no data, go immediately to the STATUS phase */
735         if (srb->datalen == 0)
736                 goto st;
737         debug("DATA phase\n");
738         if (dir_in)
739                 pipe = pipein;
740         else
741                 pipe = pipeout;
742
743         result = usb_bulk_msg(us->pusb_dev, pipe, srb->pdata, srb->datalen,
744                               &data_actlen, USB_CNTL_TIMEOUT * 5);
745         /* special handling of STALL in DATA phase */
746         if ((result < 0) && (us->pusb_dev->status & USB_ST_STALLED)) {
747                 debug("DATA:stall\n");
748                 /* clear the STALL on the endpoint */
749                 result = usb_stor_BBB_clear_endpt_stall(us,
750                                         dir_in ? us->ep_in : us->ep_out);
751                 if (result >= 0)
752                         /* continue on to STATUS phase */
753                         goto st;
754         }
755         if (result < 0) {
756                 debug("usb_bulk_msg error status %ld\n",
757                       us->pusb_dev->status);
758                 usb_stor_BBB_reset(us);
759                 return USB_STOR_TRANSPORT_FAILED;
760         }
761 #ifdef BBB_XPORT_TRACE
762         for (index = 0; index < data_actlen; index++)
763                 printf("pdata[%d] %#x ", index, srb->pdata[index]);
764         printf("\n");
765 #endif
766         /* STATUS phase + error handling */
767 st:
768         retry = 0;
769 again:
770         debug("STATUS phase\n");
771         result = usb_bulk_msg(us->pusb_dev, pipein, csw, UMASS_BBB_CSW_SIZE,
772                                 &actlen, USB_CNTL_TIMEOUT*5);
773
774         /* special handling of STALL in STATUS phase */
775         if ((result < 0) && (retry < 1) &&
776             (us->pusb_dev->status & USB_ST_STALLED)) {
777                 debug("STATUS:stall\n");
778                 /* clear the STALL on the endpoint */
779                 result = usb_stor_BBB_clear_endpt_stall(us, us->ep_in);
780                 if (result >= 0 && (retry++ < 1))
781                         /* do a retry */
782                         goto again;
783         }
784         if (result < 0) {
785                 debug("usb_bulk_msg error status %ld\n",
786                       us->pusb_dev->status);
787                 usb_stor_BBB_reset(us);
788                 return USB_STOR_TRANSPORT_FAILED;
789         }
790 #ifdef BBB_XPORT_TRACE
791         ptr = (unsigned char *)csw;
792         for (index = 0; index < UMASS_BBB_CSW_SIZE; index++)
793                 printf("ptr[%d] %#x ", index, ptr[index]);
794         printf("\n");
795 #endif
796         /* misuse pipe to get the residue */
797         pipe = le32_to_cpu(csw->dCSWDataResidue);
798         if (pipe == 0 && srb->datalen != 0 && srb->datalen - data_actlen != 0)
799                 pipe = srb->datalen - data_actlen;
800         if (CSWSIGNATURE != le32_to_cpu(csw->dCSWSignature)) {
801                 debug("!CSWSIGNATURE\n");
802                 usb_stor_BBB_reset(us);
803                 return USB_STOR_TRANSPORT_FAILED;
804         } else if ((CBWTag - 1) != le32_to_cpu(csw->dCSWTag)) {
805                 debug("!Tag\n");
806                 usb_stor_BBB_reset(us);
807                 return USB_STOR_TRANSPORT_FAILED;
808         } else if (csw->bCSWStatus > CSWSTATUS_PHASE) {
809                 debug(">PHASE\n");
810                 usb_stor_BBB_reset(us);
811                 return USB_STOR_TRANSPORT_FAILED;
812         } else if (csw->bCSWStatus == CSWSTATUS_PHASE) {
813                 debug("=PHASE\n");
814                 usb_stor_BBB_reset(us);
815                 return USB_STOR_TRANSPORT_FAILED;
816         } else if (data_actlen > srb->datalen) {
817                 debug("transferred %dB instead of %ldB\n",
818                       data_actlen, srb->datalen);
819                 return USB_STOR_TRANSPORT_FAILED;
820         } else if (csw->bCSWStatus == CSWSTATUS_FAILED) {
821                 debug("FAILED\n");
822                 return USB_STOR_TRANSPORT_FAILED;
823         }
824
825         return result;
826 }
827
828 static int usb_stor_CB_transport(struct scsi_cmd *srb, struct us_data *us)
829 {
830         int result, status;
831         struct scsi_cmd *psrb;
832         struct scsi_cmd reqsrb;
833         int retry, notready;
834
835         psrb = &reqsrb;
836         status = USB_STOR_TRANSPORT_GOOD;
837         retry = 0;
838         notready = 0;
839         /* issue the command */
840 do_retry:
841         result = usb_stor_CB_comdat(srb, us);
842         debug("command / Data returned %d, status %lX\n",
843               result, us->pusb_dev->status);
844         /* if this is an CBI Protocol, get IRQ */
845         if (us->protocol == US_PR_CBI) {
846                 status = usb_stor_CBI_get_status(srb, us);
847                 /* if the status is error, report it */
848                 if (status == USB_STOR_TRANSPORT_ERROR) {
849                         debug(" USB CBI Command Error\n");
850                         return status;
851                 }
852                 srb->sense_buf[12] = (unsigned char)(us->ip_data >> 8);
853                 srb->sense_buf[13] = (unsigned char)(us->ip_data & 0xff);
854                 if (!us->ip_data) {
855                         /* if the status is good, report it */
856                         if (status == USB_STOR_TRANSPORT_GOOD) {
857                                 debug(" USB CBI Command Good\n");
858                                 return status;
859                         }
860                 }
861         }
862         /* do we have to issue an auto request? */
863         /* HERE we have to check the result */
864         if ((result < 0) && !(us->pusb_dev->status & USB_ST_STALLED)) {
865                 debug("ERROR %lX\n", us->pusb_dev->status);
866                 us->transport_reset(us);
867                 return USB_STOR_TRANSPORT_ERROR;
868         }
869         if ((us->protocol == US_PR_CBI) &&
870             ((srb->cmd[0] == SCSI_REQ_SENSE) ||
871             (srb->cmd[0] == SCSI_INQUIRY))) {
872                 /* do not issue an autorequest after request sense */
873                 debug("No auto request and good\n");
874                 return USB_STOR_TRANSPORT_GOOD;
875         }
876         /* issue an request_sense */
877         memset(&psrb->cmd[0], 0, 12);
878         psrb->cmd[0] = SCSI_REQ_SENSE;
879         psrb->cmd[1] = srb->lun << 5;
880         psrb->cmd[4] = 18;
881         psrb->datalen = 18;
882         psrb->pdata = &srb->sense_buf[0];
883         psrb->cmdlen = 12;
884         /* issue the command */
885         result = usb_stor_CB_comdat(psrb, us);
886         debug("auto request returned %d\n", result);
887         /* if this is an CBI Protocol, get IRQ */
888         if (us->protocol == US_PR_CBI)
889                 status = usb_stor_CBI_get_status(psrb, us);
890
891         if ((result < 0) && !(us->pusb_dev->status & USB_ST_STALLED)) {
892                 debug(" AUTO REQUEST ERROR %ld\n",
893                       us->pusb_dev->status);
894                 return USB_STOR_TRANSPORT_ERROR;
895         }
896         debug("autorequest returned 0x%02X 0x%02X 0x%02X 0x%02X\n",
897               srb->sense_buf[0], srb->sense_buf[2],
898               srb->sense_buf[12], srb->sense_buf[13]);
899         /* Check the auto request result */
900         if ((srb->sense_buf[2] == 0) &&
901             (srb->sense_buf[12] == 0) &&
902             (srb->sense_buf[13] == 0)) {
903                 /* ok, no sense */
904                 return USB_STOR_TRANSPORT_GOOD;
905         }
906
907         /* Check the auto request result */
908         switch (srb->sense_buf[2]) {
909         case 0x01:
910                 /* Recovered Error */
911                 return USB_STOR_TRANSPORT_GOOD;
912                 break;
913         case 0x02:
914                 /* Not Ready */
915                 if (notready++ > USB_TRANSPORT_NOT_READY_RETRY) {
916                         printf("cmd 0x%02X returned 0x%02X 0x%02X 0x%02X"
917                                " 0x%02X (NOT READY)\n", srb->cmd[0],
918                                 srb->sense_buf[0], srb->sense_buf[2],
919                                 srb->sense_buf[12], srb->sense_buf[13]);
920                         return USB_STOR_TRANSPORT_FAILED;
921                 } else {
922                         mdelay(100);
923                         goto do_retry;
924                 }
925                 break;
926         default:
927                 if (retry++ > USB_TRANSPORT_UNKNOWN_RETRY) {
928                         printf("cmd 0x%02X returned 0x%02X 0x%02X 0x%02X"
929                                " 0x%02X\n", srb->cmd[0], srb->sense_buf[0],
930                                 srb->sense_buf[2], srb->sense_buf[12],
931                                 srb->sense_buf[13]);
932                         return USB_STOR_TRANSPORT_FAILED;
933                 } else
934                         goto do_retry;
935                 break;
936         }
937         return USB_STOR_TRANSPORT_FAILED;
938 }
939
940 static void usb_stor_set_max_xfer_blk(struct usb_device *udev,
941                                       struct us_data *us)
942 {
943         /*
944          * Limit the total size of a transfer to 120 KB.
945          *
946          * Some devices are known to choke with anything larger. It seems like
947          * the problem stems from the fact that original IDE controllers had
948          * only an 8-bit register to hold the number of sectors in one transfer
949          * and even those couldn't handle a full 256 sectors.
950          *
951          * Because we want to make sure we interoperate with as many devices as
952          * possible, we will maintain a 240 sector transfer size limit for USB
953          * Mass Storage devices.
954          *
955          * Tests show that other operating have similar limits with Microsoft
956          * Windows 7 limiting transfers to 128 sectors for both USB2 and USB3
957          * and Apple Mac OS X 10.11 limiting transfers to 256 sectors for USB2
958          * and 2048 for USB3 devices.
959          */
960         unsigned short blk = 240;
961
962 #if CONFIG_IS_ENABLED(DM_USB)
963         size_t size;
964         int ret;
965
966         ret = usb_get_max_xfer_size(udev, (size_t *)&size);
967         if ((ret >= 0) && (size < blk * 512))
968                 blk = size / 512;
969 #endif
970
971         us->max_xfer_blk = blk;
972 }
973
974 static int usb_inquiry(struct scsi_cmd *srb, struct us_data *ss)
975 {
976         int retry, i;
977         retry = 5;
978         do {
979                 memset(&srb->cmd[0], 0, 12);
980                 srb->cmd[0] = SCSI_INQUIRY;
981                 srb->cmd[1] = srb->lun << 5;
982                 srb->cmd[4] = 36;
983                 srb->datalen = 36;
984                 srb->cmdlen = 12;
985                 i = ss->transport(srb, ss);
986                 debug("inquiry returns %d\n", i);
987                 if (i == 0)
988                         break;
989         } while (--retry);
990
991         if (!retry) {
992                 printf("error in inquiry\n");
993                 return -1;
994         }
995         return 0;
996 }
997
998 static int usb_request_sense(struct scsi_cmd *srb, struct us_data *ss)
999 {
1000         char *ptr;
1001
1002         ptr = (char *)srb->pdata;
1003         memset(&srb->cmd[0], 0, 12);
1004         srb->cmd[0] = SCSI_REQ_SENSE;
1005         srb->cmd[1] = srb->lun << 5;
1006         srb->cmd[4] = 18;
1007         srb->datalen = 18;
1008         srb->pdata = &srb->sense_buf[0];
1009         srb->cmdlen = 12;
1010         ss->transport(srb, ss);
1011         debug("Request Sense returned %02X %02X %02X\n",
1012               srb->sense_buf[2], srb->sense_buf[12],
1013               srb->sense_buf[13]);
1014         srb->pdata = (uchar *)ptr;
1015         return 0;
1016 }
1017
1018 static int usb_test_unit_ready(struct scsi_cmd *srb, struct us_data *ss)
1019 {
1020         int retries = 10;
1021
1022         do {
1023                 memset(&srb->cmd[0], 0, 12);
1024                 srb->cmd[0] = SCSI_TST_U_RDY;
1025                 srb->cmd[1] = srb->lun << 5;
1026                 srb->datalen = 0;
1027                 srb->cmdlen = 12;
1028                 if (ss->transport(srb, ss) == USB_STOR_TRANSPORT_GOOD) {
1029                         ss->flags |= USB_READY;
1030                         return 0;
1031                 }
1032                 usb_request_sense(srb, ss);
1033                 /*
1034                  * Check the Key Code Qualifier, if it matches
1035                  * "Not Ready - medium not present"
1036                  * (the sense Key equals 0x2 and the ASC is 0x3a)
1037                  * return immediately as the medium being absent won't change
1038                  * unless there is a user action.
1039                  */
1040                 if ((srb->sense_buf[2] == 0x02) &&
1041                     (srb->sense_buf[12] == 0x3a))
1042                         return -1;
1043                 mdelay(100);
1044         } while (retries--);
1045
1046         return -1;
1047 }
1048
1049 static int usb_read_capacity(struct scsi_cmd *srb, struct us_data *ss)
1050 {
1051         int retry;
1052         /* XXX retries */
1053         retry = 3;
1054         do {
1055                 memset(&srb->cmd[0], 0, 12);
1056                 srb->cmd[0] = SCSI_RD_CAPAC;
1057                 srb->cmd[1] = srb->lun << 5;
1058                 srb->datalen = 8;
1059                 srb->cmdlen = 12;
1060                 if (ss->transport(srb, ss) == USB_STOR_TRANSPORT_GOOD)
1061                         return 0;
1062         } while (retry--);
1063
1064         return -1;
1065 }
1066
1067 static int usb_read_10(struct scsi_cmd *srb, struct us_data *ss,
1068                        unsigned long start, unsigned short blocks)
1069 {
1070         memset(&srb->cmd[0], 0, 12);
1071         srb->cmd[0] = SCSI_READ10;
1072         srb->cmd[1] = srb->lun << 5;
1073         srb->cmd[2] = ((unsigned char) (start >> 24)) & 0xff;
1074         srb->cmd[3] = ((unsigned char) (start >> 16)) & 0xff;
1075         srb->cmd[4] = ((unsigned char) (start >> 8)) & 0xff;
1076         srb->cmd[5] = ((unsigned char) (start)) & 0xff;
1077         srb->cmd[7] = ((unsigned char) (blocks >> 8)) & 0xff;
1078         srb->cmd[8] = (unsigned char) blocks & 0xff;
1079         srb->cmdlen = 12;
1080         debug("read10: start %lx blocks %x\n", start, blocks);
1081         return ss->transport(srb, ss);
1082 }
1083
1084 static int usb_write_10(struct scsi_cmd *srb, struct us_data *ss,
1085                         unsigned long start, unsigned short blocks)
1086 {
1087         memset(&srb->cmd[0], 0, 12);
1088         srb->cmd[0] = SCSI_WRITE10;
1089         srb->cmd[1] = srb->lun << 5;
1090         srb->cmd[2] = ((unsigned char) (start >> 24)) & 0xff;
1091         srb->cmd[3] = ((unsigned char) (start >> 16)) & 0xff;
1092         srb->cmd[4] = ((unsigned char) (start >> 8)) & 0xff;
1093         srb->cmd[5] = ((unsigned char) (start)) & 0xff;
1094         srb->cmd[7] = ((unsigned char) (blocks >> 8)) & 0xff;
1095         srb->cmd[8] = (unsigned char) blocks & 0xff;
1096         srb->cmdlen = 12;
1097         debug("write10: start %lx blocks %x\n", start, blocks);
1098         return ss->transport(srb, ss);
1099 }
1100
1101
1102 #ifdef CONFIG_USB_BIN_FIXUP
1103 /*
1104  * Some USB storage devices queried for SCSI identification data respond with
1105  * binary strings, which if output to the console freeze the terminal. The
1106  * workaround is to modify the vendor and product strings read from such
1107  * device with proper values (as reported by 'usb info').
1108  *
1109  * Vendor and product length limits are taken from the definition of
1110  * struct blk_desc in include/part.h.
1111  */
1112 static void usb_bin_fixup(struct usb_device_descriptor descriptor,
1113                                 unsigned char vendor[],
1114                                 unsigned char product[]) {
1115         const unsigned char max_vendor_len = 40;
1116         const unsigned char max_product_len = 20;
1117         if (descriptor.idVendor == 0x0424 && descriptor.idProduct == 0x223a) {
1118                 strncpy((char *)vendor, "SMSC", max_vendor_len);
1119                 strncpy((char *)product, "Flash Media Cntrller",
1120                         max_product_len);
1121         }
1122 }
1123 #endif /* CONFIG_USB_BIN_FIXUP */
1124
1125 #if CONFIG_IS_ENABLED(BLK)
1126 static unsigned long usb_stor_read(struct udevice *dev, lbaint_t blknr,
1127                                    lbaint_t blkcnt, void *buffer)
1128 #else
1129 static unsigned long usb_stor_read(struct blk_desc *block_dev, lbaint_t blknr,
1130                                    lbaint_t blkcnt, void *buffer)
1131 #endif
1132 {
1133         lbaint_t start, blks;
1134         uintptr_t buf_addr;
1135         unsigned short smallblks;
1136         struct usb_device *udev;
1137         struct us_data *ss;
1138         int retry;
1139         struct scsi_cmd *srb = &usb_ccb;
1140 #if CONFIG_IS_ENABLED(BLK)
1141         struct blk_desc *block_dev;
1142 #endif
1143
1144         if (blkcnt == 0)
1145                 return 0;
1146         /* Setup  device */
1147 #if CONFIG_IS_ENABLED(BLK)
1148         block_dev = dev_get_uclass_platdata(dev);
1149         udev = dev_get_parent_priv(dev_get_parent(dev));
1150         debug("\nusb_read: udev %d\n", block_dev->devnum);
1151 #else
1152         debug("\nusb_read: udev %d\n", block_dev->devnum);
1153         udev = usb_dev_desc[block_dev->devnum].priv;
1154         if (!udev) {
1155                 debug("%s: No device\n", __func__);
1156                 return 0;
1157         }
1158 #endif
1159         ss = (struct us_data *)udev->privptr;
1160
1161         usb_disable_asynch(1); /* asynch transfer not allowed */
1162         usb_lock_async(udev, 1);
1163         srb->lun = block_dev->lun;
1164         buf_addr = (uintptr_t)buffer;
1165         start = blknr;
1166         blks = blkcnt;
1167
1168         debug("\nusb_read: dev %d startblk " LBAF ", blccnt " LBAF " buffer %lx\n",
1169               block_dev->devnum, start, blks, buf_addr);
1170
1171         do {
1172                 /* XXX need some comment here */
1173                 retry = 2;
1174                 srb->pdata = (unsigned char *)buf_addr;
1175                 if (blks > ss->max_xfer_blk)
1176                         smallblks = ss->max_xfer_blk;
1177                 else
1178                         smallblks = (unsigned short) blks;
1179 retry_it:
1180                 if (smallblks == ss->max_xfer_blk)
1181                         usb_show_progress();
1182                 srb->datalen = block_dev->blksz * smallblks;
1183                 srb->pdata = (unsigned char *)buf_addr;
1184                 if (usb_read_10(srb, ss, start, smallblks)) {
1185                         debug("Read ERROR\n");
1186                         ss->flags &= ~USB_READY;
1187                         usb_request_sense(srb, ss);
1188                         if (retry--)
1189                                 goto retry_it;
1190                         blkcnt -= blks;
1191                         break;
1192                 }
1193                 start += smallblks;
1194                 blks -= smallblks;
1195                 buf_addr += srb->datalen;
1196         } while (blks != 0);
1197
1198         debug("usb_read: end startblk " LBAF ", blccnt %x buffer %lx\n",
1199               start, smallblks, buf_addr);
1200
1201         usb_lock_async(udev, 0);
1202         usb_disable_asynch(0); /* asynch transfer allowed */
1203         if (blkcnt >= ss->max_xfer_blk)
1204                 debug("\n");
1205         return blkcnt;
1206 }
1207
1208 #if CONFIG_IS_ENABLED(BLK)
1209 static unsigned long usb_stor_write(struct udevice *dev, lbaint_t blknr,
1210                                     lbaint_t blkcnt, const void *buffer)
1211 #else
1212 static unsigned long usb_stor_write(struct blk_desc *block_dev, lbaint_t blknr,
1213                                     lbaint_t blkcnt, const void *buffer)
1214 #endif
1215 {
1216         lbaint_t start, blks;
1217         uintptr_t buf_addr;
1218         unsigned short smallblks;
1219         struct usb_device *udev;
1220         struct us_data *ss;
1221         int retry;
1222         struct scsi_cmd *srb = &usb_ccb;
1223 #if CONFIG_IS_ENABLED(BLK)
1224         struct blk_desc *block_dev;
1225 #endif
1226
1227         if (blkcnt == 0)
1228                 return 0;
1229
1230         /* Setup  device */
1231 #if CONFIG_IS_ENABLED(BLK)
1232         block_dev = dev_get_uclass_platdata(dev);
1233         udev = dev_get_parent_priv(dev_get_parent(dev));
1234         debug("\nusb_read: udev %d\n", block_dev->devnum);
1235 #else
1236         debug("\nusb_read: udev %d\n", block_dev->devnum);
1237         udev = usb_dev_desc[block_dev->devnum].priv;
1238         if (!udev) {
1239                 debug("%s: No device\n", __func__);
1240                 return 0;
1241         }
1242 #endif
1243         ss = (struct us_data *)udev->privptr;
1244
1245         usb_disable_asynch(1); /* asynch transfer not allowed */
1246         usb_lock_async(udev, 1);
1247
1248         srb->lun = block_dev->lun;
1249         buf_addr = (uintptr_t)buffer;
1250         start = blknr;
1251         blks = blkcnt;
1252
1253         debug("\nusb_write: dev %d startblk " LBAF ", blccnt " LBAF " buffer %lx\n",
1254               block_dev->devnum, start, blks, buf_addr);
1255
1256         do {
1257                 /* If write fails retry for max retry count else
1258                  * return with number of blocks written successfully.
1259                  */
1260                 retry = 2;
1261                 srb->pdata = (unsigned char *)buf_addr;
1262                 if (blks > ss->max_xfer_blk)
1263                         smallblks = ss->max_xfer_blk;
1264                 else
1265                         smallblks = (unsigned short) blks;
1266 retry_it:
1267                 if (smallblks == ss->max_xfer_blk)
1268                         usb_show_progress();
1269                 srb->datalen = block_dev->blksz * smallblks;
1270                 srb->pdata = (unsigned char *)buf_addr;
1271                 if (usb_write_10(srb, ss, start, smallblks)) {
1272                         debug("Write ERROR\n");
1273                         ss->flags &= ~USB_READY;
1274                         usb_request_sense(srb, ss);
1275                         if (retry--)
1276                                 goto retry_it;
1277                         blkcnt -= blks;
1278                         break;
1279                 }
1280                 start += smallblks;
1281                 blks -= smallblks;
1282                 buf_addr += srb->datalen;
1283         } while (blks != 0);
1284
1285         debug("usb_write: end startblk " LBAF ", blccnt %x buffer %lx\n",
1286               start, smallblks, buf_addr);
1287
1288         usb_lock_async(udev, 0);
1289         usb_disable_asynch(0); /* asynch transfer allowed */
1290         if (blkcnt >= ss->max_xfer_blk)
1291                 debug("\n");
1292         return blkcnt;
1293
1294 }
1295
1296 /* Probe to see if a new device is actually a Storage device */
1297 int usb_storage_probe(struct usb_device *dev, unsigned int ifnum,
1298                       struct us_data *ss)
1299 {
1300         struct usb_interface *iface;
1301         int i;
1302         struct usb_endpoint_descriptor *ep_desc;
1303         unsigned int flags = 0;
1304
1305         /* let's examine the device now */
1306         iface = &dev->config.if_desc[ifnum];
1307
1308         if (dev->descriptor.bDeviceClass != 0 ||
1309                         iface->desc.bInterfaceClass != USB_CLASS_MASS_STORAGE ||
1310                         iface->desc.bInterfaceSubClass < US_SC_MIN ||
1311                         iface->desc.bInterfaceSubClass > US_SC_MAX) {
1312                 debug("Not mass storage\n");
1313                 /* if it's not a mass storage, we go no further */
1314                 return 0;
1315         }
1316
1317         memset(ss, 0, sizeof(struct us_data));
1318
1319         /* At this point, we know we've got a live one */
1320         debug("\n\nUSB Mass Storage device detected\n");
1321
1322         /* Initialize the us_data structure with some useful info */
1323         ss->flags = flags;
1324         ss->ifnum = ifnum;
1325         ss->pusb_dev = dev;
1326         ss->attention_done = 0;
1327         ss->subclass = iface->desc.bInterfaceSubClass;
1328         ss->protocol = iface->desc.bInterfaceProtocol;
1329
1330         /* set the handler pointers based on the protocol */
1331         debug("Transport: ");
1332         switch (ss->protocol) {
1333         case US_PR_CB:
1334                 debug("Control/Bulk\n");
1335                 ss->transport = usb_stor_CB_transport;
1336                 ss->transport_reset = usb_stor_CB_reset;
1337                 break;
1338
1339         case US_PR_CBI:
1340                 debug("Control/Bulk/Interrupt\n");
1341                 ss->transport = usb_stor_CB_transport;
1342                 ss->transport_reset = usb_stor_CB_reset;
1343                 break;
1344         case US_PR_BULK:
1345                 debug("Bulk/Bulk/Bulk\n");
1346                 ss->transport = usb_stor_BBB_transport;
1347                 ss->transport_reset = usb_stor_BBB_reset;
1348                 break;
1349         default:
1350                 printf("USB Storage Transport unknown / not yet implemented\n");
1351                 return 0;
1352                 break;
1353         }
1354
1355         /*
1356          * We are expecting a minimum of 2 endpoints - in and out (bulk).
1357          * An optional interrupt is OK (necessary for CBI protocol).
1358          * We will ignore any others.
1359          */
1360         for (i = 0; i < iface->desc.bNumEndpoints; i++) {
1361                 ep_desc = &iface->ep_desc[i];
1362                 /* is it an BULK endpoint? */
1363                 if ((ep_desc->bmAttributes &
1364                      USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK) {
1365                         if (ep_desc->bEndpointAddress & USB_DIR_IN)
1366                                 ss->ep_in = ep_desc->bEndpointAddress &
1367                                                 USB_ENDPOINT_NUMBER_MASK;
1368                         else
1369                                 ss->ep_out =
1370                                         ep_desc->bEndpointAddress &
1371                                         USB_ENDPOINT_NUMBER_MASK;
1372                 }
1373
1374                 /* is it an interrupt endpoint? */
1375                 if ((ep_desc->bmAttributes &
1376                      USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) {
1377                         ss->ep_int = ep_desc->bEndpointAddress &
1378                                                 USB_ENDPOINT_NUMBER_MASK;
1379                         ss->irqinterval = ep_desc->bInterval;
1380                 }
1381         }
1382         debug("Endpoints In %d Out %d Int %d\n",
1383               ss->ep_in, ss->ep_out, ss->ep_int);
1384
1385         /* Do some basic sanity checks, and bail if we find a problem */
1386         if (usb_set_interface(dev, iface->desc.bInterfaceNumber, 0) ||
1387             !ss->ep_in || !ss->ep_out ||
1388             (ss->protocol == US_PR_CBI && ss->ep_int == 0)) {
1389                 debug("Problems with device\n");
1390                 return 0;
1391         }
1392         /* set class specific stuff */
1393         /* We only handle certain protocols.  Currently, these are
1394          * the only ones.
1395          * The SFF8070 accepts the requests used in u-boot
1396          */
1397         if (ss->subclass != US_SC_UFI && ss->subclass != US_SC_SCSI &&
1398             ss->subclass != US_SC_8070) {
1399                 printf("Sorry, protocol %d not yet supported.\n", ss->subclass);
1400                 return 0;
1401         }
1402         if (ss->ep_int) {
1403                 /* we had found an interrupt endpoint, prepare irq pipe
1404                  * set up the IRQ pipe and handler
1405                  */
1406                 ss->irqinterval = (ss->irqinterval > 0) ? ss->irqinterval : 255;
1407                 ss->irqpipe = usb_rcvintpipe(ss->pusb_dev, ss->ep_int);
1408                 ss->irqmaxp = usb_maxpacket(dev, ss->irqpipe);
1409                 dev->irq_handle = usb_stor_irq;
1410         }
1411
1412         /* Set the maximum transfer size per host controller setting */
1413         usb_stor_set_max_xfer_blk(dev, ss);
1414
1415         dev->privptr = (void *)ss;
1416         return 1;
1417 }
1418
1419 int usb_stor_get_info(struct usb_device *dev, struct us_data *ss,
1420                       struct blk_desc *dev_desc)
1421 {
1422         unsigned char perq, modi;
1423         ALLOC_CACHE_ALIGN_BUFFER(u32, cap, 2);
1424         ALLOC_CACHE_ALIGN_BUFFER(u8, usb_stor_buf, 36);
1425         u32 capacity, blksz;
1426         struct scsi_cmd *pccb = &usb_ccb;
1427
1428         pccb->pdata = usb_stor_buf;
1429
1430         dev_desc->target = dev->devnum;
1431         pccb->lun = dev_desc->lun;
1432         debug(" address %d\n", dev_desc->target);
1433
1434         if (usb_inquiry(pccb, ss)) {
1435                 debug("%s: usb_inquiry() failed\n", __func__);
1436                 return -1;
1437         }
1438
1439         perq = usb_stor_buf[0];
1440         modi = usb_stor_buf[1];
1441
1442         /*
1443          * Skip unknown devices (0x1f) and enclosure service devices (0x0d),
1444          * they would not respond to test_unit_ready .
1445          */
1446         if (((perq & 0x1f) == 0x1f) || ((perq & 0x1f) == 0x0d)) {
1447                 debug("%s: unknown/unsupported device\n", __func__);
1448                 return 0;
1449         }
1450         if ((modi&0x80) == 0x80) {
1451                 /* drive is removable */
1452                 dev_desc->removable = 1;
1453         }
1454         memcpy(dev_desc->vendor, (const void *)&usb_stor_buf[8], 8);
1455         memcpy(dev_desc->product, (const void *)&usb_stor_buf[16], 16);
1456         memcpy(dev_desc->revision, (const void *)&usb_stor_buf[32], 4);
1457         dev_desc->vendor[8] = 0;
1458         dev_desc->product[16] = 0;
1459         dev_desc->revision[4] = 0;
1460 #ifdef CONFIG_USB_BIN_FIXUP
1461         usb_bin_fixup(dev->descriptor, (uchar *)dev_desc->vendor,
1462                       (uchar *)dev_desc->product);
1463 #endif /* CONFIG_USB_BIN_FIXUP */
1464         debug("ISO Vers %X, Response Data %X\n", usb_stor_buf[2],
1465               usb_stor_buf[3]);
1466         if (usb_test_unit_ready(pccb, ss)) {
1467                 printf("Device NOT ready\n"
1468                        "   Request Sense returned %02X %02X %02X\n",
1469                        pccb->sense_buf[2], pccb->sense_buf[12],
1470                        pccb->sense_buf[13]);
1471                 if (dev_desc->removable == 1)
1472                         dev_desc->type = perq;
1473                 return 0;
1474         }
1475         pccb->pdata = (unsigned char *)cap;
1476         memset(pccb->pdata, 0, 8);
1477         if (usb_read_capacity(pccb, ss) != 0) {
1478                 printf("READ_CAP ERROR\n");
1479                 ss->flags &= ~USB_READY;
1480                 cap[0] = 2880;
1481                 cap[1] = 0x200;
1482         }
1483         debug("Read Capacity returns: 0x%08x, 0x%08x\n", cap[0], cap[1]);
1484 #if 0
1485         if (cap[0] > (0x200000 * 10)) /* greater than 10 GByte */
1486                 cap[0] >>= 16;
1487
1488         cap[0] = cpu_to_be32(cap[0]);
1489         cap[1] = cpu_to_be32(cap[1]);
1490 #endif
1491
1492         capacity = be32_to_cpu(cap[0]) + 1;
1493         blksz = be32_to_cpu(cap[1]);
1494
1495         debug("Capacity = 0x%08x, blocksz = 0x%08x\n", capacity, blksz);
1496         dev_desc->lba = capacity;
1497         dev_desc->blksz = blksz;
1498         dev_desc->log2blksz = LOG2(dev_desc->blksz);
1499         dev_desc->type = perq;
1500         debug(" address %d\n", dev_desc->target);
1501
1502         return 1;
1503 }
1504
1505 #if CONFIG_IS_ENABLED(DM_USB)
1506
1507 static int usb_mass_storage_probe(struct udevice *dev)
1508 {
1509         struct usb_device *udev = dev_get_parent_priv(dev);
1510         int ret;
1511
1512         usb_disable_asynch(1); /* asynch transfer not allowed */
1513         ret = usb_stor_probe_device(udev);
1514         usb_disable_asynch(0); /* asynch transfer allowed */
1515
1516         return ret;
1517 }
1518
1519 static const struct udevice_id usb_mass_storage_ids[] = {
1520         { .compatible = "usb-mass-storage" },
1521         { }
1522 };
1523
1524 U_BOOT_DRIVER(usb_mass_storage) = {
1525         .name   = "usb_mass_storage",
1526         .id     = UCLASS_MASS_STORAGE,
1527         .of_match = usb_mass_storage_ids,
1528         .probe = usb_mass_storage_probe,
1529 #if CONFIG_IS_ENABLED(BLK)
1530         .platdata_auto_alloc_size       = sizeof(struct us_data),
1531 #endif
1532 };
1533
1534 UCLASS_DRIVER(usb_mass_storage) = {
1535         .id             = UCLASS_MASS_STORAGE,
1536         .name           = "usb_mass_storage",
1537 };
1538
1539 static const struct usb_device_id mass_storage_id_table[] = {
1540         {
1541                 .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
1542                 .bInterfaceClass = USB_CLASS_MASS_STORAGE
1543         },
1544         { }             /* Terminating entry */
1545 };
1546
1547 U_BOOT_USB_DEVICE(usb_mass_storage, mass_storage_id_table);
1548 #endif
1549
1550 #if CONFIG_IS_ENABLED(BLK)
1551 static const struct blk_ops usb_storage_ops = {
1552         .read   = usb_stor_read,
1553         .write  = usb_stor_write,
1554 };
1555
1556 U_BOOT_DRIVER(usb_storage_blk) = {
1557         .name           = "usb_storage_blk",
1558         .id             = UCLASS_BLK,
1559         .ops            = &usb_storage_ops,
1560 };
1561 #else
1562 U_BOOT_LEGACY_BLK(usb) = {
1563         .if_typename    = "usb",
1564         .if_type        = IF_TYPE_USB,
1565         .max_devs       = USB_MAX_STOR_DEV,
1566         .desc           = usb_dev_desc,
1567 };
1568 #endif