Home | History | Annotate | Download | only in mtdutils
      1 /*
      2  * Copyright (C) 2007 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 <stdio.h>
     18 #include <stdlib.h>
     19 #include <string.h>
     20 #include <unistd.h>
     21 #include <fcntl.h>
     22 #include <errno.h>
     23 #include <sys/mount.h>  // for _IOW, _IOR, mount()
     24 #include <sys/stat.h>
     25 #include <mtd/mtd-user.h>
     26 #undef NDEBUG
     27 #include <assert.h>
     28 
     29 #include "mtdutils.h"
     30 
     31 struct MtdPartition {
     32     int device_index;
     33     unsigned int size;
     34     unsigned int erase_size;
     35     char *name;
     36 };
     37 
     38 struct MtdReadContext {
     39     const MtdPartition *partition;
     40     char *buffer;
     41     size_t consumed;
     42     int fd;
     43 };
     44 
     45 struct MtdWriteContext {
     46     const MtdPartition *partition;
     47     char *buffer;
     48     size_t stored;
     49     int fd;
     50 
     51     off_t* bad_block_offsets;
     52     int bad_block_alloc;
     53     int bad_block_count;
     54 };
     55 
     56 typedef struct {
     57     MtdPartition *partitions;
     58     int partitions_allocd;
     59     int partition_count;
     60 } MtdState;
     61 
     62 static MtdState g_mtd_state = {
     63     NULL,   // partitions
     64     0,      // partitions_allocd
     65     -1      // partition_count
     66 };
     67 
     68 #define MTD_PROC_FILENAME   "/proc/mtd"
     69 
     70 int
     71 mtd_scan_partitions()
     72 {
     73     char buf[2048];
     74     const char *bufp;
     75     int fd;
     76     int i;
     77     ssize_t nbytes;
     78 
     79     if (g_mtd_state.partitions == NULL) {
     80         const int nump = 32;
     81         MtdPartition *partitions = malloc(nump * sizeof(*partitions));
     82         if (partitions == NULL) {
     83             errno = ENOMEM;
     84             return -1;
     85         }
     86         g_mtd_state.partitions = partitions;
     87         g_mtd_state.partitions_allocd = nump;
     88         memset(partitions, 0, nump * sizeof(*partitions));
     89     }
     90     g_mtd_state.partition_count = 0;
     91 
     92     /* Initialize all of the entries to make things easier later.
     93      * (Lets us handle sparsely-numbered partitions, which
     94      * may not even be possible.)
     95      */
     96     for (i = 0; i < g_mtd_state.partitions_allocd; i++) {
     97         MtdPartition *p = &g_mtd_state.partitions[i];
     98         if (p->name != NULL) {
     99             free(p->name);
    100             p->name = NULL;
    101         }
    102         p->device_index = -1;
    103     }
    104 
    105     /* Open and read the file contents.
    106      */
    107     fd = open(MTD_PROC_FILENAME, O_RDONLY);
    108     if (fd < 0) {
    109         goto bail;
    110     }
    111     nbytes = read(fd, buf, sizeof(buf) - 1);
    112     close(fd);
    113     if (nbytes < 0) {
    114         goto bail;
    115     }
    116     buf[nbytes] = '\0';
    117 
    118     /* Parse the contents of the file, which looks like:
    119      *
    120      *     # cat /proc/mtd
    121      *     dev:    size   erasesize  name
    122      *     mtd0: 00080000 00020000 "bootloader"
    123      *     mtd1: 00400000 00020000 "mfg_and_gsm"
    124      *     mtd2: 00400000 00020000 "0000000c"
    125      *     mtd3: 00200000 00020000 "0000000d"
    126      *     mtd4: 04000000 00020000 "system"
    127      *     mtd5: 03280000 00020000 "userdata"
    128      */
    129     bufp = buf;
    130     while (nbytes > 0) {
    131         int mtdnum, mtdsize, mtderasesize;
    132         int matches;
    133         char mtdname[64];
    134         mtdname[0] = '\0';
    135         mtdnum = -1;
    136 
    137         matches = sscanf(bufp, "mtd%d: %x %x \"%63[^\"]",
    138                 &mtdnum, &mtdsize, &mtderasesize, mtdname);
    139         /* This will fail on the first line, which just contains
    140          * column headers.
    141          */
    142         if (matches == 4) {
    143             MtdPartition *p = &g_mtd_state.partitions[mtdnum];
    144             p->device_index = mtdnum;
    145             p->size = mtdsize;
    146             p->erase_size = mtderasesize;
    147             p->name = strdup(mtdname);
    148             if (p->name == NULL) {
    149                 errno = ENOMEM;
    150                 goto bail;
    151             }
    152             g_mtd_state.partition_count++;
    153         }
    154 
    155         /* Eat the line.
    156          */
    157         while (nbytes > 0 && *bufp != '\n') {
    158             bufp++;
    159             nbytes--;
    160         }
    161         if (nbytes > 0) {
    162             bufp++;
    163             nbytes--;
    164         }
    165     }
    166 
    167     return g_mtd_state.partition_count;
    168 
    169 bail:
    170     // keep "partitions" around so we can free the names on a rescan.
    171     g_mtd_state.partition_count = -1;
    172     return -1;
    173 }
    174 
    175 const MtdPartition *
    176 mtd_find_partition_by_name(const char *name)
    177 {
    178     if (g_mtd_state.partitions != NULL) {
    179         int i;
    180         for (i = 0; i < g_mtd_state.partitions_allocd; i++) {
    181             MtdPartition *p = &g_mtd_state.partitions[i];
    182             if (p->device_index >= 0 && p->name != NULL) {
    183                 if (strcmp(p->name, name) == 0) {
    184                     return p;
    185                 }
    186             }
    187         }
    188     }
    189     return NULL;
    190 }
    191 
    192 int
    193 mtd_mount_partition(const MtdPartition *partition, const char *mount_point,
    194         const char *filesystem, int read_only)
    195 {
    196     const unsigned long flags = MS_NOATIME | MS_NODEV | MS_NODIRATIME;
    197     char devname[64];
    198     int rv = -1;
    199 
    200     sprintf(devname, "/dev/block/mtdblock%d", partition->device_index);
    201     if (!read_only) {
    202         rv = mount(devname, mount_point, filesystem, flags, NULL);
    203     }
    204     if (read_only || rv < 0) {
    205         rv = mount(devname, mount_point, filesystem, flags | MS_RDONLY, 0);
    206         if (rv < 0) {
    207             printf("Failed to mount %s on %s: %s\n",
    208                     devname, mount_point, strerror(errno));
    209         } else {
    210             printf("Mount %s on %s read-only\n", devname, mount_point);
    211         }
    212     }
    213 #if 1   //TODO: figure out why this is happening; remove include of stat.h
    214     if (rv >= 0) {
    215         /* For some reason, the x bits sometimes aren't set on the root
    216          * of mounted volumes.
    217          */
    218         struct stat st;
    219         rv = stat(mount_point, &st);
    220         if (rv < 0) {
    221             return rv;
    222         }
    223         mode_t new_mode = st.st_mode | S_IXUSR | S_IXGRP | S_IXOTH;
    224         if (new_mode != st.st_mode) {
    225 printf("Fixing execute permissions for %s\n", mount_point);
    226             rv = chmod(mount_point, new_mode);
    227             if (rv < 0) {
    228                 printf("Couldn't fix permissions for %s: %s\n",
    229                         mount_point, strerror(errno));
    230             }
    231         }
    232     }
    233 #endif
    234     return rv;
    235 }
    236 
    237 int
    238 mtd_partition_info(const MtdPartition *partition,
    239         size_t *total_size, size_t *erase_size, size_t *write_size)
    240 {
    241     char mtddevname[32];
    242     sprintf(mtddevname, "/dev/mtd/mtd%d", partition->device_index);
    243     int fd = open(mtddevname, O_RDONLY);
    244     if (fd < 0) return -1;
    245 
    246     struct mtd_info_user mtd_info;
    247     int ret = ioctl(fd, MEMGETINFO, &mtd_info);
    248     close(fd);
    249     if (ret < 0) return -1;
    250 
    251     if (total_size != NULL) *total_size = mtd_info.size;
    252     if (erase_size != NULL) *erase_size = mtd_info.erasesize;
    253     if (write_size != NULL) *write_size = mtd_info.writesize;
    254     return 0;
    255 }
    256 
    257 MtdReadContext *mtd_read_partition(const MtdPartition *partition)
    258 {
    259     MtdReadContext *ctx = (MtdReadContext*) malloc(sizeof(MtdReadContext));
    260     if (ctx == NULL) return NULL;
    261 
    262     ctx->buffer = malloc(partition->erase_size);
    263     if (ctx->buffer == NULL) {
    264         free(ctx);
    265         return NULL;
    266     }
    267 
    268     char mtddevname[32];
    269     sprintf(mtddevname, "/dev/mtd/mtd%d", partition->device_index);
    270     ctx->fd = open(mtddevname, O_RDONLY);
    271     if (ctx->fd < 0) {
    272         free(ctx->buffer);
    273         free(ctx);
    274         return NULL;
    275     }
    276 
    277     ctx->partition = partition;
    278     ctx->consumed = partition->erase_size;
    279     return ctx;
    280 }
    281 
    282 // Seeks to a location in the partition.  Don't mix with reads of
    283 // anything other than whole blocks; unpredictable things will result.
    284 void mtd_read_skip_to(const MtdReadContext* ctx, size_t offset) {
    285     lseek64(ctx->fd, offset, SEEK_SET);
    286 }
    287 
    288 static int read_block(const MtdPartition *partition, int fd, char *data)
    289 {
    290     struct mtd_ecc_stats before, after;
    291     if (ioctl(fd, ECCGETSTATS, &before)) {
    292         fprintf(stderr, "mtd: ECCGETSTATS error (%s)\n", strerror(errno));
    293         return -1;
    294     }
    295 
    296     loff_t pos = lseek64(fd, 0, SEEK_CUR);
    297 
    298     ssize_t size = partition->erase_size;
    299     int mgbb;
    300 
    301     while (pos + size <= (int) partition->size) {
    302         if (lseek64(fd, pos, SEEK_SET) != pos || read(fd, data, size) != size) {
    303             fprintf(stderr, "mtd: read error at 0x%08llx (%s)\n",
    304                     pos, strerror(errno));
    305         } else if (ioctl(fd, ECCGETSTATS, &after)) {
    306             fprintf(stderr, "mtd: ECCGETSTATS error (%s)\n", strerror(errno));
    307             return -1;
    308         } else if (after.failed != before.failed) {
    309             fprintf(stderr, "mtd: ECC errors (%d soft, %d hard) at 0x%08llx\n",
    310                     after.corrected - before.corrected,
    311                     after.failed - before.failed, pos);
    312             // copy the comparison baseline for the next read.
    313             memcpy(&before, &after, sizeof(struct mtd_ecc_stats));
    314         } else if ((mgbb = ioctl(fd, MEMGETBADBLOCK, &pos))) {
    315             fprintf(stderr,
    316                     "mtd: MEMGETBADBLOCK returned %d at 0x%08llx (errno=%d)\n",
    317                     mgbb, pos, errno);
    318         } else {
    319             return 0;  // Success!
    320         }
    321 
    322         pos += partition->erase_size;
    323     }
    324 
    325     errno = ENOSPC;
    326     return -1;
    327 }
    328 
    329 ssize_t mtd_read_data(MtdReadContext *ctx, char *data, size_t len)
    330 {
    331     size_t read = 0;
    332     while (read < len) {
    333         if (ctx->consumed < ctx->partition->erase_size) {
    334             size_t avail = ctx->partition->erase_size - ctx->consumed;
    335             size_t copy = len - read < avail ? len - read : avail;
    336             memcpy(data + read, ctx->buffer + ctx->consumed, copy);
    337             ctx->consumed += copy;
    338             read += copy;
    339         }
    340 
    341         // Read complete blocks directly into the user's buffer
    342         while (ctx->consumed == ctx->partition->erase_size &&
    343                len - read >= ctx->partition->erase_size) {
    344             if (read_block(ctx->partition, ctx->fd, data + read)) return -1;
    345             read += ctx->partition->erase_size;
    346         }
    347 
    348         if (read >= len) {
    349             return read;
    350         }
    351 
    352         // Read the next block into the buffer
    353         if (ctx->consumed == ctx->partition->erase_size && read < len) {
    354             if (read_block(ctx->partition, ctx->fd, ctx->buffer)) return -1;
    355             ctx->consumed = 0;
    356         }
    357     }
    358 
    359     return read;
    360 }
    361 
    362 void mtd_read_close(MtdReadContext *ctx)
    363 {
    364     close(ctx->fd);
    365     free(ctx->buffer);
    366     free(ctx);
    367 }
    368 
    369 MtdWriteContext *mtd_write_partition(const MtdPartition *partition)
    370 {
    371     MtdWriteContext *ctx = (MtdWriteContext*) malloc(sizeof(MtdWriteContext));
    372     if (ctx == NULL) return NULL;
    373 
    374     ctx->bad_block_offsets = NULL;
    375     ctx->bad_block_alloc = 0;
    376     ctx->bad_block_count = 0;
    377 
    378     ctx->buffer = malloc(partition->erase_size);
    379     if (ctx->buffer == NULL) {
    380         free(ctx);
    381         return NULL;
    382     }
    383 
    384     char mtddevname[32];
    385     sprintf(mtddevname, "/dev/mtd/mtd%d", partition->device_index);
    386     ctx->fd = open(mtddevname, O_RDWR);
    387     if (ctx->fd < 0) {
    388         free(ctx->buffer);
    389         free(ctx);
    390         return NULL;
    391     }
    392 
    393     ctx->partition = partition;
    394     ctx->stored = 0;
    395     return ctx;
    396 }
    397 
    398 static void add_bad_block_offset(MtdWriteContext *ctx, off_t pos) {
    399     if (ctx->bad_block_count + 1 > ctx->bad_block_alloc) {
    400         ctx->bad_block_alloc = (ctx->bad_block_alloc*2) + 1;
    401         ctx->bad_block_offsets = realloc(ctx->bad_block_offsets,
    402                                          ctx->bad_block_alloc * sizeof(off_t));
    403     }
    404     ctx->bad_block_offsets[ctx->bad_block_count++] = pos;
    405 }
    406 
    407 static int write_block(MtdWriteContext *ctx, const char *data)
    408 {
    409     const MtdPartition *partition = ctx->partition;
    410     int fd = ctx->fd;
    411 
    412     off_t pos = lseek(fd, 0, SEEK_CUR);
    413     if (pos == (off_t) -1) return 1;
    414 
    415     ssize_t size = partition->erase_size;
    416     while (pos + size <= (int) partition->size) {
    417         loff_t bpos = pos;
    418         int ret = ioctl(fd, MEMGETBADBLOCK, &bpos);
    419         if (ret != 0 && !(ret == -1 && errno == EOPNOTSUPP)) {
    420             add_bad_block_offset(ctx, pos);
    421             fprintf(stderr,
    422                     "mtd: not writing bad block at 0x%08lx (ret %d errno %d)\n",
    423                     pos, ret, errno);
    424             pos += partition->erase_size;
    425             continue;  // Don't try to erase known factory-bad blocks.
    426         }
    427 
    428         struct erase_info_user erase_info;
    429         erase_info.start = pos;
    430         erase_info.length = size;
    431         int retry;
    432         for (retry = 0; retry < 2; ++retry) {
    433             if (ioctl(fd, MEMERASE, &erase_info) < 0) {
    434                 fprintf(stderr, "mtd: erase failure at 0x%08lx (%s)\n",
    435                         pos, strerror(errno));
    436                 continue;
    437             }
    438             if (lseek(fd, pos, SEEK_SET) != pos ||
    439                 write(fd, data, size) != size) {
    440                 fprintf(stderr, "mtd: write error at 0x%08lx (%s)\n",
    441                         pos, strerror(errno));
    442             }
    443 
    444             char verify[size];
    445             if (lseek(fd, pos, SEEK_SET) != pos ||
    446                 read(fd, verify, size) != size) {
    447                 fprintf(stderr, "mtd: re-read error at 0x%08lx (%s)\n",
    448                         pos, strerror(errno));
    449                 continue;
    450             }
    451             if (memcmp(data, verify, size) != 0) {
    452                 fprintf(stderr, "mtd: verification error at 0x%08lx (%s)\n",
    453                         pos, strerror(errno));
    454                 continue;
    455             }
    456 
    457             if (retry > 0) {
    458                 fprintf(stderr, "mtd: wrote block after %d retries\n", retry);
    459             }
    460             fprintf(stderr, "mtd: successfully wrote block at %lx\n", pos);
    461             return 0;  // Success!
    462         }
    463 
    464         // Try to erase it once more as we give up on this block
    465         add_bad_block_offset(ctx, pos);
    466         fprintf(stderr, "mtd: skipping write block at 0x%08lx\n", pos);
    467         ioctl(fd, MEMERASE, &erase_info);
    468         pos += partition->erase_size;
    469     }
    470 
    471     // Ran out of space on the device
    472     errno = ENOSPC;
    473     return -1;
    474 }
    475 
    476 ssize_t mtd_write_data(MtdWriteContext *ctx, const char *data, size_t len)
    477 {
    478     size_t wrote = 0;
    479     while (wrote < len) {
    480         // Coalesce partial writes into complete blocks
    481         if (ctx->stored > 0 || len - wrote < ctx->partition->erase_size) {
    482             size_t avail = ctx->partition->erase_size - ctx->stored;
    483             size_t copy = len - wrote < avail ? len - wrote : avail;
    484             memcpy(ctx->buffer + ctx->stored, data + wrote, copy);
    485             ctx->stored += copy;
    486             wrote += copy;
    487         }
    488 
    489         // If a complete block was accumulated, write it
    490         if (ctx->stored == ctx->partition->erase_size) {
    491             if (write_block(ctx, ctx->buffer)) return -1;
    492             ctx->stored = 0;
    493         }
    494 
    495         // Write complete blocks directly from the user's buffer
    496         while (ctx->stored == 0 && len - wrote >= ctx->partition->erase_size) {
    497             if (write_block(ctx, data + wrote)) return -1;
    498             wrote += ctx->partition->erase_size;
    499         }
    500     }
    501 
    502     return wrote;
    503 }
    504 
    505 off_t mtd_erase_blocks(MtdWriteContext *ctx, int blocks)
    506 {
    507     // Zero-pad and write any pending data to get us to a block boundary
    508     if (ctx->stored > 0) {
    509         size_t zero = ctx->partition->erase_size - ctx->stored;
    510         memset(ctx->buffer + ctx->stored, 0, zero);
    511         if (write_block(ctx, ctx->buffer)) return -1;
    512         ctx->stored = 0;
    513     }
    514 
    515     off_t pos = lseek(ctx->fd, 0, SEEK_CUR);
    516     if ((off_t) pos == (off_t) -1) return pos;
    517 
    518     const int total = (ctx->partition->size - pos) / ctx->partition->erase_size;
    519     if (blocks < 0) blocks = total;
    520     if (blocks > total) {
    521         errno = ENOSPC;
    522         return -1;
    523     }
    524 
    525     // Erase the specified number of blocks
    526     while (blocks-- > 0) {
    527         loff_t bpos = pos;
    528         if (ioctl(ctx->fd, MEMGETBADBLOCK, &bpos) > 0) {
    529             fprintf(stderr, "mtd: not erasing bad block at 0x%08lx\n", pos);
    530             pos += ctx->partition->erase_size;
    531             continue;  // Don't try to erase known factory-bad blocks.
    532         }
    533 
    534         struct erase_info_user erase_info;
    535         erase_info.start = pos;
    536         erase_info.length = ctx->partition->erase_size;
    537         if (ioctl(ctx->fd, MEMERASE, &erase_info) < 0) {
    538             fprintf(stderr, "mtd: erase failure at 0x%08lx\n", pos);
    539         }
    540         pos += ctx->partition->erase_size;
    541     }
    542 
    543     return pos;
    544 }
    545 
    546 int mtd_write_close(MtdWriteContext *ctx)
    547 {
    548     int r = 0;
    549     // Make sure any pending data gets written
    550     if (mtd_erase_blocks(ctx, 0) == (off_t) -1) r = -1;
    551     if (close(ctx->fd)) r = -1;
    552     free(ctx->bad_block_offsets);
    553     free(ctx->buffer);
    554     free(ctx);
    555     return r;
    556 }
    557 
    558 /* Return the offset of the first good block at or after pos (which
    559  * might be pos itself).
    560  */
    561 off_t mtd_find_write_start(MtdWriteContext *ctx, off_t pos) {
    562     int i;
    563     for (i = 0; i < ctx->bad_block_count; ++i) {
    564         if (ctx->bad_block_offsets[i] == pos) {
    565             pos += ctx->partition->erase_size;
    566         } else if (ctx->bad_block_offsets[i] > pos) {
    567             return pos;
    568         }
    569     }
    570     return pos;
    571 }
    572