blob: 3bf93336285d84dd808caab42822ef368670c45e [file] [log] [blame]
Jeff Sharkeydeb24052015-03-02 21:01:40 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
Jeff Sharkeydeb24052015-03-02 21:01:40 -080017#include "Disk.h"
18#include "PublicVolume.h"
Jeff Sharkey9c484982015-03-31 10:35:33 -070019#include "PrivateVolume.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080020#include "Utils.h"
21#include "VolumeBase.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070022#include "VolumeManager.h"
23#include "ResponseCode.h"
Jeff Sharkeydeb24052015-03-02 21:01:40 -080024
Dan Albertae9e8902015-03-16 10:35:17 -070025#include <base/file.h>
26#include <base/stringprintf.h>
Jeff Sharkey36801cc2015-03-13 16:09:20 -070027#include <base/logging.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080028#include <diskconfig/diskconfig.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080029
Jeff Sharkey9c484982015-03-31 10:35:33 -070030#include <vector>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080031#include <fcntl.h>
Jeff Sharkey38cfc022015-03-30 21:22:07 -070032#include <inttypes.h>
Jeff Sharkeydeb24052015-03-02 21:01:40 -080033#include <stdio.h>
34#include <stdlib.h>
35#include <sys/types.h>
36#include <sys/stat.h>
37#include <sys/mount.h>
38
Dan Albertae9e8902015-03-16 10:35:17 -070039using android::base::ReadFileToString;
Jeff Sharkey9c484982015-03-31 10:35:33 -070040using android::base::WriteStringToFile;
Dan Albertae9e8902015-03-16 10:35:17 -070041using android::base::StringPrintf;
42
Jeff Sharkeydeb24052015-03-02 21:01:40 -080043namespace android {
44namespace vold {
45
46static const char* kSgdiskPath = "/system/bin/sgdisk";
47static const char* kSgdiskToken = " \t\n";
48
49static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
50
51static const unsigned int kMajorBlockScsi = 8;
52static const unsigned int kMajorBlockMmc = 179;
53
54static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
55static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
56static const char* kGptAndroidExt = "193D1EA4-B3CA-11E4-B075-10604B889DCF";
57
Jeff Sharkey9c484982015-03-31 10:35:33 -070058static const char* kKeyPath = "/data/misc/vold";
59
Jeff Sharkeydeb24052015-03-02 21:01:40 -080060enum class Table {
61 kUnknown,
62 kMbr,
63 kGpt,
64};
65
Jeff Sharkey36801cc2015-03-13 16:09:20 -070066Disk::Disk(const std::string& eventPath, dev_t device, const std::string& nickname, int flags) :
67 mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated(false) {
68 mId = StringPrintf("disk:%u,%u", major(device), minor(device));
69 mEventPath = eventPath;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080070 mSysPath = StringPrintf("/sys/%s", eventPath.c_str());
Jeff Sharkey36801cc2015-03-13 16:09:20 -070071 mDevPath = StringPrintf("/dev/block/vold/%s", mId.c_str());
Jeff Sharkeydeb24052015-03-02 21:01:40 -080072 CreateDeviceNode(mDevPath, mDevice);
73}
74
75Disk::~Disk() {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070076 CHECK(!mCreated);
Jeff Sharkeydeb24052015-03-02 21:01:40 -080077 DestroyDeviceNode(mDevPath);
78}
79
80std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -070081 for (auto vol : mVolumes) {
82 if (vol->getId() == id) {
83 return vol;
84 }
85 auto stackedVol = vol->findVolume(id);
86 if (stackedVol != nullptr) {
87 return stackedVol;
Jeff Sharkeydeb24052015-03-02 21:01:40 -080088 }
89 }
90 return nullptr;
91}
92
Jeff Sharkey36801cc2015-03-13 16:09:20 -070093status_t Disk::create() {
94 CHECK(!mCreated);
95 mCreated = true;
96 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(
97 ResponseCode::DiskCreated,
98 StringPrintf("%s %d", getId().c_str(), mFlags).c_str(), false);
99 readMetadata();
100 readPartitions();
101 return OK;
102}
103
104status_t Disk::destroy() {
105 CHECK(mCreated);
106 destroyAllVolumes();
107 mCreated = false;
108 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(
109 ResponseCode::DiskDestroyed, getId().c_str(), false);
110 return OK;
111}
112
Jeff Sharkey9c484982015-03-31 10:35:33 -0700113static std::string BuildKeyPath(const std::string& partGuid) {
114 return StringPrintf("%s/ext_%s.key", kKeyPath, partGuid.c_str());
115}
116
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700117void Disk::createPublicVolume(dev_t device) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700118 auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700119 vol->create();
120
Jeff Sharkey9c484982015-03-31 10:35:33 -0700121 mVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700122 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(
123 ResponseCode::DiskVolumeCreated,
124 StringPrintf("%s %s", getId().c_str(), vol->getId().c_str()).c_str(), false);
125}
126
Jeff Sharkey9c484982015-03-31 10:35:33 -0700127void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) {
128 std::string tmp;
129 std::string normalizedGuid;
130 if (HexToStr(partGuid, tmp)) {
131 LOG(WARNING) << "Invalid GUID " << partGuid;
132 return;
133 }
134 StrToHex(tmp, normalizedGuid);
135
136 std::string keyRaw;
137 if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
138 PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
139 return;
140 }
141
142 LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
143
144 auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
145 vol->create();
146
147 mVolumes.push_back(vol);
148 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(
149 ResponseCode::DiskVolumeCreated,
150 StringPrintf("%s %s", getId().c_str(), vol->getId().c_str()).c_str(), false);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700151}
152
153void Disk::destroyAllVolumes() {
154 for (auto vol : mVolumes) {
155 vol->destroy();
156 }
157 mVolumes.clear();
158}
159
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800160status_t Disk::readMetadata() {
161 mSize = -1;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700162 mLabel.clear();
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800163
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700164 int fd = open(mDevPath.c_str(), O_RDONLY);
165 if (fd != -1) {
166 if (ioctl(fd, BLKGETSIZE64, &mSize)) {
167 mSize = -1;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800168 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700169 close(fd);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800170 }
171
172 switch (major(mDevice)) {
173 case kMajorBlockScsi: {
174 std::string path(mSysPath + "/device/vendor");
175 std::string tmp;
176 if (!ReadFileToString(path, &tmp)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 PLOG(WARNING) << "Failed to read vendor from " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800178 return -errno;
179 }
180 mLabel = tmp;
181 break;
182 }
183 case kMajorBlockMmc: {
184 std::string path(mSysPath + "/device/manfid");
185 std::string tmp;
186 if (!ReadFileToString(path, &tmp)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700187 PLOG(WARNING) << "Failed to read manufacturer from " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800188 return -errno;
189 }
190 uint64_t manfid = strtoll(tmp.c_str(), nullptr, 16);
191 // Our goal here is to give the user a meaningful label, ideally
192 // matching whatever is silk-screened on the card. To reduce
193 // user confusion, this list doesn't contain white-label manfid.
194 switch (manfid) {
195 case 0x000003: mLabel = "SanDisk"; break;
196 case 0x00001b: mLabel = "Samsung"; break;
197 case 0x000028: mLabel = "Lexar"; break;
198 case 0x000074: mLabel = "Transcend"; break;
199 }
200 break;
201 }
202 default: {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700203 LOG(WARNING) << "Unsupported block major type" << major(mDevice);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800204 return -ENOTSUP;
205 }
206 }
207
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700208 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(
209 ResponseCode::DiskSizeChanged,
Jeff Sharkey38cfc022015-03-30 21:22:07 -0700210 StringPrintf("%s %" PRId64, getId().c_str(), mSize).c_str(), false);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700211 VolumeManager::Instance()->getBroadcaster()->sendBroadcast(
212 ResponseCode::DiskLabelChanged,
213 StringPrintf("%s %s", getId().c_str(), mLabel.c_str()).c_str(), false);
214
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800215 return OK;
216}
217
218status_t Disk::readPartitions() {
219 int8_t maxMinors = getMaxMinors();
220 if (maxMinors < 0) {
221 return -ENOTSUP;
222 }
223
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700224 destroyAllVolumes();
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800225
226 // Parse partition table
227 std::string path(kSgdiskPath);
228 path += " --android-dump ";
229 path += mDevPath;
230 FILE* fp = popen(path.c_str(), "r");
231 if (!fp) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700232 PLOG(ERROR) << "Failed to run " << path;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800233 return -errno;
234 }
235
236 char line[1024];
237 Table table = Table::kUnknown;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238 bool foundParts = false;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800239 while (fgets(line, sizeof(line), fp) != nullptr) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700240 LOG(DEBUG) << "sgdisk: " << line;
241
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800242 char* token = strtok(line, kSgdiskToken);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700243 if (token == nullptr) continue;
244
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800245 if (!strcmp(token, "DISK")) {
246 const char* type = strtok(nullptr, kSgdiskToken);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800247 if (!strcmp(type, "mbr")) {
248 table = Table::kMbr;
249 } else if (!strcmp(type, "gpt")) {
250 table = Table::kGpt;
251 }
252 } else if (!strcmp(token, "PART")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700253 foundParts = true;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800254 int i = strtol(strtok(nullptr, kSgdiskToken), nullptr, 10);
255 if (i <= 0 || i > maxMinors) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700256 LOG(WARNING) << mId << " is ignoring partition " << i
257 << " beyond max supported devices";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800258 continue;
259 }
260 dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
261
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800262 if (table == Table::kMbr) {
263 const char* type = strtok(nullptr, kSgdiskToken);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800264
265 switch (strtol(type, nullptr, 16)) {
266 case 0x06: // FAT16
267 case 0x0b: // W95 FAT32 (LBA)
268 case 0x0c: // W95 FAT32 (LBA)
269 case 0x0e: // W95 FAT16 (LBA)
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700270 createPublicVolume(partDevice);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800271 break;
272 }
273 } else if (table == Table::kGpt) {
274 const char* typeGuid = strtok(nullptr, kSgdiskToken);
275 const char* partGuid = strtok(nullptr, kSgdiskToken);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800276
277 if (!strcasecmp(typeGuid, kGptBasicData)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700278 createPublicVolume(partDevice);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800279 } else if (!strcasecmp(typeGuid, kGptAndroidExt)) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700280 createPrivateVolume(partDevice, partGuid);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800281 }
282 }
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800283 }
284 }
285
286 // Ugly last ditch effort, treat entire disk as partition
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700287 if (table == Table::kUnknown || !foundParts) {
288 LOG(WARNING) << mId << " has unknown partition table; trying entire device";
289 createPublicVolume(mDevice);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800290 }
291
292 pclose(fp);
293 return OK;
294}
295
Jeff Sharkey9c484982015-03-31 10:35:33 -0700296status_t Disk::unmountAll() {
297 for (auto vol : mVolumes) {
298 vol->unmount();
299 }
300 return OK;
301}
302
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800303status_t Disk::partitionPublic() {
304 // TODO: improve this code
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700305 destroyAllVolumes();
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800306
307 struct disk_info dinfo;
308 memset(&dinfo, 0, sizeof(dinfo));
309
310 if (!(dinfo.part_lst = (struct part_info *) malloc(
311 MAX_NUM_PARTS * sizeof(struct part_info)))) {
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800312 return -1;
313 }
314
315 memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
316 dinfo.device = strdup(mDevPath.c_str());
317 dinfo.scheme = PART_SCHEME_MBR;
318 dinfo.sect_size = 512;
319 dinfo.skip_lba = 2048;
320 dinfo.num_lba = 0;
321 dinfo.num_parts = 1;
322
323 struct part_info *pinfo = &dinfo.part_lst[0];
324
325 pinfo->name = strdup("android_sdcard");
326 pinfo->flags |= PART_ACTIVE_FLAG;
327 pinfo->type = PC_PART_TYPE_FAT32;
328 pinfo->len_kb = -1;
329
330 int rc = apply_disk_config(&dinfo, 0);
331 if (rc) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700332 LOG(ERROR) << "Failed to apply disk configuration: " << rc;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800333 goto out;
334 }
335
336out:
337 free(pinfo->name);
338 free(dinfo.device);
339 free(dinfo.part_lst);
340
341 return rc;
342}
343
344status_t Disk::partitionPrivate() {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700345 return partitionMixed(0);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800346}
347
348status_t Disk::partitionMixed(int8_t ratio) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700349 int status = 0;
350
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700351 destroyAllVolumes();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700352
353 // First nuke any existing partition table
354 std::vector<std::string> cmd;
355 cmd.push_back(kSgdiskPath);
356 cmd.push_back("--zap-all");
357 cmd.push_back(mDevPath);
358
359 if (ForkExecvp(cmd, &status, false, true)) {
360 LOG(ERROR) << "Failed to zap; status " << status;
361 return -EIO;
362 }
363
364 // We've had some success above, so generate both the private partition
365 // GUID and encryption key and persist them.
366 std::string partGuidRaw;
367 std::string keyRaw;
368 if (ReadRandomBytes(16, partGuidRaw) || ReadRandomBytes(16, keyRaw)) {
369 LOG(ERROR) << "Failed to generate GUID or key";
370 return -EIO;
371 }
372
373 std::string partGuid;
374 StrToHex(partGuidRaw, partGuid);
375
376 if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
377 LOG(ERROR) << "Failed to persist key";
378 return -EIO;
379 } else {
380 LOG(DEBUG) << "Persisted key for GUID " << partGuid;
381 }
382
383 // Now let's build the new GPT table. We heavily rely on sgdisk to
384 // force optimal alignment on the created partitions.
385 cmd.clear();
386 cmd.push_back(kSgdiskPath);
387
388 // If requested, create a public partition first. Mixed-mode partitioning
389 // like this is an experimental feature.
390 if (ratio > 0) {
391 if (ratio < 10 || ratio > 90) {
392 LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
393 return -EINVAL;
394 }
395
396 uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024;
397 cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb));
398 cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData));
399 cmd.push_back("--change-name=0:shared");
400 }
401
402 // Define a metadata partition which is designed for future use; there
403 // should only be one of these per physical device, even if there are
404 // multiple private volumes.
405 cmd.push_back("--new=0:0:+16M");
406 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta));
407 cmd.push_back("--change-name=0:android_meta");
408
409 // Define a single private partition filling the rest of disk.
410 cmd.push_back("--new=0:0:-0");
411 cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExt));
412 cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str()));
413 cmd.push_back("--change-name=0:android_ext");
414
415 cmd.push_back(mDevPath);
416
417 if (ForkExecvp(cmd, &status, false, true)) {
418 LOG(ERROR) << "Failed to partition; status " << status;
419 return -EIO;
420 }
421
422 return OK;
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800423}
424
425int Disk::getMaxMinors() {
426 // Figure out maximum partition devices supported
427 switch (major(mDevice)) {
428 case kMajorBlockScsi: {
429 // Per Documentation/devices.txt this is static
430 return 15;
431 }
432 case kMajorBlockMmc: {
433 // Per Documentation/devices.txt this is dynamic
434 std::string tmp;
435 if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700436 LOG(ERROR) << "Failed to read max minors";
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800437 return -errno;
438 }
439 return atoi(tmp.c_str());
440 }
441 }
442
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700443 LOG(ERROR) << "Unsupported block major type " << major(mDevice);
Jeff Sharkeydeb24052015-03-02 21:01:40 -0800444 return -ENOTSUP;
445}
446
447} // namespace vold
448} // namespace android