Fix device size calculations in write_firmware.py

The _GetDiskCapacity() function expects the device size to be reported
as XXXX MB, but large devices have their size reported as XX.X
GB. Common for all devices is reporting the size in bytes in the end
of the string.

The regex fishing out the device size is being changed to look for the
bytes size number, then the function converts it into Gigabytes and
returns.

Some other refactoring included

 - reporting the situation where no removable devices have been found;
 - eliminating the ability to include device description as the
   command line parameter;
 - adjusting the help message
 - corrected a call site of _ExtractPayloadParts() reported as a
   problem by Lint

BUG=none
TEST=manual

  . both the following commands now work even with the cards reporting
    their size in GB:

    $ cros_write_firmware --board=peach -w sd:. -i image.bin
    $ cros_write_firmware --board=peach -w sd:/dev/sdc -i image.bin

    . when no removable device is available, the following error
      message is printed:

       No removable devices found
       Did you forget to plug in the SD card?

    . unit tests still pass
    $ FEATURES=test sudo -E emerge cros-devutils

   . when a wrong device is specified in the command line, the list of
     available devices is printed:

     $ cros_write_firmware --board=peach -w sd:/dev/sda -i image.bin
     Please specify destination -w 'sd:<disk_description>':
        - description can be . for the only disk, or
          the full device name, one of listed below:
     Found 1 available disks.
        /dev/sdc: Generic Mass Storage Device 3.9 GB

Change-Id: Ie19e34712d48179fe6ea32716d202a4ddbc1b02c
Signed-off-by: Vadim Bendebury <vbendeb@chromium.org>
Reviewed-on: https://gerrit.chromium.org/gerrit/46217
Reviewed-by: Simon Glass <sjg@chromium.org>
Reviewed-by: Doug Anderson <dianders@chromium.org>
diff --git a/host/lib/write_firmware.py b/host/lib/write_firmware.py
index 0a55291..8515ff7 100644
--- a/host/lib/write_firmware.py
+++ b/host/lib/write_firmware.py
@@ -626,7 +626,7 @@
     return '[Unknown]'
 
   def _GetDiskCapacity(self, device):
-    """Returns the disk capacity in GB, or 0 if not known.
+    """Returns the disk capacity in tenth of GB, or 0 if not known.
 
     Args:
       device: Device to check, like '/dev/sdf'.
@@ -634,17 +634,13 @@
     Returns:
       Capacity of device in GB, or 0 if not known.
     """
+    re_capacity = re.compile('Disk %s: .* (\d+) bytes' % device)
     args = ['-l', device]
     stdout = self._tools.Run('fdisk', args, sudo=True)
-    if stdout:
-      # Seach for the line with capacity information.
-      re_capacity = re.compile('Disk .*: (\d+) \w+,')
-      lines = filter(re_capacity.match, stdout.splitlines())
-      if len(lines):
-        m = re_capacity.match(lines[0])
-
-        # We get something like 7859 MB, so turn into bytes, then GB
-        return int(m.group(1)) * 1024 * 1024 / 1e9
+    for line in stdout.splitlines():
+      m = re_capacity.match(line)
+      if m:
+        return int(int(m.group(1)) / 1e8)
     return 0
 
   def _ListUsbDisks(self):
@@ -655,8 +651,7 @@
         device ('/dev/sdx')
         manufacturer name
         product name
-        capacity in GB (an integer)
-        full description (all of the above concatenated).
+        capacity in tenth of GB (an integer)
     """
     disk_list = []
     for disk in glob.glob('/sys/block/sd*'):
@@ -667,14 +662,13 @@
           product = self._GetDiskInfo(disk, 'product')
           capacity = self._GetDiskCapacity(device)
           if capacity:
-            desc = '%s: %s %s %d GB' % (device, manuf, product, capacity)
-            disk_list.append([device, manuf, product, capacity, desc])
+            disk_list.append([device, manuf, product, capacity])
     return disk_list
 
   def WriteToSd(self, flash_dest, disk, uboot, payload):
     if flash_dest:
       raw_image = self._PrepareFlasher(uboot, payload, flash_dest, '1:0')
-      bl1, bl2, _ = self._ExtractPayloadParts(payload)
+      bl1, bl2, _ = self._ExtractPayloadParts(payload, True)
       spl_load_size = os.stat(raw_image).st_size
       bl2 = self._bundle.ConfigureExynosBl2(self._fdt, spl_load_size, bl2,
                                             'flasher')
@@ -701,12 +695,10 @@
 
     Args:
       dest: Destination in one of these forms:
-          ':<full description of device>'
           ':.' selects the only available device, fails if more than one option
           ':<device>' select deivce
 
           Examples:
-            ':/dev/sdd: Generic Flash Card Reader/Writer 8 GB'
             ':.'
             ':/dev/sdd'
 
@@ -717,24 +709,29 @@
     """
     disk = None
     disks = self._ListUsbDisks()
-    if dest[:1] == ':':
+
+    if not disks:
+      self._out.Error('No removable devices found')
+      self._out.Error('Did you forget to plug in the SD card?')
+      return
+
+    if dest.startswith(':'):
       name = dest[1:]
 
       # A '.' just means to use the only available disk.
       if name == '.' and len(disks) == 1:
         disk = disks[0][0]
       for disk_info in disks:
-        # Use the full name or the device name.
-        if disk_info[4] == name or disk_info[1] == name:
+        # Use the device name.
+        if disk_info[0] == name:
           disk = disk_info[0]
 
     if disk:
       self.WriteToSd(flash_dest, disk, uboot, payload)
     else:
       self._out.Error("Please specify destination -w 'sd:<disk_description>':")
-      self._out.Error('   - description can be . for the only disk, SCSI '
-                      'device letter')
-      self._out.Error('     or the full description listed here')
+      self._out.Error('   - description can be . for the only disk, or')
+      self._out.Error('     the full device name, one of listed below:')
       msg = 'Found %d available disks.' % len(disks)
       if not disks:
         msg += ' Please insert an SD card and try again.'
@@ -742,7 +739,12 @@
 
       # List available disks as a convenience.
       for disk in disks:
-        self._out.UserOutput('  %s' % disk[4])
+        self._out.UserOutput('  %s: %s %d.%d GB' % (
+            disk[0],
+            ' '.join(str(x) for x in disk[1:3]),
+            disk[3] / 10,  # Integer number of GBs
+            disk[3] % 10,  # Decimal number of GBs
+            ))
 
   def Em100FlashImage(self, image_fname):
     """Send an image to an attached EM100 device.