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