2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "PublicVolume.h"
19 #include "PrivateVolume.h"
21 #include "VolumeBase.h"
22 #include "VolumeManager.h"
23 #include "ResponseCode.h"
24 #include "Ext4Crypt.h"
26 #include <android-base/file.h>
27 #include <android-base/stringprintf.h>
28 #include <android-base/logging.h>
29 #include <diskconfig/diskconfig.h>
36 #include <sys/types.h>
38 #include <sys/sysmacros.h>
39 #include <sys/mount.h>
41 using android::base::ReadFileToString;
42 using android::base::WriteStringToFile;
43 using android::base::StringPrintf;
48 static const char* kSgdiskPath = "/system/bin/sgdisk";
49 static const char* kSgdiskToken = " \t\n";
51 static const char* kSysfsLoopMaxMinors = "/sys/module/loop/parameters/max_part";
52 static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
54 static const unsigned int kMajorBlockLoop = 7;
55 static const unsigned int kMajorBlockScsiA = 8;
56 static const unsigned int kMajorBlockScsiB = 65;
57 static const unsigned int kMajorBlockScsiC = 66;
58 static const unsigned int kMajorBlockScsiD = 67;
59 static const unsigned int kMajorBlockScsiE = 68;
60 static const unsigned int kMajorBlockScsiF = 69;
61 static const unsigned int kMajorBlockScsiG = 70;
62 static const unsigned int kMajorBlockScsiH = 71;
63 static const unsigned int kMajorBlockScsiI = 128;
64 static const unsigned int kMajorBlockScsiJ = 129;
65 static const unsigned int kMajorBlockScsiK = 130;
66 static const unsigned int kMajorBlockScsiL = 131;
67 static const unsigned int kMajorBlockScsiM = 132;
68 static const unsigned int kMajorBlockScsiN = 133;
69 static const unsigned int kMajorBlockScsiO = 134;
70 static const unsigned int kMajorBlockScsiP = 135;
71 static const unsigned int kMajorBlockMmc = 179;
72 static const unsigned int kMajorBlockExperimentalMin = 240;
73 static const unsigned int kMajorBlockExperimentalMax = 254;
75 static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
76 static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
77 static const char* kGptAndroidExpand = "193D1EA4-B3CA-11E4-B075-10604B889DCF";
85 static bool isVirtioBlkDevice(unsigned int major) {
87 * The new emulator's "ranchu" virtual board no longer includes a goldfish
88 * MMC-based SD card device; instead, it emulates SD cards with virtio-blk,
89 * which has been supported by upstream kernel and QEMU for quite a while.
90 * Unfortunately, the virtio-blk block device driver does not use a fixed
91 * major number, but relies on the kernel to assign one from a specific
92 * range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
93 * per Documentation/devices.txt. This is true even for the latest Linux
94 * kernel (4.4; see init() in drivers/block/virtio_blk.c).
96 * This makes it difficult for vold to detect a virtio-blk based SD card.
97 * The current solution checks two conditions (both must be met):
99 * a) If the running environment is the emulator;
100 * b) If the major number is an experimental block device major number (for
101 * x86/x86_64 3.10 ranchu kernels, virtio-blk always gets major number
102 * 253, but it is safer to match the range than just one value).
104 * Other conditions could be used, too, e.g. the hardware name should be
105 * "ranchu", the device's sysfs path should end with "/block/vd[d-z]", etc.
106 * But just having a) and b) is enough for now.
108 return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin
109 && major <= kMajorBlockExperimentalMax;
112 Disk::Disk(const std::string& eventPath, dev_t device,
113 const std::string& nickname, int flags) :
114 mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated(
115 false), mJustPartitioned(false) {
116 mId = StringPrintf("disk:%u,%u", major(device), minor(device));
117 mEventPath = eventPath;
118 mSysPath = StringPrintf("/sys/%s", eventPath.c_str());
119 mDevPath = StringPrintf("/dev/block/vold/%s", mId.c_str());
120 CreateDeviceNode(mDevPath, mDevice);
125 DestroyDeviceNode(mDevPath);
128 std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) {
129 for (auto vol : mVolumes) {
130 if (vol->getId() == id) {
133 auto stackedVol = vol->findVolume(id);
134 if (stackedVol != nullptr) {
141 void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) {
142 for (const auto& vol : mVolumes) {
143 if (vol->getType() == type) {
144 list.push_back(vol->getId());
146 // TODO: consider looking at stacked volumes
150 status_t Disk::create() {
153 notifyEvent(ResponseCode::DiskCreated, StringPrintf("%d", mFlags));
159 status_t Disk::destroy() {
163 notifyEvent(ResponseCode::DiskDestroyed);
167 void Disk::createPublicVolume(dev_t device) {
168 auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device));
169 if (mJustPartitioned) {
170 LOG(DEBUG) << "Device just partitioned; silently formatting";
171 vol->setSilent(true);
175 vol->setSilent(false);
178 mVolumes.push_back(vol);
179 vol->setDiskId(getId());
183 void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) {
184 std::string normalizedGuid;
185 if (NormalizeHex(partGuid, normalizedGuid)) {
186 LOG(WARNING) << "Invalid GUID " << partGuid;
191 if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
192 PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
196 LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
198 auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
199 if (mJustPartitioned) {
200 LOG(DEBUG) << "Device just partitioned; silently formatting";
201 vol->setSilent(true);
205 vol->setSilent(false);
208 mVolumes.push_back(vol);
209 vol->setDiskId(getId());
210 vol->setPartGuid(partGuid);
214 void Disk::destroyAllVolumes() {
215 for (const auto& vol : mVolumes) {
221 status_t Disk::readMetadata() {
225 int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC);
227 if (ioctl(fd, BLKGETSIZE64, &mSize)) {
233 unsigned int majorId = major(mDevice);
235 case kMajorBlockLoop: {
239 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
240 case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
241 case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
242 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
243 std::string path(mSysPath + "/device/vendor");
245 if (!ReadFileToString(path, &tmp)) {
246 PLOG(WARNING) << "Failed to read vendor from " << path;
252 case kMajorBlockMmc: {
253 std::string path(mSysPath + "/device/manfid");
255 if (!ReadFileToString(path, &tmp)) {
256 PLOG(WARNING) << "Failed to read manufacturer from " << path;
259 uint64_t manfid = strtoll(tmp.c_str(), nullptr, 16);
260 // Our goal here is to give the user a meaningful label, ideally
261 // matching whatever is silk-screened on the card. To reduce
262 // user confusion, this list doesn't contain white-label manfid.
264 case 0x000003: mLabel = "SanDisk"; break;
265 case 0x00001b: mLabel = "Samsung"; break;
266 case 0x000028: mLabel = "Lexar"; break;
267 case 0x000074: mLabel = "Transcend"; break;
272 if (isVirtioBlkDevice(majorId)) {
273 LOG(DEBUG) << "Recognized experimental block major ID " << majorId
274 << " as virtio-blk (emulator's virtual SD card device)";
278 LOG(WARNING) << "Unsupported block major type " << majorId;
283 notifyEvent(ResponseCode::DiskSizeChanged, StringPrintf("%" PRIu64, mSize));
284 notifyEvent(ResponseCode::DiskLabelChanged, mLabel);
285 notifyEvent(ResponseCode::DiskSysPathChanged, mSysPath);
289 status_t Disk::readPartitions() {
290 int8_t maxMinors = getMaxMinors();
297 // Parse partition table
299 std::vector<std::string> cmd;
300 cmd.push_back(kSgdiskPath);
301 cmd.push_back("--android-dump");
302 cmd.push_back(mDevPath);
304 std::vector<std::string> output;
305 status_t res = ForkExecvp(cmd, output);
307 LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
308 notifyEvent(ResponseCode::DiskScanned);
309 mJustPartitioned = false;
313 Table table = Table::kUnknown;
314 bool foundParts = false;
315 for (const auto& line : output) {
316 char* cline = (char*) line.c_str();
317 char* token = strtok(cline, kSgdiskToken);
318 if (token == nullptr) continue;
320 if (!strcmp(token, "DISK")) {
321 const char* type = strtok(nullptr, kSgdiskToken);
322 if (!strcmp(type, "mbr")) {
324 } else if (!strcmp(type, "gpt")) {
327 } else if (!strcmp(token, "PART")) {
329 int i = strtol(strtok(nullptr, kSgdiskToken), nullptr, 10);
330 if (i <= 0 || i > maxMinors) {
331 LOG(WARNING) << mId << " is ignoring partition " << i
332 << " beyond max supported devices";
335 dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
337 if (table == Table::kMbr) {
338 const char* type = strtok(nullptr, kSgdiskToken);
340 switch (strtol(type, nullptr, 16)) {
342 case 0x0b: // W95 FAT32 (LBA)
343 case 0x0c: // W95 FAT32 (LBA)
344 case 0x0e: // W95 FAT16 (LBA)
345 createPublicVolume(partDevice);
348 } else if (table == Table::kGpt) {
349 const char* typeGuid = strtok(nullptr, kSgdiskToken);
350 const char* partGuid = strtok(nullptr, kSgdiskToken);
352 if (!strcasecmp(typeGuid, kGptBasicData)) {
353 createPublicVolume(partDevice);
354 } else if (!strcasecmp(typeGuid, kGptAndroidExpand)) {
355 createPrivateVolume(partDevice, partGuid);
361 // Ugly last ditch effort, treat entire disk as partition
362 if (table == Table::kUnknown || !foundParts) {
363 LOG(WARNING) << mId << " has unknown partition table; trying entire device";
367 if (ReadMetadataUntrusted(mDevPath, fsType, unused, unused) == OK) {
368 createPublicVolume(mDevice);
370 LOG(WARNING) << mId << " failed to identify, giving up";
374 notifyEvent(ResponseCode::DiskScanned);
375 mJustPartitioned = false;
379 status_t Disk::unmountAll() {
380 for (const auto& vol : mVolumes) {
386 status_t Disk::partitionPublic() {
389 // TODO: improve this code
391 mJustPartitioned = true;
393 // First nuke any existing partition table
394 std::vector<std::string> cmd;
395 cmd.push_back(kSgdiskPath);
396 cmd.push_back("--zap-all");
397 cmd.push_back(mDevPath);
399 // Zap sometimes returns an error when it actually succeeded, so
400 // just log as warning and keep rolling forward.
401 if ((res = ForkExecvp(cmd)) != 0) {
402 LOG(WARNING) << "Failed to zap; status " << res;
405 struct disk_info dinfo;
406 memset(&dinfo, 0, sizeof(dinfo));
408 if (!(dinfo.part_lst = (struct part_info *) malloc(
409 MAX_NUM_PARTS * sizeof(struct part_info)))) {
413 memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
414 dinfo.device = strdup(mDevPath.c_str());
415 dinfo.scheme = PART_SCHEME_MBR;
416 dinfo.sect_size = 512;
417 dinfo.skip_lba = 2048;
421 struct part_info *pinfo = &dinfo.part_lst[0];
423 pinfo->name = strdup("android_sdcard");
424 pinfo->flags |= PART_ACTIVE_FLAG;
425 pinfo->type = PC_PART_TYPE_FAT32;
428 int rc = apply_disk_config(&dinfo, 0);
430 LOG(ERROR) << "Failed to apply disk configuration: " << rc;
437 free(dinfo.part_lst);
442 status_t Disk::partitionPrivate() {
443 return partitionMixed(0);
446 status_t Disk::partitionMixed(int8_t ratio) {
449 if (e4crypt_is_native()) {
450 LOG(ERROR) << "Private volumes not yet supported on FBE devices";
455 mJustPartitioned = true;
457 // First nuke any existing partition table
458 std::vector<std::string> cmd;
459 cmd.push_back(kSgdiskPath);
460 cmd.push_back("--zap-all");
461 cmd.push_back(mDevPath);
463 // Zap sometimes returns an error when it actually succeeded, so
464 // just log as warning and keep rolling forward.
465 if ((res = ForkExecvp(cmd)) != 0) {
466 LOG(WARNING) << "Failed to zap; status " << res;
469 // We've had some success above, so generate both the private partition
470 // GUID and encryption key and persist them.
471 std::string partGuidRaw;
473 if (ReadRandomBytes(16, partGuidRaw) || ReadRandomBytes(16, keyRaw)) {
474 LOG(ERROR) << "Failed to generate GUID or key";
478 std::string partGuid;
479 StrToHex(partGuidRaw, partGuid);
481 if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
482 LOG(ERROR) << "Failed to persist key";
485 LOG(DEBUG) << "Persisted key for GUID " << partGuid;
488 // Now let's build the new GPT table. We heavily rely on sgdisk to
489 // force optimal alignment on the created partitions.
491 cmd.push_back(kSgdiskPath);
493 // If requested, create a public partition first. Mixed-mode partitioning
494 // like this is an experimental feature.
496 if (ratio < 10 || ratio > 90) {
497 LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
501 uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024;
502 cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb));
503 cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData));
504 cmd.push_back("--change-name=0:shared");
507 // Define a metadata partition which is designed for future use; there
508 // should only be one of these per physical device, even if there are
509 // multiple private volumes.
510 cmd.push_back("--new=0:0:+16M");
511 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta));
512 cmd.push_back("--change-name=0:android_meta");
514 // Define a single private partition filling the rest of disk.
515 cmd.push_back("--new=0:0:-0");
516 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExpand));
517 cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str()));
518 cmd.push_back("--change-name=0:android_expand");
520 cmd.push_back(mDevPath);
522 if ((res = ForkExecvp(cmd)) != 0) {
523 LOG(ERROR) << "Failed to partition; status " << res;
530 void Disk::notifyEvent(int event) {
531 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
532 getId().c_str(), false);
535 void Disk::notifyEvent(int event, const std::string& value) {
536 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
537 StringPrintf("%s %s", getId().c_str(), value.c_str()).c_str(), false);
540 int Disk::getMaxMinors() {
541 // Figure out maximum partition devices supported
542 unsigned int majorId = major(mDevice);
544 case kMajorBlockLoop: {
546 if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) {
547 LOG(ERROR) << "Failed to read max minors";
550 return atoi(tmp.c_str());
552 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
553 case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
554 case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
555 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
556 // Per Documentation/devices.txt this is static
559 case kMajorBlockMmc: {
560 // Per Documentation/devices.txt this is dynamic
562 if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
563 LOG(ERROR) << "Failed to read max minors";
566 return atoi(tmp.c_str());
569 if (isVirtioBlkDevice(majorId)) {
570 // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is
577 LOG(ERROR) << "Unsupported block major type " << majorId;
582 } // namespace android