1/*
2 * Copyright (C) 2016 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 com.android.providers.settings;
18
19import android.os.Bundle;
20import android.os.UserManager;
21import android.provider.Settings;
22import android.util.MemoryIntArray;
23import android.util.Slog;
24import android.util.SparseIntArray;
25import com.android.internal.annotations.GuardedBy;
26
27import java.io.IOException;
28
29/**
30 * This class tracks changes for global/secure/system tables on a
31 * per user basis and updates a shared memory region which client
32 * processes can read to determine if their local caches are stale,
33 */
34final class GenerationRegistry {
35    private static final String LOG_TAG = "GenerationTracker";
36
37    private static final boolean DEBUG = false;
38
39    private final Object mLock;
40
41    @GuardedBy("mLock")
42    private final SparseIntArray mKeyToIndexMap = new SparseIntArray();
43
44    @GuardedBy("mLock")
45    private MemoryIntArray mBackingStore;
46
47    public GenerationRegistry(Object lock) {
48        mLock = lock;
49    }
50
51    public void incrementGeneration(int key) {
52        synchronized (mLock) {
53            MemoryIntArray backingStore = getBackingStoreLocked();
54            if (backingStore != null) {
55                try {
56                    final int index = getKeyIndexLocked(key, mKeyToIndexMap, backingStore);
57                    if (index >= 0) {
58                        final int generation = backingStore.get(index) + 1;
59                        backingStore.set(index, generation);
60                    }
61                } catch (IOException e) {
62                    Slog.e(LOG_TAG, "Error updating generation id", e);
63                    destroyBackingStore();
64                }
65            }
66        }
67    }
68
69    public void addGenerationData(Bundle bundle, int key) {
70        synchronized (mLock) {
71            MemoryIntArray backingStore = getBackingStoreLocked();
72            try {
73                if (backingStore != null) {
74                    final int index = getKeyIndexLocked(key, mKeyToIndexMap, backingStore);
75                    if (index >= 0) {
76                        bundle.putParcelable(Settings.CALL_METHOD_TRACK_GENERATION_KEY,
77                                backingStore);
78                        bundle.putInt(Settings.CALL_METHOD_GENERATION_INDEX_KEY, index);
79                        bundle.putInt(Settings.CALL_METHOD_GENERATION_KEY,
80                                backingStore.get(index));
81                        if (DEBUG) {
82                            Slog.i(LOG_TAG, "Exported index:" + index + " for key:"
83                                    + SettingsProvider.keyToString(key));
84                        }
85                    }
86                }
87            } catch (IOException e) {
88                Slog.e(LOG_TAG, "Error adding generation data", e);
89                destroyBackingStore();
90            }
91        }
92    }
93
94    public void onUserRemoved(int userId) {
95        synchronized (mLock) {
96            MemoryIntArray backingStore = getBackingStoreLocked();
97            if (backingStore != null && mKeyToIndexMap.size() > 0) {
98                try {
99                    final int secureKey = SettingsProvider.makeKey(
100                            SettingsProvider.SETTINGS_TYPE_SECURE, userId);
101                    resetSlotForKeyLocked(secureKey, mKeyToIndexMap, backingStore);
102
103                    final int systemKey = SettingsProvider.makeKey(
104                            SettingsProvider.SETTINGS_TYPE_SYSTEM, userId);
105                    resetSlotForKeyLocked(systemKey, mKeyToIndexMap, backingStore);
106                } catch (IOException e) {
107                    Slog.e(LOG_TAG, "Error cleaning up for user", e);
108                    destroyBackingStore();
109                }
110            }
111        }
112    }
113
114    private MemoryIntArray getBackingStoreLocked() {
115        if (mBackingStore == null) {
116            // One for the global table, two for system and secure tables for a
117            // managed profile (managed profile is not included in the max user
118            // count), ten for partially deleted users if users are quickly removed,
119            // and twice max user count for system and secure.
120            final int size = 1 + 2 + 10 + 2 * UserManager.getMaxSupportedUsers();
121            try {
122                mBackingStore = new MemoryIntArray(size, false);
123            } catch (IOException e) {
124                Slog.e(LOG_TAG, "Error creating generation tracker", e);
125            }
126        }
127        return mBackingStore;
128    }
129
130    private void destroyBackingStore() {
131        if (mBackingStore != null) {
132            try {
133                mBackingStore.close();
134            } catch (IOException e) {
135                Slog.e(LOG_TAG, "Cannot close generation memory array", e);
136            }
137            mBackingStore = null;
138        }
139    }
140
141    private static void resetSlotForKeyLocked(int key, SparseIntArray keyToIndexMap,
142            MemoryIntArray backingStore) throws IOException {
143        final int index = keyToIndexMap.get(key, -1);
144        if (index >= 0) {
145            keyToIndexMap.delete(key);
146            backingStore.set(index, 0);
147            if (DEBUG) {
148                Slog.i(LOG_TAG, "Freed index:" + index + " for key:"
149                        + SettingsProvider.keyToString(key));
150            }
151        }
152    }
153
154    private static int getKeyIndexLocked(int key, SparseIntArray keyToIndexMap,
155            MemoryIntArray backingStore) throws IOException {
156        int index = keyToIndexMap.get(key, -1);
157        if (index < 0) {
158            index = findNextEmptyIndex(backingStore);
159            if (index >= 0) {
160                backingStore.set(index, 1);
161                keyToIndexMap.append(key, index);
162                if (DEBUG) {
163                    Slog.i(LOG_TAG, "Allocated index:" + index + " for key:"
164                            + SettingsProvider.keyToString(key));
165                }
166            } else {
167                Slog.e(LOG_TAG, "Could not allocate generation index");
168            }
169        }
170        return index;
171    }
172
173    private static int findNextEmptyIndex(MemoryIntArray backingStore) throws IOException {
174        final int size = backingStore.size();
175        for (int i = 0; i < size; i++) {
176            if (backingStore.get(i) == 0) {
177                return i;
178            }
179        }
180        return -1;
181    }
182}