From 59fea041b601af942833880506822a50ec755407 Mon Sep 17 00:00:00 2001 From: Adriaan de Groot Date: Wed, 8 Aug 2018 05:16:46 -0400 Subject: [PATCH] [partition] Fix up calculations of sectors in auto-partition - Calculating first free sector had an off-by-one so that partitioning would start at 2049. - EFI boot partition grew 1 sector larger than desired. - While here, align everything to 1MiB boundaries as well. FIXES #1008 --- .../partition/core/PartitionActions.cpp | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/modules/partition/core/PartitionActions.cpp b/src/modules/partition/core/PartitionActions.cpp index 999847e37..87c9d6e72 100644 --- a/src/modules/partition/core/PartitionActions.cpp +++ b/src/modules/partition/core/PartitionActions.cpp @@ -101,6 +101,24 @@ swapSuggestion( const qint64 availableSpaceB ) return suggestedSwapSizeB; } +constexpr qint64 +alignBytesToBlockSize( qint64 bytes, qint64 blocksize ) +{ + Q_ASSERT( bytes >= 0 ); + Q_ASSERT( blocksize > 0 ); + qint64 blocks = bytes / blocksize; + Q_ASSERT( blocks >= 0 ); + + if ( blocks * blocksize != bytes ) + ++blocks; + return blocks * blocksize; +} + +constexpr qint64 +bytesToSectors( qint64 bytes, qint64 blocksize ) +{ + return alignBytesToBlockSize( alignBytesToBlockSize( bytes, blocksize), MiBtoBytes(1) ) / blocksize; +} void doAutopartition( PartitionCoreModule* core, Device* dev, const QString& luksPassphrase ) @@ -120,11 +138,20 @@ doAutopartition( PartitionCoreModule* core, Device* dev, const QString& luksPass int uefisys_part_size = isEfi ? 300 : 0; int empty_space_size = isEfi ? 2 : 1; - qint64 firstFreeSector = MiBtoBytes(empty_space_size) / dev->logicalSize() + 1; + // Since sectors count from 0, if the space is 2048 sectors in size, + // the first free sector has number 2048 (and there are 2048 sectors + // before that one, numbered 0..2047). + qint64 firstFreeSector = bytesToSectors( MiBtoBytes(empty_space_size), dev->logicalSize() ); if ( isEfi ) { - qint64 lastSector = firstFreeSector + ( MiBtoBytes(uefisys_part_size) / dev->logicalSize() ); + qint64 efiSectorCount = bytesToSectors( MiBtoBytes(uefisys_part_size), dev->logicalSize() ); + Q_ASSERT( efiSectorCount > 0 ); + + // Since sectors count from 0, and this partition is created starting + // at firstFreeSector, we need efiSectorCount sectors, numbered + // firstFreeSector..firstFreeSector+efiSectorCount-1. + qint64 lastSector = firstFreeSector + efiSectorCount - 1; core->createPartitionTable( dev, PartitionTable::gpt ); Partition* efiPartition = KPMHelpers::createNewPartition( dev->partitionTable(),