OSDN Git Service

vold: dont't use commas in device names
[android-x86/system-vold.git] / Disk.cpp
1 /*
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
17 #include "Disk.h"
18 #include "PublicVolume.h"
19 #include "PrivateVolume.h"
20 #include "Utils.h"
21 #include "VolumeBase.h"
22 #include "VolumeManager.h"
23 #include "ResponseCode.h"
24
25 #include <base/file.h>
26 #include <base/stringprintf.h>
27 #include <base/logging.h>
28 #include <diskconfig/diskconfig.h>
29
30 #include <vector>
31 #include <fcntl.h>
32 #include <inttypes.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/mount.h>
38
39 using android::base::ReadFileToString;
40 using android::base::WriteStringToFile;
41 using android::base::StringPrintf;
42
43 namespace android {
44 namespace vold {
45
46 #ifdef MINIVOLD
47 static const char* kSgdiskPath = "/sbin/sgdisk";
48 #else
49 static const char* kSgdiskPath = "/system/bin/sgdisk";
50 #endif
51 static const char* kSgdiskToken = " \t\n";
52
53 static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
54
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
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";
76
77 enum class Table {
78     kUnknown,
79     kMbr,
80     kGpt,
81 };
82
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);
92 }
93
94 Disk::~Disk() {
95     CHECK(!mCreated);
96     DestroyDeviceNode(mDevPath);
97 }
98
99 std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) {
100     for (auto vol : mVolumes) {
101         if (vol->getId() == id) {
102             return vol;
103         }
104         auto stackedVol = vol->findVolume(id);
105         if (stackedVol != nullptr) {
106             return stackedVol;
107         }
108     }
109     return nullptr;
110 }
111
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());
116         }
117         // TODO: consider looking at stacked volumes
118     }
119 }
120
121 status_t Disk::create() {
122     CHECK(!mCreated);
123     mCreated = true;
124     notifyEvent(ResponseCode::DiskCreated, StringPrintf("%d", mFlags));
125     readMetadata();
126     readPartitions();
127     return OK;
128 }
129
130 status_t Disk::destroy() {
131     CHECK(mCreated);
132     destroyAllVolumes();
133     mCreated = false;
134     notifyEvent(ResponseCode::DiskDestroyed);
135     return OK;
136 }
137
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);
145         vol->create();
146         vol->format("auto");
147         vol->destroy();
148         vol->setSilent(false);
149     }
150
151     mVolumes.push_back(vol);
152     vol->setDiskId(getId());
153     vol->create();
154 }
155
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;
160         return;
161     }
162
163     std::string keyRaw;
164     if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
165         PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
166         return;
167     }
168
169     LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
170
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);
175         vol->create();
176         vol->format("auto");
177         vol->destroy();
178         vol->setSilent(false);
179     }
180
181     mVolumes.push_back(vol);
182     vol->setDiskId(getId());
183     vol->setPartGuid(partGuid);
184     vol->create();
185 }
186
187 void Disk::destroyAllVolumes() {
188     for (auto vol : mVolumes) {
189         vol->destroy();
190     }
191     mVolumes.clear();
192 }
193
194 status_t Disk::readMetadata() {
195     mSize = -1;
196     mLabel.clear();
197
198     int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC);
199     if (fd != -1) {
200         if (ioctl(fd, BLKGETSIZE64, &mSize)) {
201             mSize = -1;
202         }
203         close(fd);
204     }
205
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");
212         std::string tmp;
213         if (!ReadFileToString(path, &tmp)) {
214             PLOG(WARNING) << "Failed to read vendor from " << path;
215             return -errno;
216         }
217         mLabel = tmp;
218         break;
219     }
220     case kMajorBlockMmc: {
221         std::string path(mSysPath + "/device/manfid");
222         std::string tmp;
223         if (!ReadFileToString(path, &tmp)) {
224             PLOG(WARNING) << "Failed to read manufacturer from " << path;
225             return -errno;
226         }
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.
231         switch (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;
236         }
237         break;
238     }
239     default: {
240         LOG(WARNING) << "Unsupported block major type" << major(mDevice);
241         return -ENOTSUP;
242     }
243     }
244
245     notifyEvent(ResponseCode::DiskSizeChanged, StringPrintf("%" PRId64, mSize));
246     notifyEvent(ResponseCode::DiskLabelChanged, mLabel);
247     notifyEvent(ResponseCode::DiskSysPathChanged, mSysPath);
248     return OK;
249 }
250
251 status_t Disk::readPartitions() {
252     int8_t maxMinors = getMaxMinors();
253     if (maxMinors < 0) {
254         return -ENOTSUP;
255     }
256
257     destroyAllVolumes();
258
259     // Parse partition table
260
261     std::vector<std::string> cmd;
262     cmd.push_back(kSgdiskPath);
263     cmd.push_back("--android-dump");
264     cmd.push_back(mDevPath);
265
266     std::vector<std::string> output;
267     status_t res = ForkExecvp(cmd, output);
268     if (res != OK) {
269         LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
270         notifyEvent(ResponseCode::DiskScanned);
271         mJustPartitioned = false;
272         return res;
273     }
274
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;
281
282         if (!strcmp(token, "DISK")) {
283             const char* type = strtok(nullptr, kSgdiskToken);
284             if (!strcmp(type, "mbr")) {
285                 table = Table::kMbr;
286             } else if (!strcmp(type, "gpt")) {
287                 table = Table::kGpt;
288             }
289         } else if (!strcmp(token, "PART")) {
290             foundParts = true;
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";
295                 continue;
296             }
297             dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
298
299             if (table == Table::kMbr) {
300                 const char* type = strtok(nullptr, kSgdiskToken);
301
302                 switch (strtol(type, nullptr, 16)) {
303                 case 0x06: // FAT16
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);
310                     break;
311                 }
312             } else if (table == Table::kGpt) {
313                 const char* typeGuid = strtok(nullptr, kSgdiskToken);
314                 const char* partGuid = strtok(nullptr, kSgdiskToken);
315
316                 if (!strcasecmp(typeGuid, kGptBasicData)) {
317                     createPublicVolume(partDevice);
318                 } else if (!strcasecmp(typeGuid, kGptAndroidExpand)) {
319                     createPrivateVolume(partDevice, partGuid);
320                 }
321             }
322         }
323     }
324
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";
328
329         std::string fsType;
330         std::string unused;
331         if (ReadMetadataUntrusted(mDevPath, fsType, unused, unused) == OK) {
332             createPublicVolume(mDevice);
333         } else {
334             LOG(WARNING) << mId << " failed to identify, giving up";
335         }
336     }
337
338     notifyEvent(ResponseCode::DiskScanned);
339     mJustPartitioned = false;
340     return OK;
341 }
342
343 status_t Disk::unmountAll() {
344     for (auto vol : mVolumes) {
345         vol->unmount();
346     }
347     return OK;
348 }
349
350 status_t Disk::partitionPublic() {
351     int res;
352
353     // TODO: improve this code
354     destroyAllVolumes();
355     mJustPartitioned = true;
356
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);
362
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;
367     }
368
369     struct disk_info dinfo;
370     memset(&dinfo, 0, sizeof(dinfo));
371
372     if (!(dinfo.part_lst = (struct part_info *) malloc(
373             MAX_NUM_PARTS * sizeof(struct part_info)))) {
374         return -1;
375     }
376
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;
382     dinfo.num_lba = 0;
383     dinfo.num_parts = 1;
384
385     struct part_info *pinfo = &dinfo.part_lst[0];
386
387     pinfo->name = strdup("android_sdcard");
388     pinfo->flags |= PART_ACTIVE_FLAG;
389     pinfo->type = PC_PART_TYPE_FAT32;
390     pinfo->len_kb = -1;
391
392     int rc = apply_disk_config(&dinfo, 0);
393     if (rc) {
394         LOG(ERROR) << "Failed to apply disk configuration: " << rc;
395         goto out;
396     }
397
398 out:
399     free(pinfo->name);
400     free(dinfo.device);
401     free(dinfo.part_lst);
402
403     return rc;
404 }
405
406 status_t Disk::partitionPrivate() {
407     return partitionMixed(0);
408 }
409
410 status_t Disk::partitionMixed(int8_t ratio) {
411     int res;
412
413     destroyAllVolumes();
414     mJustPartitioned = true;
415
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);
421
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;
426     }
427
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;
431     std::string keyRaw;
432     if (ReadRandomBytes(16, partGuidRaw) || ReadRandomBytes(16, keyRaw)) {
433         LOG(ERROR) << "Failed to generate GUID or key";
434         return -EIO;
435     }
436
437     std::string partGuid;
438     StrToHex(partGuidRaw, partGuid);
439
440     if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
441         LOG(ERROR) << "Failed to persist key";
442         return -EIO;
443     } else {
444         LOG(DEBUG) << "Persisted key for GUID " << partGuid;
445     }
446
447     // Now let's build the new GPT table. We heavily rely on sgdisk to
448     // force optimal alignment on the created partitions.
449     cmd.clear();
450     cmd.push_back(kSgdiskPath);
451
452     // If requested, create a public partition first. Mixed-mode partitioning
453     // like this is an experimental feature.
454     if (ratio > 0) {
455         if (ratio < 10 || ratio > 90) {
456             LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
457             return -EINVAL;
458         }
459
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");
464     }
465
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");
472
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");
478
479     cmd.push_back(mDevPath);
480
481     if ((res = ForkExecvp(cmd)) != 0) {
482         LOG(ERROR) << "Failed to partition; status " << res;
483         return res;
484     }
485
486     return OK;
487 }
488
489 void Disk::notifyEvent(int event) {
490     VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
491             getId().c_str(), false);
492 }
493
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);
497 }
498
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
507         return 15;
508     }
509     case kMajorBlockMmc: {
510         // Per Documentation/devices.txt this is dynamic
511         std::string tmp;
512         if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
513             LOG(ERROR) << "Failed to read max minors";
514             return -errno;
515         }
516         return atoi(tmp.c_str());
517     }
518     }
519
520     LOG(ERROR) << "Unsupported block major type " << major(mDevice);
521     return -ENOTSUP;
522 }
523
524 }  // namespace vold
525 }  // namespace android