+int mtdsize = 0;
+int erasesize = 0;
+
+int mtd_open(const char *mtd)
+{
+ FILE *fp;
+ char dev[PATH_MAX];
+ int i;
+ int ret;
+ int flags = O_RDWR | O_SYNC;
+
+ if ((fp = fopen("/proc/mtd", "r"))) {
+ while (fgets(dev, sizeof(dev), fp)) {
+ if (sscanf(dev, "mtd%d:", &i) && strstr(dev, mtd)) {
+ snprintf(dev, sizeof(dev), "/dev/mtd/%d", i);
+ if ((ret=open(dev, flags))<0) {
+ snprintf(dev, sizeof(dev), "/dev/mtd%d", i);
+ ret=open(dev, flags);
+ }
+ fclose(fp);
+ return ret;
+ }
+ }
+ fclose(fp);
+ }
+
+ return open(mtd, flags);
+}
+
+int mtd_check_open(const char *mtd)
+{
+ struct mtd_info_user mtdInfo;
+ int fd;
+
+ fd = mtd_open(mtd);
+ if(fd < 0) {
+ fprintf(stderr, "Could not open mtd device: %s\n", mtd);
+ return 0;
+ }
+
+ if(ioctl(fd, MEMGETINFO, &mtdInfo)) {
+ fprintf(stderr, "Could not get MTD device info from %s\n", mtd);
+ close(fd);
+ return 0;
+ }
+ mtdsize = mtdInfo.size;
+ erasesize = mtdInfo.erasesize;
+
+ return fd;
+}
+
+int mtd_erase_block(int fd, int offset)
+{
+ struct erase_info_user mtdEraseInfo;
+
+ mtdEraseInfo.start = offset;
+ mtdEraseInfo.length = erasesize;
+ ioctl(fd, MEMUNLOCK, &mtdEraseInfo);
+ if (ioctl (fd, MEMERASE, &mtdEraseInfo) < 0) {
+ fprintf(stderr, "Erasing mtd failed.\n");
+ exit(1);
+ }
+}
+
+int mtd_write_buffer(int fd, char *buf, int offset, int length)
+{
+ lseek(fd, offset, SEEK_SET);
+ write(fd, buf, length);
+}
+