Ken Sumrall | b87937c | 2013-03-19 21:46:39 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2013 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <sys/types.h> |
| 18 | #include <sys/stat.h> |
| 19 | #include <fcntl.h> |
| 20 | #include <unistd.h> |
| 21 | #include <sys/ioctl.h> |
| 22 | #include <string.h> |
| 23 | #include <limits.h> |
| 24 | #include <linux/fs.h> |
| 25 | #include <fs_mgr.h> |
| 26 | #define LOG_TAG "fstrim" |
| 27 | #include "cutils/log.h" |
| 28 | |
| 29 | int fstrim_filesystems(void) |
| 30 | { |
| 31 | int i; |
| 32 | int fd; |
| 33 | int ret = 0; |
| 34 | struct fstrim_range range = { 0 }; |
| 35 | struct stat sb; |
| 36 | extern struct fstab *fstab; |
| 37 | |
| 38 | SLOGI("Starting fstrim work...\n"); |
| 39 | |
| 40 | for (i = 0; i < fstab->num_entries; i++) { |
| 41 | /* Skip raw partitions */ |
| 42 | if (!strcmp(fstab->recs[i].fs_type, "emmc") || |
| 43 | !strcmp(fstab->recs[i].fs_type, "mtd")) { |
| 44 | continue; |
| 45 | } |
| 46 | /* Skip read-only filesystems */ |
| 47 | if (fstab->recs[i].flags & MS_RDONLY) { |
| 48 | continue; |
| 49 | } |
| 50 | if (fs_mgr_is_voldmanaged(&fstab->recs[i])) { |
| 51 | continue; /* Should we trim fat32 filesystems? */ |
| 52 | } |
| 53 | |
| 54 | if (stat(fstab->recs[i].mount_point, &sb) == -1) { |
| 55 | SLOGE("Cannot stat mount point %s\n", fstab->recs[i].mount_point); |
| 56 | ret = -1; |
| 57 | continue; |
| 58 | } |
| 59 | if (!S_ISDIR(sb.st_mode)) { |
| 60 | SLOGE("%s is not a directory\n", fstab->recs[i].mount_point); |
| 61 | ret = -1; |
| 62 | continue; |
| 63 | } |
| 64 | |
| 65 | fd = open(fstab->recs[i].mount_point, O_RDONLY); |
| 66 | if (fd < 0) { |
| 67 | SLOGE("Cannot open %s for FITRIM\n", fstab->recs[i].mount_point); |
| 68 | ret = -1; |
| 69 | continue; |
| 70 | } |
| 71 | |
| 72 | memset(&range, 0, sizeof(range)); |
| 73 | range.len = ULLONG_MAX; |
| 74 | SLOGI("Invoking FITRIM ioctl on %s", fstab->recs[i].mount_point); |
| 75 | if (ioctl(fd, FITRIM, &range)) { |
| 76 | SLOGE("FITRIM ioctl failed on %s", fstab->recs[i].mount_point); |
| 77 | ret = -1; |
| 78 | } |
| 79 | SLOGI("Trimmed %llu bytes on %s\n", range.len, fstab->recs[i].mount_point); |
| 80 | close(fd); |
| 81 | } |
| 82 | SLOGI("Finished fstrim work.\n"); |
| 83 | |
| 84 | return ret; |
| 85 | } |
| 86 | |