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"
25 #include <base/file.h>
26 #include <base/stringprintf.h>
27 #include <base/logging.h>
28 #include <diskconfig/diskconfig.h>
35 #include <sys/types.h>
37 #include <sys/mount.h>
39 using android::base::ReadFileToString;
40 using android::base::WriteStringToFile;
41 using android::base::StringPrintf;
47 static const char* kSgdiskPath = "/sbin/sgdisk";
49 static const char* kSgdiskPath = "/system/bin/sgdisk";
51 static const char* kSgdiskToken = " \t\n";
53 static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
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;
73 static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
74 static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
75 static const char* kGptAndroidExpand = "193D1EA4-B3CA-11E4-B075-10604B889DCF";
83 Disk::Disk(const std::string& eventPath, dev_t device,
84 const std::string& nickname, int flags) :
85 mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated(
86 false), mJustPartitioned(false) {
87 mId = StringPrintf("disk:%u_%u", major(device), minor(device));
88 mEventPath = eventPath;
89 mSysPath = StringPrintf("/sys/%s", eventPath.c_str());
90 mDevPath = StringPrintf("/dev/block/vold/%s", mId.c_str());
91 CreateDeviceNode(mDevPath, mDevice);
96 DestroyDeviceNode(mDevPath);
99 std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) {
100 for (auto vol : mVolumes) {
101 if (vol->getId() == id) {
104 auto stackedVol = vol->findVolume(id);
105 if (stackedVol != nullptr) {
112 void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) {
113 for (auto vol : mVolumes) {
114 if (vol->getType() == type) {
115 list.push_back(vol->getId());
117 // TODO: consider looking at stacked volumes
121 status_t Disk::create() {
124 notifyEvent(ResponseCode::DiskCreated, StringPrintf("%d", mFlags));
130 status_t Disk::destroy() {
134 notifyEvent(ResponseCode::DiskDestroyed);
138 void Disk::createPublicVolume(dev_t device,
139 const std::string& fstype /* = "" */,
140 const std::string& mntopts /* = "" */) {
141 auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device, mNickname, fstype, mntopts));
142 if (mJustPartitioned) {
143 LOG(DEBUG) << "Device just partitioned; silently formatting";
144 vol->setSilent(true);
148 vol->setSilent(false);
151 mVolumes.push_back(vol);
152 vol->setDiskId(getId());
156 void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) {
157 std::string normalizedGuid;
158 if (NormalizeHex(partGuid, normalizedGuid)) {
159 LOG(WARNING) << "Invalid GUID " << partGuid;
164 if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
165 PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
169 LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
171 auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
172 if (mJustPartitioned) {
173 LOG(DEBUG) << "Device just partitioned; silently formatting";
174 vol->setSilent(true);
178 vol->setSilent(false);
181 mVolumes.push_back(vol);
182 vol->setDiskId(getId());
183 vol->setPartGuid(partGuid);
187 void Disk::destroyAllVolumes() {
188 for (auto vol : mVolumes) {
194 status_t Disk::readMetadata() {
198 int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC);
200 if (ioctl(fd, BLKGETSIZE64, &mSize)) {
206 switch (major(mDevice)) {
207 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
208 case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
209 case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
210 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
211 std::string path(mSysPath + "/device/vendor");
213 if (!ReadFileToString(path, &tmp)) {
214 PLOG(WARNING) << "Failed to read vendor from " << path;
220 case kMajorBlockMmc: {
221 std::string path(mSysPath + "/device/manfid");
223 if (!ReadFileToString(path, &tmp)) {
224 PLOG(WARNING) << "Failed to read manufacturer from " << path;
227 uint64_t manfid = strtoll(tmp.c_str(), nullptr, 16);
228 // Our goal here is to give the user a meaningful label, ideally
229 // matching whatever is silk-screened on the card. To reduce
230 // user confusion, this list doesn't contain white-label manfid.
232 case 0x000003: mLabel = "SanDisk"; break;
233 case 0x00001b: mLabel = "Samsung"; break;
234 case 0x000028: mLabel = "Lexar"; break;
235 case 0x000074: mLabel = "Transcend"; break;
240 LOG(WARNING) << "Unsupported block major type" << major(mDevice);
245 notifyEvent(ResponseCode::DiskSizeChanged, StringPrintf("%" PRId64, mSize));
246 notifyEvent(ResponseCode::DiskLabelChanged, mLabel);
247 notifyEvent(ResponseCode::DiskSysPathChanged, mSysPath);
251 status_t Disk::readPartitions() {
252 int8_t maxMinors = getMaxMinors();
259 // Parse partition table
261 std::vector<std::string> cmd;
262 cmd.push_back(kSgdiskPath);
263 cmd.push_back("--android-dump");
264 cmd.push_back(mDevPath);
266 std::vector<std::string> output;
267 status_t res = ForkExecvp(cmd, output);
269 LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
270 notifyEvent(ResponseCode::DiskScanned);
271 mJustPartitioned = false;
275 Table table = Table::kUnknown;
276 bool foundParts = false;
277 for (auto line : output) {
278 char* cline = (char*) line.c_str();
279 char* token = strtok(cline, kSgdiskToken);
280 if (token == nullptr) continue;
282 if (!strcmp(token, "DISK")) {
283 const char* type = strtok(nullptr, kSgdiskToken);
284 if (!strcmp(type, "mbr")) {
286 } else if (!strcmp(type, "gpt")) {
289 } else if (!strcmp(token, "PART")) {
291 int i = strtol(strtok(nullptr, kSgdiskToken), nullptr, 10);
292 if (i <= 0 || i > maxMinors) {
293 LOG(WARNING) << mId << " is ignoring partition " << i
294 << " beyond max supported devices";
297 dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
299 if (table == Table::kMbr) {
300 const char* type = strtok(nullptr, kSgdiskToken);
302 switch (strtol(type, nullptr, 16)) {
304 case 0x07: // NTFS/exFAT
305 case 0x0b: // W95 FAT32 (LBA)
306 case 0x0c: // W95 FAT32 (LBA)
307 case 0x0e: // W95 FAT16 (LBA)
308 case 0x83: // Linux EXT4/F2FS/...
309 createPublicVolume(partDevice);
312 } else if (table == Table::kGpt) {
313 const char* typeGuid = strtok(nullptr, kSgdiskToken);
314 const char* partGuid = strtok(nullptr, kSgdiskToken);
316 if (!strcasecmp(typeGuid, kGptBasicData)) {
317 createPublicVolume(partDevice);
318 } else if (!strcasecmp(typeGuid, kGptAndroidExpand)) {
319 createPrivateVolume(partDevice, partGuid);
325 // Ugly last ditch effort, treat entire disk as partition
326 if (table == Table::kUnknown || !foundParts) {
327 LOG(WARNING) << mId << " has unknown partition table; trying entire device";
331 if (ReadMetadataUntrusted(mDevPath, fsType, unused, unused) == OK) {
332 createPublicVolume(mDevice);
334 LOG(WARNING) << mId << " failed to identify, giving up";
338 notifyEvent(ResponseCode::DiskScanned);
339 mJustPartitioned = false;
343 status_t Disk::unmountAll() {
344 for (auto vol : mVolumes) {
350 status_t Disk::partitionPublic() {
353 // TODO: improve this code
355 mJustPartitioned = true;
357 // First nuke any existing partition table
358 std::vector<std::string> cmd;
359 cmd.push_back(kSgdiskPath);
360 cmd.push_back("--zap-all");
361 cmd.push_back(mDevPath);
363 // Zap sometimes returns an error when it actually succeeded, so
364 // just log as warning and keep rolling forward.
365 if ((res = ForkExecvp(cmd)) != 0) {
366 LOG(WARNING) << "Failed to zap; status " << res;
369 struct disk_info dinfo;
370 memset(&dinfo, 0, sizeof(dinfo));
372 if (!(dinfo.part_lst = (struct part_info *) malloc(
373 MAX_NUM_PARTS * sizeof(struct part_info)))) {
377 memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
378 dinfo.device = strdup(mDevPath.c_str());
379 dinfo.scheme = PART_SCHEME_MBR;
380 dinfo.sect_size = 512;
381 dinfo.skip_lba = 2048;
385 struct part_info *pinfo = &dinfo.part_lst[0];
387 pinfo->name = strdup("android_sdcard");
388 pinfo->flags |= PART_ACTIVE_FLAG;
389 pinfo->type = PC_PART_TYPE_FAT32;
392 int rc = apply_disk_config(&dinfo, 0);
394 LOG(ERROR) << "Failed to apply disk configuration: " << rc;
401 free(dinfo.part_lst);
406 status_t Disk::partitionPrivate() {
407 return partitionMixed(0);
410 status_t Disk::partitionMixed(int8_t ratio) {
414 mJustPartitioned = true;
416 // First nuke any existing partition table
417 std::vector<std::string> cmd;
418 cmd.push_back(kSgdiskPath);
419 cmd.push_back("--zap-all");
420 cmd.push_back(mDevPath);
422 // Zap sometimes returns an error when it actually succeeded, so
423 // just log as warning and keep rolling forward.
424 if ((res = ForkExecvp(cmd)) != 0) {
425 LOG(WARNING) << "Failed to zap; status " << res;
428 // We've had some success above, so generate both the private partition
429 // GUID and encryption key and persist them.
430 std::string partGuidRaw;
432 if (ReadRandomBytes(16, partGuidRaw) || ReadRandomBytes(16, keyRaw)) {
433 LOG(ERROR) << "Failed to generate GUID or key";
437 std::string partGuid;
438 StrToHex(partGuidRaw, partGuid);
440 if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
441 LOG(ERROR) << "Failed to persist key";
444 LOG(DEBUG) << "Persisted key for GUID " << partGuid;
447 // Now let's build the new GPT table. We heavily rely on sgdisk to
448 // force optimal alignment on the created partitions.
450 cmd.push_back(kSgdiskPath);
452 // If requested, create a public partition first. Mixed-mode partitioning
453 // like this is an experimental feature.
455 if (ratio < 10 || ratio > 90) {
456 LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
460 uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024;
461 cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb));
462 cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData));
463 cmd.push_back("--change-name=0:shared");
466 // Define a metadata partition which is designed for future use; there
467 // should only be one of these per physical device, even if there are
468 // multiple private volumes.
469 cmd.push_back("--new=0:0:+16M");
470 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta));
471 cmd.push_back("--change-name=0:android_meta");
473 // Define a single private partition filling the rest of disk.
474 cmd.push_back("--new=0:0:-0");
475 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExpand));
476 cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str()));
477 cmd.push_back("--change-name=0:android_expand");
479 cmd.push_back(mDevPath);
481 if ((res = ForkExecvp(cmd)) != 0) {
482 LOG(ERROR) << "Failed to partition; status " << res;
489 void Disk::notifyEvent(int event) {
490 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
491 getId().c_str(), false);
494 void Disk::notifyEvent(int event, const std::string& value) {
495 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
496 StringPrintf("%s %s", getId().c_str(), value.c_str()).c_str(), false);
499 int Disk::getMaxMinors() {
500 // Figure out maximum partition devices supported
501 switch (major(mDevice)) {
502 case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
503 case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
504 case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
505 case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
506 // Per Documentation/devices.txt this is static
509 case kMajorBlockMmc: {
510 // Per Documentation/devices.txt this is dynamic
512 if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
513 LOG(ERROR) << "Failed to read max minors";
516 return atoi(tmp.c_str());
520 LOG(ERROR) << "Unsupported block major type " << major(mDevice);
525 } // namespace android