Disk.cpp revision 3b71fc51005ac566fd8120f01b784d5f251ad886
1250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar/* 2250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * Copyright (C) 2015 The Android Open Source Project 3250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * 4250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * Licensed under the Apache License, Version 2.0 (the "License"); 5250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * you may not use this file except in compliance with the License. 6250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * You may obtain a copy of the License at 7250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * 8250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * http://www.apache.org/licenses/LICENSE-2.0 9250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * 10250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * Unless required by applicable law or agreed to in writing, software 11250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * distributed under the License is distributed on an "AS IS" BASIS, 12250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * See the License for the specific language governing permissions and 14250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar * limitations under the License. 15250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar */ 16250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar 17bdc4c86d3dff74f6634a38e2f7b316b0e823a2c8Alan Viverette#include "Disk.h" 18250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar#include "PublicVolume.h" 19bdc4c86d3dff74f6634a38e2f7b316b0e823a2c8Alan Viverette#include "PrivateVolume.h" 20bdc4c86d3dff74f6634a38e2f7b316b0e823a2c8Alan Viverette#include "Utils.h" 21250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar#include "VolumeBase.h" 22250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar#include "VolumeManager.h" 23efaf86afac3163868eda7f91a1c04e3f6e6d7520Yigit Boyar#include "Ext4Crypt.h" 24250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar 258a9e8c021596439f81f210a1d2abdd047097dba2Yigit Boyar#include <android-base/file.h> 26092164e5501d0a254001225acd9dca42e5fa57e9Yigit Boyar#include <android-base/logging.h> 27092164e5501d0a254001225acd9dca42e5fa57e9Yigit Boyar#include <android-base/properties.h> 28efaf86afac3163868eda7f91a1c04e3f6e6d7520Yigit Boyar#include <android-base/stringprintf.h> 29250a3e6dc5d50c533575b7d276730b89eecc7c19Yigit Boyar#include <diskconfig/diskconfig.h> 30#include <ext4_utils/ext4_crypt.h> 31 32#include <vector> 33#include <fcntl.h> 34#include <inttypes.h> 35#include <stdio.h> 36#include <stdlib.h> 37#include <sys/types.h> 38#include <sys/stat.h> 39#include <sys/sysmacros.h> 40#include <sys/mount.h> 41 42using android::base::ReadFileToString; 43using android::base::WriteStringToFile; 44using android::base::StringPrintf; 45 46namespace android { 47namespace vold { 48 49static const char* kSgdiskPath = "/system/bin/sgdisk"; 50static const char* kSgdiskToken = " \t\n"; 51 52static const char* kSysfsLoopMaxMinors = "/sys/module/loop/parameters/max_part"; 53static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors"; 54 55static const unsigned int kMajorBlockLoop = 7; 56static const unsigned int kMajorBlockScsiA = 8; 57static const unsigned int kMajorBlockScsiB = 65; 58static const unsigned int kMajorBlockScsiC = 66; 59static const unsigned int kMajorBlockScsiD = 67; 60static const unsigned int kMajorBlockScsiE = 68; 61static const unsigned int kMajorBlockScsiF = 69; 62static const unsigned int kMajorBlockScsiG = 70; 63static const unsigned int kMajorBlockScsiH = 71; 64static const unsigned int kMajorBlockScsiI = 128; 65static const unsigned int kMajorBlockScsiJ = 129; 66static const unsigned int kMajorBlockScsiK = 130; 67static const unsigned int kMajorBlockScsiL = 131; 68static const unsigned int kMajorBlockScsiM = 132; 69static const unsigned int kMajorBlockScsiN = 133; 70static const unsigned int kMajorBlockScsiO = 134; 71static const unsigned int kMajorBlockScsiP = 135; 72static const unsigned int kMajorBlockMmc = 179; 73static const unsigned int kMajorBlockExperimentalMin = 240; 74static const unsigned int kMajorBlockExperimentalMax = 254; 75 76static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7"; 77static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF"; 78static const char* kGptAndroidExpand = "193D1EA4-B3CA-11E4-B075-10604B889DCF"; 79 80enum class Table { 81 kUnknown, 82 kMbr, 83 kGpt, 84}; 85 86static bool isVirtioBlkDevice(unsigned int major) { 87 /* 88 * The new emulator's "ranchu" virtual board no longer includes a goldfish 89 * MMC-based SD card device; instead, it emulates SD cards with virtio-blk, 90 * which has been supported by upstream kernel and QEMU for quite a while. 91 * Unfortunately, the virtio-blk block device driver does not use a fixed 92 * major number, but relies on the kernel to assign one from a specific 93 * range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE" 94 * per Documentation/devices.txt. This is true even for the latest Linux 95 * kernel (4.4; see init() in drivers/block/virtio_blk.c). 96 * 97 * This makes it difficult for vold to detect a virtio-blk based SD card. 98 * The current solution checks two conditions (both must be met): 99 * 100 * a) If the running environment is the emulator; 101 * b) If the major number is an experimental block device major number (for 102 * x86/x86_64 3.10 ranchu kernels, virtio-blk always gets major number 103 * 253, but it is safer to match the range than just one value). 104 * 105 * Other conditions could be used, too, e.g. the hardware name should be 106 * "ranchu", the device's sysfs path should end with "/block/vd[d-z]", etc. 107 * But just having a) and b) is enough for now. 108 */ 109 return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin 110 && major <= kMajorBlockExperimentalMax; 111} 112 113Disk::Disk(const std::string& eventPath, dev_t device, 114 const std::string& nickname, int flags) : 115 mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated( 116 false), mJustPartitioned(false) { 117 mId = StringPrintf("disk:%u,%u", major(device), minor(device)); 118 mEventPath = eventPath; 119 mSysPath = StringPrintf("/sys/%s", eventPath.c_str()); 120 mDevPath = StringPrintf("/dev/block/vold/%s", mId.c_str()); 121 CreateDeviceNode(mDevPath, mDevice); 122} 123 124Disk::~Disk() { 125 CHECK(!mCreated); 126 DestroyDeviceNode(mDevPath); 127} 128 129std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) { 130 for (auto vol : mVolumes) { 131 if (vol->getId() == id) { 132 return vol; 133 } 134 auto stackedVol = vol->findVolume(id); 135 if (stackedVol != nullptr) { 136 return stackedVol; 137 } 138 } 139 return nullptr; 140} 141 142void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) { 143 for (const auto& vol : mVolumes) { 144 if (vol->getType() == type) { 145 list.push_back(vol->getId()); 146 } 147 // TODO: consider looking at stacked volumes 148 } 149} 150 151status_t Disk::create() { 152 CHECK(!mCreated); 153 mCreated = true; 154 155 auto listener = VolumeManager::Instance()->getListener(); 156 if (listener) listener->onDiskCreated(getId(), mFlags); 157 158 readMetadata(); 159 readPartitions(); 160 return OK; 161} 162 163status_t Disk::destroy() { 164 CHECK(mCreated); 165 destroyAllVolumes(); 166 mCreated = false; 167 168 auto listener = VolumeManager::Instance()->getListener(); 169 if (listener) listener->onDiskDestroyed(getId()); 170 171 return OK; 172} 173 174void Disk::createPublicVolume(dev_t device) { 175 auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device)); 176 if (mJustPartitioned) { 177 LOG(DEBUG) << "Device just partitioned; silently formatting"; 178 vol->setSilent(true); 179 vol->create(); 180 vol->format("auto"); 181 vol->destroy(); 182 vol->setSilent(false); 183 } 184 185 mVolumes.push_back(vol); 186 vol->setDiskId(getId()); 187 vol->create(); 188} 189 190void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) { 191 std::string normalizedGuid; 192 if (NormalizeHex(partGuid, normalizedGuid)) { 193 LOG(WARNING) << "Invalid GUID " << partGuid; 194 return; 195 } 196 197 std::string keyRaw; 198 if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) { 199 PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid; 200 return; 201 } 202 203 LOG(DEBUG) << "Found key for GUID " << normalizedGuid; 204 205 auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw)); 206 if (mJustPartitioned) { 207 LOG(DEBUG) << "Device just partitioned; silently formatting"; 208 vol->setSilent(true); 209 vol->create(); 210 vol->format("auto"); 211 vol->destroy(); 212 vol->setSilent(false); 213 } 214 215 mVolumes.push_back(vol); 216 vol->setDiskId(getId()); 217 vol->setPartGuid(partGuid); 218 vol->create(); 219} 220 221void Disk::destroyAllVolumes() { 222 for (const auto& vol : mVolumes) { 223 vol->destroy(); 224 } 225 mVolumes.clear(); 226} 227 228status_t Disk::readMetadata() { 229 mSize = -1; 230 mLabel.clear(); 231 232 int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC); 233 if (fd != -1) { 234 if (ioctl(fd, BLKGETSIZE64, &mSize)) { 235 mSize = -1; 236 } 237 close(fd); 238 } 239 240 unsigned int majorId = major(mDevice); 241 switch (majorId) { 242 case kMajorBlockLoop: { 243 mLabel = "Virtual"; 244 break; 245 } 246 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD: 247 case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH: 248 case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL: 249 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: { 250 std::string path(mSysPath + "/device/vendor"); 251 std::string tmp; 252 if (!ReadFileToString(path, &tmp)) { 253 PLOG(WARNING) << "Failed to read vendor from " << path; 254 return -errno; 255 } 256 mLabel = tmp; 257 break; 258 } 259 case kMajorBlockMmc: { 260 std::string path(mSysPath + "/device/manfid"); 261 std::string tmp; 262 if (!ReadFileToString(path, &tmp)) { 263 PLOG(WARNING) << "Failed to read manufacturer from " << path; 264 return -errno; 265 } 266 uint64_t manfid = strtoll(tmp.c_str(), nullptr, 16); 267 // Our goal here is to give the user a meaningful label, ideally 268 // matching whatever is silk-screened on the card. To reduce 269 // user confusion, this list doesn't contain white-label manfid. 270 switch (manfid) { 271 case 0x000003: mLabel = "SanDisk"; break; 272 case 0x00001b: mLabel = "Samsung"; break; 273 case 0x000028: mLabel = "Lexar"; break; 274 case 0x000074: mLabel = "Transcend"; break; 275 } 276 break; 277 } 278 default: { 279 if (isVirtioBlkDevice(majorId)) { 280 LOG(DEBUG) << "Recognized experimental block major ID " << majorId 281 << " as virtio-blk (emulator's virtual SD card device)"; 282 mLabel = "Virtual"; 283 break; 284 } 285 LOG(WARNING) << "Unsupported block major type " << majorId; 286 return -ENOTSUP; 287 } 288 } 289 290 auto listener = VolumeManager::Instance()->getListener(); 291 if (listener) listener->onDiskMetadataChanged(getId(), 292 mSize, mLabel, mSysPath); 293 294 return OK; 295} 296 297status_t Disk::readPartitions() { 298 int8_t maxMinors = getMaxMinors(); 299 if (maxMinors < 0) { 300 return -ENOTSUP; 301 } 302 303 destroyAllVolumes(); 304 305 // Parse partition table 306 307 std::vector<std::string> cmd; 308 cmd.push_back(kSgdiskPath); 309 cmd.push_back("--android-dump"); 310 cmd.push_back(mDevPath); 311 312 std::vector<std::string> output; 313 status_t res = ForkExecvp(cmd, output); 314 if (res != OK) { 315 LOG(WARNING) << "sgdisk failed to scan " << mDevPath; 316 317 auto listener = VolumeManager::Instance()->getListener(); 318 if (listener) listener->onDiskScanned(getId()); 319 320 mJustPartitioned = false; 321 return res; 322 } 323 324 Table table = Table::kUnknown; 325 bool foundParts = false; 326 for (const auto& line : output) { 327 char* cline = (char*) line.c_str(); 328 char* token = strtok(cline, kSgdiskToken); 329 if (token == nullptr) continue; 330 331 if (!strcmp(token, "DISK")) { 332 const char* type = strtok(nullptr, kSgdiskToken); 333 if (!strcmp(type, "mbr")) { 334 table = Table::kMbr; 335 } else if (!strcmp(type, "gpt")) { 336 table = Table::kGpt; 337 } 338 } else if (!strcmp(token, "PART")) { 339 foundParts = true; 340 int i = strtol(strtok(nullptr, kSgdiskToken), nullptr, 10); 341 if (i <= 0 || i > maxMinors) { 342 LOG(WARNING) << mId << " is ignoring partition " << i 343 << " beyond max supported devices"; 344 continue; 345 } 346 dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i); 347 348 if (table == Table::kMbr) { 349 const char* type = strtok(nullptr, kSgdiskToken); 350 351 switch (strtol(type, nullptr, 16)) { 352 case 0x06: // FAT16 353 case 0x0b: // W95 FAT32 (LBA) 354 case 0x0c: // W95 FAT32 (LBA) 355 case 0x0e: // W95 FAT16 (LBA) 356 createPublicVolume(partDevice); 357 break; 358 } 359 } else if (table == Table::kGpt) { 360 const char* typeGuid = strtok(nullptr, kSgdiskToken); 361 const char* partGuid = strtok(nullptr, kSgdiskToken); 362 363 if (!strcasecmp(typeGuid, kGptBasicData)) { 364 createPublicVolume(partDevice); 365 } else if (!strcasecmp(typeGuid, kGptAndroidExpand)) { 366 createPrivateVolume(partDevice, partGuid); 367 } 368 } 369 } 370 } 371 372 // Ugly last ditch effort, treat entire disk as partition 373 if (table == Table::kUnknown || !foundParts) { 374 LOG(WARNING) << mId << " has unknown partition table; trying entire device"; 375 376 std::string fsType; 377 std::string unused; 378 if (ReadMetadataUntrusted(mDevPath, fsType, unused, unused) == OK) { 379 createPublicVolume(mDevice); 380 } else { 381 LOG(WARNING) << mId << " failed to identify, giving up"; 382 } 383 } 384 385 auto listener = VolumeManager::Instance()->getListener(); 386 if (listener) listener->onDiskScanned(getId()); 387 388 mJustPartitioned = false; 389 return OK; 390} 391 392status_t Disk::unmountAll() { 393 for (const auto& vol : mVolumes) { 394 vol->unmount(); 395 } 396 return OK; 397} 398 399status_t Disk::partitionPublic() { 400 int res; 401 402 // TODO: improve this code 403 destroyAllVolumes(); 404 mJustPartitioned = true; 405 406 // First nuke any existing partition table 407 std::vector<std::string> cmd; 408 cmd.push_back(kSgdiskPath); 409 cmd.push_back("--zap-all"); 410 cmd.push_back(mDevPath); 411 412 // Zap sometimes returns an error when it actually succeeded, so 413 // just log as warning and keep rolling forward. 414 if ((res = ForkExecvp(cmd)) != 0) { 415 LOG(WARNING) << "Failed to zap; status " << res; 416 } 417 418 struct disk_info dinfo; 419 memset(&dinfo, 0, sizeof(dinfo)); 420 421 if (!(dinfo.part_lst = (struct part_info *) malloc( 422 MAX_NUM_PARTS * sizeof(struct part_info)))) { 423 return -1; 424 } 425 426 memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info)); 427 dinfo.device = strdup(mDevPath.c_str()); 428 dinfo.scheme = PART_SCHEME_MBR; 429 dinfo.sect_size = 512; 430 dinfo.skip_lba = 2048; 431 dinfo.num_lba = 0; 432 dinfo.num_parts = 1; 433 434 struct part_info *pinfo = &dinfo.part_lst[0]; 435 436 pinfo->name = strdup("android_sdcard"); 437 pinfo->flags |= PART_ACTIVE_FLAG; 438 pinfo->type = PC_PART_TYPE_FAT32; 439 pinfo->len_kb = -1; 440 441 int rc = apply_disk_config(&dinfo, 0); 442 if (rc) { 443 LOG(ERROR) << "Failed to apply disk configuration: " << rc; 444 goto out; 445 } 446 447out: 448 free(pinfo->name); 449 free(dinfo.device); 450 free(dinfo.part_lst); 451 452 return rc; 453} 454 455status_t Disk::partitionPrivate() { 456 return partitionMixed(0); 457} 458 459status_t Disk::partitionMixed(int8_t ratio) { 460 int res; 461 462 if (e4crypt_is_native() 463 && !android::base::GetBoolProperty("persist.sys.adoptable_fbe", false)) { 464 LOG(ERROR) << "Private volumes not yet supported on FBE devices"; 465 return -EINVAL; 466 } 467 468 destroyAllVolumes(); 469 mJustPartitioned = true; 470 471 // First nuke any existing partition table 472 std::vector<std::string> cmd; 473 cmd.push_back(kSgdiskPath); 474 cmd.push_back("--zap-all"); 475 cmd.push_back(mDevPath); 476 477 // Zap sometimes returns an error when it actually succeeded, so 478 // just log as warning and keep rolling forward. 479 if ((res = ForkExecvp(cmd)) != 0) { 480 LOG(WARNING) << "Failed to zap; status " << res; 481 } 482 483 // We've had some success above, so generate both the private partition 484 // GUID and encryption key and persist them. 485 std::string partGuidRaw; 486 if (GenerateRandomUuid(partGuidRaw) != OK) { 487 LOG(ERROR) << "Failed to generate GUID"; 488 return -EIO; 489 } 490 491 std::string keyRaw; 492 if (ReadRandomBytes(16, keyRaw) != OK) { 493 LOG(ERROR) << "Failed to generate key"; 494 return -EIO; 495 } 496 497 std::string partGuid; 498 StrToHex(partGuidRaw, partGuid); 499 500 if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) { 501 LOG(ERROR) << "Failed to persist key"; 502 return -EIO; 503 } else { 504 LOG(DEBUG) << "Persisted key for GUID " << partGuid; 505 } 506 507 // Now let's build the new GPT table. We heavily rely on sgdisk to 508 // force optimal alignment on the created partitions. 509 cmd.clear(); 510 cmd.push_back(kSgdiskPath); 511 512 // If requested, create a public partition first. Mixed-mode partitioning 513 // like this is an experimental feature. 514 if (ratio > 0) { 515 if (ratio < 10 || ratio > 90) { 516 LOG(ERROR) << "Mixed partition ratio must be between 10-90%"; 517 return -EINVAL; 518 } 519 520 uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024; 521 cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb)); 522 cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData)); 523 cmd.push_back("--change-name=0:shared"); 524 } 525 526 // Define a metadata partition which is designed for future use; there 527 // should only be one of these per physical device, even if there are 528 // multiple private volumes. 529 cmd.push_back("--new=0:0:+16M"); 530 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta)); 531 cmd.push_back("--change-name=0:android_meta"); 532 533 // Define a single private partition filling the rest of disk. 534 cmd.push_back("--new=0:0:-0"); 535 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExpand)); 536 cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str())); 537 cmd.push_back("--change-name=0:android_expand"); 538 539 cmd.push_back(mDevPath); 540 541 if ((res = ForkExecvp(cmd)) != 0) { 542 LOG(ERROR) << "Failed to partition; status " << res; 543 return res; 544 } 545 546 return OK; 547} 548 549int Disk::getMaxMinors() { 550 // Figure out maximum partition devices supported 551 unsigned int majorId = major(mDevice); 552 switch (majorId) { 553 case kMajorBlockLoop: { 554 std::string tmp; 555 if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) { 556 LOG(ERROR) << "Failed to read max minors"; 557 return -errno; 558 } 559 return std::stoi(tmp); 560 } 561 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD: 562 case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH: 563 case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL: 564 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: { 565 // Per Documentation/devices.txt this is static 566 return 15; 567 } 568 case kMajorBlockMmc: { 569 // Per Documentation/devices.txt this is dynamic 570 std::string tmp; 571 if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) { 572 LOG(ERROR) << "Failed to read max minors"; 573 return -errno; 574 } 575 return std::stoi(tmp); 576 } 577 default: { 578 if (isVirtioBlkDevice(majorId)) { 579 // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is 580 // 2^4 - 1 = 15 581 return 15; 582 } 583 } 584 } 585 586 LOG(ERROR) << "Unsupported block major type " << majorId; 587 return -ENOTSUP; 588} 589 590} // namespace vold 591} // namespace android 592