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 = "GenerationRegistry";
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);
123                if (DEBUG) {
124                    Slog.e(LOG_TAG, "Created backing store " + mBackingStore);
125                }
126            } catch (IOException e) {
127                Slog.e(LOG_TAG, "Error creating generation tracker", e);
128            }
129        }
130        return mBackingStore;
131    }
132
133    private void destroyBackingStore() {
134        if (mBackingStore != null) {
135            try {
136                mBackingStore.close();
137                if (DEBUG) {
138                    Slog.e(LOG_TAG, "Destroyed backing store " + mBackingStore);
139                }
140            } catch (IOException e) {
141                Slog.e(LOG_TAG, "Cannot close generation memory array", e);
142            }
143            mBackingStore = null;
144        }
145    }
146
147    private static void resetSlotForKeyLocked(int key, SparseIntArray keyToIndexMap,
148            MemoryIntArray backingStore) throws IOException {
149        final int index = keyToIndexMap.get(key, -1);
150        if (index >= 0) {
151            keyToIndexMap.delete(key);
152            backingStore.set(index, 0);
153            if (DEBUG) {
154                Slog.i(LOG_TAG, "Freed index:" + index + " for key:"
155                        + SettingsProvider.keyToString(key));
156            }
157        }
158    }
159
160    private static int getKeyIndexLocked(int key, SparseIntArray keyToIndexMap,
161            MemoryIntArray backingStore) throws IOException {
162        int index = keyToIndexMap.get(key, -1);
163        if (index < 0) {
164            index = findNextEmptyIndex(backingStore);
165            if (index >= 0) {
166                backingStore.set(index, 1);
167                keyToIndexMap.append(key, index);
168                if (DEBUG) {
169                    Slog.i(LOG_TAG, "Allocated index:" + index + " for key:"
170                            + SettingsProvider.keyToString(key));
171                }
172            } else {
173                Slog.e(LOG_TAG, "Could not allocate generation index");
174            }
175        }
176        return index;
177    }
178
179    private static int findNextEmptyIndex(MemoryIntArray backingStore) throws IOException {
180        final int size = backingStore.size();
181        for (int i = 0; i < size; i++) {
182            if (backingStore.get(i) == 0) {
183                return i;
184            }
185        }
186        return -1;
187    }
188}