Skip to content
Snippets Groups Projects
usbdev_scsi.c 84 KiB
Newer Older
patacongo's avatar
patacongo committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
          ret = -EINVAL;
        }

      /* Verify that LBA lies in the range supported by the block driver */

      else if (lba >= lun->nsectors || lba + blocks > lun->nsectors)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_VERIFY10LBARANGE), 0);
          lun->sd = SCSI_KCQIR_LBAOUTOFRANGE;
          ret     = -EINVAL;
        }
      else
        {
          /* Try to read the requested blocks */

          for (i = 0, sector = lba + lun->startsector; i < blocks; i++, sector++)
            {
              nread = USBSTRG_DRVR_READ(lun, priv->iobuffer, sector, 1);
              if (nread < 0)
                {
                  usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_VERIFY10READFAIL), i);
                  lun->sd     = SCSI_KCQME_UNRRE1;
                  lun->sdinfo = sector;
                  ret         = -EIO;
                  break;
                }
            }
        }
    }
  return ret;
}

/****************************************************************************
 * Name: usbstrg_cmdsynchronizecache10
 *
 * Description:
 *   Handle SCSI_CMD_SYNCHCACHE10 command
 *
 ****************************************************************************/

static inline int usbstrg_cmdsynchronizecache10(FAR struct usbstrg_dev_s *priv)
{
  int ret;

  priv->u.alloclen = 0;

  /* Verify that we have the LUN structure and the block driver has been bound */

  if (!priv->lun->inode)
    {
      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_SYNCCACHEMEDIANOTPRESENT), 0);
      priv->lun->sd = SCSI_KCQNR_MEDIANOTPRESENT;
      ret = -EINVAL;
    }
  else
    {
      ret = usbstrg_setupcmd(priv, SCSICMD_SYNCHRONIZECACHE10_SIZEOF, USBSTRG_FLAGS_DIRNONE);
    }
  return ret;
}

/****************************************************************************
 * Name: usbstrg_cmdmodeselect10
 *
 * Description:
 *   Handle SCSI_CMD_MODESELECT10 command
 *
 ****************************************************************************/

static inline int usbstrg_cmdmodeselect10(FAR struct usbstrg_dev_s *priv)
{
  FAR struct scsicmd_modeselect10_s *modeselect = (FAR struct scsicmd_modeselect10_s *)priv->cdb;

  priv->u.alloclen = usbstrg_getbe16(modeselect->parmlen);
  (void)usbstrg_setupcmd(priv, SCSICMD_MODESELECT10_SIZEOF, USBSTRG_FLAGS_DIRHOST2DEVICE);

  /* Not supported */

  priv->lun->sd = SCSI_KCQIR_INVALIDCOMMAND;
  return -EINVAL;
}

/****************************************************************************
 * Name: usbstrg_cmdmodesense10
 *
 * Description:
 *   Handle SCSI_CMD_MODESENSE10 command
 *
 ****************************************************************************/

static int inline usbstrg_cmdmodesense10(FAR struct usbstrg_dev_s *priv,
                                         FAR ubyte *buf)
{
  FAR struct scsicmd_modesense10_s *modesense = (FAR struct scsicmd_modesense10_s *)priv->cdb;
  FAR struct scsiresp_modeparameterhdr10_s *mph = (FAR struct scsiresp_modeparameterhdr10_s *)buf;
  int mdlen;
  int ret;

  priv->u.alloclen = usbstrg_getbe16(modesense->alloclen);
  ret = usbstrg_setupcmd(priv, SCSICMD_MODESENSE10_SIZEOF, USBSTRG_FLAGS_DIRDEVICE2HOST);
  if (ret == OK)
    {
      if ((modesense->flags & ~SCSICMD_MODESENSE10_DBD) != 0 || modesense->subpgcode != 0)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_MODESENSE10FLAGS), 0);
          priv->lun->sd = SCSI_KCQIR_INVALIDFIELDINCBA;
          ret = -EINVAL;
        }
      else
        {
          /* The response consists of:
           *
           * (1) A MODESENSE6-specific mode parameter header,
           * (2) A variable length list of block descriptors, and
           * (3) A variable lengtth list of mode page formats
           */

          memset(mph, 0, SCSIREP_MODEPARAMETERHDR10_SIZEOF);
          mph->param = (priv->lun->readonly ? SCSIRESP_MODEPARMHDR_DAPARM_WP : 0x00);

          /* There are no block descriptors, only the following mode page: */

          ret = usbstrg_modepage(priv, &buf[SCSIREP_MODEPARAMETERHDR10_SIZEOF], modesense->pcpgcode, &mdlen);
          if (ret == OK)
            {
               /* Store the mode data length and return the total message size */

              usbstrg_putbe16(mph->mdlen, mdlen - 2);
              priv->nreqbytes = mdlen + SCSIREP_MODEPARAMETERHDR10_SIZEOF;
            }
        }
    }
  return ret;
}

/****************************************************************************
 * Name: usbstrg_cmdread12
 *
 * Description:
 *   Handle SCSI_CMD_READ12 command
 *
 ****************************************************************************/

static inline int usbstrg_cmdread12(FAR struct usbstrg_dev_s *priv)
{
  struct scsicmd_read12_s *read12 = (struct scsicmd_read12_s*)priv->cdb;
  FAR struct usbstrg_lun_s *lun = priv->lun;
  int ret;

  priv->u.xfrlen = usbstrg_getbe32(read12->xfrlen);
  ret = usbstrg_setupcmd(priv, SCSICMD_READ12_SIZEOF, USBSTRG_FLAGS_DIRDEVICE2HOST|USBSTRG_FLAGS_BLOCKXFR);
  if (ret == OK)
    {
      /* Get the Logical Block Address (LBA) from cdb[] as the starting sector */

      priv->sector = usbstrg_getbe32(read12->lba);

      /* Verify that we can support this read command */

      if ((read12->flags & ~(SCSICMD_READ12FLAGS_DPO|SCSICMD_READ12FLAGS_FUA)) != 0)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_READ12FLAGS), 0);
          lun->sd = SCSI_KCQIR_INVALIDFIELDINCBA;
          ret     = -EINVAL;
        }

      /* Verify that a block driver has been bound to the LUN */

      else if (!lun->inode)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_READ12MEDIANOTPRESENT), 0);
          lun->sd = SCSI_KCQNR_MEDIANOTPRESENT;
          ret     = -EINVAL;
        }

      /* Verify that LBA lies in the range supported by the block driver */

      else if (priv->sector >= lun->nsectors)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_READ12LBARANGE), 0);
          lun->sd = SCSI_KCQIR_LBAOUTOFRANGE;
          ret     = -EINVAL;
        }

      /* Looks like we are good to go */

      else
        {
          usbtrace(TRACE_CLASSSTATE(USBSTRG_CLASSSTATE_CMDPARSECMDREAD12), priv->cdb[0]);
          priv->thstate = USBSTRG_STATE_CMDREAD;
        }
    }
  return ret;
}

/****************************************************************************
 * Name: usbstrg_cmdwrite12
 *
 * Description:
 *   Handle SCSI_CMD_WRITE12 command
 *
 ****************************************************************************/

static inline int usbstrg_cmdwrite12(FAR struct usbstrg_dev_s *priv)
{
  struct scsicmd_write12_s *write12 = (struct scsicmd_write12_s *)priv->cdb;
  FAR struct usbstrg_lun_s *lun = priv->lun;
  int ret;

  priv->u.xfrlen = usbstrg_getbe32(write12->xfrlen);
  ret = usbstrg_setupcmd(priv, SCSICMD_WRITE12_SIZEOF, USBSTRG_FLAGS_DIRHOST2DEVICE|USBSTRG_FLAGS_BLOCKXFR);
  if (ret == OK)
    {
      /* Get the Logical Block Address (LBA) from cdb[] as the starting sector */

      priv->sector = usbstrg_getbe32(write12->lba);

      /* Verify that we can support this write command */

      if ((write12->flags & ~(SCSICMD_WRITE12FLAGS_DPO|SCSICMD_WRITE12FLAGS_FUA)) != 0)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_WRITE12FLAGS), 0);
          lun->sd = SCSI_KCQIR_INVALIDFIELDINCBA;
        }

      /* Verify that a block driver has been bound to the LUN */

      else if (!lun->inode)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_WRITE12MEDIANOTPRESENT), 0);
          lun->sd = SCSI_KCQNR_MEDIANOTPRESENT;
          ret = -EINVAL;
        }

      /* Check for attempts to write to a read-only device */

      else if (lun->readonly)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_WRITE12READONLY), 0);
          lun->sd = SCSI_KCQWP_COMMANDNOTALLOWED;
        }

      /* Verify that LBA lies in the range supported by the block driver */

      else if (priv->sector >= lun->nsectors)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_WRITE12LBARANGE), 0);
          lun->sd = SCSI_KCQIR_LBAOUTOFRANGE;
        }

      /* Looks like we are good to go */

      else
        {
          usbtrace(TRACE_CLASSSTATE(USBSTRG_CLASSSTATE_CMDPARSECMDWRITE12), priv->cdb[0]);
          priv->thstate = USBSTRG_STATE_CMDWRITE;
          return OK;
        }
    }

  return ret;
}

/****************************************************************************
 * Name: usbstrg_setupcmd
 *
 * Description:
 *   Called after each SCSI command is identified in order to perform setup
 *   and verification operations that are common to all SCSI commands.  This
 *   function performs the following common setup operations:
 *
 *   1. Determine the direction of the response
 *   2. Verify lengths
 *   3. Setup and verify the LUN
 *
 *   Includes special logic for INQUIRY and REQUESTSENSE commands
 *
 ****************************************************************************/

static int inline usbstrg_setupcmd(FAR struct usbstrg_dev_s *priv, ubyte cdblen, ubyte flags)
{
  FAR struct usbstrg_lun_s *lun;
  uint32 datlen;
  ubyte  dir = flags & USBSTRG_FLAGS_DIRMASK;
  int    ret = OK;

  /* Verify the LUN and set up the current LUN reference in the
   * device structure
   */

  if (priv->cbwlun < priv->nluns)
    {
      /* LUN number is valid in a valid range, but the LUN is not necessarily
       * bound to a block driver.  That will be checked as necessary in each
       * individual command.
       */

      lun       = &priv->luntab[priv->cbwlun];
      priv->lun = lun;
    }
  else
    {
      priv->lun = NULL;

      /* Only a few commands may specify unsupported LUNs */

      if ((flags & USBSTRG_FLAGS_LUNNOTNEEDED) == 0)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_CMDBADLUN), priv->cbwlun);
          ret = -EINVAL;
        }
    }

  /* Extract the direction and data transfer length */

  dir    = flags & USBSTRG_FLAGS_DIRMASK;      /* Expected data direction */
  datlen = 0;
  if ((flags & USBSTRG_FLAGS_BLOCKXFR) == 0)
    {
      /* Non-block transfer.  Data length: Host allocation to receive data
       * (only for device-to-host transfers.  At present, alloclen is set
       * to zero for all host-to-device, non-block transfers.
       */

      datlen = priv->u.alloclen;
    }
  else if (lun)
    {
      /* Block transfer: Calculate the total size of all sectors to be transferred */

      datlen = priv->u.alloclen * lun->sectorsize;
    }

  /* Check the data direction.  This was set up at the end of the
   * IDLE state when the CBW was parsed, but if there is no data,
   * then the direction is none.
   */

  if (datlen == 0)
    {
      /* No data.. then direction is none */

      dir = USBSTRG_FLAGS_DIRNONE;
    }

  /* Compare the expected data length in the command to the data length
   * in the CBW.
   */

  else if (priv->cbwlen < datlen)
    {
      /* Clip to the length in the CBW and declare a phase error */

      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_PHASEERROR1), priv->cdb[0]);
      if ((flags & USBSTRG_FLAGS_BLOCKXFR) != 0)
        {
          priv->u.alloclen = priv->cbwlen;
        }
      else
        {
          priv->u.xfrlen = priv->cbwlen / lun->sectorsize;
        }

      priv->phaseerror = 1;
    }

  /* Initialize the residue */

  priv->residue = priv->cbwlen;

  /* Conflicting data directions is a phase error */

  if (priv->cbwdir != dir && datlen > 0)
    {
      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_PHASEERROR2), priv->cdb[0]);
      priv->phaseerror = 1;
      ret             = -EINVAL;
    }

  /* Compare the length of data in the cdb[] with the expected length
   * of the command.
   */

  if (cdblen != priv->cdblen)
    {
      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_PHASEERROR3), priv->cdb[0]);
      priv->phaseerror = 1;
      ret              = -EINVAL;
    }

  if (lun)
    {
      /* Retain the sense data for the REQUEST SENSE command */

      if ((flags & USBSTRG_FLAGS_RETAINSENSEDATA) == 0)
        {
          /* Discard the sense data */

          lun->sd     = SCSI_KCQ_NOSENSE;
          lun->sdinfo = 0;
        }

      /* If a unit attention condition exists, then only a restricted set of
       * commands is permitted.
       */

      if (lun->uad != SCSI_KCQ_NOSENSE && (flags & USBSTRG_FLAGS_UACOKAY) != 0)
        {
          /* Command not permitted */

          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_CMDUNEVIOLATION), priv->cbwlun);
          lun->sd  = lun->uad;
          lun->uad = SCSI_KCQ_NOSENSE;
          ret      = -EINVAL;
        }
    }

  /* The final, 1-byte field of every SCSI command is the Control field which
   * must be zero
   */

  if (priv->cdb[cdblen-1] != 0)
    {
      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_SCSICMDCONTROL), 0);
      if (lun)
        {
          lun->sd = SCSI_KCQIR_INVALIDFIELDINCBA;
        }
      ret     = -EINVAL;
    }
  return ret;
}

/****************************************************************************
 * Name: usbstrg_idlestate
 *
 * Description:
 *   Called from the worker thread in the USBSTRG_STATE_IDLE state.  Checks
 *   for the receipt of a bulk CBW.
 *
 * Returned value:
 *   If no new, valid CBW is available, this function returns a negated errno.
 *   Otherwise, when a new CBW is successfully parsed, this function sets
 *   priv->thstate to USBSTRG_STATE_CMDPARSE and returns OK.
 *
 ****************************************************************************/

static int usbstrg_idlestate(FAR struct usbstrg_dev_s *priv)
{
  FAR struct usbstrg_req_s *privreq;
  FAR struct usbdev_req_s *req;
  FAR struct usbstrg_cbw_s *cbw;
  irqstate_t flags;
  int ret = -EINVAL;

  /* Take a request from the rdreqlist */

  flags = irqsave();
  privreq = (FAR struct usbstrg_req_s *)sq_remfirst(&priv->rdreqlist);
  irqrestore(flags);

  /* Has anything been received? If not, just return an error.
   * This will cause us to remain in the IDLE state.  When a USB request is
   * received, the worker thread will be awakened in the USBSTRG_STATE_IDLE
   * and we will be called again.
   */

  if (!privreq)
    {
      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_IDLERDREQLISTEMPTY), 0);
      return -ENOMEM;
    }

  req = privreq->req;
  cbw = (FAR struct usbstrg_cbw_s *)req->buf;

  /* Handle the CBW */

  usbstrg_dumpdata("SCSCI CBW", (ubyte*)cbw, USBSTRG_CBW_SIZEOF - USBSTRG_MAXCDBLEN);
  usbstrg_dumpdata("      CDB", cbw->cdb, min(cbw->cdblen, USBSTRG_MAXCDBLEN));

  /* Check for properly formatted CBW? */

  if (req->xfrd != USBSTRG_CBW_SIZEOF ||
      cbw->signature[0] != 'U' ||
      cbw->signature[1] != 'S' ||
      cbw->signature[2] != 'B' ||
      cbw->signature[3] != 'C')
    {
      /* CBS BAD: Stall the bulk endpoints.  If the CBW is bad we must stall the
       * bulk IN endpoint and either (1) stall the bulk OUT endpoint, or
       * (2) discard data from the endpoint.
       */

      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_INVALIDCBWSIGNATURE), 0);
      EP_STALL(priv->epbulkout);
      EP_STALL(priv->epbulkin);
    }

  /* Is the CBW meaningful? */

  else if (cbw->lun >= priv->nluns || (cbw->flags & ~USBSTRG_CBWFLAG_IN) != 0 ||
           cbw->cdblen < 6 || cbw->cdblen > USBSTRG_MAXCDBLEN)
    {
      /* CBS BAD: Stall the bulk endpoints.  If the CBW is bad we must stall the
       * bulk IN endpoint and either (1) stall the bulk OUT endpoint, or
       * (2) discard data from the endpoint.
       */

      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_INVALIDCBWCONTENT), 0);
      EP_STALL(priv->epbulkout);
      EP_STALL(priv->epbulkin);
    }

  /* Save the information from the CBW */

  else
    {
      /* Extract the CDB and copy the whole CBD[] for later use */

      priv->cdblen = cbw->cdblen;
      memcpy(priv->cdb, cbw->cdb, priv->cdblen);

      /* Extract the data direction */

      if ((cbw->flags & USBSTRG_CBWFLAG_IN) != 0)
        {
          /* IN: Device-to-host */

          priv->cbwdir = USBSTRG_FLAGS_DIRDEVICE2HOST;
        }
      else
        {
          /* OUT: Host-to-device */

          priv->cbwdir = USBSTRG_FLAGS_DIRHOST2DEVICE;
        }

      /* Get the max size of the data response */

      priv->cbwlen = usbstrg_getle32(cbw->datlen);
      if (priv->cbwlen == 0)
        {
          /* No length?  Then no direction either */

          priv->cbwdir = USBSTRG_FLAGS_DIRNONE;
        }

      /* Extract and save the LUN index and TAG value */

      priv->cbwlun = cbw->lun;
      priv->cbwtag = usbstrg_getle32(cbw->tag);

      /* Return the read request to the bulk out endpoint for re-filling */

      req           = privreq->req;
      req->len      = CONFIG_USBSTRG_BULKOUTREQLEN;
      req->private  = privreq;
      req->callback = usbstrg_rdcomplete;

      if (EP_SUBMIT(priv->epbulkout, req) != OK)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_IDLERDSUBMIT), (uint16)-ret);
        }

      /* Change to the CMDPARSE state and return success */

      usbtrace(TRACE_CLASSSTATE(USBSTRG_CLASSSTATE_IDLECMDPARSE), priv->cdb[0]);
      priv->thstate = USBSTRG_STATE_CMDPARSE;
      ret = OK;
    }

  return ret;
}

/****************************************************************************
 * Name: usbstrg_cmdparsestate
 *
 * Description:
 *   Called from the worker thread in the USBSTRG_STATE_CMDPARSE state.
 *   This state is entered when usbstrg_idlestate obtains a valid CBW
 *   containing SCSI commands.  This function processes those SCSI commands.
 *
 * Returned value:
 *   If no write request is available or certain other errors occur, this
 *   function returns a negated errno and stays in the USBSTRG_STATE_CMDPARSE
 *   state.  Otherwise, when the new CBW is successfully process, this
 *   function sets priv->thstate to one of USBSTRG_STATE_CMDREAD,
 *   USBSTRG_STATE_CMDWRITE, or USBSTRG_STATE_CMDFINISH and returns OK.
 *
 ****************************************************************************/

static int usbstrg_cmdparsestate(FAR struct usbstrg_dev_s *priv)
{
  FAR struct usbstrg_req_s *privreq;
  FAR ubyte *buf;
  int ret = -EINVAL;

  usbstrg_dumpdata("SCSCI CDB", priv->cdb, priv->cdblen);

  /* Check if there is a request in the wrreqlist that we will be able to
   * use for data or status.
   */

  privreq = (FAR struct usbstrg_req_s *)sq_peek(&priv->wrreqlist);

  /* If there no request structures available, then just return an error.
   * This will cause us to remain in the CMDPARSE state.  When a request is
   * returned, the worker thread will be awakened in the USBSTRG_STATE_CMDPARSE
   * and we will be called again.
   */

  if (!privreq)
    {
      usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_CMDPARSEWRREQLISTEMPTY), 0);
      return -ENOMEM;
    }
  DEBUGASSERT(privreq->req && privreq->req->buf);
  buf               = privreq->req->buf;

  /* Assume that no errors will be encountered */

  priv->phaseerror  = 0;
  priv->shortpacket = 0;

  /* No data is buffered */

  priv->nsectbytes   = 0;
  priv->nreqbytes    = 0;

  /* Get exclusive access to the block driver */

  pthread_mutex_lock(&priv->mutex);
  switch (priv->cdb[0])
    {
    case SCSI_CMD_TESTUNITREADY:                  /* 0x00 Mandatory */
      ret = usbstrg_cmdtestunitready(priv);
      break;

 /* case SCSI_CMD_REZEROUNIT:                      * 0x01 Obsolete
  *                                                * 0x02 Vendor-specific */

    case SCSI_CMD_REQUESTSENSE:                   /* 0x03 Mandatory */
      ret = usbstrg_cmdrequestsense(priv, buf);
      break;

 /* case SCSI_CMD_FORMAT_UNIT:                     * 0x04 Mandatory, but not implemented
  *                                                * 0x05 Vendor specific
  *                                                * 0x06 Vendor specific
  * case SCSI_CMD_REASSIGNBLOCKS:                  * 0x07 Optional */

    case SCSI_CMD_READ6:                          /* 0x08 Mandatory */
      return usbstrg_cmdread6(priv);
      break;

 /*                                                * 0x09 Vendor specific */

    case SCSI_CMD_WRITE6:                         /* 0x0a Optional */
      return usbstrg_cmdwrite6(priv);
      break;

 /* case SCSI_CMD_SEEK6:                           * 0x0b Obsolete
  *                                                * 0x0c-0x10 Vendor specific
  * case SCSI_CMD_SPACE6:                          * 0x11 Vendor specific */

    case SCSI_CMD_INQUIRY:                        /* 0x12 Mandatory */
      ret = usbstrg_cmdinquiry(priv, buf);
      break;

 /*                                                * 0x13-0x14 Vendor specific */

    case SCSI_CMD_MODESELECT6:                    /* 0x15 Optional */
      ret = usbstrg_cmdmodeselect6(priv);
      break;

 /* case SCSI_CMD_RESERVE6:                        * 0x16 Obsolete
  * case SCSI_CMD_RELEASE6:                        * 0x17 Obsolete
  * case SCSI_CMD_COPY:                            * 0x18 Obsolete
  *                                                * 0x19 Vendor specific */

    case SCSI_CMD_MODESENSE6:                     /* 0x1a Optional */
      ret = usbstrg_cmdmodesense6(priv, buf);
      break;

    case SCSI_CMD_STARTSTOPUNIT:                  /* 0x1b Optional */
      ret = usbstrg_cmdstartstopunit(priv);
      break;

 /* case SCSI_CMD_RECEIVEDIAGNOSTICRESULTS:        * 0x1c Optional
  * case SCSI_CMD_SENDDIAGNOSTIC:                  * 0x1d Mandatory, but not implemented */

    case SCSI_CMD_PREVENTMEDIAREMOVAL:            /* 0x1e Optional */
      ret = usbstrg_cmdpreventmediumremoval(priv);
      break;

 /*                                                * 0x20-22 Vendor specific
  * case SCSI_CMD_READFORMATCAPACITIES:            * 0x23 Vendor-specific
  *                                                * 0x24 Vendor specific */

    case SCSI_CMD_READCAPACITY10:                 /* 0x25 Mandatory */
      ret = usbstrg_cmdreadcapacity10(priv, buf);
      break;

 /*                                                * 0x26-27 Vendor specific */

    case SCSI_CMD_READ10:                         /* 0x28 Mandatory */
      return usbstrg_cmdread10(priv);
      break;

 /*                                                * 0x29 Vendor specific */

    case SCSI_CMD_WRITE10:                        /* 0x2a Optional */
      return usbstrg_cmdwrite10(priv);
      break;

 /* case SCSI_CMD_SEEK10:                          * 0x2b Obsolete
  *                                                * 0x2c-2d Vendor specific
  * case SCSI_CMD_WRITEANDVERIFY:                  * 0x2e Optional */

    case SCSI_CMD_VERIFY10:                       /* 0x2f Optional, but needed my MS Windows */
      ret = usbstrg_cmdverify10(priv);
      break;

 /* case SCSI_CMD_SEARCHDATAHIGH:                  * 0x30 Obsolete
  * case SCSI_CMD_SEARCHDATAEQUAL:                 * 0x31 Obsolete
  * case SCSI_CMD_SEARCHDATALOW:                   * 0x32 Obsolete
  * case SCSI_CMD_SETLIMITS10:                     * 0x33 Obsolete
  * case SCSI_CMD_PREFETCH10:                      * 0x34 Optional */

    case SCSI_CMD_SYNCHCACHE10:                   /* 0x35 Optional */
      ret = usbstrg_cmdsynchronizecache10(priv);
      break;

 /* case SCSI_CMD_LOCKCACHE:                       * 0x36 Obsolete
  * case SCSI_CMD_READDEFECTDATA10:                * 0x37 Optional
  * case SCSI_CMD_COMPARE:                         * 0x39 Obsolete
  * case SCSI_CMD_COPYANDVERIFY:                   * 0x3a Obsolete
  * case SCSI_CMD_WRITEBUFFER:                     * 0x3b Optional
  * case SCSI_CMD_READBUFFER:                      * 0x3c Optional
  * case SCSI_CMD_READLONG10:                      * 0x3e Optional
  * case SCSI_CMD_WRITELONG10:                     * 0x3f Optional
  * case SCSI_CMD_CHANGEDEFINITION:                * 0x40 Obsolete
  * case SCSI_CMD_WRITESAME10:                     * 0x41 Optional
  * case SCSI_CMD_LOGSELECT:                       * 0x4c Optional
  * case SCSI_CMD_LOGSENSE:                        * 0x4d Optional
  * case SCSI_CMD_XDWRITE10:                       * 0x50 Optional
  * case SCSI_CMD_XPWRITE10:                       * 0x51 Optional
  * case SCSI_CMD_XDREAD10:                        * 0x52 Optional */

    case SCSI_CMD_MODESELECT10:                   /* 0x55 Optional */
      ret = usbstrg_cmdmodeselect10(priv);
      break;

 /* case SCSI_CMD_RESERVE10:                       * 0x56 Obsolete
  * case SCSI_CMD_RELEASE10:                       * 0x57 Obsolete */

    case SCSI_CMD_MODESENSE10:                    /* 0x5a Optional */
      ret = usbstrg_cmdmodesense10(priv, buf);
      break;

 /* case SCSI_CMD_PERSISTENTRESERVEIN:             * 0x5e Optional
  * case SCSI_CMD_PERSISTENTRESERVEOUT:            * 0x5f Optional
  * case SCSI_CMD_32:                              * 0x7f Optional
  * case SCSI_CMD_XDWRITEEXTENDED:                 * 0x80 Obsolete
  * case SCSI_CMD_REBUILD:                         * 0x81 Obsolete
  * case SCSI_CMD_REGENERATE:                      * 0x82 Obsolete
  * case SCSI_CMD_EXTENDEDCOPY:                    * 0x83 Optional
  * case SCSI_CMD_COPYRESULTS:                     * 0x84 Optional
  * case SCSI_CMD_ACCESSCONTROLIN:                 * 0x86 Optional
  * case SCSI_CMD_ACCESSCONTROLOUT:                * 0x87 Optional
  * case SCSI_CMD_READ16:                          * 0x88 Optional
  * case SCSI_CMD_WRITE16:                         * 0x8a Optional
  * case SCSI_CMD_READATTRIBUTE:                   * 0x8c Optional
  * case SCSI_CMD_WRITEATTRIBUTE:                  * 0x8d Optional
  * case SCSI_CMD_WRITEANDVERIFY16:                * 0x8e Optional
  * case SCSI_CMD_SYNCHCACHE16:                    * 0x91 Optional
  * case SCSI_CMD_LOCKUNLOCKACACHE:                * 0x92 Optional
  * case SCSI_CMD_WRITESAME16:                     * 0x93 Optional
  * case SCSI_CMD_READCAPACITY16:                  * 0x9e Optional
  * case SCSI_CMD_READLONG16:                      * 0x9e Optional
  * case SCSI_CMD_WRITELONG16                      * 0x9f Optional
  * case SCSI_CMD_REPORTLUNS:                      * 0xa0 Mandatory, but not implemented
  * case SCSI_CMD_MAINTENANCEIN:                   * 0xa3 Optional (SCCS==0)
  * case SCSI_CMD_MAINTENANCEOUT:                  * 0xa4 Optional (SCCS==0)
  * case SCSI_CMD_MOVEMEDIUM:                      * 0xa5 ?
  * case SCSI_CMD_MOVEMEDIUMATTACHED:              * 0xa7 Optional (MCHNGR==0) */

    case SCSI_CMD_READ12:                         /* 0xa8 Optional */
      return usbstrg_cmdread12(priv);
      break;

    case SCSI_CMD_WRITE12:                        /* 0xaa Optional */
      return usbstrg_cmdwrite12(priv);
      break;

 /* case SCSI_CMD_READMEDIASERIALNUMBER:           * 0xab Optional
  * case SCSI_CMD_WRITEANDVERIFY12:                * 0xae Optional
  * case SCSI_CMD_VERIFY12:                        * 0xaf Optional
  * case SCSI_CMD_SETLIMITS12                      * 0xb3 Obsolete
  * case SCSI_CMD_READELEMENTSTATUS:               * 0xb4 Optional (MCHNGR==0)
  * case SCSI_CMD_READDEFECTDATA12:                * 0xb7 Optional
  * case SCSI_CMD_REDUNDANCYGROUPIN:               * 0xba Optional
  * case SCSI_CMD_REDUNDANCYGROUPOUT:              * 0xbb Optional
  * case SCSI_CMD_SPAREIN:                         * 0xbc Optional (SCCS==0)
  * case SCSI_CMD_SPAREOUT:                        * 0xbd Optional (SCCS==0)
  * case SCSI_CMD_VOLUMESETIN:                     * 0xbe Optional (SCCS==0)
  * case SCSI_CMD_VOLUMESETOUT:                    * 0xbe Optional (SCCS==0)
  *                                                * 0xc0-0xff Vendor specific */

    default:
      priv->u.alloclen = 0;
      if (ret == OK)
        {
          priv->lun->sd = SCSI_KCQIR_INVALIDCOMMAND;
          ret = -EINVAL;
        }
      break;
    }
  pthread_mutex_unlock(&priv->mutex);

  /* All commands come through this path (EXCEPT read6/10/12 and write6/10/12). 
   * For all other commands, the following setup is expected for the response
   * based on data direction:
   *
   * For direction NONE:
   *   1. priv->u.alloclen == 0
   *   2. priv->nreqbytes == 0
   *
   * For direction = device-to-host:
   *   1. priv->u.alloclen == allocation length; space set aside by the
   *      host to receive the device data.  The size of the response
   *      cannot exceed this value.
   *   2. response data is in the request currently at the head of
   *      the priv->wrreqlist queue.  priv->nreqbytes is set to the length
   *      of data in the response.
   *
   * For direction host-to-device
   *   At present, there are no supported commands that should have host-to-device
   *   transfers (except write6/10/12 and that command logic does not take this
   *   path.  The 'residue' is left at the full host-to-device data size.
   *
   * For all:
   *   ret set to <0 if an error occurred in parsing the commands.
   */

  /* For from device-to-hose operations, the residue is the expected size
   * (the initial value of 'residue') minus the amount actually returned
   * in the response:
   */

  if (priv->cbwdir == USBSTRG_FLAGS_DIRDEVICE2HOST)
    {
      /* The number of bytes in the response cannot exceed the the host
       * 'allocation length' in the command.
       */

      if (priv->nreqbytes > priv->u.alloclen)
        {
          priv->nreqbytes = priv->u.alloclen;
        }

      /* The residue is then the number of bytes that were not sent */

      priv->residue -= priv->nreqbytes;
    }

  /* On return, we need the following:
   *
   *   1. Setup for CMDFINISH state if appropriate
   *   2. priv->thstate set to either CMDPARSE if no buffer was available or
   *      CMDFINISH to send the response
   *   3. Return OK to continue; <0 to wait for the next event
   */

  usbtrace(TRACE_CLASSSTATE(USBSTRG_CLASSSTATE_CMDPARSECMDFINISH), priv->cdb[0]);
  priv->thstate    = USBSTRG_STATE_CMDFINISH;
  return OK;
}

/****************************************************************************
 * Name: usbstrg_cmdreadstate
 *
 * Description:
 *   Called from the worker thread in the USBSTRG_STATE_CMDREAD state.
 *   The USBSTRG_STATE_CMDREAD state is entered when usbstrg_cmdparsestate
 *   obtains a valid SCSI read command. This state is really a continuation
 *   of the USBSTRG_STATE_CMDPARSE state that handles extended SCSI read
 *   command handling.
 *
 * Returned value:
 *   If no USBDEV write request is available or certain other errors occur, this
 *   function returns a negated errno and stays in the USBSTRG_STATE_CMDREAD
 *   state.  Otherwise, when the new SCSI read command is fully processed,
 *   this function sets priv->thstate to USBSTRG_STATE_CMDFINISH and returns OK.
 *
 * State variables:
 *   xfrlen     - holds the number of sectors read to be read.
 *   sector     - holds the sector number of the next sector to be read
 *   nsectbytes - holds the number of bytes buffered for the current sector
 *   nreqbytes  - holds the number of bytes currently buffered in the request
 *                at the head of the wrreqlist.
 *
 ****************************************************************************/

static int usbstrg_cmdreadstate(FAR struct usbstrg_dev_s *priv)
{
  FAR struct usbstrg_lun_s *lun = priv->lun;
  FAR struct usbstrg_req_s *privreq;
  FAR struct usbdev_req_s *req;
  irqstate_t flags;
  ssize_t nread;
  ubyte *src;
  ubyte *dest;
  int nbytes;
  int ret;

  /* Loop transferring data until either (1) all of the data has been
   * transferred, or (2) we have used up all of the write requests that we have
   * available.
   */

  while (priv->u.xfrlen > 0 || priv->nsectbytes > 0)
    {
      usbtrace(TRACE_CLASSSTATE(USBSTRG_CLASSSTATE_CMDREAD), priv->u.xfrlen);

      /* Is the I/O buffer empty? */

      if (priv->nsectbytes <= 0)
        {
          /* Yes.. read the next sector */

          nread = USBSTRG_DRVR_READ(lun, priv->iobuffer, priv->sector, 1);
          if (nread < 0)
            {
              usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_CMDREADREADFAIL), -nread);
              lun->sd     = SCSI_KCQME_UNRRE1;
              lun->sdinfo = priv->sector;
              break;
            }

          priv->nsectbytes = lun->sectorsize;
          priv->u.xfrlen--;
          priv->sector++;
        }

      /* Check if there is a request in the wrreqlist that we will be able to
       * use for data transfer.
       */

      privreq = (FAR struct usbstrg_req_s *)sq_peek(&priv->wrreqlist);

      /* If there no request structures available, then just return an error.
       * This will cause us to remain in the CMDREAD state.  When a request is
       * returned, the worker thread will be awakened in the USBSTRG_STATE_CMDREAD
       * and we will be called again.
       */

      if (!privreq)
        {
          usbtrace(TRACE_CLSERROR(USBSTRG_TRACEERR_CMDREADWRRQEMPTY), 0);
          priv->nreqbytes = 0;
          return -ENOMEM;
        }
      req = privreq->req;

      /* Transfer all of the data that will (1) fit into the request buffer, OR (2)
       * all of the data available in the sector buffer.
       */

      src    = &priv->iobuffer[lun->sectorsize - priv->nsectbytes];
      dest   = &req->buf[priv->nreqbytes];

      nbytes = min(CONFIG_USBSTRG_BULKINREQLEN - priv->nreqbytes, priv->nsectbytes);

      /* Copy the data from the sector buffer to the USB request and update counts */

      memcpy(dest, src, nbytes);
      priv->nreqbytes  += nbytes;
      priv->nsectbytes -= nbytes;

      /* If (1) the request buffer is full OR (2) this is the final request full of data,
       * then submit the request
       */

      if (priv->nreqbytes >= CONFIG_USBSTRG_BULKINREQLEN ||
          (priv->u.xfrlen <= 0 && priv->nsectbytes <= 0))
        {
          /* Remove the request that we just filled from wrreqlist (we've already checked
           * that is it not NULL
           */

          flags = irqsave();
          privreq = (FAR struct usbstrg_req_s *)sq_remfirst(&priv->wrreqlist);
          irqrestore(flags);

          /* And submit the request to the bulk IN endpoint */

          req->len      = priv->nreqbytes;
          req->private  = privreq;
          req->callback = usbstrg_wrcomplete;