StorageManager.java revision b302c54f11d5468100c566fba8e70d8614490e1a
1/*
2 * Copyright (C) 2008 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
17package android.os.storage;
18
19import static android.net.TrafficStats.GB_IN_BYTES;
20import static android.net.TrafficStats.MB_IN_BYTES;
21
22import android.annotation.BytesLong;
23import android.annotation.IntDef;
24import android.annotation.NonNull;
25import android.annotation.Nullable;
26import android.annotation.RequiresPermission;
27import android.annotation.SdkConstant;
28import android.annotation.SuppressLint;
29import android.annotation.SystemApi;
30import android.annotation.SystemService;
31import android.annotation.WorkerThread;
32import android.app.Activity;
33import android.app.ActivityThread;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageMoveObserver;
39import android.content.pm.PackageManager;
40import android.os.Binder;
41import android.os.Environment;
42import android.os.FileUtils;
43import android.os.Handler;
44import android.os.IVold;
45import android.os.Looper;
46import android.os.Message;
47import android.os.ParcelFileDescriptor;
48import android.os.ParcelableException;
49import android.os.ProxyFileDescriptorCallback;
50import android.os.RemoteException;
51import android.os.ServiceManager;
52import android.os.ServiceManager.ServiceNotFoundException;
53import android.os.SystemProperties;
54import android.os.UserHandle;
55import android.provider.Settings;
56import android.system.ErrnoException;
57import android.system.Os;
58import android.system.OsConstants;
59import android.text.TextUtils;
60import android.util.Log;
61import android.util.Pair;
62import android.util.Slog;
63import android.util.SparseArray;
64
65import com.android.internal.annotations.GuardedBy;
66import com.android.internal.annotations.VisibleForTesting;
67import com.android.internal.logging.MetricsLogger;
68import com.android.internal.os.AppFuseMount;
69import com.android.internal.os.FuseAppLoop;
70import com.android.internal.os.FuseUnavailableMountException;
71import com.android.internal.os.RoSystemProperties;
72import com.android.internal.os.SomeArgs;
73import com.android.internal.util.Preconditions;
74
75import java.io.File;
76import java.io.FileDescriptor;
77import java.io.FileNotFoundException;
78import java.io.IOException;
79import java.lang.annotation.Retention;
80import java.lang.annotation.RetentionPolicy;
81import java.lang.ref.WeakReference;
82import java.nio.charset.StandardCharsets;
83import java.util.ArrayList;
84import java.util.Arrays;
85import java.util.Collections;
86import java.util.Iterator;
87import java.util.List;
88import java.util.Objects;
89import java.util.UUID;
90import java.util.concurrent.ThreadFactory;
91import java.util.concurrent.atomic.AtomicInteger;
92
93/**
94 * StorageManager is the interface to the systems storage service. The storage
95 * manager handles storage-related items such as Opaque Binary Blobs (OBBs).
96 * <p>
97 * OBBs contain a filesystem that maybe be encrypted on disk and mounted
98 * on-demand from an application. OBBs are a good way of providing large amounts
99 * of binary assets without packaging them into APKs as they may be multiple
100 * gigabytes in size. However, due to their size, they're most likely stored in
101 * a shared storage pool accessible from all programs. The system does not
102 * guarantee the security of the OBB file itself: if any program modifies the
103 * OBB, there is no guarantee that a read from that OBB will produce the
104 * expected output.
105 */
106@SystemService(Context.STORAGE_SERVICE)
107public class StorageManager {
108    private static final String TAG = "StorageManager";
109
110    /** {@hide} */
111    public static final String PROP_PRIMARY_PHYSICAL = "ro.vold.primary_physical";
112    /** {@hide} */
113    public static final String PROP_HAS_ADOPTABLE = "vold.has_adoptable";
114    /** {@hide} */
115    public static final String PROP_FORCE_ADOPTABLE = "persist.fw.force_adoptable";
116    /** {@hide} */
117    public static final String PROP_EMULATE_FBE = "persist.sys.emulate_fbe";
118    /** {@hide} */
119    public static final String PROP_SDCARDFS = "persist.sys.sdcardfs";
120    /** {@hide} */
121    public static final String PROP_VIRTUAL_DISK = "persist.sys.virtual_disk";
122    /** {@hide} */
123    public static final String PROP_ADOPTABLE_FBE = "persist.sys.adoptable_fbe";
124
125    /** {@hide} */
126    public static final String UUID_PRIVATE_INTERNAL = null;
127    /** {@hide} */
128    public static final String UUID_PRIMARY_PHYSICAL = "primary_physical";
129    /** {@hide} */
130    public static final String UUID_SYSTEM = "system";
131
132    // NOTE: UUID constants below are namespaced
133    // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad default
134    // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad primary_physical
135    // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad system
136
137    /**
138     * UUID representing the default internal storage of this device which
139     * provides {@link Environment#getDataDirectory()}.
140     * <p>
141     * This value is constant across all devices and it will never change, and
142     * thus it cannot be used to uniquely identify a particular physical device.
143     *
144     * @see #getUuidForPath(File)
145     * @see ApplicationInfo#storageUuid
146     */
147    public static final UUID UUID_DEFAULT = UUID
148            .fromString("41217664-9172-527a-b3d5-edabb50a7d69");
149
150    /** {@hide} */
151    public static final UUID UUID_PRIMARY_PHYSICAL_ = UUID
152            .fromString("0f95a519-dae7-5abf-9519-fbd6209e05fd");
153
154    /** {@hide} */
155    public static final UUID UUID_SYSTEM_ = UUID
156            .fromString("5d258386-e60d-59e3-826d-0089cdd42cc0");
157
158    /**
159     * Activity Action: Allows the user to manage their storage. This activity
160     * provides the ability to free up space on the device by deleting data such
161     * as apps.
162     * <p>
163     * If the sending application has a specific storage device or allocation
164     * size in mind, they can optionally define {@link #EXTRA_UUID} or
165     * {@link #EXTRA_REQUESTED_BYTES}, respectively.
166     * <p>
167     * This intent should be launched using
168     * {@link Activity#startActivityForResult(Intent, int)} so that the user
169     * knows which app is requesting the storage space. The returned result will
170     * be {@link Activity#RESULT_OK} if the requested space was made available,
171     * or {@link Activity#RESULT_CANCELED} otherwise.
172     */
173    @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
174    public static final String ACTION_MANAGE_STORAGE = "android.os.storage.action.MANAGE_STORAGE";
175
176    /**
177     * Extra {@link UUID} used to indicate the storage volume where an
178     * application is interested in allocating or managing disk space.
179     *
180     * @see #ACTION_MANAGE_STORAGE
181     * @see #UUID_DEFAULT
182     * @see #getUuidForPath(File)
183     * @see Intent#putExtra(String, java.io.Serializable)
184     */
185    public static final String EXTRA_UUID = "android.os.storage.extra.UUID";
186
187    /**
188     * Extra used to indicate the total size (in bytes) that an application is
189     * interested in allocating.
190     * <p>
191     * When defined, the management UI will help guide the user to free up
192     * enough disk space to reach this requested value.
193     *
194     * @see #ACTION_MANAGE_STORAGE
195     */
196    public static final String EXTRA_REQUESTED_BYTES = "android.os.storage.extra.REQUESTED_BYTES";
197
198    /** {@hide} */
199    public static final int DEBUG_FORCE_ADOPTABLE = 1 << 0;
200    /** {@hide} */
201    public static final int DEBUG_EMULATE_FBE = 1 << 1;
202    /** {@hide} */
203    public static final int DEBUG_SDCARDFS_FORCE_ON = 1 << 2;
204    /** {@hide} */
205    public static final int DEBUG_SDCARDFS_FORCE_OFF = 1 << 3;
206    /** {@hide} */
207    public static final int DEBUG_VIRTUAL_DISK = 1 << 4;
208
209    // NOTE: keep in sync with installd
210    /** {@hide} */
211    public static final int FLAG_STORAGE_DE = 1 << 0;
212    /** {@hide} */
213    public static final int FLAG_STORAGE_CE = 1 << 1;
214
215    /** {@hide} */
216    public static final int FLAG_FOR_WRITE = 1 << 8;
217    /** {@hide} */
218    public static final int FLAG_REAL_STATE = 1 << 9;
219    /** {@hide} */
220    public static final int FLAG_INCLUDE_INVISIBLE = 1 << 10;
221
222    /** {@hide} */
223    public static final int FSTRIM_FLAG_DEEP = IVold.FSTRIM_FLAG_DEEP_TRIM;
224
225    /** @hide The volume is not encrypted. */
226    public static final int ENCRYPTION_STATE_NONE =
227            IVold.ENCRYPTION_STATE_NONE;
228
229    /** @hide The volume has been encrypted succesfully. */
230    public static final int ENCRYPTION_STATE_OK =
231            IVold.ENCRYPTION_STATE_OK;
232
233    /** @hide The volume is in a bad state. */
234    public static final int ENCRYPTION_STATE_ERROR_UNKNOWN =
235            IVold.ENCRYPTION_STATE_ERROR_UNKNOWN;
236
237    /** @hide Encryption is incomplete */
238    public static final int ENCRYPTION_STATE_ERROR_INCOMPLETE =
239            IVold.ENCRYPTION_STATE_ERROR_INCOMPLETE;
240
241    /** @hide Encryption is incomplete and irrecoverable */
242    public static final int ENCRYPTION_STATE_ERROR_INCONSISTENT =
243            IVold.ENCRYPTION_STATE_ERROR_INCONSISTENT;
244
245    /** @hide Underlying data is corrupt */
246    public static final int ENCRYPTION_STATE_ERROR_CORRUPT =
247            IVold.ENCRYPTION_STATE_ERROR_CORRUPT;
248
249    private static volatile IStorageManager sStorageManager = null;
250
251    private final Context mContext;
252    private final ContentResolver mResolver;
253
254    private final IStorageManager mStorageManager;
255    private final Looper mLooper;
256    private final AtomicInteger mNextNonce = new AtomicInteger(0);
257
258    private final ArrayList<StorageEventListenerDelegate> mDelegates = new ArrayList<>();
259
260    private static class StorageEventListenerDelegate extends IStorageEventListener.Stub implements
261            Handler.Callback {
262        private static final int MSG_STORAGE_STATE_CHANGED = 1;
263        private static final int MSG_VOLUME_STATE_CHANGED = 2;
264        private static final int MSG_VOLUME_RECORD_CHANGED = 3;
265        private static final int MSG_VOLUME_FORGOTTEN = 4;
266        private static final int MSG_DISK_SCANNED = 5;
267        private static final int MSG_DISK_DESTROYED = 6;
268
269        final StorageEventListener mCallback;
270        final Handler mHandler;
271
272        public StorageEventListenerDelegate(StorageEventListener callback, Looper looper) {
273            mCallback = callback;
274            mHandler = new Handler(looper, this);
275        }
276
277        @Override
278        public boolean handleMessage(Message msg) {
279            final SomeArgs args = (SomeArgs) msg.obj;
280            switch (msg.what) {
281                case MSG_STORAGE_STATE_CHANGED:
282                    mCallback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
283                            (String) args.arg3);
284                    args.recycle();
285                    return true;
286                case MSG_VOLUME_STATE_CHANGED:
287                    mCallback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
288                    args.recycle();
289                    return true;
290                case MSG_VOLUME_RECORD_CHANGED:
291                    mCallback.onVolumeRecordChanged((VolumeRecord) args.arg1);
292                    args.recycle();
293                    return true;
294                case MSG_VOLUME_FORGOTTEN:
295                    mCallback.onVolumeForgotten((String) args.arg1);
296                    args.recycle();
297                    return true;
298                case MSG_DISK_SCANNED:
299                    mCallback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
300                    args.recycle();
301                    return true;
302                case MSG_DISK_DESTROYED:
303                    mCallback.onDiskDestroyed((DiskInfo) args.arg1);
304                    args.recycle();
305                    return true;
306            }
307            args.recycle();
308            return false;
309        }
310
311        @Override
312        public void onUsbMassStorageConnectionChanged(boolean connected) throws RemoteException {
313            // Ignored
314        }
315
316        @Override
317        public void onStorageStateChanged(String path, String oldState, String newState) {
318            final SomeArgs args = SomeArgs.obtain();
319            args.arg1 = path;
320            args.arg2 = oldState;
321            args.arg3 = newState;
322            mHandler.obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
323        }
324
325        @Override
326        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
327            final SomeArgs args = SomeArgs.obtain();
328            args.arg1 = vol;
329            args.argi2 = oldState;
330            args.argi3 = newState;
331            mHandler.obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
332        }
333
334        @Override
335        public void onVolumeRecordChanged(VolumeRecord rec) {
336            final SomeArgs args = SomeArgs.obtain();
337            args.arg1 = rec;
338            mHandler.obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
339        }
340
341        @Override
342        public void onVolumeForgotten(String fsUuid) {
343            final SomeArgs args = SomeArgs.obtain();
344            args.arg1 = fsUuid;
345            mHandler.obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
346        }
347
348        @Override
349        public void onDiskScanned(DiskInfo disk, int volumeCount) {
350            final SomeArgs args = SomeArgs.obtain();
351            args.arg1 = disk;
352            args.argi2 = volumeCount;
353            mHandler.obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
354        }
355
356        @Override
357        public void onDiskDestroyed(DiskInfo disk) throws RemoteException {
358            final SomeArgs args = SomeArgs.obtain();
359            args.arg1 = disk;
360            mHandler.obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
361        }
362    }
363
364    /**
365     * Binder listener for OBB action results.
366     */
367    private final ObbActionListener mObbActionListener = new ObbActionListener();
368
369    private class ObbActionListener extends IObbActionListener.Stub {
370        @SuppressWarnings("hiding")
371        private SparseArray<ObbListenerDelegate> mListeners = new SparseArray<ObbListenerDelegate>();
372
373        @Override
374        public void onObbResult(String filename, int nonce, int status) {
375            final ObbListenerDelegate delegate;
376            synchronized (mListeners) {
377                delegate = mListeners.get(nonce);
378                if (delegate != null) {
379                    mListeners.remove(nonce);
380                }
381            }
382
383            if (delegate != null) {
384                delegate.sendObbStateChanged(filename, status);
385            }
386        }
387
388        public int addListener(OnObbStateChangeListener listener) {
389            final ObbListenerDelegate delegate = new ObbListenerDelegate(listener);
390
391            synchronized (mListeners) {
392                mListeners.put(delegate.nonce, delegate);
393            }
394
395            return delegate.nonce;
396        }
397    }
398
399    private int getNextNonce() {
400        return mNextNonce.getAndIncrement();
401    }
402
403    /**
404     * Private class containing sender and receiver code for StorageEvents.
405     */
406    private class ObbListenerDelegate {
407        private final WeakReference<OnObbStateChangeListener> mObbEventListenerRef;
408        private final Handler mHandler;
409
410        private final int nonce;
411
412        ObbListenerDelegate(OnObbStateChangeListener listener) {
413            nonce = getNextNonce();
414            mObbEventListenerRef = new WeakReference<OnObbStateChangeListener>(listener);
415            mHandler = new Handler(mLooper) {
416                @Override
417                public void handleMessage(Message msg) {
418                    final OnObbStateChangeListener changeListener = getListener();
419                    if (changeListener == null) {
420                        return;
421                    }
422
423                    changeListener.onObbStateChange((String) msg.obj, msg.arg1);
424                }
425            };
426        }
427
428        OnObbStateChangeListener getListener() {
429            if (mObbEventListenerRef == null) {
430                return null;
431            }
432            return mObbEventListenerRef.get();
433        }
434
435        void sendObbStateChanged(String path, int state) {
436            mHandler.obtainMessage(0, state, 0, path).sendToTarget();
437        }
438    }
439
440    /** {@hide} */
441    @Deprecated
442    public static StorageManager from(Context context) {
443        return context.getSystemService(StorageManager.class);
444    }
445
446    /**
447     * Constructs a StorageManager object through which an application can
448     * can communicate with the systems mount service.
449     *
450     * @param looper The {@link android.os.Looper} which events will be received on.
451     *
452     * <p>Applications can get instance of this class by calling
453     * {@link android.content.Context#getSystemService(java.lang.String)} with an argument
454     * of {@link android.content.Context#STORAGE_SERVICE}.
455     *
456     * @hide
457     */
458    public StorageManager(Context context, Looper looper) throws ServiceNotFoundException {
459        mContext = context;
460        mResolver = context.getContentResolver();
461        mLooper = looper;
462        mStorageManager = IStorageManager.Stub.asInterface(ServiceManager.getServiceOrThrow("mount"));
463    }
464
465    /**
466     * Registers a {@link android.os.storage.StorageEventListener StorageEventListener}.
467     *
468     * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object.
469     *
470     * @hide
471     */
472    public void registerListener(StorageEventListener listener) {
473        synchronized (mDelegates) {
474            final StorageEventListenerDelegate delegate = new StorageEventListenerDelegate(listener,
475                    mLooper);
476            try {
477                mStorageManager.registerListener(delegate);
478            } catch (RemoteException e) {
479                throw e.rethrowFromSystemServer();
480            }
481            mDelegates.add(delegate);
482        }
483    }
484
485    /**
486     * Unregisters a {@link android.os.storage.StorageEventListener StorageEventListener}.
487     *
488     * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object.
489     *
490     * @hide
491     */
492    public void unregisterListener(StorageEventListener listener) {
493        synchronized (mDelegates) {
494            for (Iterator<StorageEventListenerDelegate> i = mDelegates.iterator(); i.hasNext();) {
495                final StorageEventListenerDelegate delegate = i.next();
496                if (delegate.mCallback == listener) {
497                    try {
498                        mStorageManager.unregisterListener(delegate);
499                    } catch (RemoteException e) {
500                        throw e.rethrowFromSystemServer();
501                    }
502                    i.remove();
503                }
504            }
505        }
506    }
507
508    /**
509     * Enables USB Mass Storage (UMS) on the device.
510     *
511     * @hide
512     */
513    @Deprecated
514    public void enableUsbMassStorage() {
515    }
516
517    /**
518     * Disables USB Mass Storage (UMS) on the device.
519     *
520     * @hide
521     */
522    @Deprecated
523    public void disableUsbMassStorage() {
524    }
525
526    /**
527     * Query if a USB Mass Storage (UMS) host is connected.
528     * @return true if UMS host is connected.
529     *
530     * @hide
531     */
532    @Deprecated
533    public boolean isUsbMassStorageConnected() {
534        return false;
535    }
536
537    /**
538     * Query if a USB Mass Storage (UMS) is enabled on the device.
539     * @return true if UMS host is enabled.
540     *
541     * @hide
542     */
543    @Deprecated
544    public boolean isUsbMassStorageEnabled() {
545        return false;
546    }
547
548    /**
549     * Mount an Opaque Binary Blob (OBB) file. If a <code>key</code> is
550     * specified, it is supplied to the mounting process to be used in any
551     * encryption used in the OBB.
552     * <p>
553     * The OBB will remain mounted for as long as the StorageManager reference
554     * is held by the application. As soon as this reference is lost, the OBBs
555     * in use will be unmounted. The {@link OnObbStateChangeListener} registered
556     * with this call will receive the success or failure of this operation.
557     * <p>
558     * <em>Note:</em> you can only mount OBB files for which the OBB tag on the
559     * file matches a package ID that is owned by the calling program's UID.
560     * That is, shared UID applications can attempt to mount any other
561     * application's OBB that shares its UID.
562     *
563     * @param rawPath the path to the OBB file
564     * @param key secret used to encrypt the OBB; may be <code>null</code> if no
565     *            encryption was used on the OBB.
566     * @param listener will receive the success or failure of the operation
567     * @return whether the mount call was successfully queued or not
568     */
569    public boolean mountObb(String rawPath, String key, OnObbStateChangeListener listener) {
570        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
571        Preconditions.checkNotNull(listener, "listener cannot be null");
572
573        try {
574            final String canonicalPath = new File(rawPath).getCanonicalPath();
575            final int nonce = mObbActionListener.addListener(listener);
576            mStorageManager.mountObb(rawPath, canonicalPath, key, mObbActionListener, nonce);
577            return true;
578        } catch (IOException e) {
579            throw new IllegalArgumentException("Failed to resolve path: " + rawPath, e);
580        } catch (RemoteException e) {
581            throw e.rethrowFromSystemServer();
582        }
583    }
584
585    /**
586     * Unmount an Opaque Binary Blob (OBB) file asynchronously. If the
587     * <code>force</code> flag is true, it will kill any application needed to
588     * unmount the given OBB (even the calling application).
589     * <p>
590     * The {@link OnObbStateChangeListener} registered with this call will
591     * receive the success or failure of this operation.
592     * <p>
593     * <em>Note:</em> you can only mount OBB files for which the OBB tag on the
594     * file matches a package ID that is owned by the calling program's UID.
595     * That is, shared UID applications can obtain access to any other
596     * application's OBB that shares its UID.
597     * <p>
598     *
599     * @param rawPath path to the OBB file
600     * @param force whether to kill any programs using this in order to unmount
601     *            it
602     * @param listener will receive the success or failure of the operation
603     * @return whether the unmount call was successfully queued or not
604     */
605    public boolean unmountObb(String rawPath, boolean force, OnObbStateChangeListener listener) {
606        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
607        Preconditions.checkNotNull(listener, "listener cannot be null");
608
609        try {
610            final int nonce = mObbActionListener.addListener(listener);
611            mStorageManager.unmountObb(rawPath, force, mObbActionListener, nonce);
612            return true;
613        } catch (RemoteException e) {
614            throw e.rethrowFromSystemServer();
615        }
616    }
617
618    /**
619     * Check whether an Opaque Binary Blob (OBB) is mounted or not.
620     *
621     * @param rawPath path to OBB image
622     * @return true if OBB is mounted; false if not mounted or on error
623     */
624    public boolean isObbMounted(String rawPath) {
625        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
626
627        try {
628            return mStorageManager.isObbMounted(rawPath);
629        } catch (RemoteException e) {
630            throw e.rethrowFromSystemServer();
631        }
632    }
633
634    /**
635     * Check the mounted path of an Opaque Binary Blob (OBB) file. This will
636     * give you the path to where you can obtain access to the internals of the
637     * OBB.
638     *
639     * @param rawPath path to OBB image
640     * @return absolute path to mounted OBB image data or <code>null</code> if
641     *         not mounted or exception encountered trying to read status
642     */
643    public String getMountedObbPath(String rawPath) {
644        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
645
646        try {
647            return mStorageManager.getMountedObbPath(rawPath);
648        } catch (RemoteException e) {
649            throw e.rethrowFromSystemServer();
650        }
651    }
652
653    /** {@hide} */
654    public @NonNull List<DiskInfo> getDisks() {
655        try {
656            return Arrays.asList(mStorageManager.getDisks());
657        } catch (RemoteException e) {
658            throw e.rethrowFromSystemServer();
659        }
660    }
661
662    /** {@hide} */
663    public @Nullable DiskInfo findDiskById(String id) {
664        Preconditions.checkNotNull(id);
665        // TODO; go directly to service to make this faster
666        for (DiskInfo disk : getDisks()) {
667            if (Objects.equals(disk.id, id)) {
668                return disk;
669            }
670        }
671        return null;
672    }
673
674    /** {@hide} */
675    public @Nullable VolumeInfo findVolumeById(String id) {
676        Preconditions.checkNotNull(id);
677        // TODO; go directly to service to make this faster
678        for (VolumeInfo vol : getVolumes()) {
679            if (Objects.equals(vol.id, id)) {
680                return vol;
681            }
682        }
683        return null;
684    }
685
686    /** {@hide} */
687    public @Nullable VolumeInfo findVolumeByUuid(String fsUuid) {
688        Preconditions.checkNotNull(fsUuid);
689        // TODO; go directly to service to make this faster
690        for (VolumeInfo vol : getVolumes()) {
691            if (Objects.equals(vol.fsUuid, fsUuid)) {
692                return vol;
693            }
694        }
695        return null;
696    }
697
698    /** {@hide} */
699    public @Nullable VolumeRecord findRecordByUuid(String fsUuid) {
700        Preconditions.checkNotNull(fsUuid);
701        // TODO; go directly to service to make this faster
702        for (VolumeRecord rec : getVolumeRecords()) {
703            if (Objects.equals(rec.fsUuid, fsUuid)) {
704                return rec;
705            }
706        }
707        return null;
708    }
709
710    /** {@hide} */
711    public @Nullable VolumeInfo findPrivateForEmulated(VolumeInfo emulatedVol) {
712        if (emulatedVol != null) {
713            return findVolumeById(emulatedVol.getId().replace("emulated", "private"));
714        } else {
715            return null;
716        }
717    }
718
719    /** {@hide} */
720    public @Nullable VolumeInfo findEmulatedForPrivate(VolumeInfo privateVol) {
721        if (privateVol != null) {
722            return findVolumeById(privateVol.getId().replace("private", "emulated"));
723        } else {
724            return null;
725        }
726    }
727
728    /** {@hide} */
729    public @Nullable VolumeInfo findVolumeByQualifiedUuid(String volumeUuid) {
730        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
731            return findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
732        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
733            return getPrimaryPhysicalVolume();
734        } else {
735            return findVolumeByUuid(volumeUuid);
736        }
737    }
738
739    /**
740     * Return a UUID identifying the storage volume that hosts the given
741     * filesystem path.
742     * <p>
743     * If this path is hosted by the default internal storage of the device at
744     * {@link Environment#getDataDirectory()}, the returned value will be
745     * {@link #UUID_DEFAULT}.
746     *
747     * @throws IOException when the storage device hosting the given path isn't
748     *             present, or when it doesn't have a valid UUID.
749     */
750    public @NonNull UUID getUuidForPath(@NonNull File path) throws IOException {
751        Preconditions.checkNotNull(path);
752        final String pathString = path.getCanonicalPath();
753        if (FileUtils.contains(Environment.getDataDirectory().getAbsolutePath(), pathString)) {
754            return UUID_DEFAULT;
755        }
756        try {
757            for (VolumeInfo vol : mStorageManager.getVolumes(0)) {
758                if (vol.path != null && FileUtils.contains(vol.path, pathString)) {
759                    // TODO: verify that emulated adopted devices have UUID of
760                    // underlying volume
761                    return convert(vol.fsUuid);
762                }
763            }
764        } catch (RemoteException e) {
765            throw e.rethrowFromSystemServer();
766        }
767        throw new FileNotFoundException("Failed to find a storage device for " + path);
768    }
769
770    /** {@hide} */
771    public @NonNull File findPathForUuid(String volumeUuid) throws FileNotFoundException {
772        final VolumeInfo vol = findVolumeByQualifiedUuid(volumeUuid);
773        if (vol != null) {
774            return vol.getPath();
775        }
776        throw new FileNotFoundException("Failed to find a storage device for " + volumeUuid);
777    }
778
779    /**
780     * Test if the given file descriptor supports allocation of disk space using
781     * {@link #allocateBytes(FileDescriptor, long)}.
782     */
783    public boolean isAllocationSupported(@NonNull FileDescriptor fd) {
784        try {
785            getUuidForPath(ParcelFileDescriptor.getFile(fd));
786            return true;
787        } catch (IOException e) {
788            return false;
789        }
790    }
791
792    /** {@hide} */
793    public @NonNull List<VolumeInfo> getVolumes() {
794        try {
795            return Arrays.asList(mStorageManager.getVolumes(0));
796        } catch (RemoteException e) {
797            throw e.rethrowFromSystemServer();
798        }
799    }
800
801    /** {@hide} */
802    public @NonNull List<VolumeInfo> getWritablePrivateVolumes() {
803        try {
804            final ArrayList<VolumeInfo> res = new ArrayList<>();
805            for (VolumeInfo vol : mStorageManager.getVolumes(0)) {
806                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
807                    res.add(vol);
808                }
809            }
810            return res;
811        } catch (RemoteException e) {
812            throw e.rethrowFromSystemServer();
813        }
814    }
815
816    /** {@hide} */
817    public @NonNull List<VolumeRecord> getVolumeRecords() {
818        try {
819            return Arrays.asList(mStorageManager.getVolumeRecords(0));
820        } catch (RemoteException e) {
821            throw e.rethrowFromSystemServer();
822        }
823    }
824
825    /** {@hide} */
826    public @Nullable String getBestVolumeDescription(VolumeInfo vol) {
827        if (vol == null) return null;
828
829        // Nickname always takes precedence when defined
830        if (!TextUtils.isEmpty(vol.fsUuid)) {
831            final VolumeRecord rec = findRecordByUuid(vol.fsUuid);
832            if (rec != null && !TextUtils.isEmpty(rec.nickname)) {
833                return rec.nickname;
834            }
835        }
836
837        if (!TextUtils.isEmpty(vol.getDescription())) {
838            return vol.getDescription();
839        }
840
841        if (vol.disk != null) {
842            return vol.disk.getDescription();
843        }
844
845        return null;
846    }
847
848    /** {@hide} */
849    public @Nullable VolumeInfo getPrimaryPhysicalVolume() {
850        final List<VolumeInfo> vols = getVolumes();
851        for (VolumeInfo vol : vols) {
852            if (vol.isPrimaryPhysical()) {
853                return vol;
854            }
855        }
856        return null;
857    }
858
859    /** {@hide} */
860    public void mount(String volId) {
861        try {
862            mStorageManager.mount(volId);
863        } catch (RemoteException e) {
864            throw e.rethrowFromSystemServer();
865        }
866    }
867
868    /** {@hide} */
869    public void unmount(String volId) {
870        try {
871            mStorageManager.unmount(volId);
872        } catch (RemoteException e) {
873            throw e.rethrowFromSystemServer();
874        }
875    }
876
877    /** {@hide} */
878    public void format(String volId) {
879        try {
880            mStorageManager.format(volId);
881        } catch (RemoteException e) {
882            throw e.rethrowFromSystemServer();
883        }
884    }
885
886    /** {@hide} */
887    public long benchmark(String volId) {
888        try {
889            return mStorageManager.benchmark(volId);
890        } catch (RemoteException e) {
891            throw e.rethrowFromSystemServer();
892        }
893    }
894
895    /** {@hide} */
896    public void partitionPublic(String diskId) {
897        try {
898            mStorageManager.partitionPublic(diskId);
899        } catch (RemoteException e) {
900            throw e.rethrowFromSystemServer();
901        }
902    }
903
904    /** {@hide} */
905    public void partitionPrivate(String diskId) {
906        try {
907            mStorageManager.partitionPrivate(diskId);
908        } catch (RemoteException e) {
909            throw e.rethrowFromSystemServer();
910        }
911    }
912
913    /** {@hide} */
914    public void partitionMixed(String diskId, int ratio) {
915        try {
916            mStorageManager.partitionMixed(diskId, ratio);
917        } catch (RemoteException e) {
918            throw e.rethrowFromSystemServer();
919        }
920    }
921
922    /** {@hide} */
923    public void wipeAdoptableDisks() {
924        // We only wipe devices in "adoptable" locations, which are in a
925        // long-term stable slot/location on the device, where apps have a
926        // reasonable chance of storing sensitive data. (Apps need to go through
927        // SAF to write to transient volumes.)
928        final List<DiskInfo> disks = getDisks();
929        for (DiskInfo disk : disks) {
930            final String diskId = disk.getId();
931            if (disk.isAdoptable()) {
932                Slog.d(TAG, "Found adoptable " + diskId + "; wiping");
933                try {
934                    // TODO: switch to explicit wipe command when we have it,
935                    // for now rely on the fact that vfat format does a wipe
936                    mStorageManager.partitionPublic(diskId);
937                } catch (Exception e) {
938                    Slog.w(TAG, "Failed to wipe " + diskId + ", but soldiering onward", e);
939                }
940            } else {
941                Slog.d(TAG, "Ignorning non-adoptable disk " + disk.getId());
942            }
943        }
944    }
945
946    /** {@hide} */
947    public void setVolumeNickname(String fsUuid, String nickname) {
948        try {
949            mStorageManager.setVolumeNickname(fsUuid, nickname);
950        } catch (RemoteException e) {
951            throw e.rethrowFromSystemServer();
952        }
953    }
954
955    /** {@hide} */
956    public void setVolumeInited(String fsUuid, boolean inited) {
957        try {
958            mStorageManager.setVolumeUserFlags(fsUuid, inited ? VolumeRecord.USER_FLAG_INITED : 0,
959                    VolumeRecord.USER_FLAG_INITED);
960        } catch (RemoteException e) {
961            throw e.rethrowFromSystemServer();
962        }
963    }
964
965    /** {@hide} */
966    public void setVolumeSnoozed(String fsUuid, boolean snoozed) {
967        try {
968            mStorageManager.setVolumeUserFlags(fsUuid, snoozed ? VolumeRecord.USER_FLAG_SNOOZED : 0,
969                    VolumeRecord.USER_FLAG_SNOOZED);
970        } catch (RemoteException e) {
971            throw e.rethrowFromSystemServer();
972        }
973    }
974
975    /** {@hide} */
976    public void forgetVolume(String fsUuid) {
977        try {
978            mStorageManager.forgetVolume(fsUuid);
979        } catch (RemoteException e) {
980            throw e.rethrowFromSystemServer();
981        }
982    }
983
984    /**
985     * This is not the API you're looking for.
986     *
987     * @see PackageManager#getPrimaryStorageCurrentVolume()
988     * @hide
989     */
990    public String getPrimaryStorageUuid() {
991        try {
992            return mStorageManager.getPrimaryStorageUuid();
993        } catch (RemoteException e) {
994            throw e.rethrowFromSystemServer();
995        }
996    }
997
998    /**
999     * This is not the API you're looking for.
1000     *
1001     * @see PackageManager#movePrimaryStorage(VolumeInfo)
1002     * @hide
1003     */
1004    public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
1005        try {
1006            mStorageManager.setPrimaryStorageUuid(volumeUuid, callback);
1007        } catch (RemoteException e) {
1008            throw e.rethrowFromSystemServer();
1009        }
1010    }
1011
1012    /**
1013     * Return the {@link StorageVolume} that contains the given file, or {@code null} if none.
1014     */
1015    public @Nullable StorageVolume getStorageVolume(File file) {
1016        return getStorageVolume(getVolumeList(), file);
1017    }
1018
1019    /** {@hide} */
1020    public static @Nullable StorageVolume getStorageVolume(File file, int userId) {
1021        return getStorageVolume(getVolumeList(userId, 0), file);
1022    }
1023
1024    /** {@hide} */
1025    private static @Nullable StorageVolume getStorageVolume(StorageVolume[] volumes, File file) {
1026        if (file == null) {
1027            return null;
1028        }
1029        try {
1030            file = file.getCanonicalFile();
1031        } catch (IOException ignored) {
1032            Slog.d(TAG, "Could not get canonical path for " + file);
1033            return null;
1034        }
1035        for (StorageVolume volume : volumes) {
1036            File volumeFile = volume.getPathFile();
1037            try {
1038                volumeFile = volumeFile.getCanonicalFile();
1039            } catch (IOException ignored) {
1040                continue;
1041            }
1042            if (FileUtils.contains(volumeFile, file)) {
1043                return volume;
1044            }
1045        }
1046        return null;
1047    }
1048
1049    /**
1050     * Gets the state of a volume via its mountpoint.
1051     * @hide
1052     */
1053    @Deprecated
1054    public @NonNull String getVolumeState(String mountPoint) {
1055        final StorageVolume vol = getStorageVolume(new File(mountPoint));
1056        if (vol != null) {
1057            return vol.getState();
1058        } else {
1059            return Environment.MEDIA_UNKNOWN;
1060        }
1061    }
1062
1063    /**
1064     * Return the list of shared/external storage volumes available to the
1065     * current user. This includes both the primary shared storage device and
1066     * any attached external volumes including SD cards and USB drives.
1067     *
1068     * @see Environment#getExternalStorageDirectory()
1069     * @see StorageVolume#createAccessIntent(String)
1070     */
1071    public @NonNull List<StorageVolume> getStorageVolumes() {
1072        final ArrayList<StorageVolume> res = new ArrayList<>();
1073        Collections.addAll(res,
1074                getVolumeList(UserHandle.myUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE));
1075        return res;
1076    }
1077
1078    /**
1079     * Return the primary shared/external storage volume available to the
1080     * current user. This volume is the same storage device returned by
1081     * {@link Environment#getExternalStorageDirectory()} and
1082     * {@link Context#getExternalFilesDir(String)}.
1083     */
1084    public @NonNull StorageVolume getPrimaryStorageVolume() {
1085        return getVolumeList(UserHandle.myUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE)[0];
1086    }
1087
1088    /** {@hide} */
1089    public static Pair<String, Long> getPrimaryStoragePathAndSize() {
1090        return Pair.create(null,
1091                FileUtils.roundStorageSize(Environment.getDataDirectory().getTotalSpace()));
1092    }
1093
1094    /** {@hide} */
1095    public long getPrimaryStorageSize() {
1096        return FileUtils.roundStorageSize(Environment.getDataDirectory().getTotalSpace());
1097    }
1098
1099    /** @removed */
1100    public @NonNull StorageVolume[] getVolumeList() {
1101        return getVolumeList(mContext.getUserId(), 0);
1102    }
1103
1104    /** {@hide} */
1105    public static @NonNull StorageVolume[] getVolumeList(int userId, int flags) {
1106        final IStorageManager storageManager = IStorageManager.Stub.asInterface(
1107                ServiceManager.getService("mount"));
1108        try {
1109            String packageName = ActivityThread.currentOpPackageName();
1110            if (packageName == null) {
1111                // Package name can be null if the activity thread is running but the app
1112                // hasn't bound yet. In this case we fall back to the first package in the
1113                // current UID. This works for runtime permissions as permission state is
1114                // per UID and permission realted app ops are updated for all UID packages.
1115                String[] packageNames = ActivityThread.getPackageManager().getPackagesForUid(
1116                        android.os.Process.myUid());
1117                if (packageNames == null || packageNames.length <= 0) {
1118                    return new StorageVolume[0];
1119                }
1120                packageName = packageNames[0];
1121            }
1122            final int uid = ActivityThread.getPackageManager().getPackageUid(packageName,
1123                    PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
1124            if (uid <= 0) {
1125                return new StorageVolume[0];
1126            }
1127            return storageManager.getVolumeList(uid, packageName, flags);
1128        } catch (RemoteException e) {
1129            throw e.rethrowFromSystemServer();
1130        }
1131    }
1132
1133    /**
1134     * Returns list of paths for all mountable volumes.
1135     * @hide
1136     */
1137    @Deprecated
1138    public @NonNull String[] getVolumePaths() {
1139        StorageVolume[] volumes = getVolumeList();
1140        int count = volumes.length;
1141        String[] paths = new String[count];
1142        for (int i = 0; i < count; i++) {
1143            paths[i] = volumes[i].getPath();
1144        }
1145        return paths;
1146    }
1147
1148    /** @removed */
1149    public @NonNull StorageVolume getPrimaryVolume() {
1150        return getPrimaryVolume(getVolumeList());
1151    }
1152
1153    /** {@hide} */
1154    public static @NonNull StorageVolume getPrimaryVolume(StorageVolume[] volumes) {
1155        for (StorageVolume volume : volumes) {
1156            if (volume.isPrimary()) {
1157                return volume;
1158            }
1159        }
1160        throw new IllegalStateException("Missing primary storage");
1161    }
1162
1163    private static final int DEFAULT_THRESHOLD_PERCENTAGE = 5;
1164    private static final long DEFAULT_THRESHOLD_MAX_BYTES = 500 * MB_IN_BYTES;
1165
1166    private static final int DEFAULT_CACHE_PERCENTAGE = 10;
1167    private static final long DEFAULT_CACHE_MAX_BYTES = 5 * GB_IN_BYTES;
1168
1169    private static final long DEFAULT_FULL_THRESHOLD_BYTES = MB_IN_BYTES;
1170
1171    /**
1172     * Return the number of available bytes until the given path is considered
1173     * running low on storage.
1174     *
1175     * @hide
1176     */
1177    public long getStorageBytesUntilLow(File path) {
1178        return path.getUsableSpace() - getStorageFullBytes(path);
1179    }
1180
1181    /**
1182     * Return the number of available bytes at which the given path is
1183     * considered running low on storage.
1184     *
1185     * @hide
1186     */
1187    public long getStorageLowBytes(File path) {
1188        final long lowPercent = Settings.Global.getInt(mResolver,
1189                Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE, DEFAULT_THRESHOLD_PERCENTAGE);
1190        final long lowBytes = (path.getTotalSpace() * lowPercent) / 100;
1191
1192        final long maxLowBytes = Settings.Global.getLong(mResolver,
1193                Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES, DEFAULT_THRESHOLD_MAX_BYTES);
1194
1195        return Math.min(lowBytes, maxLowBytes);
1196    }
1197
1198    /**
1199     * Return the minimum number of bytes of storage on the device that should
1200     * be reserved for cached data.
1201     *
1202     * @hide
1203     */
1204    public long getStorageCacheBytes(File path, @AllocateFlags int flags) {
1205        final long cachePercent = Settings.Global.getInt(mResolver,
1206                Settings.Global.SYS_STORAGE_CACHE_PERCENTAGE, DEFAULT_CACHE_PERCENTAGE);
1207        final long cacheBytes = (path.getTotalSpace() * cachePercent) / 100;
1208
1209        final long maxCacheBytes = Settings.Global.getLong(mResolver,
1210                Settings.Global.SYS_STORAGE_CACHE_MAX_BYTES, DEFAULT_CACHE_MAX_BYTES);
1211
1212        final long result = Math.min(cacheBytes, maxCacheBytes);
1213        if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
1214            return 0;
1215        } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED) != 0) {
1216            return 0;
1217        } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED) != 0) {
1218            return result / 2;
1219        } else {
1220            return result;
1221        }
1222    }
1223
1224    /**
1225     * Return the number of available bytes at which the given path is
1226     * considered full.
1227     *
1228     * @hide
1229     */
1230    public long getStorageFullBytes(File path) {
1231        return Settings.Global.getLong(mResolver, Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
1232                DEFAULT_FULL_THRESHOLD_BYTES);
1233    }
1234
1235    /** {@hide} */
1236    public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
1237        try {
1238            mStorageManager.createUserKey(userId, serialNumber, ephemeral);
1239        } catch (RemoteException e) {
1240            throw e.rethrowFromSystemServer();
1241        }
1242    }
1243
1244    /** {@hide} */
1245    public void destroyUserKey(int userId) {
1246        try {
1247            mStorageManager.destroyUserKey(userId);
1248        } catch (RemoteException e) {
1249            throw e.rethrowFromSystemServer();
1250        }
1251    }
1252
1253    /** {@hide} */
1254    public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
1255        try {
1256            mStorageManager.unlockUserKey(userId, serialNumber, token, secret);
1257        } catch (RemoteException e) {
1258            throw e.rethrowFromSystemServer();
1259        }
1260    }
1261
1262    /** {@hide} */
1263    public void lockUserKey(int userId) {
1264        try {
1265            mStorageManager.lockUserKey(userId);
1266        } catch (RemoteException e) {
1267            throw e.rethrowFromSystemServer();
1268        }
1269    }
1270
1271    /** {@hide} */
1272    public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
1273        try {
1274            mStorageManager.prepareUserStorage(volumeUuid, userId, serialNumber, flags);
1275        } catch (RemoteException e) {
1276            throw e.rethrowFromSystemServer();
1277        }
1278    }
1279
1280    /** {@hide} */
1281    public void destroyUserStorage(String volumeUuid, int userId, int flags) {
1282        try {
1283            mStorageManager.destroyUserStorage(volumeUuid, userId, flags);
1284        } catch (RemoteException e) {
1285            throw e.rethrowFromSystemServer();
1286        }
1287    }
1288
1289    /** {@hide} */
1290    public void secdiscard(String path) {
1291        try {
1292            mStorageManager.secdiscard(path);
1293        } catch (RemoteException e) {
1294            throw e.rethrowFromSystemServer();
1295        }
1296    }
1297
1298    /** {@hide} */
1299    public static boolean isUserKeyUnlocked(int userId) {
1300        if (sStorageManager == null) {
1301            sStorageManager = IStorageManager.Stub
1302                    .asInterface(ServiceManager.getService("mount"));
1303        }
1304        if (sStorageManager == null) {
1305            Slog.w(TAG, "Early during boot, assuming locked");
1306            return false;
1307        }
1308        final long token = Binder.clearCallingIdentity();
1309        try {
1310            return sStorageManager.isUserKeyUnlocked(userId);
1311        } catch (RemoteException e) {
1312            throw e.rethrowAsRuntimeException();
1313        } finally {
1314            Binder.restoreCallingIdentity(token);
1315        }
1316    }
1317
1318    /**
1319     * Return if data stored at or under the given path will be encrypted while
1320     * at rest. This can help apps avoid the overhead of double-encrypting data.
1321     */
1322    public boolean isEncrypted(File file) {
1323        if (FileUtils.contains(Environment.getDataDirectory(), file)) {
1324            return isEncrypted();
1325        } else if (FileUtils.contains(Environment.getExpandDirectory(), file)) {
1326            return true;
1327        }
1328        // TODO: extend to support shared storage
1329        return false;
1330    }
1331
1332    /** {@hide}
1333     * Is this device encryptable or already encrypted?
1334     * @return true for encryptable or encrypted
1335     *         false not encrypted and not encryptable
1336     */
1337    public static boolean isEncryptable() {
1338        return RoSystemProperties.CRYPTO_ENCRYPTABLE;
1339    }
1340
1341    /** {@hide}
1342     * Is this device already encrypted?
1343     * @return true for encrypted. (Implies isEncryptable() == true)
1344     *         false not encrypted
1345     */
1346    public static boolean isEncrypted() {
1347        return RoSystemProperties.CRYPTO_ENCRYPTED;
1348    }
1349
1350    /** {@hide}
1351     * Is this device file encrypted?
1352     * @return true for file encrypted. (Implies isEncrypted() == true)
1353     *         false not encrypted or block encrypted
1354     */
1355    public static boolean isFileEncryptedNativeOnly() {
1356        if (!isEncrypted()) {
1357            return false;
1358        }
1359        return RoSystemProperties.CRYPTO_FILE_ENCRYPTED;
1360    }
1361
1362    /** {@hide}
1363     * Is this device block encrypted?
1364     * @return true for block encrypted. (Implies isEncrypted() == true)
1365     *         false not encrypted or file encrypted
1366     */
1367    public static boolean isBlockEncrypted() {
1368        if (!isEncrypted()) {
1369            return false;
1370        }
1371        return RoSystemProperties.CRYPTO_BLOCK_ENCRYPTED;
1372    }
1373
1374    /** {@hide}
1375     * Is this device block encrypted with credentials?
1376     * @return true for crediential block encrypted.
1377     *         (Implies isBlockEncrypted() == true)
1378     *         false not encrypted, file encrypted or default block encrypted
1379     */
1380    public static boolean isNonDefaultBlockEncrypted() {
1381        if (!isBlockEncrypted()) {
1382            return false;
1383        }
1384
1385        try {
1386            IStorageManager storageManager = IStorageManager.Stub.asInterface(
1387                    ServiceManager.getService("mount"));
1388            return storageManager.getPasswordType() != CRYPT_TYPE_DEFAULT;
1389        } catch (RemoteException e) {
1390            Log.e(TAG, "Error getting encryption type");
1391            return false;
1392        }
1393    }
1394
1395    /** {@hide}
1396     * Is this device in the process of being block encrypted?
1397     * @return true for encrypting.
1398     *         false otherwise
1399     * Whether device isEncrypted at this point is undefined
1400     * Note that only system services and CryptKeeper will ever see this return
1401     * true - no app will ever be launched in this state.
1402     * Also note that this state will not change without a teardown of the
1403     * framework, so no service needs to check for changes during their lifespan
1404     */
1405    public static boolean isBlockEncrypting() {
1406        final String state = SystemProperties.get("vold.encrypt_progress", "");
1407        return !"".equalsIgnoreCase(state);
1408    }
1409
1410    /** {@hide}
1411     * Is this device non default block encrypted and in the process of
1412     * prompting for credentials?
1413     * @return true for prompting for credentials.
1414     *         (Implies isNonDefaultBlockEncrypted() == true)
1415     *         false otherwise
1416     * Note that only system services and CryptKeeper will ever see this return
1417     * true - no app will ever be launched in this state.
1418     * Also note that this state will not change without a teardown of the
1419     * framework, so no service needs to check for changes during their lifespan
1420     */
1421    public static boolean inCryptKeeperBounce() {
1422        final String status = SystemProperties.get("vold.decrypt");
1423        return "trigger_restart_min_framework".equals(status);
1424    }
1425
1426    /** {@hide} */
1427    public static boolean isFileEncryptedEmulatedOnly() {
1428        return SystemProperties.getBoolean(StorageManager.PROP_EMULATE_FBE, false);
1429    }
1430
1431    /** {@hide}
1432     * Is this device running in a file encrypted mode, either native or emulated?
1433     * @return true for file encrypted, false otherwise
1434     */
1435    public static boolean isFileEncryptedNativeOrEmulated() {
1436        return isFileEncryptedNativeOnly()
1437               || isFileEncryptedEmulatedOnly();
1438    }
1439
1440    /** {@hide} */
1441    public static File maybeTranslateEmulatedPathToInternal(File path) {
1442        // Disabled now that FUSE has been replaced by sdcardfs
1443        return path;
1444    }
1445
1446    /** {@hide} */
1447    @VisibleForTesting
1448    public @NonNull ParcelFileDescriptor openProxyFileDescriptor(
1449            int mode, ProxyFileDescriptorCallback callback, Handler handler, ThreadFactory factory)
1450                    throws IOException {
1451        Preconditions.checkNotNull(callback);
1452        MetricsLogger.count(mContext, "storage_open_proxy_file_descriptor", 1);
1453        // Retry is needed because the mount point mFuseAppLoop is using may be unmounted before
1454        // invoking StorageManagerService#openProxyFileDescriptor. In this case, we need to re-mount
1455        // the bridge by calling mountProxyFileDescriptorBridge.
1456        while (true) {
1457            try {
1458                synchronized (mFuseAppLoopLock) {
1459                    boolean newlyCreated = false;
1460                    if (mFuseAppLoop == null) {
1461                        final AppFuseMount mount = mStorageManager.mountProxyFileDescriptorBridge();
1462                        if (mount == null) {
1463                            throw new IOException("Failed to mount proxy bridge");
1464                        }
1465                        mFuseAppLoop = new FuseAppLoop(mount.mountPointId, mount.fd, factory);
1466                        newlyCreated = true;
1467                    }
1468                    if (handler == null) {
1469                        handler = new Handler(Looper.getMainLooper());
1470                    }
1471                    try {
1472                        final int fileId = mFuseAppLoop.registerCallback(callback, handler);
1473                        final ParcelFileDescriptor pfd = mStorageManager.openProxyFileDescriptor(
1474                                mFuseAppLoop.getMountPointId(), fileId, mode);
1475                        if (pfd == null) {
1476                            mFuseAppLoop.unregisterCallback(fileId);
1477                            throw new FuseUnavailableMountException(
1478                                    mFuseAppLoop.getMountPointId());
1479                        }
1480                        return pfd;
1481                    } catch (FuseUnavailableMountException exception) {
1482                        // The bridge is being unmounted. Tried to recreate it unless the bridge was
1483                        // just created.
1484                        if (newlyCreated) {
1485                            throw new IOException(exception);
1486                        }
1487                        mFuseAppLoop = null;
1488                        continue;
1489                    }
1490                }
1491            } catch (RemoteException e) {
1492                // Cannot recover from remote exception.
1493                throw new IOException(e);
1494            }
1495        }
1496    }
1497
1498    /** {@hide} */
1499    public @NonNull ParcelFileDescriptor openProxyFileDescriptor(
1500            int mode, ProxyFileDescriptorCallback callback)
1501                    throws IOException {
1502        return openProxyFileDescriptor(mode, callback, null, null);
1503    }
1504
1505    /**
1506     * Opens a seekable {@link ParcelFileDescriptor} that proxies all low-level
1507     * I/O requests back to the given {@link ProxyFileDescriptorCallback}.
1508     * <p>
1509     * This can be useful when you want to provide quick access to a large file
1510     * that isn't backed by a real file on disk, such as a file on a network
1511     * share, cloud storage service, etc. As an example, you could respond to a
1512     * {@link ContentResolver#openFileDescriptor(android.net.Uri, String)}
1513     * request by returning a {@link ParcelFileDescriptor} created with this
1514     * method, and then stream the content on-demand as requested.
1515     * <p>
1516     * Another useful example might be where you have an encrypted file that
1517     * you're willing to decrypt on-demand, but where you want to avoid
1518     * persisting the cleartext version.
1519     *
1520     * @param mode The desired access mode, must be one of
1521     *            {@link ParcelFileDescriptor#MODE_READ_ONLY},
1522     *            {@link ParcelFileDescriptor#MODE_WRITE_ONLY}, or
1523     *            {@link ParcelFileDescriptor#MODE_READ_WRITE}
1524     * @param callback Callback to process file operation requests issued on
1525     *            returned file descriptor.
1526     * @param handler Handler that invokes callback methods.
1527     * @return Seekable ParcelFileDescriptor.
1528     * @throws IOException
1529     */
1530    public @NonNull ParcelFileDescriptor openProxyFileDescriptor(
1531            int mode, ProxyFileDescriptorCallback callback, Handler handler)
1532                    throws IOException {
1533        Preconditions.checkNotNull(handler);
1534        return openProxyFileDescriptor(mode, callback, handler, null);
1535    }
1536
1537    /** {@hide} */
1538    @VisibleForTesting
1539    public int getProxyFileDescriptorMountPointId() {
1540        synchronized (mFuseAppLoopLock) {
1541            return mFuseAppLoop != null ? mFuseAppLoop.getMountPointId() : -1;
1542        }
1543    }
1544
1545    /**
1546     * Return quota size in bytes for all cached data belonging to the calling
1547     * app on the given storage volume.
1548     * <p>
1549     * If your app goes above this quota, your cached files will be some of the
1550     * first to be deleted when additional disk space is needed. Conversely, if
1551     * your app stays under this quota, your cached files will be some of the
1552     * last to be deleted when additional disk space is needed.
1553     * <p>
1554     * This quota will change over time depending on how frequently the user
1555     * interacts with your app, and depending on how much system-wide disk space
1556     * is used.
1557     * <p class="note">
1558     * Note: if your app uses the {@code android:sharedUserId} manifest feature,
1559     * then cached data for all packages in your shared UID is tracked together
1560     * as a single unit.
1561     * </p>
1562     *
1563     * @param storageUuid the UUID of the storage volume that you're interested
1564     *            in. The UUID for a specific path can be obtained using
1565     *            {@link #getUuidForPath(File)}.
1566     * @throws IOException when the storage device isn't present, or when it
1567     *             doesn't support cache quotas.
1568     * @see #getCacheSizeBytes(UUID)
1569     */
1570    @WorkerThread
1571    public @BytesLong long getCacheQuotaBytes(@NonNull UUID storageUuid) throws IOException {
1572        try {
1573            final ApplicationInfo app = mContext.getApplicationInfo();
1574            return mStorageManager.getCacheQuotaBytes(convert(storageUuid), app.uid);
1575        } catch (ParcelableException e) {
1576            e.maybeRethrow(IOException.class);
1577            throw new RuntimeException(e);
1578        } catch (RemoteException e) {
1579            throw e.rethrowFromSystemServer();
1580        }
1581    }
1582
1583    /**
1584     * Return total size in bytes of all cached data belonging to the calling
1585     * app on the given storage volume.
1586     * <p>
1587     * Cached data tracked by this method always includes
1588     * {@link Context#getCacheDir()} and {@link Context#getCodeCacheDir()}, and
1589     * it also includes {@link Context#getExternalCacheDir()} if the primary
1590     * shared/external storage is hosted on the same storage device as your
1591     * private data.
1592     * <p class="note">
1593     * Note: if your app uses the {@code android:sharedUserId} manifest feature,
1594     * then cached data for all packages in your shared UID is tracked together
1595     * as a single unit.
1596     * </p>
1597     *
1598     * @param storageUuid the UUID of the storage volume that you're interested
1599     *            in. The UUID for a specific path can be obtained using
1600     *            {@link #getUuidForPath(File)}.
1601     * @throws IOException when the storage device isn't present, or when it
1602     *             doesn't support cache quotas.
1603     * @see #getCacheQuotaBytes(UUID)
1604     */
1605    @WorkerThread
1606    public @BytesLong long getCacheSizeBytes(@NonNull UUID storageUuid) throws IOException {
1607        try {
1608            final ApplicationInfo app = mContext.getApplicationInfo();
1609            return mStorageManager.getCacheSizeBytes(convert(storageUuid), app.uid);
1610        } catch (ParcelableException e) {
1611            e.maybeRethrow(IOException.class);
1612            throw new RuntimeException(e);
1613        } catch (RemoteException e) {
1614            throw e.rethrowFromSystemServer();
1615        }
1616    }
1617
1618    /**
1619     * Flag indicating that a disk space allocation request should operate in an
1620     * aggressive mode. This flag should only be rarely used in situations that
1621     * are critical to system health or security.
1622     * <p>
1623     * When set, the system is more aggressive about the data that it considers
1624     * for possible deletion when allocating disk space.
1625     * <p class="note">
1626     * Note: your app must hold the
1627     * {@link android.Manifest.permission#ALLOCATE_AGGRESSIVE} permission for
1628     * this flag to take effect.
1629     * </p>
1630     *
1631     * @see #getAllocatableBytes(UUID, int)
1632     * @see #allocateBytes(UUID, long, int)
1633     * @see #allocateBytes(FileDescriptor, long, int)
1634     * @hide
1635     */
1636    @RequiresPermission(android.Manifest.permission.ALLOCATE_AGGRESSIVE)
1637    @SystemApi
1638    public static final int FLAG_ALLOCATE_AGGRESSIVE = 1 << 0;
1639
1640    /**
1641     * Flag indicating that a disk space allocation request should be allowed to
1642     * clear up to all reserved disk space.
1643     *
1644     * @hide
1645     */
1646    public static final int FLAG_ALLOCATE_DEFY_ALL_RESERVED = 1 << 1;
1647
1648    /**
1649     * Flag indicating that a disk space allocation request should be allowed to
1650     * clear up to half of all reserved disk space.
1651     *
1652     * @hide
1653     */
1654    public static final int FLAG_ALLOCATE_DEFY_HALF_RESERVED = 1 << 2;
1655
1656    /** @hide */
1657    @IntDef(flag = true, value = {
1658            FLAG_ALLOCATE_AGGRESSIVE,
1659            FLAG_ALLOCATE_DEFY_ALL_RESERVED,
1660            FLAG_ALLOCATE_DEFY_HALF_RESERVED,
1661    })
1662    @Retention(RetentionPolicy.SOURCE)
1663    public @interface AllocateFlags {}
1664
1665    /**
1666     * Return the maximum number of new bytes that your app can allocate for
1667     * itself on the given storage volume. This value is typically larger than
1668     * {@link File#getUsableSpace()}, since the system may be willing to delete
1669     * cached files to satisfy an allocation request. You can then allocate
1670     * space for yourself using {@link #allocateBytes(UUID, long)} or
1671     * {@link #allocateBytes(FileDescriptor, long)}.
1672     * <p>
1673     * This method is best used as a pre-flight check, such as deciding if there
1674     * is enough space to store an entire music album before you allocate space
1675     * for each audio file in the album. Attempts to allocate disk space beyond
1676     * the returned value will fail.
1677     * <p>
1678     * If the returned value is not large enough for the data you'd like to
1679     * persist, you can launch {@link #ACTION_MANAGE_STORAGE} with the
1680     * {@link #EXTRA_UUID} and {@link #EXTRA_REQUESTED_BYTES} options to help
1681     * involve the user in freeing up disk space.
1682     * <p>
1683     * If you're progressively allocating an unbounded amount of storage space
1684     * (such as when recording a video) you should avoid calling this method
1685     * more than once every 30 seconds.
1686     * <p class="note">
1687     * Note: if your app uses the {@code android:sharedUserId} manifest feature,
1688     * then allocatable space for all packages in your shared UID is tracked
1689     * together as a single unit.
1690     * </p>
1691     *
1692     * @param storageUuid the UUID of the storage volume where you're
1693     *            considering allocating disk space, since allocatable space can
1694     *            vary widely depending on the underlying storage device. The
1695     *            UUID for a specific path can be obtained using
1696     *            {@link #getUuidForPath(File)}.
1697     * @return the maximum number of new bytes that the calling app can allocate
1698     *         using {@link #allocateBytes(UUID, long)} or
1699     *         {@link #allocateBytes(FileDescriptor, long)}.
1700     * @throws IOException when the storage device isn't present, or when it
1701     *             doesn't support allocating space.
1702     */
1703    @WorkerThread
1704    public @BytesLong long getAllocatableBytes(@NonNull UUID storageUuid)
1705            throws IOException {
1706        return getAllocatableBytes(storageUuid, 0);
1707    }
1708
1709    /** @hide */
1710    @SystemApi
1711    @WorkerThread
1712    @SuppressLint("Doclava125")
1713    public long getAllocatableBytes(@NonNull UUID storageUuid,
1714            @RequiresPermission @AllocateFlags int flags) throws IOException {
1715        try {
1716            return mStorageManager.getAllocatableBytes(convert(storageUuid), flags,
1717                    mContext.getOpPackageName());
1718        } catch (ParcelableException e) {
1719            e.maybeRethrow(IOException.class);
1720            throw new RuntimeException(e);
1721        } catch (RemoteException e) {
1722            throw e.rethrowFromSystemServer();
1723        }
1724    }
1725
1726    /**
1727     * Allocate the requested number of bytes for your application to use on the
1728     * given storage volume. This will cause the system to delete any cached
1729     * files necessary to satisfy your request.
1730     * <p>
1731     * Attempts to allocate disk space beyond the value returned by
1732     * {@link #getAllocatableBytes(UUID)} will fail.
1733     * <p>
1734     * Since multiple apps can be running simultaneously, this method may be
1735     * subject to race conditions. If possible, consider using
1736     * {@link #allocateBytes(FileDescriptor, long)} which will guarantee
1737     * that bytes are allocated to an opened file.
1738     * <p>
1739     * If you're progressively allocating an unbounded amount of storage space
1740     * (such as when recording a video) you should avoid calling this method
1741     * more than once every 60 seconds.
1742     *
1743     * @param storageUuid the UUID of the storage volume where you'd like to
1744     *            allocate disk space. The UUID for a specific path can be
1745     *            obtained using {@link #getUuidForPath(File)}.
1746     * @param bytes the number of bytes to allocate.
1747     * @throws IOException when the storage device isn't present, or when it
1748     *             doesn't support allocating space, or if the device had
1749     *             trouble allocating the requested space.
1750     * @see #getAllocatableBytes(UUID)
1751     */
1752    @WorkerThread
1753    public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes)
1754            throws IOException {
1755        allocateBytes(storageUuid, bytes, 0);
1756    }
1757
1758    /** @hide */
1759    @SystemApi
1760    @WorkerThread
1761    @SuppressLint("Doclava125")
1762    public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes,
1763            @RequiresPermission @AllocateFlags int flags) throws IOException {
1764        try {
1765            mStorageManager.allocateBytes(convert(storageUuid), bytes, flags,
1766                    mContext.getOpPackageName());
1767        } catch (ParcelableException e) {
1768            e.maybeRethrow(IOException.class);
1769        } catch (RemoteException e) {
1770            throw e.rethrowFromSystemServer();
1771        }
1772    }
1773
1774    /**
1775     * Allocate the requested number of bytes for your application to use in the
1776     * given open file. This will cause the system to delete any cached files
1777     * necessary to satisfy your request.
1778     * <p>
1779     * Attempts to allocate disk space beyond the value returned by
1780     * {@link #getAllocatableBytes(UUID)} will fail.
1781     * <p>
1782     * This method guarantees that bytes have been allocated to the opened file,
1783     * otherwise it will throw if fast allocation is not possible. Fast
1784     * allocation is typically only supported in private app data directories,
1785     * and on shared/external storage devices which are emulated.
1786     * <p>
1787     * If you're progressively allocating an unbounded amount of storage space
1788     * (such as when recording a video) you should avoid calling this method
1789     * more than once every 60 seconds.
1790     *
1791     * @param fd the open file that you'd like to allocate disk space for.
1792     * @param bytes the number of bytes to allocate. This is the desired final
1793     *            size of the open file. If the open file is smaller than this
1794     *            requested size, it will be extended without modifying any
1795     *            existing contents. If the open file is larger than this
1796     *            requested size, it will be truncated.
1797     * @throws IOException when the storage device isn't present, or when it
1798     *             doesn't support allocating space, or if the device had
1799     *             trouble allocating the requested space.
1800     * @see #getAllocatableBytes(UUID, int)
1801     * @see #isAllocationSupported(FileDescriptor)
1802     * @see Environment#isExternalStorageEmulated(File)
1803     */
1804    @WorkerThread
1805    public void allocateBytes(FileDescriptor fd, @BytesLong long bytes) throws IOException {
1806        allocateBytes(fd, bytes, 0);
1807    }
1808
1809    /** @hide */
1810    @SystemApi
1811    @WorkerThread
1812    @SuppressLint("Doclava125")
1813    public void allocateBytes(FileDescriptor fd, @BytesLong long bytes,
1814            @RequiresPermission @AllocateFlags int flags) throws IOException {
1815        final File file = ParcelFileDescriptor.getFile(fd);
1816        final UUID uuid = getUuidForPath(file);
1817        for (int i = 0; i < 3; i++) {
1818            try {
1819                final long haveBytes = Os.fstat(fd).st_blocks * 512;
1820                final long needBytes = bytes - haveBytes;
1821
1822                if (needBytes > 0) {
1823                    allocateBytes(uuid, needBytes, flags);
1824                }
1825
1826                try {
1827                    Os.posix_fallocate(fd, 0, bytes);
1828                    return;
1829                } catch (ErrnoException e) {
1830                    if (e.errno == OsConstants.ENOSYS || e.errno == OsConstants.ENOTSUP) {
1831                        Log.w(TAG, "fallocate() not supported; falling back to ftruncate()");
1832                        Os.ftruncate(fd, bytes);
1833                        return;
1834                    } else {
1835                        throw e;
1836                    }
1837                }
1838            } catch (ErrnoException e) {
1839                if (e.errno == OsConstants.ENOSPC) {
1840                    Log.w(TAG, "Odd, not enough space; let's try again?");
1841                    continue;
1842                }
1843                throw e.rethrowAsIOException();
1844            }
1845        }
1846        throw new IOException(
1847                "Well this is embarassing; we can't allocate " + bytes + " for " + file);
1848    }
1849
1850    private static final String XATTR_CACHE_GROUP = "user.cache_group";
1851    private static final String XATTR_CACHE_TOMBSTONE = "user.cache_tombstone";
1852
1853    /** {@hide} */
1854    private static void setCacheBehavior(File path, String name, boolean enabled)
1855            throws IOException {
1856        if (!path.isDirectory()) {
1857            throw new IOException("Cache behavior can only be set on directories");
1858        }
1859        if (enabled) {
1860            try {
1861                Os.setxattr(path.getAbsolutePath(), name,
1862                        "1".getBytes(StandardCharsets.UTF_8), 0);
1863            } catch (ErrnoException e) {
1864                throw e.rethrowAsIOException();
1865            }
1866        } else {
1867            try {
1868                Os.removexattr(path.getAbsolutePath(), name);
1869            } catch (ErrnoException e) {
1870                if (e.errno != OsConstants.ENODATA) {
1871                    throw e.rethrowAsIOException();
1872                }
1873            }
1874        }
1875    }
1876
1877    /** {@hide} */
1878    private static boolean isCacheBehavior(File path, String name) throws IOException {
1879        try {
1880            Os.getxattr(path.getAbsolutePath(), name);
1881            return true;
1882        } catch (ErrnoException e) {
1883            if (e.errno != OsConstants.ENODATA) {
1884                throw e.rethrowAsIOException();
1885            } else {
1886                return false;
1887            }
1888        }
1889    }
1890
1891    /**
1892     * Enable or disable special cache behavior that treats this directory and
1893     * its contents as an entire group.
1894     * <p>
1895     * When enabled and this directory is considered for automatic deletion by
1896     * the OS, all contained files will either be deleted together, or not at
1897     * all. This is useful when you have a directory that contains several
1898     * related metadata files that depend on each other, such as movie file and
1899     * a subtitle file.
1900     * <p>
1901     * When enabled, the <em>newest</em> {@link File#lastModified()} value of
1902     * any contained files is considered the modified time of the entire
1903     * directory.
1904     * <p>
1905     * This behavior can only be set on a directory, and it applies recursively
1906     * to all contained files and directories.
1907     */
1908    public void setCacheBehaviorGroup(File path, boolean group) throws IOException {
1909        setCacheBehavior(path, XATTR_CACHE_GROUP, group);
1910    }
1911
1912    /**
1913     * Read the current value set by
1914     * {@link #setCacheBehaviorGroup(File, boolean)}.
1915     */
1916    public boolean isCacheBehaviorGroup(File path) throws IOException {
1917        return isCacheBehavior(path, XATTR_CACHE_GROUP);
1918    }
1919
1920    /**
1921     * Enable or disable special cache behavior that leaves deleted cache files
1922     * intact as tombstones.
1923     * <p>
1924     * When enabled and a file contained in this directory is automatically
1925     * deleted by the OS, the file will be truncated to have a length of 0 bytes
1926     * instead of being fully deleted. This is useful if you need to distinguish
1927     * between a file that was deleted versus one that never existed.
1928     * <p>
1929     * This behavior can only be set on a directory, and it applies recursively
1930     * to all contained files and directories.
1931     * <p class="note">
1932     * Note: this behavior is ignored completely if the user explicitly requests
1933     * that all cached data be cleared.
1934     * </p>
1935     */
1936    public void setCacheBehaviorTombstone(File path, boolean tombstone) throws IOException {
1937        setCacheBehavior(path, XATTR_CACHE_TOMBSTONE, tombstone);
1938    }
1939
1940    /**
1941     * Read the current value set by
1942     * {@link #setCacheBehaviorTombstone(File, boolean)}.
1943     */
1944    public boolean isCacheBehaviorTombstone(File path) throws IOException {
1945        return isCacheBehavior(path, XATTR_CACHE_TOMBSTONE);
1946    }
1947
1948    /** {@hide} */
1949    public static UUID convert(String uuid) {
1950        if (Objects.equals(uuid, UUID_PRIVATE_INTERNAL)) {
1951            return UUID_DEFAULT;
1952        } else if (Objects.equals(uuid, UUID_PRIMARY_PHYSICAL)) {
1953            return UUID_PRIMARY_PHYSICAL_;
1954        } else if (Objects.equals(uuid, UUID_SYSTEM)) {
1955            return UUID_SYSTEM_;
1956        } else {
1957            return UUID.fromString(uuid);
1958        }
1959    }
1960
1961    /** {@hide} */
1962    public static String convert(UUID storageUuid) {
1963        if (UUID_DEFAULT.equals(storageUuid)) {
1964            return UUID_PRIVATE_INTERNAL;
1965        } else if (UUID_PRIMARY_PHYSICAL_.equals(storageUuid)) {
1966            return UUID_PRIMARY_PHYSICAL;
1967        } else if (UUID_SYSTEM_.equals(storageUuid)) {
1968            return UUID_SYSTEM;
1969        } else {
1970            return storageUuid.toString();
1971        }
1972    }
1973
1974    private final Object mFuseAppLoopLock = new Object();
1975
1976    @GuardedBy("mFuseAppLoopLock")
1977    private @Nullable FuseAppLoop mFuseAppLoop = null;
1978
1979    /// Consts to match the password types in cryptfs.h
1980    /** @hide */
1981    public static final int CRYPT_TYPE_PASSWORD = IVold.PASSWORD_TYPE_PASSWORD;
1982    /** @hide */
1983    public static final int CRYPT_TYPE_DEFAULT = IVold.PASSWORD_TYPE_DEFAULT;
1984    /** @hide */
1985    public static final int CRYPT_TYPE_PATTERN = IVold.PASSWORD_TYPE_PATTERN;
1986    /** @hide */
1987    public static final int CRYPT_TYPE_PIN = IVold.PASSWORD_TYPE_PIN;
1988
1989    // Constants for the data available via StorageManagerService.getField.
1990    /** @hide */
1991    public static final String SYSTEM_LOCALE_KEY = "SystemLocale";
1992    /** @hide */
1993    public static final String OWNER_INFO_KEY = "OwnerInfo";
1994    /** @hide */
1995    public static final String PATTERN_VISIBLE_KEY = "PatternVisible";
1996    /** @hide */
1997    public static final String PASSWORD_VISIBLE_KEY = "PasswordVisible";
1998}
1999