Disk.cpp revision f3ee200303f632d940588926f9d31d1e1d51a5c6
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#define ENTIRE_DEVICE_FALLBACK 0
40
41using android::base::ReadFileToString;
42using android::base::WriteStringToFile;
43using android::base::StringPrintf;
44
45namespace android {
46namespace vold {
47
48static const char* kSgdiskPath = "/system/bin/sgdisk";
49static const char* kSgdiskToken = " \t\n";
50
51static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
52
53static const unsigned int kMajorBlockScsiA = 8;
54static const unsigned int kMajorBlockScsiB = 65;
55static const unsigned int kMajorBlockScsiC = 66;
56static const unsigned int kMajorBlockScsiD = 67;
57static const unsigned int kMajorBlockScsiE = 68;
58static const unsigned int kMajorBlockScsiF = 69;
59static const unsigned int kMajorBlockScsiG = 70;
60static const unsigned int kMajorBlockScsiH = 71;
61static const unsigned int kMajorBlockScsiI = 128;
62static const unsigned int kMajorBlockScsiJ = 129;
63static const unsigned int kMajorBlockScsiK = 130;
64static const unsigned int kMajorBlockScsiL = 131;
65static const unsigned int kMajorBlockScsiM = 132;
66static const unsigned int kMajorBlockScsiN = 133;
67static const unsigned int kMajorBlockScsiO = 134;
68static const unsigned int kMajorBlockScsiP = 135;
69static const unsigned int kMajorBlockMmc = 179;
70
71static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
72static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
73static const char* kGptAndroidExpand = "193D1EA4-B3CA-11E4-B075-10604B889DCF";
74
75static const char* kKeyPath = "/data/misc/vold";
76
77enum class Table {
78    kUnknown,
79    kMbr,
80    kGpt,
81};
82
83Disk::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
94Disk::~Disk() {
95    CHECK(!mCreated);
96    DestroyDeviceNode(mDevPath);
97}
98
99std::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
112status_t Disk::create() {
113    CHECK(!mCreated);
114    mCreated = true;
115    notifyEvent(ResponseCode::DiskCreated, StringPrintf("%d", mFlags));
116    readMetadata();
117    readPartitions();
118    return OK;
119}
120
121status_t Disk::destroy() {
122    CHECK(mCreated);
123    destroyAllVolumes();
124    mCreated = false;
125    notifyEvent(ResponseCode::DiskDestroyed);
126    return OK;
127}
128
129static std::string BuildKeyPath(const std::string& partGuid) {
130    return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
131}
132
133void Disk::createPublicVolume(dev_t device) {
134    auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device));
135    if (mJustPartitioned) {
136        LOG(DEBUG) << "Device just partitioned; silently formatting";
137        vol->setSilent(true);
138        vol->create();
139        vol->format();
140        vol->destroy();
141        vol->setSilent(false);
142    }
143
144    mVolumes.push_back(vol);
145    vol->setDiskId(getId());
146    vol->create();
147}
148
149void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) {
150    std::string tmp;
151    std::string normalizedGuid;
152    if (HexToStr(partGuid, tmp)) {
153        LOG(WARNING) << "Invalid GUID " << partGuid;
154        return;
155    }
156    StrToHex(tmp, normalizedGuid);
157
158    std::string keyRaw;
159    if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
160        PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
161        return;
162    }
163
164    LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
165
166    auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
167    if (mJustPartitioned) {
168        LOG(DEBUG) << "Device just partitioned; silently formatting";
169        vol->setSilent(true);
170        vol->create();
171        vol->format();
172        vol->destroy();
173        vol->setSilent(false);
174    }
175
176    mVolumes.push_back(vol);
177    vol->setDiskId(getId());
178    vol->create();
179}
180
181void Disk::destroyAllVolumes() {
182    for (auto vol : mVolumes) {
183        vol->destroy();
184    }
185    mVolumes.clear();
186}
187
188status_t Disk::readMetadata() {
189    mSize = -1;
190    mLabel.clear();
191
192    int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC);
193    if (fd != -1) {
194        if (ioctl(fd, BLKGETSIZE64, &mSize)) {
195            mSize = -1;
196        }
197        close(fd);
198    }
199
200    switch (major(mDevice)) {
201    case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
202    case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
203    case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
204    case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
205        std::string path(mSysPath + "/device/vendor");
206        std::string tmp;
207        if (!ReadFileToString(path, &tmp)) {
208            PLOG(WARNING) << "Failed to read vendor from " << path;
209            return -errno;
210        }
211        mLabel = tmp;
212        break;
213    }
214    case kMajorBlockMmc: {
215        std::string path(mSysPath + "/device/manfid");
216        std::string tmp;
217        if (!ReadFileToString(path, &tmp)) {
218            PLOG(WARNING) << "Failed to read manufacturer from " << path;
219            return -errno;
220        }
221        uint64_t manfid = strtoll(tmp.c_str(), nullptr, 16);
222        // Our goal here is to give the user a meaningful label, ideally
223        // matching whatever is silk-screened on the card.  To reduce
224        // user confusion, this list doesn't contain white-label manfid.
225        switch (manfid) {
226        case 0x000003: mLabel = "SanDisk"; break;
227        case 0x00001b: mLabel = "Samsung"; break;
228        case 0x000028: mLabel = "Lexar"; break;
229        case 0x000074: mLabel = "Transcend"; break;
230        }
231        break;
232    }
233    default: {
234        LOG(WARNING) << "Unsupported block major type" << major(mDevice);
235        return -ENOTSUP;
236    }
237    }
238
239    notifyEvent(ResponseCode::DiskSizeChanged, StringPrintf("%" PRId64, mSize));
240    notifyEvent(ResponseCode::DiskLabelChanged, mLabel);
241    return OK;
242}
243
244status_t Disk::readPartitions() {
245    std::lock_guard<std::mutex> lock(mLock);
246
247    int8_t maxMinors = getMaxMinors();
248    if (maxMinors < 0) {
249        return -ENOTSUP;
250    }
251
252    destroyAllVolumes();
253
254    // Parse partition table
255
256    std::vector<std::string> cmd;
257    cmd.push_back(kSgdiskPath);
258    cmd.push_back("--android-dump");
259    cmd.push_back(mDevPath);
260
261    std::vector<std::string> output;
262    status_t res = ForkExecvp(cmd, output);
263    if (res != OK) {
264        LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
265        mJustPartitioned = false;
266        return res;
267    }
268
269    Table table = Table::kUnknown;
270    bool foundParts = false;
271    for (auto line : output) {
272        char* cline = (char*) line.c_str();
273        char* token = strtok(cline, kSgdiskToken);
274        if (token == nullptr) continue;
275
276        if (!strcmp(token, "DISK")) {
277            const char* type = strtok(nullptr, kSgdiskToken);
278            if (!strcmp(type, "mbr")) {
279                table = Table::kMbr;
280            } else if (!strcmp(type, "gpt")) {
281                table = Table::kGpt;
282            }
283        } else if (!strcmp(token, "PART")) {
284            foundParts = true;
285            int i = strtol(strtok(nullptr, kSgdiskToken), nullptr, 10);
286            if (i <= 0 || i > maxMinors) {
287                LOG(WARNING) << mId << " is ignoring partition " << i
288                        << " beyond max supported devices";
289                continue;
290            }
291            dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
292
293            if (table == Table::kMbr) {
294                const char* type = strtok(nullptr, kSgdiskToken);
295
296                switch (strtol(type, nullptr, 16)) {
297                case 0x06: // FAT16
298                case 0x0b: // W95 FAT32 (LBA)
299                case 0x0c: // W95 FAT32 (LBA)
300                case 0x0e: // W95 FAT16 (LBA)
301                    createPublicVolume(partDevice);
302                    break;
303                }
304            } else if (table == Table::kGpt) {
305                const char* typeGuid = strtok(nullptr, kSgdiskToken);
306                const char* partGuid = strtok(nullptr, kSgdiskToken);
307
308                if (!strcasecmp(typeGuid, kGptBasicData)) {
309                    createPublicVolume(partDevice);
310                } else if (!strcasecmp(typeGuid, kGptAndroidExpand)) {
311                    createPrivateVolume(partDevice, partGuid);
312                }
313            }
314        }
315    }
316
317#if ENTIRE_DEVICE_FALLBACK
318    // Ugly last ditch effort, treat entire disk as partition
319    if (table == Table::kUnknown || !foundParts) {
320        // TODO: use blkid to confirm filesystem before doing this
321        LOG(WARNING) << mId << " has unknown partition table; trying entire device";
322        createPublicVolume(mDevice);
323    }
324#endif
325
326    notifyEvent(ResponseCode::DiskScanned);
327
328    mJustPartitioned = false;
329    return OK;
330}
331
332status_t Disk::unmountAll() {
333    for (auto vol : mVolumes) {
334        vol->unmount();
335    }
336    return OK;
337}
338
339status_t Disk::partitionPublic() {
340    std::lock_guard<std::mutex> lock(mLock);
341
342    // TODO: improve this code
343    destroyAllVolumes();
344    mJustPartitioned = true;
345
346    struct disk_info dinfo;
347    memset(&dinfo, 0, sizeof(dinfo));
348
349    if (!(dinfo.part_lst = (struct part_info *) malloc(
350            MAX_NUM_PARTS * sizeof(struct part_info)))) {
351        return -1;
352    }
353
354    memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
355    dinfo.device = strdup(mDevPath.c_str());
356    dinfo.scheme = PART_SCHEME_MBR;
357    dinfo.sect_size = 512;
358    dinfo.skip_lba = 2048;
359    dinfo.num_lba = 0;
360    dinfo.num_parts = 1;
361
362    struct part_info *pinfo = &dinfo.part_lst[0];
363
364    pinfo->name = strdup("android_sdcard");
365    pinfo->flags |= PART_ACTIVE_FLAG;
366    pinfo->type = PC_PART_TYPE_FAT32;
367    pinfo->len_kb = -1;
368
369    int rc = apply_disk_config(&dinfo, 0);
370    if (rc) {
371        LOG(ERROR) << "Failed to apply disk configuration: " << rc;
372        goto out;
373    }
374
375out:
376    free(pinfo->name);
377    free(dinfo.device);
378    free(dinfo.part_lst);
379
380    return rc;
381}
382
383status_t Disk::partitionPrivate() {
384    return partitionMixed(0);
385}
386
387status_t Disk::partitionMixed(int8_t ratio) {
388    std::lock_guard<std::mutex> lock(mLock);
389
390    int res;
391
392    destroyAllVolumes();
393    mJustPartitioned = true;
394
395    // First nuke any existing partition table
396    std::vector<std::string> cmd;
397    cmd.push_back(kSgdiskPath);
398    cmd.push_back("--zap-all");
399    cmd.push_back(mDevPath);
400
401    // Zap sometimes returns an error when it actually succeeded, so
402    // just log as warning and keep rolling forward.
403    if ((res = ForkExecvp(cmd)) != 0) {
404        LOG(WARNING) << "Failed to zap; status " << res;
405    }
406
407    // We've had some success above, so generate both the private partition
408    // GUID and encryption key and persist them.
409    std::string partGuidRaw;
410    std::string keyRaw;
411    if (ReadRandomBytes(16, partGuidRaw) || ReadRandomBytes(16, keyRaw)) {
412        LOG(ERROR) << "Failed to generate GUID or key";
413        return -EIO;
414    }
415
416    std::string partGuid;
417    StrToHex(partGuidRaw, partGuid);
418
419    if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
420        LOG(ERROR) << "Failed to persist key";
421        return -EIO;
422    } else {
423        LOG(DEBUG) << "Persisted key for GUID " << partGuid;
424    }
425
426    // Now let's build the new GPT table. We heavily rely on sgdisk to
427    // force optimal alignment on the created partitions.
428    cmd.clear();
429    cmd.push_back(kSgdiskPath);
430
431    // If requested, create a public partition first. Mixed-mode partitioning
432    // like this is an experimental feature.
433    if (ratio > 0) {
434        if (ratio < 10 || ratio > 90) {
435            LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
436            return -EINVAL;
437        }
438
439        uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024;
440        cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb));
441        cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData));
442        cmd.push_back("--change-name=0:shared");
443    }
444
445    // Define a metadata partition which is designed for future use; there
446    // should only be one of these per physical device, even if there are
447    // multiple private volumes.
448    cmd.push_back("--new=0:0:+16M");
449    cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta));
450    cmd.push_back("--change-name=0:android_meta");
451
452    // Define a single private partition filling the rest of disk.
453    cmd.push_back("--new=0:0:-0");
454    cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExpand));
455    cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str()));
456    cmd.push_back("--change-name=0:android_expand");
457
458    cmd.push_back(mDevPath);
459
460    if ((res = ForkExecvp(cmd)) != 0) {
461        LOG(ERROR) << "Failed to partition; status " << res;
462        return res;
463    }
464
465    return OK;
466}
467
468void Disk::notifyEvent(int event) {
469    VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
470            getId().c_str(), false);
471}
472
473void Disk::notifyEvent(int event, const std::string& value) {
474    VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
475            StringPrintf("%s %s", getId().c_str(), value.c_str()).c_str(), false);
476}
477
478int Disk::getMaxMinors() {
479    // Figure out maximum partition devices supported
480    switch (major(mDevice)) {
481    case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
482    case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
483    case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
484    case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
485        // Per Documentation/devices.txt this is static
486        return 15;
487    }
488    case kMajorBlockMmc: {
489        // Per Documentation/devices.txt this is dynamic
490        std::string tmp;
491        if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
492            LOG(ERROR) << "Failed to read max minors";
493            return -errno;
494        }
495        return atoi(tmp.c_str());
496    }
497    }
498
499    LOG(ERROR) << "Unsupported block major type " << major(mDevice);
500    return -ENOTSUP;
501}
502
503}  // namespace vold
504}  // namespace android
505