code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * (C) Copyright 2008 * Marvell Semiconductor <www.marvell.com> * Written-by: Prafulla Wadaskar <prafulla@marvell.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* Required to obtain the getline prototype from stdio.h */ #define _GNU_SOURCE #include "mkimage.h" #include <image.h> #include "kwbimage.h" /* * Supported commands for configuration file */ static table_entry_t kwbimage_cmds[] = { {CMD_BOOT_FROM, "BOOT_FROM", "boot command", }, {CMD_NAND_ECC_MODE, "NAND_ECC_MODE", "NAND mode", }, {CMD_NAND_PAGE_SIZE, "NAND_PAGE_SIZE", "NAND size", }, {CMD_SATA_PIO_MODE, "SATA_PIO_MODE", "SATA mode", }, {CMD_DDR_INIT_DELAY, "DDR_INIT_DELAY", "DDR init dly", }, {CMD_DATA, "DATA", "Reg Write Data", }, {CMD_INVALID, "", "", }, }; /* * Supported Boot options for configuration file */ static table_entry_t kwbimage_bootops[] = { {IBR_HDR_SPI_ID, "spi", "SPI Flash", }, {IBR_HDR_NAND_ID, "nand", "NAND Flash", }, {IBR_HDR_SATA_ID, "sata", "Sata port", }, {IBR_HDR_PEX_ID, "pex", "PCIe port", }, {IBR_HDR_UART_ID, "uart", "Serial port", }, {-1, "", "Invalid", }, }; /* * Supported NAND ecc options configuration file */ static table_entry_t kwbimage_eccmodes[] = { {IBR_HDR_ECC_DEFAULT, "default", "Default mode", }, {IBR_HDR_ECC_FORCED_HAMMING, "hamming", "Hamming mode", }, {IBR_HDR_ECC_FORCED_RS, "rs", "RS mode", }, {IBR_HDR_ECC_DISABLED, "disabled", "ECC Disabled", }, {-1, "", "", }, }; static struct kwb_header kwbimage_header; static int datacmd_cnt = 0; static char * fname = "Unknown"; static int lineno = -1; /* * Report Error if xflag is set in addition to default */ static int kwbimage_check_params (struct mkimage_params *params) { if (!strlen (params->imagename)) { printf ("Error:%s - Configuration file not specified, " "it is needed for kwbimage generation\n", params->cmdname); return CFG_INVALID; } return ((params->dflag && (params->fflag || params->lflag)) || (params->fflag && (params->dflag || params->lflag)) || (params->lflag && (params->dflag || params->fflag)) || (params->xflag) || !(strlen (params->imagename))); } static uint32_t check_get_hexval (char *token) { uint32_t hexval; if (!sscanf (token, "%x", &hexval)) { printf ("Error:%s[%d] - Invalid hex data(%s)\n", fname, lineno, token); exit (EXIT_FAILURE); } return hexval; } /* * Generates 8 bit checksum */ static uint8_t kwbimage_checksum8 (void *start, uint32_t len, uint8_t csum) { register uint8_t sum = csum; volatile uint8_t *p = (volatile uint8_t *)start; /* check len and return zero checksum if invalid */ if (!len) return 0; do { sum += *p; p++; } while (--len); return (sum); } /* * Generates 32 bit checksum */ static uint32_t kwbimage_checksum32 (uint32_t *start, uint32_t len, uint32_t csum) { register uint32_t sum = csum; volatile uint32_t *p = start; /* check len and return zero checksum if invalid */ if (!len) return 0; if (len % sizeof(uint32_t)) { printf ("Error:%s[%d] - length is not in multiple of %zu\n", __FUNCTION__, len, sizeof(uint32_t)); return 0; } do { sum += *p; p++; len -= sizeof(uint32_t); } while (len > 0); return (sum); } static void kwbimage_check_cfgdata (char *token, enum kwbimage_cmd cmdsw, struct kwb_header *kwbhdr) { bhr_t *mhdr = &kwbhdr->kwb_hdr; extbhr_t *exthdr = &kwbhdr->kwb_exthdr; int i; switch (cmdsw) { case CMD_BOOT_FROM: i = get_table_entry_id (kwbimage_bootops, "Kwbimage boot option", token); if (i < 0) goto INVL_DATA; mhdr->blockid = i; printf ("Preparing kirkwood boot image to boot " "from %s\n", token); break; case CMD_NAND_ECC_MODE: i = get_table_entry_id (kwbimage_eccmodes, "NAND ecc mode", token); if (i < 0) goto INVL_DATA; mhdr->nandeccmode = i; printf ("Nand ECC mode = %s\n", token); break; case CMD_NAND_PAGE_SIZE: mhdr->nandpagesize = (uint16_t) check_get_hexval (token); printf ("Nand page size = 0x%x\n", mhdr->nandpagesize); break; case CMD_SATA_PIO_MODE: mhdr->satapiomode = (uint8_t) check_get_hexval (token); printf ("Sata PIO mode = 0x%x\n", mhdr->satapiomode); break; case CMD_DDR_INIT_DELAY: mhdr->ddrinitdelay = (uint16_t) check_get_hexval (token); printf ("DDR init delay = %d msec\n", mhdr->ddrinitdelay); break; case CMD_DATA: exthdr->rcfg[datacmd_cnt].raddr = check_get_hexval (token); break; case CMD_INVALID: goto INVL_DATA; default: goto INVL_DATA; } return; INVL_DATA: printf ("Error:%s[%d] - Invalid data\n", fname, lineno); exit (EXIT_FAILURE); } /* * this function sets the kwbimage header by- * 1. Abstracting input command line arguments data * 2. parses the kwbimage configuration file and update extebded header data * 3. calculates header, extended header and image checksums */ static void kwdimage_set_ext_header (struct kwb_header *kwbhdr, char* name) { bhr_t *mhdr = &kwbhdr->kwb_hdr; extbhr_t *exthdr = &kwbhdr->kwb_exthdr; FILE *fd = NULL; int j; char *line = NULL; char * token, *saveptr1, *saveptr2; size_t len = 0; enum kwbimage_cmd cmd; fname = name; /* set dram register offset */ exthdr->dramregsoffs = (intptr_t)&exthdr->rcfg - (intptr_t)mhdr; if ((fd = fopen (name, "r")) == 0) { printf ("Error:%s - Can't open\n", fname); exit (EXIT_FAILURE); } /* Simple kwimage.cfg file parser */ lineno=0; while ((getline (&line, &len, fd)) > 0) { lineno++; token = strtok_r (line, "\r\n", &saveptr1); /* drop all lines with zero tokens (= empty lines) */ if (token == NULL) continue; for (j = 0, cmd = CMD_INVALID, line = token; ; line = NULL) { token = strtok_r (line, " \t", &saveptr2); if (token == NULL) break; /* Drop all text starting with '#' as comments */ if (token[0] == '#') break; /* Process rest as valid config command line */ switch (j) { case CFG_COMMAND: cmd = get_table_entry_id (kwbimage_cmds, "Kwbimage command", token); if (cmd == CMD_INVALID) goto INVL_CMD; break; case CFG_DATA0: kwbimage_check_cfgdata (token, cmd, kwbhdr); break; case CFG_DATA1: if (cmd != CMD_DATA) goto INVL_CMD; exthdr->rcfg[datacmd_cnt].rdata = check_get_hexval (token); if (datacmd_cnt > KWBIMAGE_MAX_CONFIG ) { printf ("Error:%s[%d] - Found more " "than max(%zd) allowed " "data configurations\n", fname, lineno, KWBIMAGE_MAX_CONFIG); exit (EXIT_FAILURE); } else datacmd_cnt++; break; default: goto INVL_CMD; } j++; } } if (line) free (line); fclose (fd); return; /* * Invalid Command error reporring * * command CMD_DATA needs three strings on a line * whereas other commands need only two. * * if more than two/three (as per command type) are observed, * then error will be reported */ INVL_CMD: printf ("Error:%s[%d] - Invalid command\n", fname, lineno); exit (EXIT_FAILURE); } static void kwbimage_set_header (void *ptr, struct stat *sbuf, int ifd, struct mkimage_params *params) { struct kwb_header *hdr = (struct kwb_header *)ptr; bhr_t *mhdr = &hdr->kwb_hdr; extbhr_t *exthdr = &hdr->kwb_exthdr; uint32_t checksum; int size; /* Build and add image checksum header */ checksum = kwbimage_checksum32 ((uint32_t *)ptr, sbuf->st_size, 0); size = write (ifd, &checksum, sizeof(uint32_t)); if (size != sizeof(uint32_t)) { printf ("Error:%s - Checksum write %d bytes %s\n", params->cmdname, size, params->imagefile); exit (EXIT_FAILURE); } sbuf->st_size += sizeof(uint32_t); mhdr->blocksize = sbuf->st_size - sizeof(struct kwb_header); mhdr->srcaddr = sizeof(struct kwb_header); mhdr->destaddr= params->addr; mhdr->execaddr =params->ep; mhdr->ext = 0x1; /* header extension appended */ kwdimage_set_ext_header (hdr, params->imagename); /* calculate checksums */ mhdr->checkSum = kwbimage_checksum8 ((void *)mhdr, sizeof(bhr_t), 0); exthdr->checkSum = kwbimage_checksum8 ((void *)exthdr, sizeof(extbhr_t), 0); } static int kwbimage_verify_header (unsigned char *ptr, int image_size, struct mkimage_params *params) { struct kwb_header *hdr = (struct kwb_header *)ptr; bhr_t *mhdr = &hdr->kwb_hdr; extbhr_t *exthdr = &hdr->kwb_exthdr; uint8_t calc_hdrcsum; uint8_t calc_exthdrcsum; calc_hdrcsum = kwbimage_checksum8 ((void *)mhdr, sizeof(bhr_t) - sizeof(uint8_t), 0); if (calc_hdrcsum != mhdr->checkSum) return -FDT_ERR_BADSTRUCTURE; /* mhdr csum not matched */ calc_exthdrcsum = kwbimage_checksum8 ((void *)exthdr, sizeof(extbhr_t) - sizeof(uint8_t), 0); if (calc_exthdrcsum != exthdr->checkSum) return -FDT_ERR_BADSTRUCTURE; /* exthdr csum not matched */ return 0; } static void kwbimage_print_header (const void *ptr) { struct kwb_header *hdr = (struct kwb_header *) ptr; bhr_t *mhdr = &hdr->kwb_hdr; char *name = get_table_entry_name (kwbimage_bootops, "Kwbimage boot option", (int) mhdr->blockid); printf ("Image Type: Kirkwood Boot from %s Image\n", name); printf ("Data Size: "); genimg_print_size (mhdr->blocksize - sizeof(uint32_t)); printf ("Load Address: %08x\n", mhdr->destaddr); printf ("Entry Point: %08x\n", mhdr->execaddr); } static int kwbimage_check_image_types (uint8_t type) { if (type == IH_TYPE_KWBIMAGE) return EXIT_SUCCESS; else return EXIT_FAILURE; } /* * kwbimage type parameters definition */ static struct image_type_params kwbimage_params = { .name = "Kirkwood Boot Image support", .header_size = sizeof(struct kwb_header), .hdr = (void*)&kwbimage_header, .check_image_type = kwbimage_check_image_types, .verify_header = kwbimage_verify_header, .print_header = kwbimage_print_header, .set_header = kwbimage_set_header, .check_params = kwbimage_check_params, }; void init_kwb_image_type (void) { mkimage_register (&kwbimage_params); }
1001-study-uboot
tools/kwbimage.c
C
gpl3
10,585
/* getline.c -- Replacement for GNU C library function getline Copyright (C) 1993, 1996, 2001, 2002 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Written by Jan Brittenson, bson@gnu.ai.mit.edu. */ #include <assert.h> #include <stdio.h> /* Always add at least this many bytes when extending the buffer. */ #define MIN_CHUNK 64 /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from malloc (or NULL), pointing to *N characters of space. It is realloc'd as necessary. Return the number of characters read (not including the null terminator), or -1 on error or EOF. NOTE: There is another getstr() function declared in <curses.h>. */ static int getstr(char **lineptr, size_t *n, FILE *stream, char terminator, size_t offset) { int nchars_avail; /* Allocated but unused chars in *LINEPTR. */ char *read_pos; /* Where we're reading into *LINEPTR. */ int ret; if (!lineptr || !n || !stream) return -1; if (!*lineptr) { *n = MIN_CHUNK; *lineptr = malloc(*n); if (!*lineptr) return -1; } nchars_avail = *n - offset; read_pos = *lineptr + offset; for (;;) { register int c = getc(stream); /* We always want at least one char left in the buffer, since we always (unless we get an error while reading the first char) NUL-terminate the line buffer. */ assert(*n - nchars_avail == read_pos - *lineptr); if (nchars_avail < 2) { if (*n > MIN_CHUNK) *n *= 2; else *n += MIN_CHUNK; nchars_avail = *n + *lineptr - read_pos; *lineptr = realloc(*lineptr, *n); if (!*lineptr) return -1; read_pos = *n - nchars_avail + *lineptr; assert(*n - nchars_avail == read_pos - *lineptr); } if (c == EOF || ferror (stream)) { /* Return partial line, if any. */ if (read_pos == *lineptr) return -1; else break; } *read_pos++ = c; nchars_avail--; if (c == terminator) /* Return the line. */ break; } /* Done - NUL terminate and return the number of chars read. */ *read_pos = '\0'; ret = read_pos - (*lineptr + offset); return ret; } int getline (char **lineptr, size_t *n, FILE *stream) { return getstr(lineptr, n, stream, '\n', 0); }
1001-study-uboot
tools/getline.c
C
gpl3
2,914
#!/bin/sh usage() { ( echo "Usage: $0 <board IP> [board port]" echo "" echo "If port is not specified, '6666' will be used" [ -z "$*" ] && exit 0 echo "" echo "ERROR: $*" exit 1 ) 1>&2 exit $? } while [ -n "$1" ] ; do case $1 in -h|--help) usage;; --) break;; -*) usage "Invalid option $1";; *) break;; esac shift done ip=$1 port=${2:-6666} if [ -z "${ip}" ] || [ -n "$3" ] ; then usage "Invalid number of arguments" fi for nc in netcat nc ; do type ${nc} >/dev/null 2>&1 && break done trap "stty icanon echo intr ^C" 0 2 3 5 10 13 15 echo "NOTE: the interrupt signal (normally ^C) has been remapped to ^T" stty -icanon -echo intr ^T ( if type ncb 2>/dev/null ; then # see if ncb is in $PATH exec ncb ${port} elif [ -x ${0%/*}/ncb ] ; then # maybe it's in the same dir as the netconsole script exec ${0%/*}/ncb ${port} else # blah, just use regular netcat while ${nc} -u -l -p ${port} < /dev/null ; do : done fi ) & pid=$! ${nc} -u ${ip} ${port} kill ${pid} 2>/dev/null
1001-study-uboot
tools/netconsole
Shell
gpl3
1,033
# # (C) Copyright 2000-2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # TOOLSUBDIRS = # # Include this after HOSTOS HOSTARCH check # so that we can act intelligently. # include $(TOPDIR)/config.mk # # toolchains targeting win32 generate .exe files # ifneq (,$(findstring WIN32 ,$(shell $(HOSTCC) -E -dM -xc /dev/null))) SFX = .exe else SFX = endif # Enable all the config-independent tools ifneq ($(HOST_TOOLS_ALL),) CONFIG_LCD_LOGO = y CONFIG_CMD_LOADS = y CONFIG_CMD_NET = y CONFIG_XWAY_SWAP_BYTES = y CONFIG_NETCONSOLE = y CONFIG_SHA1_CHECK_UB_IMG = y endif # Merge all the different vars for envcrc into one ENVCRC-$(CONFIG_ENV_IS_EMBEDDED) = y ENVCRC-$(CONFIG_ENV_IS_IN_DATAFLASH) = y ENVCRC-$(CONFIG_ENV_IS_IN_EEPROM) = y ENVCRC-$(CONFIG_ENV_IS_IN_FLASH) = y ENVCRC-$(CONFIG_ENV_IS_IN_ONENAND) = y ENVCRC-$(CONFIG_ENV_IS_IN_NAND) = y ENVCRC-$(CONFIG_ENV_IS_IN_NVRAM) = y ENVCRC-$(CONFIG_ENV_IS_IN_SPI_FLASH) = y CONFIG_BUILD_ENVCRC ?= $(ENVCRC-y) # Generated executable files BIN_FILES-$(CONFIG_LCD_LOGO) += bmp_logo$(SFX) BIN_FILES-$(CONFIG_VIDEO_LOGO) += bmp_logo$(SFX) BIN_FILES-$(CONFIG_BUILD_ENVCRC) += envcrc$(SFX) BIN_FILES-$(CONFIG_CMD_NET) += gen_eth_addr$(SFX) BIN_FILES-$(CONFIG_CMD_LOADS) += img2srec$(SFX) BIN_FILES-$(CONFIG_XWAY_SWAP_BYTES) += xway-swap-bytes$(SFX) BIN_FILES-y += mkenvimage$(SFX) BIN_FILES-y += mkimage$(SFX) BIN_FILES-$(CONFIG_MX28) += mxsboot$(SFX) BIN_FILES-$(CONFIG_NETCONSOLE) += ncb$(SFX) BIN_FILES-$(CONFIG_SHA1_CHECK_UB_IMG) += ubsha1$(SFX) # Source files which exist outside the tools directory EXT_OBJ_FILES-$(CONFIG_BUILD_ENVCRC) += common/env_embedded.o EXT_OBJ_FILES-y += common/image.o EXT_OBJ_FILES-y += lib/crc32.o EXT_OBJ_FILES-y += lib/md5.o EXT_OBJ_FILES-y += lib/sha1.o # Source files located in the tools directory OBJ_FILES-$(CONFIG_LCD_LOGO) += bmp_logo.o OBJ_FILES-$(CONFIG_VIDEO_LOGO) += bmp_logo.o NOPED_OBJ_FILES-y += default_image.o OBJ_FILES-$(CONFIG_BUILD_ENVCRC) += envcrc.o NOPED_OBJ_FILES-y += fit_image.o OBJ_FILES-$(CONFIG_CMD_NET) += gen_eth_addr.o OBJ_FILES-$(CONFIG_CMD_LOADS) += img2srec.o OBJ_FILES-$(CONFIG_XWAY_SWAP_BYTES) += xway-swap-bytes.o NOPED_OBJ_FILES-y += aisimage.o NOPED_OBJ_FILES-y += kwbimage.o NOPED_OBJ_FILES-y += imximage.o NOPED_OBJ_FILES-y += omapimage.o NOPED_OBJ_FILES-y += mkenvimage.o NOPED_OBJ_FILES-y += mkimage.o OBJ_FILES-$(CONFIG_MX28) += mxsboot.o OBJ_FILES-$(CONFIG_NETCONSOLE) += ncb.o NOPED_OBJ_FILES-y += os_support.o OBJ_FILES-$(CONFIG_SHA1_CHECK_UB_IMG) += ubsha1.o NOPED_OBJ_FILES-y += ublimage.o # Don't build by default #ifeq ($(ARCH),ppc) #BIN_FILES-y += mpc86x_clk$(SFX) #OBJ_FILES-y += mpc86x_clk.o #endif # Flattened device tree objects LIBFDT_OBJ_FILES-y += fdt.o LIBFDT_OBJ_FILES-y += fdt_ro.o LIBFDT_OBJ_FILES-y += fdt_rw.o LIBFDT_OBJ_FILES-y += fdt_strerror.o LIBFDT_OBJ_FILES-y += fdt_wip.o # Generated LCD/video logo LOGO_H = $(OBJTREE)/include/bmp_logo.h LOGO_DATA_H = $(OBJTREE)/include/bmp_logo_data.h LOGO-$(CONFIG_LCD_LOGO) += $(LOGO_H) LOGO-$(CONFIG_LCD_LOGO) += $(LOGO_DATA_H) LOGO-$(CONFIG_VIDEO_LOGO) += $(LOGO_H) LOGO-$(CONFIG_VIDEO_LOGO) += $(LOGO_DATA_H) ifeq ($(LOGO_BMP),) LOGO_BMP= logos/denx.bmp endif ifeq ($(VENDOR),atmel) LOGO_BMP= logos/atmel.bmp endif ifeq ($(VENDOR),esd) LOGO_BMP= logos/esd.bmp endif ifeq ($(VENDOR),freescale) LOGO_BMP= logos/freescale.bmp endif ifeq ($(VENDOR),ronetix) LOGO_BMP= logos/ronetix.bmp endif ifeq ($(VENDOR),syteco) LOGO_BMP= logos/syteco.bmp endif ifeq ($(VENDOR),intercontrol) LOGO_BMP= logos/intercontrol.bmp endif # now $(obj) is defined HOSTSRCS += $(addprefix $(SRCTREE)/,$(EXT_OBJ_FILES-y:.o=.c)) HOSTSRCS += $(addprefix $(SRCTREE)/tools/,$(OBJ_FILES-y:.o=.c)) HOSTSRCS += $(addprefix $(SRCTREE)/lib/libfdt/,$(LIBFDT_OBJ_FILES-y:.o=.c)) BINS := $(addprefix $(obj),$(sort $(BIN_FILES-y))) LIBFDT_OBJS := $(addprefix $(obj),$(LIBFDT_OBJ_FILES-y)) HOSTOBJS := $(addprefix $(obj),$(OBJ_FILES-y)) NOPEDOBJS := $(addprefix $(obj),$(NOPED_OBJ_FILES-y)) # # Use native tools and options # Define __KERNEL_STRICT_NAMES to prevent typedef overlaps # HOSTCPPFLAGS = -idirafter $(SRCTREE)/include \ -idirafter $(OBJTREE)/include2 \ -idirafter $(OBJTREE)/include \ -I $(SRCTREE)/lib/libfdt \ -I $(SRCTREE)/tools \ -DCONFIG_SYS_TEXT_BASE=$(CONFIG_SYS_TEXT_BASE) \ -DUSE_HOSTCC \ -D__KERNEL_STRICT_NAMES all: $(obj).depend $(BINS) $(LOGO-y) subdirs $(obj)bin2header$(SFX): $(obj)bin2header.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)bmp_logo$(SFX): $(obj)bmp_logo.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)envcrc$(SFX): $(obj)crc32.o $(obj)env_embedded.o $(obj)envcrc.o $(obj)sha1.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(obj)gen_eth_addr$(SFX): $(obj)gen_eth_addr.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)img2srec$(SFX): $(obj)img2srec.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)xway-swap-bytes$(SFX): $(obj)xway-swap-bytes.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)mkenvimage$(SFX): $(obj)crc32.o $(obj)mkenvimage.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(obj)mkimage$(SFX): $(obj)aisimage.o \ $(obj)crc32.o \ $(obj)default_image.o \ $(obj)fit_image.o \ $(obj)image.o \ $(obj)imximage.o \ $(obj)kwbimage.o \ $(obj)md5.o \ $(obj)mkimage.o \ $(obj)os_support.o \ $(obj)omapimage.o \ $(obj)sha1.o \ $(obj)ublimage.o \ $(LIBFDT_OBJS) $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)mpc86x_clk$(SFX): $(obj)mpc86x_clk.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)mxsboot$(SFX): $(obj)mxsboot.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)ncb$(SFX): $(obj)ncb.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(HOSTSTRIP) $@ $(obj)ubsha1$(SFX): $(obj)os_support.o $(obj)sha1.o $(obj)ubsha1.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ # Some of the tool objects need to be accessed from outside the tools directory $(obj)%.o: $(SRCTREE)/common/%.c $(HOSTCC) -g $(HOSTCFLAGS_NOPED) -c -o $@ $< $(obj)%.o: $(SRCTREE)/lib/%.c $(HOSTCC) -g $(HOSTCFLAGS) -c -o $@ $< $(obj)%.o: $(SRCTREE)/lib/libfdt/%.c $(HOSTCC) -g $(HOSTCFLAGS_NOPED) -c -o $@ $< subdirs: ifeq ($(TOOLSUBDIRS),) @: else @for dir in $(TOOLSUBDIRS) ; do \ $(MAKE) \ HOSTOS=$(HOSTOS) \ HOSTARCH=$(HOSTARCH) \ -C $$dir || exit 1 ; \ done endif $(LOGO_H): $(obj)bmp_logo $(LOGO_BMP) $(obj)./bmp_logo --gen-info $(LOGO_BMP) > $@ $(LOGO_DATA_H): $(obj)bmp_logo $(LOGO_BMP) $(obj)./bmp_logo --gen-data $(LOGO_BMP) > $@ ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
tools/Makefile
Makefile
gpl3
7,655
# # Sed script to parse CPP macros and generate output usable by make # # It is expected that this script is fed the output of 'gpp -dM' # which preprocesses the common.h header files and outputs the final # list of CPP macros (and whitespace is sanitized) # # Only process values prefixed with #define CONFIG_ /^#define CONFIG_[A-Za-z0-9_][A-Za-z0-9_]*/ { # Strip the #define prefix s/#define *//; # Change to form CONFIG_*=VALUE s/ */=/; # Drop trailing spaces s/ *$//; # drop quotes around string values s/="\(.*\)"$/=\1/; # Concatenate string values s/" *"//g; # Assume strings as default - add quotes around values s/=\(..*\)/="\1"/; # but remove again from decimal numbers s/="\([0-9][0-9]*\)"/=\1/; # ... and from hex numbers s/="\(0[Xx][0-9a-fA-F][0-9a-fA-F]*\)"/=\1/; # Change '1' and empty values to "y" (not perfect, but # supports conditional compilation in the makefiles s/=$/=y/; s/=1$/=y/; # print the line p }
1001-study-uboot
tools/scripts/define2mk.sed
sed
gpl3
950
#!/bin/sh # Adapted from Linux kernel's "Kbuild": # commit 1cdf25d704f7951d02a04064c97db547d6021872 # Author: Christoph Lameter <clameter@sgi.com> mkdir -p $(dirname $2) # Default sed regexp - multiline due to syntax constraints SED_CMD="/^->/{s:->#\(.*\):/* \1 */:; \ s:^->\([^ ]*\) [\$#]*\([-0-9]*\) \(.*\):#define \1 (\2) /* \3 */:; \ s:^->\([^ ]*\) [\$#]*\([^ ]*\) \(.*\):#define \1 \2 /* \3 */:; \ s:->::; p;}" (set -e echo "#ifndef __ASM_OFFSETS_H__" echo "#define __ASM_OFFSETS_H__" echo "/*" echo " * DO NOT MODIFY." echo " *" echo " * This file was generated by $(basename $0)" echo " *" echo " */" echo "" sed -ne "${SED_CMD}" $1 echo "" echo "#endif" ) > $2
1001-study-uboot
tools/scripts/make-asm-offsets
Shell
gpl3
689
/* * (C) Copyright 2000 * Murray Jensen <Murray.Jensen@csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "serial.h" #include "error.h" #include "remote.h" char *serialdev = "/dev/term/b"; speed_t speed = B230400; int verbose = 0; int main(int ac, char **av) { int c, sfd; if ((pname = strrchr(av[0], '/')) == NULL) pname = av[0]; else pname++; while ((c = getopt(ac, av, "b:p:v")) != EOF) switch (c) { case 'b': if ((speed = cvtspeed(optarg)) == B0) Error("can't decode baud rate specified in -b option"); break; case 'p': serialdev = optarg; break; case 'v': verbose = 1; break; default: usage: fprintf(stderr, "Usage: %s [-b bps] [-p dev] [-v]\n", pname); exit(1); } if (optind != ac) goto usage; if (verbose) fprintf(stderr, "Opening serial port and sending continue...\n"); if ((sfd = serialopen(serialdev, speed)) < 0) Perror("open of serial device '%s' failed", serialdev); remote_desc = sfd; remote_reset(); remote_continue(); if (serialclose(sfd) < 0) Perror("close of serial device '%s' failed", serialdev); if (verbose) fprintf(stderr, "Done.\n"); return (0); }
1001-study-uboot
tools/gdb/gdbcont.c
C
gpl3
2,044
/* * (C) Copyright 2000 * Murray Jensen <Murray.Jensen@csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/time.h> #include "serial.h" #if defined(__sun__) || \ defined(__OpenBSD__) || \ defined(__FreeBSD__) || \ defined(__NetBSD__) || \ defined(__APPLE__) static struct termios tios = { BRKINT, 0, B115200|CS8|CREAD, 0, { 0 } }; #else static struct termios tios = { BRKINT, 0, B115200|CS8|CREAD, 0, 0 }; #endif static struct speedmap { char *str; speed_t val; } speedmap[] = { { "50", B50 }, { "75", B75 }, { "110", B110 }, { "134", B134 }, { "150", B150 }, { "200", B200 }, { "300", B300 }, { "600", B600 }, { "1200", B1200 }, { "1800", B1800 }, { "2400", B2400 }, { "4800", B4800 }, { "9600", B9600 }, { "19200", B19200 }, { "38400", B38400 }, { "57600", B57600 }, #ifdef B76800 { "76800", B76800 }, #endif { "115200", B115200 }, #ifdef B153600 { "153600", B153600 }, #endif { "230400", B230400 }, #ifdef B307200 { "307200", B307200 }, #endif #ifdef B460800 { "460800", B460800 } #endif }; static int nspeeds = sizeof speedmap / sizeof speedmap[0]; speed_t cvtspeed(char *str) { struct speedmap *smp = speedmap, *esmp = &speedmap[nspeeds]; while (smp < esmp) { if (strcmp(str, smp->str) == 0) return (smp->val); smp++; } return B0; } int serialopen(char *device, speed_t speed) { int fd; if (cfsetospeed(&tios, speed) < 0) return -1; if ((fd = open(device, O_RDWR)) < 0) return -1; if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) { (void)close(fd); return -1; } return fd; } int serialreadchar(int fd, int timeout) { fd_set fds; struct timeval tv; int n; char ch; tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(fd, &fds); /* this is a fucking horrible quick hack - fix this */ if ((n = select(fd + 1, &fds, 0, 0, &tv)) < 0) return SERIAL_ERROR; if (n == 0) return SERIAL_TIMEOUT; if ((n = read(fd, &ch, 1)) < 0) return SERIAL_ERROR; if (n == 0) return SERIAL_EOF; return ch; } int serialwrite(int fd, char *buf, int len) { int n; do { n = write(fd, buf, len); if (n < 0) return 1; len -= n; buf += n; } while (len > 0); return 0; } int serialclose(int fd) { return close(fd); }
1001-study-uboot
tools/gdb/serial.c
C
gpl3
3,164
/* * (C) Copyright 2000 * Murray Jensen <Murray.Jensen@csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "error.h" char *pname; void Warning(char *fmt, ...) { va_list args; fprintf(stderr, "%s: WARNING: ", pname); va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, "\n"); } void Error(char *fmt, ...) { va_list args; fprintf(stderr, "%s: ERROR: ", pname); va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, "\n"); exit(1); } void Perror(char *fmt, ...) { va_list args; int e = errno; char *p; fprintf(stderr, "%s: ERROR: ", pname); va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); if ((p = strerror(e)) == NULL || *p == '\0') fprintf(stderr, ": Unknown Error (%d)\n", e); else fprintf(stderr, ": %s\n", p); exit(1); }
1001-study-uboot
tools/gdb/error.c
C
gpl3
1,749
/* * taken from gdb/remote.c * * I am only interested in the write to memory stuff - everything else * has been ripped out * * all the copyright notices etc have been left in */ /* enough so that it will compile */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> /*nicked from gcc..*/ #ifndef alloca #ifdef __GNUC__ #define alloca __builtin_alloca #else /* not GNU C. */ #if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi) #include <alloca.h> #else /* not sparc */ #if defined (MSDOS) && !defined (__TURBOC__) #include <malloc.h> #else /* not MSDOS, or __TURBOC__ */ #if defined(_AIX) #include <malloc.h> #pragma alloca #else /* not MSDOS, __TURBOC__, or _AIX */ #ifdef __hpux #endif /* __hpux */ #endif /* not _AIX */ #endif /* not MSDOS, or __TURBOC__ */ #endif /* not sparc. */ #endif /* not GNU C. */ #ifdef __cplusplus extern "C" { #endif void* alloca(size_t); #ifdef __cplusplus } #endif #endif /* alloca not defined. */ #include "serial.h" #include "error.h" #include "remote.h" #define REGISTER_BYTES 0 #define fprintf_unfiltered fprintf #define fprintf_filtered fprintf #define fputs_unfiltered fputs #define fputs_filtered fputs #define fputc_unfiltered fputc #define fputc_filtered fputc #define printf_unfiltered printf #define printf_filtered printf #define puts_unfiltered puts #define puts_filtered puts #define putchar_unfiltered putchar #define putchar_filtered putchar #define fputstr_unfiltered(a,b,c) fputs((a), (c)) #define gdb_stdlog stderr #define SERIAL_READCHAR(fd,timo) serialreadchar((fd), (timo)) #define SERIAL_WRITE(fd, addr, len) serialwrite((fd), (addr), (len)) #define error Error #define perror_with_name Perror #define gdb_flush fflush #define max(a,b) (((a)>(b))?(a):(b)) #define min(a,b) (((a)<(b))?(a):(b)) #define target_mourn_inferior() {} #define ULONGEST unsigned long #define CORE_ADDR unsigned long static int putpkt (char *); static int putpkt_binary(char *, int); static void getpkt (char *, int); static int remote_debug = 0, remote_register_buf_size = 0, watchdog = 0; int remote_desc = -1, remote_timeout = 10; static void fputstrn_unfiltered(char *s, int n, int x, FILE *fp) { while (n-- > 0) fputc(*s++, fp); } void remote_reset(void) { SERIAL_WRITE(remote_desc, "+", 1); } void remote_continue(void) { putpkt("c"); } /* Remote target communications for serial-line targets in custom GDB protocol Copyright 1988, 91, 92, 93, 94, 95, 96, 97, 98, 1999 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* *INDENT-OFF* */ /* Remote communication protocol. A debug packet whose contents are <data> is encapsulated for transmission in the form: $ <data> # CSUM1 CSUM2 <data> must be ASCII alphanumeric and cannot include characters '$' or '#'. If <data> starts with two characters followed by ':', then the existing stubs interpret this as a sequence number. CSUM1 and CSUM2 are ascii hex representation of an 8-bit checksum of <data>, the most significant nibble is sent first. the hex digits 0-9,a-f are used. Receiver responds with: + - if CSUM is correct and ready for next packet - - if CSUM is incorrect <data> is as follows: Most values are encoded in ascii hex digits. Signal numbers are according to the numbering in target.h. Request Packet set thread Hct... Set thread for subsequent operations. c = 'c' for thread used in step and continue; t... can be -1 for all threads. c = 'g' for thread used in other operations. If zero, pick a thread, any thread. reply OK for success ENN for an error. read registers g reply XX....X Each byte of register data is described by two hex digits. Registers are in the internal order for GDB, and the bytes in a register are in the same order the machine uses. or ENN for an error. write regs GXX..XX Each byte of register data is described by two hex digits. reply OK for success ENN for an error write reg Pn...=r... Write register n... with value r..., which contains two hex digits for each byte in the register (target byte order). reply OK for success ENN for an error (not supported by all stubs). read mem mAA..AA,LLLL AA..AA is address, LLLL is length. reply XX..XX XX..XX is mem contents Can be fewer bytes than requested if able to read only part of the data. or ENN NN is errno write mem MAA..AA,LLLL:XX..XX AA..AA is address, LLLL is number of bytes, XX..XX is data reply OK for success ENN for an error (this includes the case where only part of the data was written). write mem XAA..AA,LLLL:XX..XX (binary) AA..AA is address, LLLL is number of bytes, XX..XX is binary data reply OK for success ENN for an error continue cAA..AA AA..AA is address to resume If AA..AA is omitted, resume at same address. step sAA..AA AA..AA is address to resume If AA..AA is omitted, resume at same address. continue with Csig;AA..AA Continue with signal sig (hex signal signal number). If ;AA..AA is omitted, resume at same address. step with Ssig;AA..AA Like 'C' but step not continue. signal last signal ? Reply the current reason for stopping. This is the same reply as is generated for step or cont : SAA where AA is the signal number. detach D Reply OK. There is no immediate reply to step or cont. The reply comes when the machine stops. It is SAA AA is the signal number. or... TAAn...:r...;n...:r...;n...:r...; AA = signal number n... = register number (hex) r... = register contents n... = `thread' r... = thread process ID. This is a hex integer. n... = other string not starting with valid hex digit. gdb should ignore this n,r pair and go on to the next. This way we can extend the protocol. or... WAA The process exited, and AA is the exit status. This is only applicable for certains sorts of targets. or... XAA The process terminated with signal AA. or (obsolete) NAA;tttttttt;dddddddd;bbbbbbbb AA = signal number tttttttt = address of symbol "_start" dddddddd = base of data section bbbbbbbb = base of bss section. Note: only used by Cisco Systems targets. The difference between this reply and the "qOffsets" query is that the 'N' packet may arrive spontaneously whereas the 'qOffsets' is a query initiated by the host debugger. or... OXX..XX XX..XX is hex encoding of ASCII data. This can happen at any time while the program is running and the debugger should continue to wait for 'W', 'T', etc. thread alive TXX Find out if the thread XX is alive. reply OK thread is still alive ENN thread is dead remote restart RXX Restart the remote server extended ops ! Use the extended remote protocol. Sticky -- only needs to be set once. kill request k toggle debug d toggle debug flag (see 386 & 68k stubs) reset r reset -- see sparc stub. reserved <other> On other requests, the stub should ignore the request and send an empty response ($#<checksum>). This way we can extend the protocol and GDB can tell whether the stub it is talking to uses the old or the new. search tAA:PP,MM Search backwards starting at address AA for a match with pattern PP and mask MM. PP and MM are 4 bytes. Not supported by all stubs. general query qXXXX Request info about XXXX. general set QXXXX=yyyy Set value of XXXX to yyyy. query sect offs qOffsets Get section offsets. Reply is Text=xxx;Data=yyy;Bss=zzz Responses can be run-length encoded to save space. A '*' means that the next character is an ASCII encoding giving a repeat count which stands for that many repititions of the character preceding the '*'. The encoding is n+29, yielding a printable character where n >=3 (which is where rle starts to win). Don't use an n > 126. So "0* " means the same as "0000". */ /* *INDENT-ON* */ /* This variable (available to the user via "set remotebinarydownload") dictates whether downloads are sent in binary (via the 'X' packet). We assume that the stub can, and attempt to do it. This will be cleared if the stub does not understand it. This switch is still needed, though in cases when the packet is supported in the stub, but the connection does not allow it (i.e., 7-bit serial connection only). */ static int remote_binary_download = 1; /* Have we already checked whether binary downloads work? */ static int remote_binary_checked; /* Maximum number of bytes to read/write at once. The value here is chosen to fill up a packet (the headers account for the 32). */ #define MAXBUFBYTES(N) (((N)-32)/2) /* Having this larger than 400 causes us to be incompatible with m68k-stub.c and i386-stub.c. Normally, no one would notice because it only matters for writing large chunks of memory (e.g. in downloads). Also, this needs to be more than 400 if required to hold the registers (see below, where we round it up based on REGISTER_BYTES). */ /* Round up PBUFSIZ to hold all the registers, at least. */ #define PBUFSIZ ((REGISTER_BYTES > MAXBUFBYTES (400)) \ ? (REGISTER_BYTES * 2 + 32) \ : 400) /* This variable sets the number of bytes to be written to the target in a single packet. Normally PBUFSIZ is satisfactory, but some targets need smaller values (perhaps because the receiving end is slow). */ static int remote_write_size = 0x7fffffff; /* This variable sets the number of bits in an address that are to be sent in a memory ("M" or "m") packet. Normally, after stripping leading zeros, the entire address would be sent. This variable restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The initial implementation of remote.c restricted the address sent in memory packets to ``host::sizeof long'' bytes - (typically 32 bits). Consequently, for 64 bit targets, the upper 32 bits of an address was never sent. Since fixing this bug may cause a break in some remote targets this variable is principly provided to facilitate backward compatibility. */ static int remote_address_size; /* Convert hex digit A to a number. */ static int fromhex (int a) { if (a >= '0' && a <= '9') return a - '0'; else if (a >= 'a' && a <= 'f') return a - 'a' + 10; else if (a >= 'A' && a <= 'F') return a - 'A' + 10; else { error ("Reply contains invalid hex digit %d", a); return -1; } } /* Convert number NIB to a hex digit. */ static int tohex (int nib) { if (nib < 10) return '0' + nib; else return 'a' + nib - 10; } /* Return the number of hex digits in num. */ static int hexnumlen (ULONGEST num) { int i; for (i = 0; num != 0; i++) num >>= 4; return max (i, 1); } /* Set BUF to the hex digits representing NUM. */ static int hexnumstr (char *buf, ULONGEST num) { int i; int len = hexnumlen (num); buf[len] = '\0'; for (i = len - 1; i >= 0; i--) { buf[i] = "0123456789abcdef"[(num & 0xf)]; num >>= 4; } return len; } /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */ static CORE_ADDR remote_address_masked (CORE_ADDR addr) { if (remote_address_size > 0 && remote_address_size < (sizeof (ULONGEST) * 8)) { /* Only create a mask when that mask can safely be constructed in a ULONGEST variable. */ ULONGEST mask = 1; mask = (mask << remote_address_size) - 1; addr &= mask; } return addr; } /* Determine whether the remote target supports binary downloading. This is accomplished by sending a no-op memory write of zero length to the target at the specified address. It does not suffice to send the whole packet, since many stubs strip the eighth bit and subsequently compute a wrong checksum, which causes real havoc with remote_write_bytes. NOTE: This can still lose if the serial line is not eight-bit clean. In cases like this, the user should clear "remotebinarydownload". */ static void check_binary_download (CORE_ADDR addr) { if (remote_binary_download && !remote_binary_checked) { char *buf = alloca (PBUFSIZ); char *p; remote_binary_checked = 1; p = buf; *p++ = 'X'; p += hexnumstr (p, (ULONGEST) addr); *p++ = ','; p += hexnumstr (p, (ULONGEST) 0); *p++ = ':'; *p = '\0'; putpkt_binary (buf, (int) (p - buf)); getpkt (buf, 0); if (buf[0] == '\0') remote_binary_download = 0; } if (remote_debug) { if (remote_binary_download) fprintf_unfiltered (gdb_stdlog, "binary downloading suppported by target\n"); else fprintf_unfiltered (gdb_stdlog, "binary downloading NOT suppported by target\n"); } } /* Write memory data directly to the remote machine. This does not inform the data cache; the data cache uses this. MEMADDR is the address in the remote memory space. MYADDR is the address of the buffer in our space. LEN is the number of bytes. Returns number of bytes transferred, or 0 for error. */ int remote_write_bytes (memaddr, myaddr, len) CORE_ADDR memaddr; char *myaddr; int len; { unsigned char *buf = alloca (PBUFSIZ); int max_buf_size; /* Max size of packet output buffer */ int origlen; extern int verbose; /* Verify that the target can support a binary download */ check_binary_download (memaddr); /* Chop the transfer down if necessary */ max_buf_size = min (remote_write_size, PBUFSIZ); if (remote_register_buf_size != 0) max_buf_size = min (max_buf_size, remote_register_buf_size); /* Subtract header overhead from max payload size - $M<memaddr>,<len>:#nn */ max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4; origlen = len; while (len > 0) { unsigned char *p, *plen; int todo; int i; /* construct "M"<memaddr>","<len>":" */ /* sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo); */ memaddr = remote_address_masked (memaddr); p = buf; if (remote_binary_download) { *p++ = 'X'; todo = min (len, max_buf_size); } else { *p++ = 'M'; todo = min (len, max_buf_size / 2); /* num bytes that will fit */ } p += hexnumstr ((char *)p, (ULONGEST) memaddr); *p++ = ','; plen = p; /* remember where len field goes */ p += hexnumstr ((char *)p, (ULONGEST) todo); *p++ = ':'; *p = '\0'; /* We send target system values byte by byte, in increasing byte addresses, each byte encoded as two hex characters (or one binary character). */ if (remote_binary_download) { int escaped = 0; for (i = 0; (i < todo) && (i + escaped) < (max_buf_size - 2); i++) { switch (myaddr[i] & 0xff) { case '$': case '#': case 0x7d: /* These must be escaped */ escaped++; *p++ = 0x7d; *p++ = (myaddr[i] & 0xff) ^ 0x20; break; default: *p++ = myaddr[i] & 0xff; break; } } if (i < todo) { /* Escape chars have filled up the buffer prematurely, and we have actually sent fewer bytes than planned. Fix-up the length field of the packet. */ /* FIXME: will fail if new len is a shorter string than old len. */ plen += hexnumstr ((char *)plen, (ULONGEST) i); *plen++ = ':'; } } else { for (i = 0; i < todo; i++) { *p++ = tohex ((myaddr[i] >> 4) & 0xf); *p++ = tohex (myaddr[i] & 0xf); } *p = '\0'; } putpkt_binary ((char *)buf, (int) (p - buf)); getpkt ((char *)buf, 0); if (buf[0] == 'E') { /* There is no correspondance between what the remote protocol uses for errors and errno codes. We would like a cleaner way of representing errors (big enough to include errno codes, bfd_error codes, and others). But for now just return EIO. */ errno = EIO; return 0; } /* Increment by i, not by todo, in case escape chars caused us to send fewer bytes than we'd planned. */ myaddr += i; memaddr += i; len -= i; if (verbose) putc('.', stderr); } return origlen; } /* Stuff for dealing with the packets which are part of this protocol. See comment at top of file for details. */ /* Read a single character from the remote end, masking it down to 7 bits. */ static int readchar (int timeout) { int ch; ch = SERIAL_READCHAR (remote_desc, timeout); switch (ch) { case SERIAL_EOF: error ("Remote connection closed"); case SERIAL_ERROR: perror_with_name ("Remote communication error"); case SERIAL_TIMEOUT: return ch; default: return ch & 0x7f; } } static int putpkt (buf) char *buf; { return putpkt_binary (buf, strlen (buf)); } /* Send a packet to the remote machine, with error checking. The data of the packet is in BUF. The string in BUF can be at most PBUFSIZ - 5 to account for the $, # and checksum, and for a possible /0 if we are debugging (remote_debug) and want to print the sent packet as a string */ static int putpkt_binary (buf, cnt) char *buf; int cnt; { int i; unsigned char csum = 0; char *buf2 = alloca (PBUFSIZ); char *junkbuf = alloca (PBUFSIZ); int ch; int tcount = 0; char *p; /* Copy the packet into buffer BUF2, encapsulating it and giving it a checksum. */ if (cnt > BUFSIZ - 5) /* Prosanity check */ abort (); p = buf2; *p++ = '$'; for (i = 0; i < cnt; i++) { csum += buf[i]; *p++ = buf[i]; } *p++ = '#'; *p++ = tohex ((csum >> 4) & 0xf); *p++ = tohex (csum & 0xf); /* Send it over and over until we get a positive ack. */ while (1) { int started_error_output = 0; if (remote_debug) { *p = '\0'; fprintf_unfiltered (gdb_stdlog, "Sending packet: "); fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog); fprintf_unfiltered (gdb_stdlog, "..."); gdb_flush (gdb_stdlog); } if (SERIAL_WRITE (remote_desc, buf2, p - buf2)) perror_with_name ("putpkt: write failed"); /* read until either a timeout occurs (-2) or '+' is read */ while (1) { ch = readchar (remote_timeout); if (remote_debug) { switch (ch) { case '+': case SERIAL_TIMEOUT: case '$': if (started_error_output) { putchar_unfiltered ('\n'); started_error_output = 0; } } } switch (ch) { case '+': if (remote_debug) fprintf_unfiltered (gdb_stdlog, "Ack\n"); return 1; case SERIAL_TIMEOUT: tcount++; if (tcount > 3) return 0; break; /* Retransmit buffer */ case '$': { /* It's probably an old response, and we're out of sync. Just gobble up the packet and ignore it. */ getpkt (junkbuf, 0); continue; /* Now, go look for + */ } default: if (remote_debug) { if (!started_error_output) { started_error_output = 1; fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: "); } fputc_unfiltered (ch & 0177, gdb_stdlog); } continue; } break; /* Here to retransmit */ } #if 0 /* This is wrong. If doing a long backtrace, the user should be able to get out next time we call QUIT, without anything as violent as interrupt_query. If we want to provide a way out of here without getting to the next QUIT, it should be based on hitting ^C twice as in remote_wait. */ if (quit_flag) { quit_flag = 0; interrupt_query (); } #endif } } /* Come here after finding the start of the frame. Collect the rest into BUF, verifying the checksum, length, and handling run-length compression. Returns 0 on any error, 1 on success. */ static int read_frame (char *buf) { unsigned char csum; char *bp; int c; csum = 0; bp = buf; while (1) { c = readchar (remote_timeout); switch (c) { case SERIAL_TIMEOUT: if (remote_debug) fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog); return 0; case '$': if (remote_debug) fputs_filtered ("Saw new packet start in middle of old one\n", gdb_stdlog); return 0; /* Start a new packet, count retries */ case '#': { unsigned char pktcsum; *bp = '\000'; pktcsum = fromhex (readchar (remote_timeout)) << 4; pktcsum |= fromhex (readchar (remote_timeout)); if (csum == pktcsum) { return 1; } if (remote_debug) { fprintf_filtered (gdb_stdlog, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=", pktcsum, csum); fputs_filtered (buf, gdb_stdlog); fputs_filtered ("\n", gdb_stdlog); } return 0; } case '*': /* Run length encoding */ csum += c; c = readchar (remote_timeout); csum += c; c = c - ' ' + 3; /* Compute repeat count */ if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1) { memset (bp, *(bp - 1), c); bp += c; continue; } *bp = '\0'; printf_filtered ("Repeat count %d too large for buffer: ", c); puts_filtered (buf); puts_filtered ("\n"); return 0; default: if (bp < buf + PBUFSIZ - 1) { *bp++ = c; csum += c; continue; } *bp = '\0'; puts_filtered ("Remote packet too long: "); puts_filtered (buf); puts_filtered ("\n"); return 0; } } } /* Read a packet from the remote machine, with error checking, and store it in BUF. BUF is expected to be of size PBUFSIZ. If FOREVER, wait forever rather than timing out; this is used while the target is executing user code. */ static void getpkt (buf, forever) char *buf; int forever; { int c; int tries; int timeout; int val; strcpy (buf, "timeout"); if (forever) { timeout = watchdog > 0 ? watchdog : -1; } else timeout = remote_timeout; #define MAX_TRIES 3 for (tries = 1; tries <= MAX_TRIES; tries++) { /* This can loop forever if the remote side sends us characters continuously, but if it pauses, we'll get a zero from readchar because of timeout. Then we'll count that as a retry. */ /* Note that we will only wait forever prior to the start of a packet. After that, we expect characters to arrive at a brisk pace. They should show up within remote_timeout intervals. */ do { c = readchar (timeout); if (c == SERIAL_TIMEOUT) { if (forever) /* Watchdog went off. Kill the target. */ { target_mourn_inferior (); error ("Watchdog has expired. Target detached.\n"); } if (remote_debug) fputs_filtered ("Timed out.\n", gdb_stdlog); goto retry; } } while (c != '$'); /* We've found the start of a packet, now collect the data. */ val = read_frame (buf); if (val == 1) { if (remote_debug) { fprintf_unfiltered (gdb_stdlog, "Packet received: "); fputstr_unfiltered (buf, 0, gdb_stdlog); fprintf_unfiltered (gdb_stdlog, "\n"); } SERIAL_WRITE (remote_desc, "+", 1); return; } /* Try the whole thing again. */ retry: SERIAL_WRITE (remote_desc, "-", 1); } /* We have tried hard enough, and just can't receive the packet. Give up. */ printf_unfiltered ("Ignoring packet error, continuing...\n"); SERIAL_WRITE (remote_desc, "+", 1); }
1001-study-uboot
tools/gdb/remote.c
C
gpl3
24,491
/* * (C) Copyright 2000 * Murray Jensen <Murray.Jensen@csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <termios.h> #define SERIAL_ERROR -1 /* General error, see errno for details */ #define SERIAL_TIMEOUT -2 #define SERIAL_EOF -3 extern speed_t cvtspeed(char *); extern int serialopen(char *, speed_t); extern int serialreadchar(int, int); extern int serialwrite(int, char *, int); extern int serialclose(int);
1001-study-uboot
tools/gdb/serial.h
C
gpl3
1,186
/* * (C) Copyright 2000 * Murray Jensen <Murray.Jensen@csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ extern int remote_desc, remote_timeout; extern void remote_reset(void); extern void remote_continue(void); extern int remote_write_bytes(unsigned long, char *, int);
1001-study-uboot
tools/gdb/remote.h
C
gpl3
1,034
# # (C) Copyright 2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # (C) Copyright 2000 # Murray Jensen <Murray.Jensen@csiro.au> # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk BINS = gdbsend gdbcont COBJS = gdbsend.o gdbcont.o error.o remote.o serial.o HOSTOBJS := $(addprefix $(obj),$(COBJS)) HOSTSRCS := $(COBJS:.o=.c) BINS := $(addprefix $(obj),$(BINS)) # # Use native tools and options # HOSTCPPFLAGS = -I$(BFD_ROOT_DIR)/include HOSTOS := $(shell uname -s | sed -e 's/\([Cc][Yy][Gg][Ww][Ii][Nn]\).*/cygwin/') ifeq ($(HOSTOS),cygwin) all: $(obj).depend: else # ! CYGWIN all: $(obj).depend $(BINS) $(obj)gdbsend: $(obj)gdbsend.o $(obj)error.o $(obj)remote.o $(obj)serial.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(obj)gdbcont: $(obj)gdbcont.o $(obj)error.o $(obj)remote.o $(obj)serial.o $(HOSTCC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ clean: rm -f $(HOSTOBJS) distclean: clean rm -f $(BINS) $(obj)core $(obj)*.bak $(obj).depend ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend ######################################################################### endif # cygwin
1001-study-uboot
tools/gdb/Makefile
Makefile
gpl3
1,983
/* * (C) Copyright 2000 * Murray Jensen <Murray.Jensen@csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include "serial.h" #include "error.h" #include "remote.h" char *serialdev = "/dev/term/b"; speed_t speed = B230400; int verbose = 0, docont = 0; unsigned long addr = 0x10000UL; int main(int ac, char **av) { int c, sfd, ifd; char *ifn, *image; struct stat ist; if ((pname = strrchr(av[0], '/')) == NULL) pname = av[0]; else pname++; while ((c = getopt(ac, av, "a:b:cp:v")) != EOF) switch (c) { case 'a': { char *ep; addr = strtol(optarg, &ep, 0); if (ep == optarg || *ep != '\0') Error("can't decode address specified in -a option"); break; } case 'b': if ((speed = cvtspeed(optarg)) == B0) Error("can't decode baud rate specified in -b option"); break; case 'c': docont = 1; break; case 'p': serialdev = optarg; break; case 'v': verbose = 1; break; default: usage: fprintf(stderr, "Usage: %s [-a addr] [-b bps] [-c] [-p dev] [-v] imagefile\n", pname); exit(1); } if (optind != ac - 1) goto usage; ifn = av[optind++]; if (verbose) fprintf(stderr, "Opening file and reading image...\n"); if ((ifd = open(ifn, O_RDONLY)) < 0) Perror("can't open kernel image file '%s'", ifn); if (fstat(ifd, &ist) < 0) Perror("fstat '%s' failed", ifn); if ((image = (char *)malloc(ist.st_size)) == NULL) Perror("can't allocate %ld bytes for image", ist.st_size); if ((c = read(ifd, image, ist.st_size)) < 0) Perror("read of %d bytes from '%s' failed", ist.st_size, ifn); if (c != ist.st_size) Error("read of %ld bytes from '%s' failed (%d)", ist.st_size, ifn, c); if (close(ifd) < 0) Perror("close of '%s' failed", ifn); if (verbose) fprintf(stderr, "Opening serial port and sending image...\n"); if ((sfd = serialopen(serialdev, speed)) < 0) Perror("open of serial device '%s' failed", serialdev); remote_desc = sfd; remote_reset(); remote_write_bytes(addr, image, ist.st_size); if (docont) { if (verbose) fprintf(stderr, "[continue]"); remote_continue(); } if (serialclose(sfd) < 0) Perror("close of serial device '%s' failed", serialdev); if (verbose) fprintf(stderr, "Done.\n"); return (0); }
1001-study-uboot
tools/gdb/gdbsend.c
C
gpl3
3,223
/* * (C) Copyright 2000 * Murray Jensen <Murray.Jensen@csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdarg.h> extern char *pname; extern void Warning(char *, ...); extern void Error(char *, ...); extern void Perror(char *, ...);
1001-study-uboot
tools/gdb/error.h
C
gpl3
1,008
/* * String handling functions for PowerPC. * * Copyright (C) 1996 Paul Mackerras. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <ppc_asm.tmpl> #include <asm/errno.h> .globl strcpy strcpy: addi r5,r3,-1 addi r4,r4,-1 1: lbzu r0,1(r4) cmpwi 0,r0,0 stbu r0,1(r5) bne 1b blr .globl strncpy strncpy: cmpwi 0,r5,0 beqlr mtctr r5 addi r6,r3,-1 addi r4,r4,-1 1: lbzu r0,1(r4) cmpwi 0,r0,0 stbu r0,1(r6) bdnzf 2,1b /* dec ctr, branch if ctr != 0 && !cr0.eq */ blr .globl strcat strcat: addi r5,r3,-1 addi r4,r4,-1 1: lbzu r0,1(r5) cmpwi 0,r0,0 bne 1b addi r5,r5,-1 1: lbzu r0,1(r4) cmpwi 0,r0,0 stbu r0,1(r5) bne 1b blr .globl strcmp strcmp: addi r5,r3,-1 addi r4,r4,-1 1: lbzu r3,1(r5) cmpwi 1,r3,0 lbzu r0,1(r4) subf. r3,r0,r3 beqlr 1 beq 1b blr .globl strlen strlen: addi r4,r3,-1 1: lbzu r0,1(r4) cmpwi 0,r0,0 bne 1b subf r3,r3,r4 blr .globl memset memset: rlwimi r4,r4,8,16,23 rlwimi r4,r4,16,0,15 addi r6,r3,-4 cmplwi 0,r5,4 blt 7f stwu r4,4(r6) beqlr andi. r0,r6,3 add r5,r0,r5 subf r6,r0,r6 rlwinm r0,r5,32-2,2,31 mtctr r0 bdz 6f 1: stwu r4,4(r6) bdnz 1b 6: andi. r5,r5,3 7: cmpwi 0,r5,0 beqlr mtctr r5 addi r6,r6,3 8: stbu r4,1(r6) bdnz 8b blr .globl bcopy bcopy: mr r6,r3 mr r3,r4 mr r4,r6 b memcpy .globl memmove memmove: cmplw 0,r3,r4 bgt backwards_memcpy /* fall through */ .globl memcpy memcpy: rlwinm. r7,r5,32-3,3,31 /* r0 = r5 >> 3 */ addi r6,r3,-4 addi r4,r4,-4 beq 2f /* if less than 8 bytes to do */ andi. r0,r6,3 /* get dest word aligned */ mtctr r7 bne 5f 1: lwz r7,4(r4) lwzu r8,8(r4) stw r7,4(r6) stwu r8,8(r6) bdnz 1b andi. r5,r5,7 2: cmplwi 0,r5,4 blt 3f lwzu r0,4(r4) addi r5,r5,-4 stwu r0,4(r6) 3: cmpwi 0,r5,0 beqlr mtctr r5 addi r4,r4,3 addi r6,r6,3 4: lbzu r0,1(r4) stbu r0,1(r6) bdnz 4b blr 5: subfic r0,r0,4 mtctr r0 6: lbz r7,4(r4) addi r4,r4,1 stb r7,4(r6) addi r6,r6,1 bdnz 6b subf r5,r0,r5 rlwinm. r7,r5,32-3,3,31 beq 2b mtctr r7 b 1b .globl backwards_memcpy backwards_memcpy: rlwinm. r7,r5,32-3,3,31 /* r0 = r5 >> 3 */ add r6,r3,r5 add r4,r4,r5 beq 2f andi. r0,r6,3 mtctr r7 bne 5f 1: lwz r7,-4(r4) lwzu r8,-8(r4) stw r7,-4(r6) stwu r8,-8(r6) bdnz 1b andi. r5,r5,7 2: cmplwi 0,r5,4 blt 3f lwzu r0,-4(r4) subi r5,r5,4 stwu r0,-4(r6) 3: cmpwi 0,r5,0 beqlr mtctr r5 4: lbzu r0,-1(r4) stbu r0,-1(r6) bdnz 4b blr 5: mtctr r0 6: lbzu r7,-1(r4) stbu r7,-1(r6) bdnz 6b subf r5,r0,r5 rlwinm. r7,r5,32-3,3,31 beq 2b mtctr r7 b 1b .globl memcmp memcmp: cmpwi 0,r5,0 ble- 2f mtctr r5 addi r6,r3,-1 addi r4,r4,-1 1: lbzu r3,1(r6) lbzu r0,1(r4) subf. r3,r0,r3 bdnzt 2,1b blr 2: li r3,0 blr .global memchr memchr: cmpwi 0,r5,0 ble- 2f mtctr r5 addi r3,r3,-1 1: lbzu r0,1(r3) cmpw 0,r0,r4 bdnzf 2,1b beqlr 2: li r3,0 blr
1001-study-uboot
tools/updater/ppcstring.S
Unix Assembly
gpl3
3,033
/* * linux/lib/string.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * stupid library routines.. The optimized versions should generally be found * as inline code in <asm-xx/string.h> * * These are buggy as well.. */ #include <linux/types.h> #include <linux/string.h> #include <malloc.h> #define __HAVE_ARCH_BCOPY #define __HAVE_ARCH_MEMCMP #define __HAVE_ARCH_MEMCPY #define __HAVE_ARCH_MEMMOVE #define __HAVE_ARCH_MEMSET #define __HAVE_ARCH_STRCAT #define __HAVE_ARCH_STRCMP #define __HAVE_ARCH_STRCPY #define __HAVE_ARCH_STRLEN #define __HAVE_ARCH_STRNCPY char * ___strtok = NULL; #ifndef __HAVE_ARCH_STRCPY char * strcpy(char * dest,const char *src) { char *tmp = dest; while ((*dest++ = *src++) != '\0') /* nothing */; return tmp; } #endif #ifndef __HAVE_ARCH_STRNCPY char * strncpy(char * dest,const char *src,size_t count) { char *tmp = dest; while (count-- && (*dest++ = *src++) != '\0') /* nothing */; return tmp; } #endif #ifndef __HAVE_ARCH_STRCAT char * strcat(char * dest, const char * src) { char *tmp = dest; while (*dest) dest++; while ((*dest++ = *src++) != '\0') ; return tmp; } #endif #ifndef __HAVE_ARCH_STRNCAT char * strncat(char *dest, const char *src, size_t count) { char *tmp = dest; if (count) { while (*dest) dest++; while ((*dest++ = *src++)) { if (--count == 0) { *dest = '\0'; break; } } } return tmp; } #endif #ifndef __HAVE_ARCH_STRCMP int strcmp(const char * cs,const char * ct) { register signed char __res; while (1) { if ((__res = *cs - *ct++) != 0 || !*cs++) break; } return __res; } #endif #ifndef __HAVE_ARCH_STRNCMP int strncmp(const char * cs,const char * ct,size_t count) { register signed char __res = 0; while (count) { if ((__res = *cs - *ct++) != 0 || !*cs++) break; count--; } return __res; } #endif #ifndef __HAVE_ARCH_STRCHR char * strchr(const char * s, int c) { for(; *s != (char) c; ++s) if (*s == '\0') return NULL; return (char *) s; } #endif #ifndef __HAVE_ARCH_STRRCHR char * strrchr(const char * s, int c) { const char *p = s + strlen(s); do { if (*p == (char)c) return (char *)p; } while (--p >= s); return NULL; } #endif #ifndef __HAVE_ARCH_STRLEN size_t strlen(const char * s) { const char *sc; for (sc = s; *sc != '\0'; ++sc) /* nothing */; return sc - s; } #endif #ifndef __HAVE_ARCH_STRNLEN size_t strnlen(const char * s, size_t count) { const char *sc; for (sc = s; count-- && *sc != '\0'; ++sc) /* nothing */; return sc - s; } #endif #ifndef __HAVE_ARCH_STRDUP char * strdup(const char *s) { char *new; if ((s == NULL) || ((new = malloc (strlen(s) + 1)) == NULL) ) { return NULL; } strcpy (new, s); return new; } #endif #ifndef __HAVE_ARCH_STRSPN size_t strspn(const char *s, const char *accept) { const char *p; const char *a; size_t count = 0; for (p = s; *p != '\0'; ++p) { for (a = accept; *a != '\0'; ++a) { if (*p == *a) break; } if (*a == '\0') return count; ++count; } return count; } #endif #ifndef __HAVE_ARCH_STRPBRK char * strpbrk(const char * cs,const char * ct) { const char *sc1,*sc2; for( sc1 = cs; *sc1 != '\0'; ++sc1) { for( sc2 = ct; *sc2 != '\0'; ++sc2) { if (*sc1 == *sc2) return (char *) sc1; } } return NULL; } #endif #ifndef __HAVE_ARCH_STRTOK char * strtok(char * s,const char * ct) { char *sbegin, *send; sbegin = s ? s : ___strtok; if (!sbegin) { return NULL; } sbegin += strspn(sbegin,ct); if (*sbegin == '\0') { ___strtok = NULL; return( NULL ); } send = strpbrk( sbegin, ct); if (send && *send != '\0') *send++ = '\0'; ___strtok = send; return (sbegin); } #endif #ifndef __HAVE_ARCH_MEMSET void * memset(void * s,char c,size_t count) { char *xs = (char *) s; while (count--) *xs++ = c; return s; } #endif #ifndef __HAVE_ARCH_BCOPY char * bcopy(const char * src, char * dest, int count) { char *tmp = dest; while (count--) *tmp++ = *src++; return dest; } #endif #ifndef __HAVE_ARCH_MEMCPY void * memcpy(void * dest,const void *src,size_t count) { char *tmp = (char *) dest, *s = (char *) src; while (count--) *tmp++ = *s++; return dest; } #endif #ifndef __HAVE_ARCH_MEMMOVE void * memmove(void * dest,const void *src,size_t count) { char *tmp, *s; if (dest <= src) { tmp = (char *) dest; s = (char *) src; while (count--) *tmp++ = *s++; } else { tmp = (char *) dest + count; s = (char *) src + count; while (count--) *--tmp = *--s; } return dest; } #endif #ifndef __HAVE_ARCH_MEMCMP int memcmp(const void * cs,const void * ct,size_t count) { const unsigned char *su1, *su2; signed char res = 0; for( su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--) if ((res = *su1 - *su2) != 0) break; return res; } #endif /* * find the first occurrence of byte 'c', or 1 past the area if none */ #ifndef __HAVE_ARCH_MEMSCAN void * memscan(void * addr, int c, size_t size) { unsigned char * p = (unsigned char *) addr; while (size) { if (*p == c) return (void *) p; p++; size--; } return (void *) p; } #endif #ifndef __HAVE_ARCH_STRSTR char * strstr(const char * s1,const char * s2) { int l1, l2; l2 = strlen(s2); if (!l2) return (char *) s1; l1 = strlen(s1); while (l1 >= l2) { l1--; if (!memcmp(s1,s2,l2)) return (char *) s1; s1++; } return NULL; } #endif
1001-study-uboot
tools/updater/string.c
C
gpl3
5,390
volatile int __dummy = 0xDEADBEEF;
1001-study-uboot
tools/updater/dummy.c
C
gpl3
35
/* * (C) Copyright 2001 * Josh Huber <huber@mclx.com>, Mission Critical Linux, Inc. * * (C) Copyright 2002 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <flash.h> #include <asm/io.h> #include <memio.h> /*---------------------------------------------------------------------*/ #undef DEBUG_FLASH #ifdef DEBUG_FLASH #define DEBUGF(fmt,args...) printf(fmt ,##args) #else #define DEBUGF(fmt,args...) #endif /*---------------------------------------------------------------------*/ flash_info_t flash_info[]; static ulong flash_get_size (ulong addr, flash_info_t *info); static int flash_get_offsets (ulong base, flash_info_t *info); static int write_word (flash_info_t *info, ulong dest, ulong data); static void flash_reset (ulong addr); int flash_xd_nest; static void flash_to_xd(void) { unsigned char x; flash_xd_nest ++; if (flash_xd_nest == 1) { DEBUGF("Flash on XD\n"); x = pci_read_cfg_byte(0, 0, 0x74); pci_write_cfg_byte(0, 0, 0x74, x|1); } } static void flash_to_mem(void) { unsigned char x; flash_xd_nest --; if (flash_xd_nest == 0) { DEBUGF("Flash on memory bus\n"); x = pci_read_cfg_byte(0, 0, 0x74); pci_write_cfg_byte(0, 0, 0x74, x&0xFE); } } unsigned long flash_init_old(void) { int i; for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) { flash_info[i].flash_id = FLASH_UNKNOWN; flash_info[i].sector_count = 0; flash_info[i].size = 0; } return 1; } unsigned long flash_init (void) { unsigned int i; unsigned long flash_size = 0; flash_xd_nest = 0; flash_to_xd(); /* Init: no FLASHes known */ for (i=0; i<CONFIG_SYS_MAX_FLASH_BANKS; ++i) { flash_info[i].flash_id = FLASH_UNKNOWN; flash_info[i].sector_count = 0; flash_info[i].size = 0; } DEBUGF("\n## Get flash size @ 0x%08x\n", CONFIG_SYS_FLASH_BASE); flash_size = flash_get_size (CONFIG_SYS_FLASH_BASE, flash_info); DEBUGF("## Flash bank size: %08lx\n", flash_size); if (flash_size) { #if CONFIG_SYS_MONITOR_BASE >= CONFIG_SYS_FLASH_BASE && \ CONFIG_SYS_MONITOR_BASE < CONFIG_SYS_FLASH_BASE + CONFIG_SYS_FLASH_MAX_SIZE /* monitor protection ON by default */ flash_protect(FLAG_PROTECT_SET, CONFIG_SYS_MONITOR_BASE, CONFIG_SYS_MONITOR_BASE + CONFIG_SYS_MONITOR_LEN - 1, &flash_info[0]); #endif #ifdef CONFIG_ENV_IS_IN_FLASH /* ENV protection ON by default */ flash_protect(FLAG_PROTECT_SET, CONFIG_ENV_ADDR, CONFIG_ENV_ADDR + CONFIG_ENV_SECT_SIZE - 1, &flash_info[0]); #endif } else { printf ("Warning: the BOOT Flash is not initialised !"); } flash_to_mem(); return flash_size; } /* * The following code cannot be run from FLASH! */ static ulong flash_get_size (ulong addr, flash_info_t *info) { short i; uchar value; uchar *x = (uchar *)addr; flash_to_xd(); /* Write auto select command: read Manufacturer ID */ x[0x0555] = 0xAA; __asm__ volatile ("sync\n eieio"); x[0x02AA] = 0x55; __asm__ volatile ("sync\n eieio"); x[0x0555] = 0x90; __asm__ volatile ("sync\n eieio"); value = x[0]; __asm__ volatile ("sync\n eieio"); DEBUGF("Manuf. ID @ 0x%08lx: 0x%08x\n", (ulong)addr, value); switch (value | (value << 16)) { case AMD_MANUFACT: info->flash_id = FLASH_MAN_AMD; break; case FUJ_MANUFACT: info->flash_id = FLASH_MAN_FUJ; break; case STM_MANUFACT: info->flash_id = FLASH_MAN_STM; break; default: info->flash_id = FLASH_UNKNOWN; info->sector_count = 0; info->size = 0; flash_reset (addr); return 0; } value = x[1]; __asm__ volatile ("sync\n eieio"); DEBUGF("Device ID @ 0x%08lx: 0x%08x\n", addr+1, value); switch (value) { case AMD_ID_F040B: DEBUGF("Am29F040B\n"); info->flash_id += FLASH_AM040; info->sector_count = 8; info->size = 0x00080000; break; /* => 512 kB */ case AMD_ID_LV040B: DEBUGF("Am29LV040B\n"); info->flash_id += FLASH_AM040; info->sector_count = 8; info->size = 0x00080000; break; /* => 512 kB */ case AMD_ID_LV400T: DEBUGF("Am29LV400T\n"); info->flash_id += FLASH_AM400T; info->sector_count = 11; info->size = 0x00100000; break; /* => 1 MB */ case AMD_ID_LV400B: DEBUGF("Am29LV400B\n"); info->flash_id += FLASH_AM400B; info->sector_count = 11; info->size = 0x00100000; break; /* => 1 MB */ case AMD_ID_LV800T: DEBUGF("Am29LV800T\n"); info->flash_id += FLASH_AM800T; info->sector_count = 19; info->size = 0x00200000; break; /* => 2 MB */ case AMD_ID_LV800B: DEBUGF("Am29LV400B\n"); info->flash_id += FLASH_AM800B; info->sector_count = 19; info->size = 0x00200000; break; /* => 2 MB */ case AMD_ID_LV160T: DEBUGF("Am29LV160T\n"); info->flash_id += FLASH_AM160T; info->sector_count = 35; info->size = 0x00400000; break; /* => 4 MB */ case AMD_ID_LV160B: DEBUGF("Am29LV160B\n"); info->flash_id += FLASH_AM160B; info->sector_count = 35; info->size = 0x00400000; break; /* => 4 MB */ case AMD_ID_LV320T: DEBUGF("Am29LV320T\n"); info->flash_id += FLASH_AM320T; info->sector_count = 67; info->size = 0x00800000; break; /* => 8 MB */ #if 0 /* Has the same ID as AMD_ID_LV320T, to be fixed */ case AMD_ID_LV320B: DEBUGF("Am29LV320B\n"); info->flash_id += FLASH_AM320B; info->sector_count = 67; info->size = 0x00800000; break; /* => 8 MB */ #endif case AMD_ID_LV033C: DEBUGF("Am29LV033C\n"); info->flash_id += FLASH_AM033C; info->sector_count = 64; info->size = 0x01000000; break; /* => 16Mb */ case STM_ID_F040B: DEBUGF("M29F040B\n"); info->flash_id += FLASH_AM040; info->sector_count = 8; info->size = 0x00080000; break; /* => 512 kB */ default: info->flash_id = FLASH_UNKNOWN; flash_reset (addr); flash_to_mem(); return (0); /* => no or unknown flash */ } if (info->sector_count > CONFIG_SYS_MAX_FLASH_SECT) { printf ("** ERROR: sector count %d > max (%d) **\n", info->sector_count, CONFIG_SYS_MAX_FLASH_SECT); info->sector_count = CONFIG_SYS_MAX_FLASH_SECT; } if (! flash_get_offsets (addr, info)) { flash_reset (addr); flash_to_mem(); return 0; } /* check for protected sectors */ for (i = 0; i < info->sector_count; i++) { /* read sector protection at sector address, (A7 .. A0) = 0x02 */ /* D0 = 1 if protected */ value = in8(info->start[i] + 2); iobarrier_rw(); info->protect[i] = (value & 1) != 0; } /* * Reset bank to read mode */ flash_reset (addr); flash_to_mem(); return (info->size); } static int flash_get_offsets (ulong base, flash_info_t *info) { unsigned int i; switch (info->flash_id & FLASH_TYPEMASK) { case FLASH_AM040: /* set sector offsets for uniform sector type */ for (i = 0; i < info->sector_count; i++) { info->start[i] = base + i * info->size / info->sector_count; } break; default: return 0; } return 1; } int flash_erase (flash_info_t *info, int s_first, int s_last) { volatile ulong addr = info->start[0]; int flag, prot, sect, l_sect; ulong start, now, last; flash_to_xd(); if (s_first < 0 || s_first > s_last) { if (info->flash_id == FLASH_UNKNOWN) { printf ("- missing\n"); } else { printf ("- no sectors to erase\n"); } flash_to_mem(); return 1; } if (info->flash_id == FLASH_UNKNOWN) { printf ("Can't erase unknown flash type %08lx - aborted\n", info->flash_id); flash_to_mem(); return 1; } prot = 0; for (sect=s_first; sect<=s_last; ++sect) { if (info->protect[sect]) { prot++; } } if (prot) { printf ("- Warning: %d protected sectors will not be erased!\n", prot); } else { printf (""); } l_sect = -1; /* Disable interrupts which might cause a timeout here */ flag = disable_interrupts(); out8(addr + 0x555, 0xAA); iobarrier_rw(); out8(addr + 0x2AA, 0x55); iobarrier_rw(); out8(addr + 0x555, 0x80); iobarrier_rw(); out8(addr + 0x555, 0xAA); iobarrier_rw(); out8(addr + 0x2AA, 0x55); iobarrier_rw(); /* Start erase on unprotected sectors */ for (sect = s_first; sect<=s_last; sect++) { if (info->protect[sect] == 0) { /* not protected */ addr = info->start[sect]; out8(addr, 0x30); iobarrier_rw(); l_sect = sect; } } /* re-enable interrupts if necessary */ if (flag) enable_interrupts(); /* wait at least 80us - let's wait 1 ms */ udelay (1000); /* * We wait for the last triggered sector */ if (l_sect < 0) goto DONE; start = get_timer (0); last = start; addr = info->start[l_sect]; DEBUGF ("Start erase timeout: %d\n", CONFIG_SYS_FLASH_ERASE_TOUT); while ((in8(addr) & 0x80) != 0x80) { if ((now = get_timer(start)) > CONFIG_SYS_FLASH_ERASE_TOUT) { printf ("Timeout\n"); flash_reset (info->start[0]); flash_to_mem(); return 1; } /* show that we're waiting */ if ((now - last) > 1000) { /* every second */ putc ('.'); last = now; } iobarrier_rw(); } DONE: /* reset to read mode */ flash_reset (info->start[0]); flash_to_mem(); printf (" done\n"); return 0; } /* * Copy memory to flash, returns: * 0 - OK * 1 - write timeout * 2 - Flash not erased */ int write_buff (flash_info_t *info, uchar *src, ulong addr, ulong cnt) { ulong cp, wp, data; int i, l, rc; ulong out_cnt = 0; flash_to_xd(); wp = (addr & ~3); /* get lower word aligned address */ /* * handle unaligned start bytes */ if ((l = addr - wp) != 0) { data = 0; for (i=0, cp=wp; i<l; ++i, ++cp) { data = (data << 8) | (*(uchar *)cp); } for (; i<4 && cnt>0; ++i) { data = (data << 8) | *src++; --cnt; ++cp; } for (; cnt==0 && i<4; ++i, ++cp) { data = (data << 8) | (*(uchar *)cp); } if ((rc = write_word(info, wp, data)) != 0) { flash_to_mem(); return (rc); } wp += 4; } putc(219); /* * handle word aligned part */ while (cnt >= 4) { if (out_cnt>26214) { putc(219); out_cnt = 0; } data = 0; for (i=0; i<4; ++i) { data = (data << 8) | *src++; } if ((rc = write_word(info, wp, data)) != 0) { flash_to_mem(); return (rc); } wp += 4; cnt -= 4; out_cnt += 4; } if (cnt == 0) { flash_to_mem(); return (0); } /* * handle unaligned tail bytes */ data = 0; for (i=0, cp=wp; i<4 && cnt>0; ++i, ++cp) { data = (data << 8) | *src++; --cnt; } for (; i<4; ++i, ++cp) { data = (data << 8) | (*(uchar *)cp); } flash_to_mem(); return (write_word(info, wp, data)); } /* * Write a word to Flash, returns: * 0 - OK * 1 - write timeout * 2 - Flash not erased */ static int write_word (flash_info_t *info, ulong dest, ulong data) { volatile ulong addr = info->start[0]; ulong start; int i; flash_to_xd(); /* Check if Flash is (sufficiently) erased */ if ((in32(dest) & data) != data) { flash_to_mem(); return (2); } /* write each byte out */ for (i = 0; i < 4; i++) { char *data_ch = (char *)&data; int flag = disable_interrupts(); out8(addr + 0x555, 0xAA); iobarrier_rw(); out8(addr + 0x2AA, 0x55); iobarrier_rw(); out8(addr + 0x555, 0xA0); iobarrier_rw(); out8(dest+i, data_ch[i]); iobarrier_rw(); /* re-enable interrupts if necessary */ if (flag) enable_interrupts(); /* data polling for D7 */ start = get_timer (0); while ((in8(dest+i) & 0x80) != (data_ch[i] & 0x80)) { if (get_timer(start) > CONFIG_SYS_FLASH_WRITE_TOUT) { flash_reset (addr); flash_to_mem(); return (1); } iobarrier_rw(); } } flash_reset (addr); flash_to_mem(); return (0); } /* * Reset bank to read mode */ static void flash_reset (ulong addr) { flash_to_xd(); out8(addr, 0xF0); /* reset bank */ iobarrier_rw(); flash_to_mem(); } void flash_print_info (flash_info_t *info) { int i; if (info->flash_id == FLASH_UNKNOWN) { printf ("missing or unknown FLASH type\n"); return; } switch (info->flash_id & FLASH_VENDMASK) { case FLASH_MAN_AMD: printf ("AMD "); break; case FLASH_MAN_FUJ: printf ("FUJITSU "); break; case FLASH_MAN_BM: printf ("BRIGHT MICRO "); break; case FLASH_MAN_STM: printf ("SGS THOMSON "); break; default: printf ("Unknown Vendor "); break; } switch (info->flash_id & FLASH_TYPEMASK) { case FLASH_AM040: printf ("29F040 or 29LV040 (4 Mbit, uniform sectors)\n"); break; case FLASH_AM400B: printf ("AM29LV400B (4 Mbit, bottom boot sect)\n"); break; case FLASH_AM400T: printf ("AM29LV400T (4 Mbit, top boot sector)\n"); break; case FLASH_AM800B: printf ("AM29LV800B (8 Mbit, bottom boot sect)\n"); break; case FLASH_AM800T: printf ("AM29LV800T (8 Mbit, top boot sector)\n"); break; case FLASH_AM160B: printf ("AM29LV160B (16 Mbit, bottom boot sect)\n"); break; case FLASH_AM160T: printf ("AM29LV160T (16 Mbit, top boot sector)\n"); break; case FLASH_AM320B: printf ("AM29LV320B (32 Mbit, bottom boot sect)\n"); break; case FLASH_AM320T: printf ("AM29LV320T (32 Mbit, top boot sector)\n"); break; default: printf ("Unknown Chip Type\n"); break; } if (info->size % 0x100000 == 0) { printf (" Size: %ld MB in %d Sectors\n", info->size / 0x100000, info->sector_count); } else if (info->size % 0x400 == 0) { printf (" Size: %ld KB in %d Sectors\n", info->size / 0x400, info->sector_count); } else { printf (" Size: %ld B in %d Sectors\n", info->size, info->sector_count); } printf (" Sector Start Addresses:"); for (i=0; i<info->sector_count; ++i) { if ((i % 5) == 0) printf ("\n "); printf (" %08lX%s", info->start[i], info->protect[i] ? " (RO)" : " " ); } printf ("\n"); }
1001-study-uboot
tools/updater/flash_hw.c
C
gpl3
14,406
/* * (C) Copyright 2000 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* * linux/lib/ctype.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/ctype.h> unsigned char _ctype[] = { _C,_C,_C,_C,_C,_C,_C,_C, /* 0-7 */ _C,_C|_S,_C|_S,_C|_S,_C|_S,_C|_S,_C,_C, /* 8-15 */ _C,_C,_C,_C,_C,_C,_C,_C, /* 16-23 */ _C,_C,_C,_C,_C,_C,_C,_C, /* 24-31 */ _S|_SP,_P,_P,_P,_P,_P,_P,_P, /* 32-39 */ _P,_P,_P,_P,_P,_P,_P,_P, /* 40-47 */ _D,_D,_D,_D,_D,_D,_D,_D, /* 48-55 */ _D,_D,_P,_P,_P,_P,_P,_P, /* 56-63 */ _P,_U|_X,_U|_X,_U|_X,_U|_X,_U|_X,_U|_X,_U, /* 64-71 */ _U,_U,_U,_U,_U,_U,_U,_U, /* 72-79 */ _U,_U,_U,_U,_U,_U,_U,_U, /* 80-87 */ _U,_U,_U,_P,_P,_P,_P,_P, /* 88-95 */ _P,_L|_X,_L|_X,_L|_X,_L|_X,_L|_X,_L|_X,_L, /* 96-103 */ _L,_L,_L,_L,_L,_L,_L,_L, /* 104-111 */ _L,_L,_L,_L,_L,_L,_L,_L, /* 112-119 */ _L,_L,_L,_P,_P,_P,_P,_C, /* 120-127 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 128-143 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 144-159 */ _S|_SP,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P, /* 160-175 */ _P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P,_P, /* 176-191 */ _U,_U,_U,_U,_U,_U,_U,_U,_U,_U,_U,_U,_U,_U,_U,_U, /* 192-207 */ _U,_U,_U,_U,_U,_U,_U,_P,_U,_U,_U,_U,_U,_U,_U,_L, /* 208-223 */ _L,_L,_L,_L,_L,_L,_L,_L,_L,_L,_L,_L,_L,_L,_L,_L, /* 224-239 */ _L,_L,_L,_L,_L,_L,_L,_P,_L,_L,_L,_L,_L,_L,_L,_L}; /* 240-255 */
1001-study-uboot
tools/updater/ctype.c
C
gpl3
2,201
# # (C) Copyright 2000-2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # LOAD_ADDR = 0x40000 include $(TOPDIR)/config.mk PROG = $(obj)updater IMAGE = $(obj)updater.image COBJS = update.o flash.o flash_hw.o utils.o cmd_flash.o string.o ctype.o dummy.o COBJS_LINKS = stubs.o AOBJS = ppcstring.o AOBJS_LINKS = memio.o OBJS := $(addprefix $(obj),$(COBJS) $(COBJS_LINKS) $(AOBJS) $(AOBJS_LINKS)) SRCS := $(COBJS:.o=.c) $(AOBJS:.o=.S) $(addprefix $(obj), $(COBJS_LINKS:.o:.c) $(AOBJS_LINKS:.o:.S)) CPPFLAGS += -I$(TOPDIR) -I$(TOPDIR)/board/MAI/AmigaOneG3SE CFLAGS += -I$(TOPDIR)/board/MAI/AmigaOneG3SE AFLAGS += -I$(TOPDIR)/board/MAI/AmigaOneG3SE DEPS = $(OBJTREE)/u-boot.bin $(OBJTREE)/tools/mkimage ifneq ($(DEPS),$(wildcard $(DEPS))) $(error "updater: Missing required objects, please run regular build first") endif all: $(obj).depend $(PROG) $(IMAGE) ######################################################################### $(obj)%.srec: %.o $(LIB) $(LD) -g -Ttext $(LOAD_ADDR) -o $(<:.o=) -e $(<:.o=) $< $(LIB) $(OBJCOPY) -O srec $(<:.o=) $@ $(obj)%.o: %.c $(CC) $(CFLAGS) -c -o $@ $< $(obj)%.o: %.S $(CC) $(AFLAGS) -c -o $@ $< $(obj)memio.o: $(obj)memio.S $(CC) $(AFLAGS) -c -o $@ $< $(obj)memio.S: rm -f $(obj)memio.c ln -s $(SRCTREE)/board/MAI/AmigaOneG3SE/memio.S $(obj)memio.S $(obj)stubs.o: $(obj)stubs.c $(CC) $(CFLAGS) -c -o $@ $< $(obj)stubs.c: rm -f $(obj)stubs.c ln -s $(SRCTREE)/examples/stubs.c $(obj)stubs.c ######################################################################### $(obj)updater: $(OBJS) $(LD) -g -Ttext $(LOAD_ADDR) -o $(obj)updater -e _main $(OBJS) $(OBJCOPY) -O binary $(obj)updater $(obj)updater.bin $(obj)updater.image: $(obj)updater $(OBJTREE)/u-boot.bin cat >/tmp/tempimage $(obj)updater.bin junk $(OBJTREE)/u-boot.bin $(OBJTREE)/tools/mkimage -A ppc -O u-boot -T standalone -C none -a $(LOAD_ADDR) \ -e `$(NM) $(obj)updater | grep _main | cut --bytes=0-8` \ -n "Firmware Updater" -d /tmp/tempimage $(obj)updater.image rm /tmp/tempimage cp $(obj)updater.image /tftpboot (obj)updater.image2: $(obj)updater $(OBJTREE)/u-boot.bin cat >/tmp/tempimage $(obj)updater.bin junk ../../create_image/image $(OBJTREE)/tools/mkimage -A ppc -O u-boot -T standalone -C none -a $(LOAD_ADDR) \ -e `$(NM) $(obj)updater | grep _main | cut --bytes=0-8` \ -n "Firmware Updater" -d /tmp/tempimage $(obj)updater.image rm /tmp/tempimage cp $(obj)updater.image /tftpboot ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
tools/updater/Makefile
Makefile
gpl3
3,461
/* * (C) Copyright 2000-2006 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <flash.h> extern flash_info_t flash_info[]; /* info for FLASH chips */ /*----------------------------------------------------------------------- * Functions */ /*----------------------------------------------------------------------- * Set protection status for monitor sectors * * The monitor is always located in the _first_ Flash bank. * If necessary you have to map the second bank at lower addresses. */ void flash_protect (int flag, ulong from, ulong to, flash_info_t *info) { ulong b_end = info->start[0] + info->size - 1; /* bank end address */ short s_end = info->sector_count - 1; /* index of last sector */ int i; /* Do nothing if input data is bad. */ if (info->sector_count == 0 || info->size == 0 || to < from) { return; } /* There is nothing to do if we have no data about the flash * or the protect range and flash range don't overlap. */ if (info->flash_id == FLASH_UNKNOWN || to < info->start[0] || from > b_end) { return; } for (i=0; i<info->sector_count; ++i) { ulong end; /* last address in current sect */ end = (i == s_end) ? b_end : info->start[i + 1] - 1; /* Update protection if any part of the sector * is in the specified range. */ if (from <= end && to >= info->start[i]) { if (flag & FLAG_PROTECT_CLEAR) { #if defined(CONFIG_SYS_FLASH_PROTECTION) flash_real_protect(info, i, 0); #else info->protect[i] = 0; #endif /* CONFIG_SYS_FLASH_PROTECTION */ } else if (flag & FLAG_PROTECT_SET) { #if defined(CONFIG_SYS_FLASH_PROTECTION) flash_real_protect(info, i, 1); #else info->protect[i] = 1; #endif /* CONFIG_SYS_FLASH_PROTECTION */ } } } } /*----------------------------------------------------------------------- */ flash_info_t * addr2info (ulong addr) { #ifndef CONFIG_SPD823TS flash_info_t *info; int i; for (i=0, info = &flash_info[0]; i<CONFIG_SYS_MAX_FLASH_BANKS; ++i, ++info) { if (info->flash_id != FLASH_UNKNOWN && addr >= info->start[0] && /* WARNING - The '- 1' is needed if the flash * is at the end of the address space, since * info->start[0] + info->size wraps back to 0. * Please don't change this unless you understand this. */ addr <= info->start[0] + info->size - 1) { return (info); } } #endif /* CONFIG_SPD823TS */ return (NULL); } /*----------------------------------------------------------------------- * Copy memory to flash. * Make sure all target addresses are within Flash bounds, * and no protected sectors are hit. * Returns: * ERR_OK 0 - OK * ERR_TIMOUT 1 - write timeout * ERR_NOT_ERASED 2 - Flash not erased * ERR_PROTECTED 4 - target range includes protected sectors * ERR_INVAL 8 - target address not in Flash memory * ERR_ALIGN 16 - target address not aligned on boundary * (only some targets require alignment) */ int flash_write (char *src, ulong addr, ulong cnt) { #ifdef CONFIG_SPD823TS return (ERR_TIMOUT); /* any other error codes are possible as well */ #else int i; ulong end = addr + cnt - 1; flash_info_t *info_first = addr2info (addr); flash_info_t *info_last = addr2info (end ); flash_info_t *info; int j; if (cnt == 0) { return (ERR_OK); } if (!info_first || !info_last) { return (ERR_INVAL); } for (info = info_first; info <= info_last; ++info) { ulong b_end = info->start[0] + info->size; /* bank end addr */ short s_end = info->sector_count - 1; for (i=0; i<info->sector_count; ++i) { ulong e_addr = (i == s_end) ? b_end : info->start[i + 1]; if ((end >= info->start[i]) && (addr < e_addr) && (info->protect[i] != 0) ) { return (ERR_PROTECTED); } } } printf("\rWriting "); for (j=0; j<20; j++) putc(177); printf("\rWriting "); /* finally write data to flash */ for (info = info_first; info <= info_last && cnt>0; ++info) { ulong len; len = info->start[0] + info->size - addr; if (len > cnt) len = cnt; if ((i = write_buff(info, src, addr, len)) != 0) { return (i); } cnt -= len; addr += len; src += len; } return (ERR_OK); #endif /* CONFIG_SPD823TS */ } /*----------------------------------------------------------------------- */
1001-study-uboot
tools/updater/flash.c
C
gpl3
5,120
/* * (C) Copyright 2000 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* * FLASH support */ #include <common.h> #include <command.h> #include <flash.h> #if defined(CONFIG_CMD_FLASH) extern flash_info_t flash_info[]; /* info for FLASH chips */ /* * The user interface starts numbering for Flash banks with 1 * for historical reasons. */ /* * this routine looks for an abbreviated flash range specification. * the syntax is B:SF[-SL], where B is the bank number, SF is the first * sector to erase, and SL is the last sector to erase (defaults to SF). * bank numbers start at 1 to be consistent with other specs, sector numbers * start at zero. * * returns: 1 - correct spec; *pinfo, *psf and *psl are * set appropriately * 0 - doesn't look like an abbreviated spec * -1 - looks like an abbreviated spec, but got * a parsing error, a number out of range, * or an invalid flash bank. */ static int abbrev_spec(char *str, flash_info_t **pinfo, int *psf, int *psl) { flash_info_t *fp; int bank, first, last; char *p, *ep; if ((p = strchr(str, ':')) == NULL) return 0; *p++ = '\0'; bank = simple_strtoul(str, &ep, 10); if (ep == str || *ep != '\0' || bank < 1 || bank > CONFIG_SYS_MAX_FLASH_BANKS || (fp = &flash_info[bank - 1])->flash_id == FLASH_UNKNOWN) return -1; str = p; if ((p = strchr(str, '-')) != NULL) *p++ = '\0'; first = simple_strtoul(str, &ep, 10); if (ep == str || *ep != '\0' || first >= fp->sector_count) return -1; if (p != NULL) { last = simple_strtoul(p, &ep, 10); if (ep == p || *ep != '\0' || last < first || last >= fp->sector_count) return -1; } else last = first; *pinfo = fp; *psf = first; *psl = last; return 1; } int do_flinfo (cmd_tbl_t *cmdtp, bd_t *bd, int flag, int argc, char *argv[]) { ulong bank; if (argc == 1) { /* print info for all FLASH banks */ for (bank=0; bank <CONFIG_SYS_MAX_FLASH_BANKS; ++bank) { printf ("\nBank # %ld: ", bank+1); flash_print_info (&flash_info[bank]); } return 0; } bank = simple_strtoul(argv[1], NULL, 16); if ((bank < 1) || (bank > CONFIG_SYS_MAX_FLASH_BANKS)) { printf ("Only FLASH Banks # 1 ... # %d supported\n", CONFIG_SYS_MAX_FLASH_BANKS); return 1; } printf ("\nBank # %ld: ", bank); flash_print_info (&flash_info[bank-1]); return 0; } int do_flerase(cmd_tbl_t *cmdtp, bd_t *bd, int flag, int argc, char *argv[]) { flash_info_t *info; ulong bank, addr_first, addr_last; int n, sect_first, sect_last; int rcode = 0; if (argc < 2) return cmd_usage(cmdtp); if (strcmp(argv[1], "all") == 0) { for (bank=1; bank<=CONFIG_SYS_MAX_FLASH_BANKS; ++bank) { printf ("Erase Flash Bank # %ld ", bank); info = &flash_info[bank-1]; rcode = flash_erase (info, 0, info->sector_count-1); } return rcode; } if ((n = abbrev_spec(argv[1], &info, &sect_first, &sect_last)) != 0) { if (n < 0) { printf("Bad sector specification\n"); return 1; } printf ("Erase Flash Sectors %d-%d in Bank # %d ", sect_first, sect_last, (info-flash_info)+1); rcode = flash_erase(info, sect_first, sect_last); return rcode; } if (argc != 3) return cmd_usage(cmdtp); if (strcmp(argv[1], "bank") == 0) { bank = simple_strtoul(argv[2], NULL, 16); if ((bank < 1) || (bank > CONFIG_SYS_MAX_FLASH_BANKS)) { printf ("Only FLASH Banks # 1 ... # %d supported\n", CONFIG_SYS_MAX_FLASH_BANKS); return 1; } printf ("Erase Flash Bank # %ld ", bank); info = &flash_info[bank-1]; rcode = flash_erase (info, 0, info->sector_count-1); return rcode; } addr_first = simple_strtoul(argv[1], NULL, 16); addr_last = simple_strtoul(argv[2], NULL, 16); if (addr_first >= addr_last) return cmd_usage(cmdtp); printf ("Erase Flash from 0x%08lx to 0x%08lx ", addr_first, addr_last); rcode = flash_sect_erase(addr_first, addr_last); return rcode; } int flash_sect_erase (ulong addr_first, ulong addr_last) { flash_info_t *info; ulong bank; int s_first, s_last; int erased; int rcode = 0; erased = 0; for (bank=0,info = &flash_info[0]; bank < CONFIG_SYS_MAX_FLASH_BANKS; ++bank, ++info) { ulong b_end; int sect; if (info->flash_id == FLASH_UNKNOWN) { continue; } b_end = info->start[0] + info->size - 1; /* bank end addr */ s_first = -1; /* first sector to erase */ s_last = -1; /* last sector to erase */ for (sect=0; sect < info->sector_count; ++sect) { ulong end; /* last address in current sect */ short s_end; s_end = info->sector_count - 1; end = (sect == s_end) ? b_end : info->start[sect + 1] - 1; if (addr_first > end) continue; if (addr_last < info->start[sect]) continue; if (addr_first == info->start[sect]) { s_first = sect; } if (addr_last == end) { s_last = sect; } } if (s_first>=0 && s_first<=s_last) { erased += s_last - s_first + 1; rcode = flash_erase (info, s_first, s_last); } } if (erased) { /* printf ("Erased %d sectors\n", erased); */ } else { printf ("Error: start and/or end address" " not on sector boundary\n"); rcode = 1; } return rcode; } int do_protect(cmd_tbl_t *cmdtp, bd_t *bd, int flag, int argc, char *argv[]) { flash_info_t *info; ulong bank, addr_first, addr_last; int i, p, n, sect_first, sect_last; int rcode = 0; if (argc < 3) return cmd_usage(cmdtp); if (strcmp(argv[1], "off") == 0) p = 0; else if (strcmp(argv[1], "on") == 0) p = 1; else return cmd_usage(cmdtp); if (strcmp(argv[2], "all") == 0) { for (bank=1; bank<=CONFIG_SYS_MAX_FLASH_BANKS; ++bank) { info = &flash_info[bank-1]; if (info->flash_id == FLASH_UNKNOWN) { continue; } /*printf ("%sProtect Flash Bank # %ld\n", */ /* p ? "" : "Un-", bank); */ for (i=0; i<info->sector_count; ++i) { #if defined(CONFIG_SYS_FLASH_PROTECTION) if (flash_real_protect(info, i, p)) rcode = 1; putc ('.'); #else info->protect[i] = p; #endif /* CONFIG_SYS_FLASH_PROTECTION */ } } #if defined(CONFIG_SYS_FLASH_PROTECTION) if (!rcode) puts (" done\n"); #endif /* CONFIG_SYS_FLASH_PROTECTION */ return rcode; } if ((n = abbrev_spec(argv[2], &info, &sect_first, &sect_last)) != 0) { if (n < 0) { printf("Bad sector specification\n"); return 1; } /*printf("%sProtect Flash Sectors %d-%d in Bank # %d\n", */ /* p ? "" : "Un-", sect_first, sect_last, */ /* (info-flash_info)+1); */ for (i = sect_first; i <= sect_last; i++) { #if defined(CONFIG_SYS_FLASH_PROTECTION) if (flash_real_protect(info, i, p)) rcode = 1; putc ('.'); #else info->protect[i] = p; #endif /* CONFIG_SYS_FLASH_PROTECTION */ } #if defined(CONFIG_SYS_FLASH_PROTECTION) if (!rcode) puts (" done\n"); #endif /* CONFIG_SYS_FLASH_PROTECTION */ return rcode; } if (argc != 4) return cmd_usage(cmdtp); if (strcmp(argv[2], "bank") == 0) { bank = simple_strtoul(argv[3], NULL, 16); if ((bank < 1) || (bank > CONFIG_SYS_MAX_FLASH_BANKS)) { printf ("Only FLASH Banks # 1 ... # %d supported\n", CONFIG_SYS_MAX_FLASH_BANKS); return 1; } printf ("%sProtect Flash Bank # %ld\n", p ? "" : "Un-", bank); info = &flash_info[bank-1]; if (info->flash_id == FLASH_UNKNOWN) { printf ("missing or unknown FLASH type\n"); return 1; } for (i=0; i<info->sector_count; ++i) { #if defined(CONFIG_SYS_FLASH_PROTECTION) if (flash_real_protect(info, i, p)) rcode = 1; putc ('.'); #else info->protect[i] = p; #endif /* CONFIG_SYS_FLASH_PROTECTION */ } #if defined(CONFIG_SYS_FLASH_PROTECTION) if (!rcode) puts(" done\n"); #endif /* CONFIG_SYS_FLASH_PROTECTION */ return rcode; } addr_first = simple_strtoul(argv[2], NULL, 16); addr_last = simple_strtoul(argv[3], NULL, 16); if (addr_first >= addr_last) return cmd_usage(cmdtp); return flash_sect_protect (p, addr_first, addr_last); } int flash_sect_protect (int p, ulong addr_first, ulong addr_last) { flash_info_t *info; ulong bank; int s_first, s_last; int protected, i; int rcode = 0; protected = 0; for (bank=0,info = &flash_info[0]; bank < CONFIG_SYS_MAX_FLASH_BANKS; ++bank, ++info) { ulong b_end; int sect; if (info->flash_id == FLASH_UNKNOWN) { continue; } b_end = info->start[0] + info->size - 1; /* bank end addr */ s_first = -1; /* first sector to erase */ s_last = -1; /* last sector to erase */ for (sect=0; sect < info->sector_count; ++sect) { ulong end; /* last address in current sect */ short s_end; s_end = info->sector_count - 1; end = (sect == s_end) ? b_end : info->start[sect + 1] - 1; if (addr_first > end) continue; if (addr_last < info->start[sect]) continue; if (addr_first == info->start[sect]) { s_first = sect; } if (addr_last == end) { s_last = sect; } } if (s_first>=0 && s_first<=s_last) { protected += s_last - s_first + 1; for (i=s_first; i<=s_last; ++i) { #if defined(CONFIG_SYS_FLASH_PROTECTION) if (flash_real_protect(info, i, p)) rcode = 1; putc ('.'); #else info->protect[i] = p; #endif /* CONFIG_SYS_FLASH_PROTECTION */ } } #if defined(CONFIG_SYS_FLASH_PROTECTION) if (!rcode) putc ('\n'); #endif /* CONFIG_SYS_FLASH_PROTECTION */ } if (protected) { /* printf ("%sProtected %d sectors\n", */ /* p ? "" : "Un-", protected); */ } else { printf ("Error: start and/or end address" " not on sector boundary\n"); rcode = 1; } return rcode; } #endif
1001-study-uboot
tools/updater/cmd_flash.c
C
gpl3
10,285
#include <common.h> #include <exports.h> extern unsigned long __dummy; void do_reset (void); void do_updater(void); void _main(void) { int i; printf("U-Boot Firmware Updater\n\n\n"); printf("****************************************************\n" "* ATTENTION!! PLEASE READ THIS NOTICE CAREFULLY! *\n" "****************************************************\n\n" "This program will update your computer's firmware.\n" "Do NOT remove the disk, reset the machine, or do\n" "anything that might disrupt functionality. If this\n"); printf("Program fails, your computer might be unusable, and\n" "you will need to return your board for reflashing.\n" "If you find this too risky, remove the diskette and\n" "switch off your machine now. Otherwise press the \n" "SPACE key now to start the process\n\n"); do { char x; while (!tstc()); x = getc(); if (x == ' ') break; } while (1); do_updater(); i = 5; printf("\nUpdate done. Please remove diskette.\n"); printf("The machine will automatically reset in %d seconds\n", i); printf("You can switch off/reset now when the floppy is removed\n\n"); while (i) { printf("Resetting in %d\r", i); udelay(1000000); i--; } do_reset(); while (1); } void do_updater(void) { unsigned long *addr = &__dummy + 65; unsigned long flash_size = flash_init(); int rc; flash_sect_protect(0, 0xFFF00000, 0xFFF7FFFF); printf("Erasing "); flash_sect_erase(0xFFF00000, 0xFFF7FFFF); printf("Writing "); rc = flash_write((uchar *)addr, 0xFFF00000, 0x7FFFF); if (rc != 0) printf("\nFlashing failed due to error %d\n", rc); else printf("\ndone\n"); flash_sect_protect(1, 0xFFF00000, 0xFFF7FFFF); }
1001-study-uboot
tools/updater/update.c
C
gpl3
1,824
#include <common.h> #include <asm/processor.h> #include <memio.h> #include <linux/ctype.h> static __inline__ unsigned long get_msr(void) { unsigned long msr; asm volatile("mfmsr %0" : "=r" (msr) :); return msr; } static __inline__ void set_msr(unsigned long msr) { asm volatile("mtmsr %0" : : "r" (msr)); } static __inline__ unsigned long get_dec(void) { unsigned long val; asm volatile("mfdec %0" : "=r" (val) :); return val; } static __inline__ void set_dec(unsigned long val) { asm volatile("mtdec %0" : : "r" (val)); } void enable_interrupts(void) { set_msr (get_msr() | MSR_EE); } /* returns flag if MSR_EE was set before */ int disable_interrupts(void) { ulong msr; msr = get_msr(); set_msr (msr & ~MSR_EE); return ((msr & MSR_EE) != 0); } u8 in8(u32 port) { return in_byte(port); } void out8(u32 port, u8 val) { out_byte(port, val); } unsigned long in32(u32 port) { return in_long(port); } unsigned long simple_strtoul(const char *cp,char **endp,unsigned int base) { unsigned long result = 0,value; if (*cp == '0') { cp++; if ((*cp == 'x') && isxdigit(cp[1])) { base = 16; cp++; } if (!base) { base = 8; } } if (!base) { base = 10; } while (isxdigit(*cp) && (value = isdigit(*cp) ? *cp-'0' : (islower(*cp) ? toupper(*cp) : *cp)-'A'+10) < base) { result = result*base + value; cp++; } if (endp) *endp = (char *)cp; return result; } long simple_strtol(const char *cp,char **endp,unsigned int base) { if(*cp=='-') return -simple_strtoul(cp+1,endp,base); return simple_strtoul(cp,endp,base); } static inline void soft_restart(unsigned long addr) { /* SRR0 has system reset vector, SRR1 has default MSR value */ /* rfi restores MSR from SRR1 and sets the PC to the SRR0 value */ __asm__ __volatile__ ("mtspr 26, %0" :: "r" (addr)); __asm__ __volatile__ ("li 4, (1 << 6)" ::: "r4"); __asm__ __volatile__ ("mtspr 27, 4"); __asm__ __volatile__ ("rfi"); while(1); /* not reached */ } void do_reset (void) { ulong addr; /* flush and disable I/D cache */ __asm__ __volatile__ ("mfspr 3, 1008" ::: "r3"); __asm__ __volatile__ ("ori 5, 5, 0xcc00" ::: "r5"); __asm__ __volatile__ ("ori 4, 3, 0xc00" ::: "r4"); __asm__ __volatile__ ("andc 5, 3, 5" ::: "r5"); __asm__ __volatile__ ("sync"); __asm__ __volatile__ ("mtspr 1008, 4"); __asm__ __volatile__ ("isync"); __asm__ __volatile__ ("sync"); __asm__ __volatile__ ("mtspr 1008, 5"); __asm__ __volatile__ ("isync"); __asm__ __volatile__ ("sync"); #ifdef CONFIG_SYS_RESET_ADDRESS addr = CONFIG_SYS_RESET_ADDRESS; #else /* * note: when CONFIG_SYS_MONITOR_BASE points to a RAM address, * CONFIG_SYS_MONITOR_BASE - sizeof (ulong) is usually a valid * address. Better pick an address known to be invalid on your * system and assign it to CONFIG_SYS_RESET_ADDRESS. */ addr = CONFIG_SYS_MONITOR_BASE - sizeof (ulong); #endif soft_restart(addr); while(1); /* not reached */ }
1001-study-uboot
tools/updater/utils.c
C
gpl3
3,028
/* * (C) Copyright 2008 Semihalf * * (C) Copyright 2000-2004 * DENX Software Engineering * Wolfgang Denk, wd@denx.de * * Updated-by: Prafulla Wadaskar <prafulla@marvell.com> * FIT image specific code abstracted from mkimage.c * some functions added to address abstraction * * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include "mkimage.h" #include <image.h> #include <u-boot/crc.h> static image_header_t header; static int fit_verify_header (unsigned char *ptr, int image_size, struct mkimage_params *params) { return fdt_check_header ((void *)ptr); } static int fit_check_image_types (uint8_t type) { if (type == IH_TYPE_FLATDT) return EXIT_SUCCESS; else return EXIT_FAILURE; } /** * fit_handle_file - main FIT file processing function * * fit_handle_file() runs dtc to convert .its to .itb, includes * binary data, updates timestamp property and calculates hashes. * * datafile - .its file * imagefile - .itb file * * returns: * only on success, otherwise calls exit (EXIT_FAILURE); */ static int fit_handle_file (struct mkimage_params *params) { char tmpfile[MKIMAGE_MAX_TMPFILE_LEN]; char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN]; int tfd; struct stat sbuf; unsigned char *ptr; /* Flattened Image Tree (FIT) format handling */ debug ("FIT format handling\n"); /* call dtc to include binary properties into the tmp file */ if (strlen (params->imagefile) + strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) { fprintf (stderr, "%s: Image file name (%s) too long, " "can't create tmpfile", params->imagefile, params->cmdname); return (EXIT_FAILURE); } sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX); /* dtc -I dts -O -p 200 datafile > tmpfile */ sprintf (cmd, "%s %s %s > %s", MKIMAGE_DTC, params->dtc, params->datafile, tmpfile); debug ("Trying to execute \"%s\"\n", cmd); if (system (cmd) == -1) { fprintf (stderr, "%s: system(%s) failed: %s\n", params->cmdname, cmd, strerror(errno)); unlink (tmpfile); return (EXIT_FAILURE); } /* load FIT blob into memory */ tfd = open (tmpfile, O_RDWR|O_BINARY); if (tfd < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", params->cmdname, tmpfile, strerror(errno)); unlink (tmpfile); return (EXIT_FAILURE); } if (fstat (tfd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", params->cmdname, tmpfile, strerror(errno)); unlink (tmpfile); return (EXIT_FAILURE); } ptr = mmap (0, sbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, tfd, 0); if (ptr == MAP_FAILED) { fprintf (stderr, "%s: Can't read %s: %s\n", params->cmdname, tmpfile, strerror(errno)); unlink (tmpfile); return (EXIT_FAILURE); } /* check if ptr has a valid blob */ if (fdt_check_header (ptr)) { fprintf (stderr, "%s: Invalid FIT blob\n", params->cmdname); unlink (tmpfile); return (EXIT_FAILURE); } /* set hashes for images in the blob */ if (fit_set_hashes (ptr)) { fprintf (stderr, "%s Can't add hashes to FIT blob", params->cmdname); unlink (tmpfile); return (EXIT_FAILURE); } /* add a timestamp at offset 0 i.e., root */ if (fit_set_timestamp (ptr, 0, sbuf.st_mtime)) { fprintf (stderr, "%s: Can't add image timestamp\n", params->cmdname); unlink (tmpfile); return (EXIT_FAILURE); } debug ("Added timestamp successfully\n"); munmap ((void *)ptr, sbuf.st_size); close (tfd); if (rename (tmpfile, params->imagefile) == -1) { fprintf (stderr, "%s: Can't rename %s to %s: %s\n", params->cmdname, tmpfile, params->imagefile, strerror (errno)); unlink (tmpfile); unlink (params->imagefile); return (EXIT_FAILURE); } return (EXIT_SUCCESS); } static int fit_check_params (struct mkimage_params *params) { return ((params->dflag && (params->fflag || params->lflag)) || (params->fflag && (params->dflag || params->lflag)) || (params->lflag && (params->dflag || params->fflag))); } static struct image_type_params fitimage_params = { .name = "FIT Image support", .header_size = sizeof(image_header_t), .hdr = (void*)&header, .verify_header = fit_verify_header, .print_header = fit_print_contents, .check_image_type = fit_check_image_types, .fflag_handle = fit_handle_file, .set_header = NULL, /* FIT images use DTB header */ .check_params = fit_check_params, }; void init_fit_image_type (void) { mkimage_register (&fitimage_params); }
1001-study-uboot
tools/fit_image.c
C
gpl3
5,074
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // doedit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Add Log Entry Results"); if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '') die("serial number not specified!"); $serno=intval($_REQUEST['serno']); if (isset($_REQUEST['logno'])) { $logno=$_REQUEST['logno']; die("log number must not be set ($logno) when Creating!"); } $query="update log set serno=$serno"; list($y, $m, $d) = split("-", $date); if (!checkdate($m, $d, $y) || $y < 1999) die("date is invalid (input '$date', yyyy-mm-dd '$y-$m-$d')"); $query.=", date='$date'"; if (isset($_REQUEST['who'])) { $who=$_REQUEST['who']; $query.=", who='" . $who . "'"; } if (isset($_REQUEST['details'])) { $details=$_REQUEST['details']; $query.=", details='" . rawurlencode($details) . "'"; } // echo "final query = '$query'<br>\n"; $sqlerr = ''; mysql_query("insert into log (logno) values (null)"); if (mysql_errno()) $sqlerr = mysql_error(); else { $logno = mysql_insert_id(); if (!$logno) $sqlerr = "couldn't allocate new serial number"; else { mysql_query($query . " where logno=$logno"); if (mysql_errno()) $sqlerr = mysql_error(); } } if ($sqlerr == '') { echo "<font size=+2>\n"; echo "\t<p>\n"; echo "\t\tA log entry with log number '$logno' was " . "added to the board with serial number '$serno'\n"; echo "\t</p>\n"; echo "</font>\n"; } else { echo "\t<font size=+4>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe following SQL error was encountered:\n"; echo "\t\t</p>\n"; echo "\t\t<center>\n"; printf("\t\t\t<b>%s</b>\n", $sqlerr); echo "\t\t</center>\n"; echo "\t</font>\n"; } ?> <p></p> <table width="100%"> <tr> <td align=center><a href="brlog.php?serno=<?php echo "$serno"; ?>">Go to Browse</a></td> <td align=center><a href="index.php">Back to Start</a></td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/donewlog.php
PHP
gpl3
2,106
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // edit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - New Board Registration"); ?> <form action=donew.php method=POST> <p></p> <?php $serno=intval($serno); // if a serial number was supplied, fetch the record // and use its contents as defaults if ($serno != 0) { $r=mysql_query("select * from boards where serno=$serno"); $row=mysql_fetch_array($r); if(!$row)die("no record of serial number '$serno' in database"); } else $row = array(); begin_table(5); // date date print_field("date", array('date' => date("Y-m-d"))); // batch char(32) print_field("batch", $row, 32); // type enum('IO','CLP','DSP','INPUT','ALT-INPUT','DISPLAY') print_enum("type", $row, $type_vals, 0); // rev tinyint(3) unsigned zerofill print_field("rev", $row, 3, 'rev_filter'); // sdram[0-3] enum('32M','64M','128M','256M') print_enum_multi("sdram", $row, $sdram_vals, 4, array(2)); // flash[0-3] enum('4M','8M','16M','32M','64M') print_enum_multi("flash", $row, $flash_vals, 4, array(2)); // zbt[0-f] enum('512K','1M','2M','4M') print_enum_multi("zbt", $row, $zbt_vals, 16, array(2, 2)); // xlxtyp[0-3] enum('XCV300E','XCV400E','XCV600E') print_enum_multi("xlxtyp", $row, $xlxtyp_vals, 4, array(1), 1); // xlxspd[0-3] enum('6','7','8') print_enum_multi("xlxspd", $row, $xlxspd_vals, 4, array(1), 1); // xlxtmp[0-3] enum('COM','IND') print_enum_multi("xlxtmp", $row, $xlxtmp_vals, 4, array(1), 1); // xlxgrd[0-3] enum('NORMAL','ENGSAMP') print_enum_multi("xlxgrd", $row, $xlxgrd_vals, 4, array(1), 1); // cputyp enum('MPC8260(HIP3)','MPC8260A(HIP4)','MPC8280(HIP7)') print_enum("cputyp", $row, $cputyp_vals, 1); // cpuspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ') print_enum_select("cpuspd", $row, $clk_vals, 4); // cpmspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ') print_enum_select("cpmspd", $row, $clk_vals, 4); // busspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ') print_enum_select("busspd", $row, $clk_vals, 2); // hstype enum('AMCC-S2064A') print_enum("hstype", $row, $hstype_vals, 1); // hschin enum('0','1','2','3','4') print_enum("hschin", $row, $hschin_vals, 4); // hschout enum('0','1','2','3','4') print_enum("hschout", $row, $hschout_vals, 4); end_table(); ?> <p></p> <table width="100%"> <tr> <td align=center colspan=3> Allocate <input type=text name=quant size=2 maxlength=2 value=" 1"> board serial number(s) </td> </tr> <tr> <td align=center colspan=3> <input type=checkbox name=geneths checked> Generate Ethernet Address(es) </td> </tr> <tr> <td colspan=3> &nbsp; </td> </tr> <tr> <td align=center> <input type=submit value="Register Board"> </td> <td> &nbsp; </td> <td align=center> <input type=reset value="Reset Form Contents"> </td> </tr> </table> </form> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/new.php
PHP
gpl3
3,145
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // dodelete page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Delete Log Entry Results"); if (!isset($_REQUEST['serno'])) die("the board serial number was not specified"); $serno=intval($_REQUEST['serno']); if (!isset($_REQUEST['logno']) || $_REQUEST['logno'] == 0) die("the log entry number not specified!"); $logno=$_REQUEST['logno']; mysql_query("delete from log where serno=$serno and logno=$logno"); if(mysql_errno()) { $errstr = mysql_error(); echo "\t<font size=+4>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe following error was encountered:\n"; echo "\t\t</p>\n"; echo "\t\t<center>\n"; printf("\t\t\t<b>%s</b>\n", $errstr); echo "\t\t</center>\n"; echo "\t</font>\n"; } else { echo "\t<font size=+2>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe log entry with log number <b>$logno</b>\n"; echo "\t\t\tand serial number <b>$serno</b> "; echo "was successfully deleted\n"; echo "\t\t</p>\n"; echo "\t</font>\n"; } ?> <p> <table width="100%"> <tr> <td align=center> <a href="brlog.php?serno=<?php echo "$serno"; ?>">Back to Log</a> </td> <td align=center> <a href="index.php">Back to Start</a> </td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/dodellog.php
PHP
gpl3
1,430
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab require("defs.php"); pg_head("$bddb_label - Unknown Submit Type"); ?> <center> <font size="+4"> <b> The <?php echo "$bddb_label"; ?> form was submitted with an unknown SUBMIT type <?php echo "(value was '$submit')" ?>. <br></br> Perhaps you typed the URL in directly? Click here to go to the home page of the <a href="index.php"><?php echo "$bddb_label"; ?></a>. </b> </font> </center> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/badsubmit.php
PHP
gpl3
660
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // doedit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Board Registration Results"); if (isset($_REQUEST['serno'])) { $serno=$_REQUEST['serno']; die("serial number must not be set ($serno) when Creating!"); } $query="update boards set"; list($y, $m, $d) = split("-", $date); if (!checkdate($m, $d, $y) || $y < 1999) die("date is invalid (input '$date', yyyy-mm-dd '$y-$m-$d')"); $query.=" date='$date'"; if ($batch != '') { if (strlen($batch) > 32) die("batch field too long (>32)"); $query.=", batch='$batch'"; } if (!in_array($type, $type_vals)) die("Invalid type ($type) specified"); $query.=", type='$type'"; if (($rev = intval($rev)) <= 0 || $rev > 255) die("Revision number is invalid ($rev)"); $query.=sprintf(", rev=%d", $rev); $query.=gather_enum_multi_query("sdram", 4); $query.=gather_enum_multi_query("flash", 4); $query.=gather_enum_multi_query("zbt", 16); $query.=gather_enum_multi_query("xlxtyp", 4); $nxlx = count_enum_multi("xlxtyp", 4); $query.=gather_enum_multi_query("xlxspd", 4); if (count_enum_multi("xlxspd", 4) != $nxlx) die("number of xilinx speeds not same as number of types"); $query.=gather_enum_multi_query("xlxtmp", 4); if (count_enum_multi("xlxtmp", 4) != $nxlx) die("number of xilinx temps. not same as number of types"); $query.=gather_enum_multi_query("xlxgrd", 4); if (count_enum_multi("xlxgrd", 4) != $nxlx) die("number of xilinx grades not same as number of types"); if ($cputyp == '') { if ($cpuspd != '') die("can't specify cpu speed if there is no cpu"); if ($cpmspd != '') die("can't specify cpm speed if there is no cpu"); if ($busspd != '') die("can't specify bus speed if there is no cpu"); } else { $query.=", cputyp='$cputyp'"; if ($cpuspd == '') die("must specify cpu speed if cpu type is defined"); $query.=", cpuspd='$cpuspd'"; if ($cpmspd == '') die("must specify cpm speed if cpu type is defined"); $query.=", cpmspd='$cpmspd'"; if ($busspd == '') die("must specify bus speed if cpu type is defined"); $query.=", busspd='$busspd'"; } if (($hschin = intval($hschin)) < 0 || $hschin > 4) die("Invalid number of hs input chans ($hschin)"); if (($hschout = intval($hschout)) < 0 || $hschout > 4) die("Invalid number of hs output chans ($hschout)"); if ($hstype == '') { if ($hschin != 0) die("number of high-speed input channels must be zero" . " if high-speed chip is not present"); if ($hschout != 0) die("number of high-speed output channels must be zero" . " if high-speed chip is not present"); } else $query.=", hstype='$hstype'"; $query.=", hschin='$hschin'"; $query.=", hschout='$hschout'"; // echo "final query = '$query'<br>\n"; $quant = intval($quant); if ($quant <= 0) $quant = 1; $sernos = array(); if ($geneths) $ethaddrs = array(); $sqlerr = ''; while ($quant-- > 0) { mysql_query("insert into boards (serno) values (null)"); if (mysql_errno()) { $sqlerr = mysql_error(); break; } $serno = mysql_insert_id(); if (!$serno) { $sqlerr = "couldn't allocate new serial number"; break; } mysql_query($query . " where serno=$serno"); if (mysql_errno()) { $sqlerr = mysql_error(); break; } array_push($sernos, $serno); if ($geneths) { $ethaddr = gen_eth_addr($serno); mysql_query("update boards set ethaddr='$ethaddr'" . " where serno=$serno"); if (mysql_errno()) { $sqlerr = mysql_error(); array_push($ethaddrs, "<font color=#ff0000><b>" . "db save fail" . "</b></font>"); break; } array_push($ethaddrs, $ethaddr); } } $nsernos = count($sernos); if ($nsernos > 0) { write_eeprom_cfg_file(); echo "<font size=+2>\n"; echo "\t<p>\n"; echo "\t\tThe following board serial numbers were" . " successfully allocated"; if ($numerrs > 0) echo " (but with $numerrs cfg file error" . ($numerrs > 1 ? "s" : "") . ")"; echo ":\n"; echo "\t</p>\n"; echo "</font>\n"; echo "<table align=center width=\"100%\">\n"; echo "<tr>\n"; echo "\t<th>Serial Number</th>\n"; if ($numerrs > 0) echo "\t<th>Cfg File Errs</th>\n"; if ($geneths) echo "\t<th>Ethernet Address</th>\n"; echo "</tr>\n"; for ($i = 0; $i < $nsernos; $i++) { $serno = sprintf("%010d", $sernos[$i]); echo "<tr>\n"; echo "\t<td align=center><font size=+2>" . "<b>$serno</b></font></td>\n"; if ($numerrs > 0) { if (($errstr = $cfgerrs[$i]) == '') $errstr = '&nbsp;'; echo "\t<td align=center>" . "<font size=+2 color=#ff0000><b>" . $errstr . "</b></font></td>\n"; } if ($geneths) { echo "\t<td align=center>" . "<font size=+2 color=#00ff00><b>" . $ethaddrs[$i] . "</b></font></td>\n"; } echo "</tr>\n"; } echo "</table>\n"; } if ($sqlerr != '') { echo "\t<font size=+4>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe following SQL error was encountered:\n"; echo "\t\t</p>\n"; echo "\t\t<center>\n"; printf("\t\t\t<b>%s</b>\n", $sqlerr); echo "\t\t</center>\n"; echo "\t</font>\n"; } ?> <p> <table align=center width="100%"> <tr> <td align=center><a href="browse.php">Go to Browse</a></td> <td align=center><a href="index.php">Back to Start</a></td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/donew.php
PHP
gpl3
5,533
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab $serno=isset($_REQUEST['serno'])?$_REQUEST['serno']:''; $submit=isset($_REQUEST['submit'])?$_REQUEST['submit']:"[NOT SET]"; switch ($submit) { case "New": require("new.php"); break; case "Edit": require("edit.php"); break; case "Browse": require("browse.php"); break; case "Log": require("brlog.php"); break; default: require("badsubmit.php"); break; } ?>
1001-study-uboot
tools/bddb/execute.php
PHP
gpl3
601
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // contains mysql user id and password - keep secret require("config.php"); if (isset($_REQUEST['logout'])) { Header("status: 401 Unauthorized"); Header("HTTP/1.0 401 Unauthorized"); Header("WWW-authenticate: basic realm=\"$bddb_label\""); echo "<html><head><title>" . "Access to '$bddb_label' Denied" . "</title></head>\n"; echo "<body bgcolor=#ffffff><br></br><br></br><center><h1>" . "You must be an Authorised User " . "to access the '$bddb_label'" . "</h1>\n</center></body></html>\n"; exit; } // contents of the various enumerated types - if first item is // empty ('') then the enum is allowed to be null (ie "not null" // is not set on the column) // all column names in the database table $columns = array( 'serno','ethaddr','date','batch', 'type','rev','location','comments', 'sdram0','sdram1','sdram2','sdram3', 'flash0','flash1','flash2','flash3', 'zbt0','zbt1','zbt2','zbt3','zbt4','zbt5','zbt6','zbt7', 'zbt8','zbt9','zbta','zbtb','zbtc','zbtd','zbte','zbtf', 'xlxtyp0','xlxtyp1','xlxtyp2','xlxtyp3', 'xlxspd0','xlxspd1','xlxspd2','xlxspd3', 'xlxtmp0','xlxtmp1','xlxtmp2','xlxtmp3', 'xlxgrd0','xlxgrd1','xlxgrd2','xlxgrd3', 'cputyp','cpuspd','cpmspd','busspd', 'hstype','hschin','hschout' ); // board type $type_vals = array('IO','CLP','DSP','INPUT','ALT-INPUT','DISPLAY'); // Xilinx fpga types $xlxtyp_vals = array('','XCV300E','XCV400E','XCV600E','XC2V2000','XC2V3000','XC2V4000','XC2V6000','XC2VP2','XC2VP4','XC2VP7','XC2VP20','XC2VP30','XC2VP50','XC4VFX20','XC4VFX40','XC4VFX60','XC4VFX100','XC4VFX140'); // Xilinx fpga speeds $xlxspd_vals = array('','6','7','8','4','5','9','10','11','12'); // Xilinx fpga temperatures (commercial or industrial) $xlxtmp_vals = array('','COM','IND'); // Xilinx fpga grades (normal or engineering sample) $xlxgrd_vals = array('','NORMAL','ENGSAMP'); // CPU types $cputyp_vals = array('','MPC8260(HIP3)','MPC8260A(HIP4)','MPC8280(HIP7)','MPC8560'); // CPU/BUS/CPM clock speeds $clk_vals = array('','33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ','300MHZ','333MHZ','366MHZ','400MHZ','433MHZ','466MHZ','500MHZ','533MHZ','566MHZ','600MHZ','633MHZ','666MHZ','700MHZ','733MHZ','766MHZ','800MHZ','833MHZ','866MHZ','900MHZ','933MHZ','966MHZ','1000MHZ','1033MHZ','1066MHZ','1100MHZ','1133MHZ','1166MHZ','1200MHZ','1233MHZ','1266MHZ','1300MHZ','1333MHZ'); // sdram sizes (nbits array is for eeprom config file) $sdram_vals = array('','32M','64M','128M','256M','512M','1G','2G','4G'); $sdram_nbits = array(0,25,26,27,28,29,30,31,32); // flash sizes (nbits array is for eeprom config file) $flash_vals = array('','4M','8M','16M','32M','64M','128M','256M','512M','1G'); $flash_nbits = array(0,22,23,24,25,26,27,28,29,30); // zbt ram sizes (nbits array is for write into eeprom config file) $zbt_vals = array('','512K','1M','2M','4M','8M','16M'); $zbt_nbits = array(0,19,20,21,22,23,24); // high-speed serial attributes $hstype_vals = array('','AMCC-S2064A','Xilinx-Rockets'); $hschin_vals = array('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'); $hschout_vals = array('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'); // value filters - used when outputting html function rev_filter($num) { if ($num == 0) return "001"; else return sprintf("%03d", $num); } function text_filter($str) { return urldecode($str); } mt_srand(time() | getmypid()); // set up MySQL connection mysql_connect("", $mysql_user, $mysql_pw) || die("cannot connect"); mysql_select_db($mysql_db) || die("cannot select db"); // page header function pg_head($title) { echo "<html>\n<head>\n"; echo "<link rel=stylesheet href=\"bddb.css\" type=\"text/css\" title=\"style sheet\"></link>\n"; echo "<title>$title</title>\n"; echo "</head>\n"; echo "<body>\n"; echo "<center><h1>$title</h1></center>\n"; echo "<hr></hr>\n"; } // page footer function pg_foot() { echo "<hr></hr>\n"; echo "<table width=\"100%\"><tr><td align=left>\n<address>" . "If you have any problems, email " . "<a href=\"mailto:Murray.Jensen@csiro.au\">" . "Murray Jensen" . "</a></address>\n" . "</td><td align=right>\n" . "<a href=\"index.php?logout=true\">logout</a>\n" . "</td></tr></table>\n"; echo "<p><small><i>Made with " . "<a href=\"http://kyber.dk/phpMyBuilder/\">" . "Kyber phpMyBuilder</a></i></small></p>\n"; echo "</body>\n"; echo "</html>\n"; } // some support functions if (!function_exists('array_search')) { function array_search($needle, $haystack, $strict = false) { if (is_array($haystack) && count($haystack)) { $ntype = gettype($needle); foreach ($haystack as $key => $value) { if ($value == $needle && (!$strict || gettype($value) == $ntype)) return $key; } } return false; } } if (!function_exists('in_array')) { function in_array($needle, $haystack, $strict = false) { if (is_array($haystack) && count($haystack)) { $ntype = gettype($needle); foreach ($haystack as $key => $value) { if ($value == $needle && (!$strict || gettype($value) == $ntype)) return true; } } return false; } } function key_in_array($key, $array) { return in_array($key, array_keys($array), true); } function enum_to_index($name, $vals) { $index = array_search($GLOBALS[$name], $vals); if ($vals[0] != '') $index++; return $index; } // fetch a value from an array - return empty string is not present function get_key_value($key, $array) { if (key_in_array($key, $array)) return $array[$key]; else return ''; } function fprintf() { $n = func_num_args(); if ($n < 2) return FALSE; $a = func_get_args(); $fp = array_shift($a); $x = "\$s = sprintf"; $sep = '('; foreach ($a as $z) { $x .= "$sep'$z'"; $sep = ','; } $x .= ');'; eval($x); $l = strlen($s); $r = fwrite($fp, $s, $l); if ($r != $l) return FALSE; else return TRUE; } // functions to display (print) a database table and its columns function begin_table($ncols) { global $table_ncols; $table_ncols = $ncols; echo "<table align=center width=\"100%\"" . " border=1 cellpadding=4 cols=$table_ncols>\n"; } function begin_field($name, $span = 0) { global $table_ncols; echo "<tr valign=top>\n"; echo "\t<th align=center>$name</th>\n"; if ($span <= 0) $span = $table_ncols - 1; if ($span > 1) echo "\t<td colspan=$span>\n"; else echo "\t<td>\n"; } function cont_field($span = 1) { echo "\t</td>\n"; if ($span > 1) echo "\t<td colspan=$span>\n"; else echo "\t<td>\n"; } function end_field() { echo "\t</td>\n"; echo "</tr>\n"; } function end_table() { echo "</table>\n"; } function print_field($name, $array, $size = 0, $filt='') { begin_field($name); if (key_in_array($name, $array)) $value = $array[$name]; else $value = ''; if ($filt != '') $value = $filt($value); echo "\t\t<input name=$name value=\"$value\""; if ($size > 0) echo " size=$size maxlength=$size"; echo "></input>\n"; end_field(); } function print_field_multiline($name, $array, $cols, $rows, $filt='') { begin_field($name); if (key_in_array($name, $array)) $value = $array[$name]; else $value = ''; if ($filt != '') $value = $filt($value); echo "\t\t<textarea name=$name " . "cols=$cols rows=$rows wrap=off>\n"; echo "$value"; echo "</textarea>\n"; end_field(); } // print a mysql ENUM as an html RADIO INPUT function print_enum($name, $array, $vals, $def = -1) { begin_field($name); if (key_in_array($name, $array)) $chk = array_search($array[$name], $vals, FALSE); else $chk = $def; $nval = count($vals); for ($i = 0; $i < $nval; $i++) { $val = $vals[$i]; if ($val == '') $pval = "none"; else $pval = "$val"; printf("\t\t<input type=radio name=$name" . " value=\"$val\"%s>$pval</input>\n", $i == $chk ? " checked" : ""); } end_field(); } // print a mysql ENUM as an html SELECT INPUT function print_enum_select($name, $array, $vals, $def = -1) { begin_field($name); echo "\t\t<select name=$name>\n"; if (key_in_array($name, $array)) $chk = array_search($array[$name], $vals, FALSE); else $chk = $def; $nval = count($vals); for ($i = 0; $i < $nval; $i++) { $val = $vals[$i]; if ($val == '') $pval = "none"; else $pval = "$val"; printf("\t\t\t<option " . "value=\"%s\"%s>%s</option>\n", $val, $i == $chk ? " selected" : "", $pval); } echo "\t\t</select>\n"; end_field(); } // print a group of mysql ENUMs (e.g. name0,name1,...) as an html SELECT function print_enum_multi($base, $array, $vals, $cnt, $defs, $grp = 0) { global $table_ncols; if ($grp <= 0) $grp = $cnt; $ncell = $cnt / $grp; $span = ($table_ncols - 1) / $ncell; begin_field($base, $span); $nval = count($vals); for ($i = 0; $i < $cnt; $i++) { if ($i > 0 && ($i % $grp) == 0) cont_field($span); $name = sprintf("%s%x", $base, $i); echo "\t\t<select name=$name>\n"; if (key_in_array($name, $array)) $ai = array_search($array[$name], $vals, FALSE); else { if (key_in_array($i, $defs)) $ai = $defs[$i]; else $ai = 0; } for ($j = 0; $j < $nval; $j++) { $val = $vals[$j]; if ($val == '') $pval = "&nbsp;"; else $pval = "$val"; printf("\t\t\t<option " . "value=\"%s\"%s>%s</option>\n", $val, $j == $ai ? " selected" : "", $pval); } echo "\t\t</select>\n"; } end_field(); } // functions to handle the form input // fetch all the parts of an "enum_multi" into a string suitable // for a MySQL query function gather_enum_multi_query($base, $cnt) { $retval = ''; for ($i = 0; $i < $cnt; $i++) { $name = sprintf("%s%x", $base, $i); if (isset($_REQUEST[$name])) { $retval .= sprintf(", %s='%s'", $name, $_REQUEST[$name]); } } return $retval; } // fetch all the parts of an "enum_multi" into a string suitable // for a display e.g. in an html table cell function gather_enum_multi_print($base, $cnt, $array) { $retval = ''; for ($i = 0; $i < $cnt; $i++) { $name = sprintf("%s%x", $base, $i); if ($array[$name] != '') { if ($retval != '') $retval .= ','; $retval .= $array[$name]; } } return $retval; } // fetch all the parts of an "enum_multi" into a string suitable // for writing to the eeprom data file function gather_enum_multi_write($base, $cnt, $vals, $xfrm = array()) { $retval = ''; for ($i = 0; $i < $cnt; $i++) { $name = sprintf("%s%x", $base, $i); if ($GLOBALS[$name] != '') { if ($retval != '') $retval .= ','; $index = enum_to_index($name, $vals); if ($xfrm != array()) $retval .= $xfrm[$index]; else $retval .= $index; } } return $retval; } // count how many parts of an "enum_multi" are actually set function count_enum_multi($base, $cnt) { $retval = 0; for ($i = 0; $i < $cnt; $i++) { $name = sprintf("%s%x", $base, $i); if (isset($_REQUEST[$name])) $retval++; } return $retval; } // ethernet address functions // generate a (possibly not unique) random vendor ethernet address // (setting bit 6 in the ethernet address - motorola wise i.e. bit 0 // is the most significant bit - means it is not an assigned ethernet // address - it is a "locally administered" address). Also, make sure // it is NOT a multicast ethernet address (by setting bit 7 to 0). // e.g. the first byte of all ethernet addresses generated here will // have 2 in the bottom two bits (incidentally, these are the first // two bits transmitted on the wire, since the octets in ethernet // addresses are transmitted LSB first). function gen_eth_addr($serno) { $ethaddr_hgh = (mt_rand(0, 65535) & 0xfeff) | 0x0200; $ethaddr_mid = mt_rand(0, 65535); $ethaddr_low = mt_rand(0, 65535); return sprintf("%02lx:%02lx:%02lx:%02lx:%02lx:%02lx", $ethaddr_hgh >> 8, $ethaddr_hgh & 0xff, $ethaddr_mid >> 8, $ethaddr_mid & 0xff, $ethaddr_low >> 8, $ethaddr_low & 0xff); } // check that an ethernet address is valid function eth_addr_is_valid($ethaddr) { $ethbytes = split(':', $ethaddr); if (count($ethbytes) != 6) return FALSE; for ($i = 0; $i < 6; $i++) { $ethbyte = $ethbytes[$i]; if (!ereg('^[0-9a-f][0-9a-f]$', $ethbyte)) return FALSE; } return TRUE; } // write a simple eeprom configuration file function write_eeprom_cfg_file() { global $sernos, $nsernos, $bddb_cfgdir, $numerrs, $cfgerrs; global $date, $batch, $type_vals, $rev; global $sdram_vals, $sdram_nbits; global $flash_vals, $flash_nbits; global $zbt_vals, $zbt_nbits; global $xlxtyp_vals, $xlxspd_vals, $xlxtmp_vals, $xlxgrd_vals; global $cputyp, $cputyp_vals, $clk_vals; global $hstype, $hstype_vals, $hschin, $hschout; $numerrs = 0; $cfgerrs = array(); for ($i = 0; $i < $nsernos; $i++) { $serno = sprintf("%010d", $sernos[$i]); $wfp = @fopen($bddb_cfgdir . "/$serno.cfg", "w"); if (!$wfp) { $cfgerrs[$i] = 'file create fail'; $numerrs++; continue; } set_file_buffer($wfp, 0); if (!fprintf($wfp, "serno=%d\n", $sernos[$i])) { $cfgerrs[$i] = 'cfg wr fail (serno)'; fclose($wfp); $numerrs++; continue; } if (!fprintf($wfp, "date=%s\n", $date)) { $cfgerrs[$i] = 'cfg wr fail (date)'; fclose($wfp); $numerrs++; continue; } if ($batch != '') { if (!fprintf($wfp, "batch=%s\n", $batch)) { $cfgerrs[$i] = 'cfg wr fail (batch)'; fclose($wfp); $numerrs++; continue; } } $typei = enum_to_index("type", $type_vals); if (!fprintf($wfp, "type=%d\n", $typei)) { $cfgerrs[$i] = 'cfg wr fail (type)'; fclose($wfp); $numerrs++; continue; } if (!fprintf($wfp, "rev=%d\n", $rev)) { $cfgerrs[$i] = 'cfg wr fail (rev)'; fclose($wfp); $numerrs++; continue; } $s = gather_enum_multi_write("sdram", 4, $sdram_vals, $sdram_nbits); if ($s != '') { $b = fprintf($wfp, "sdram=%s\n", $s); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (sdram)'; fclose($wfp); $numerrs++; continue; } } $s = gather_enum_multi_write("flash", 4, $flash_vals, $flash_nbits); if ($s != '') { $b = fprintf($wfp, "flash=%s\n", $s); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (flash)'; fclose($wfp); $numerrs++; continue; } } $s = gather_enum_multi_write("zbt", 16, $zbt_vals, $zbt_nbits); if ($s != '') { $b = fprintf($wfp, "zbt=%s\n", $s); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (zbt)'; fclose($wfp); $numerrs++; continue; } } $s = gather_enum_multi_write("xlxtyp", 4, $xlxtyp_vals); if ($s != '') { $b = fprintf($wfp, "xlxtyp=%s\n", $s); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (xlxtyp)'; fclose($wfp); $numerrs++; continue; } } $s = gather_enum_multi_write("xlxspd", 4, $xlxspd_vals); if ($s != '') { $b = fprintf($wfp, "xlxspd=%s\n", $s); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (xlxspd)'; fclose($wfp); $numerrs++; continue; } } $s = gather_enum_multi_write("xlxtmp", 4, $xlxtmp_vals); if ($s != '') { $b = fprintf($wfp, "xlxtmp=%s\n", $s); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (xlxtmp)'; fclose($wfp); $numerrs++; continue; } } $s = gather_enum_multi_write("xlxgrd", 4, $xlxgrd_vals); if ($s != '') { $b = fprintf($wfp, "xlxgrd=%s\n", $s); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (xlxgrd)'; fclose($wfp); $numerrs++; continue; } } if ($cputyp != '') { $cputypi = enum_to_index("cputyp",$cputyp_vals); $cpuspdi = enum_to_index("cpuspd", $clk_vals); $busspdi = enum_to_index("busspd", $clk_vals); $cpmspdi = enum_to_index("cpmspd", $clk_vals); $b = fprintf($wfp, "cputyp=%d\ncpuspd=%d\n" . "busspd=%d\ncpmspd=%d\n", $cputypi, $cpuspdi, $busspdi, $cpmspdi); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (cputyp)'; fclose($wfp); $numerrs++; continue; } } if ($hstype != '') { $hstypei = enum_to_index("hstype",$hstype_vals); $b = fprintf($wfp, "hstype=%d\n" . "hschin=%s\nhschout=%s\n", $hstypei, $hschin, $hschout); if (!$b) { $cfgerrs[$i] = 'cfg wr fail (hstype)'; fclose($wfp); $numerrs++; continue; } } if (!fclose($wfp)) { $cfgerrs[$i] = 'file cls fail'; $numerrs++; } } return $numerrs; } ?>
1001-study-uboot
tools/bddb/defs.php
PHP
gpl3
16,949
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // list page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Browse Board Log"); $serno=intval($serno); if ($serno == 0) die("serial number not specified or invalid!"); function print_cell($str) { if ($str == '') $str = '&nbsp;'; echo "\t<td>$str</td>\n"; } ?> <table align=center border=1 cellpadding=10> <tr> <th>serno / edit</th> <th>ethaddr</th> <th>date</th> <th>batch</th> <th>type</th> <th>rev</th> <th>location</th> </tr> <?php $r=mysql_query("select * from boards where serno=$serno"); while($row=mysql_fetch_array($r)){ foreach ($columns as $key) { if (!key_in_array($key, $row)) $row[$key] = ''; } echo "<tr>\n"; print_cell("<a href=\"edit.php?serno=$row[serno]\">$row[serno]</a>"); print_cell($row['ethaddr']); print_cell($row['date']); print_cell($row['batch']); print_cell($row['type']); print_cell($row['rev']); print_cell($row['location']); echo "</tr>\n"; } mysql_free_result($r); ?> </table> <hr></hr> <p></p> <?php $limit=abs(isset($_REQUEST['limit'])?$_REQUEST['limit']:20); $offset=abs(isset($_REQUEST['offset'])?$_REQUEST['offset']:0); $lr=mysql_query("select count(*) as n from log where serno=$serno"); $lrow=mysql_fetch_array($lr); if($lrow['n']>$limit){ $preoffset=max(0,$offset-$limit); $postoffset=$offset+$limit; echo "<table width=\"100%\">\n<tr align=center>\n"; printf("<td><%sa href=\"%s?submit=Log&serno=$serno&offset=%d\"><img border=0 alt=\"&lt;\" src=\"/icons/left.gif\"></a></td>\n", $offset>0?"":"no", $PHP_SELF, $preoffset); printf("<td><%sa href=\"%s?submit=Log&serno=$serno&offset=%d\"><img border=0 alt=\"&gt;\" src=\"/icons/right.gif\"></a></td>\n", $postoffset<$lrow['n']?"":"no", $PHP_SELF, $postoffset); echo "</tr>\n</table>\n"; } mysql_free_result($lr); ?> <table width="100%" border=1 cellpadding=10> <tr valign=top> <th>logno / edit</th> <th>date</th> <th>who</th> <th width="70%">details</th> </tr> <?php $r=mysql_query("select * from log where serno=$serno order by logno limit $offset,$limit"); while($row=mysql_fetch_array($r)){ echo "<tr>\n"; print_cell("<a href=\"edlog.php?serno=$row[serno]&logno=$row[logno]\">$row[logno]</a>"); print_cell($row['date']); print_cell($row['who']); print_cell("<pre>" . urldecode($row['details']) . "</pre>"); echo "</tr>\n"; } mysql_free_result($r); ?> </table> <hr></hr> <p></p> <table width="100%"> <tr> <td align=center> <a href="newlog.php?serno=<?php echo "$serno"; ?>">Add to Log</a> </td> <td align=center> <a href="index.php">Back to Start</a> </td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/brlog.php
PHP
gpl3
2,821
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // edit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - New Log Entry"); if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '') die("serial number not specified or invalid!"); $serno=intval($_REQUEST['serno']); if (isset($_REQUEST['logno'])) { $logno=$_REQUEST['logno']; die("log number must not be specified when adding! ($logno)"); } ?> <form action=donewlog.php method=POST> <p></p> <?php echo "<input type=hidden name=serno value=$serno>\n"; begin_table(3); // date date print_field("date", array('date' => date("Y-m-d"))); // who char(20) print_field("who", array()); // details text print_field_multiline("details", array(), 60, 10, 'text_filter'); end_table(); ?> <p></p> <table width="100%"> <tr> <td align=center> <input type=submit value="Add Log Entry"> </td> <td align=center> <input type=reset value="Reset Form Contents"> </td> </tr> </table> </form> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/newlog.php
PHP
gpl3
1,170
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // edit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Edit Board Registration"); if ($serno == 0) die("serial number not specified or invalid!"); $pserno = sprintf("%010d", $serno); echo "<center><b><font size=+2>"; echo "Board Serial Number: $pserno"; echo "</font></b></center>\n"; ?> <p> <form action=doedit.php method=POST> <?php echo "<input type=hidden name=serno value=$serno>\n"; $r=mysql_query("select * from boards where serno=$serno"); $row=mysql_fetch_array($r); if(!$row) die("no record of serial number '$serno' in database"); begin_table(5); // ethaddr char(17) print_field("ethaddr", $row, 17); // date date print_field("date", $row); // batch char(32) print_field("batch", $row, 32); // type enum('IO','CLP','DSP','INPUT','ALT-INPUT','DISPLAY') print_enum("type", $row, $type_vals); // rev tinyint(3) unsigned zerofill print_field("rev", $row, 3, 'rev_filter'); // location char(64) print_field("location", $row, 64); // comments text print_field_multiline("comments", $row, 60, 10, 'text_filter'); // sdram[0-3] enum('32M','64M','128M','256M') print_enum_multi("sdram", $row, $sdram_vals, 4, array()); // flash[0-3] enum('4M','8M','16M','32M','64M') print_enum_multi("flash", $row, $flash_vals, 4, array()); // zbt[0-f] enum('512K','1M','2M','4M') print_enum_multi("zbt", $row, $zbt_vals, 16, array()); // xlxtyp[0-3] enum('XCV300E','XCV400E','XCV600E') print_enum_multi("xlxtyp", $row, $xlxtyp_vals, 4, array(), 1); // xlxspd[0-3] enum('6','7','8') print_enum_multi("xlxspd", $row, $xlxspd_vals, 4, array(), 1); // xlxtmp[0-3] enum('COM','IND') print_enum_multi("xlxtmp", $row, $xlxtmp_vals, 4, array(), 1); // xlxgrd[0-3] enum('NORMAL','ENGSAMP') print_enum_multi("xlxgrd", $row, $xlxgrd_vals, 4, array(), 1); // cputyp enum('MPC8260(HIP3)','MPC8260A(HIP4)','MPC8280(HIP7)') print_enum("cputyp", $row, $cputyp_vals); // cpuspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ') print_enum_select("cpuspd", $row, $clk_vals); // cpmspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ') print_enum_select("cpmspd", $row, $clk_vals); // busspd enum('33MHZ','66MHZ','100MHZ','133MHZ','166MHZ','200MHZ','233MHZ','266MHZ') print_enum_select("busspd", $row, $clk_vals); // hstype enum('AMCC-S2064A') print_enum("hstype", $row, $hstype_vals); // hschin enum('0','1','2','3','4') print_enum("hschin", $row, $hschin_vals); // hschout enum('0','1','2','3','4') print_enum("hschout", $row, $hschout_vals); end_table(); echo "<p>\n"; echo "<center><b>"; echo "<font color=#ff0000>WARNING: NO UNDO ON DELETE!</font>"; echo "<br></br>\n"; echo "<tt>[ <a href=\"dodelete.php?serno=$serno\">delete</a> ]</tt>"; echo "</b></center>\n"; echo "</p>\n"; ?> <p> <table align=center width="100%"> <tr> <td align=center> <input type=submit value=Edit> </td> <td> &nbsp; </td> <td align=center> <input type=reset value=Reset> </td> <td> &nbsp; </td> <td align=center> <a href="index.php">Back to Start</a> </td> </tr> </table> </p> </form> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/edit.php
PHP
gpl3
3,376
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // doedit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Edit Board Results"); if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '') die("the board serial number was not specified"); $serno=intval($_REQUEST['serno']); $query="update boards set"; if (isset($_REQUEST['ethaddr'])) { $ethaddr=$_REQUEST['ethaddr']; if (!eth_addr_is_valid($ethaddr)) die("ethaddr is invalid ('$ethaddr')"); $query.=" ethaddr='$ethaddr',"; } if (isset($_REQUEST['date'])) { $date=$_REQUEST['date']; list($y, $m, $d) = split("-", $date); if (!checkdate($m, $d, $y) || $y < 1999) die("date is invalid (input '$date', " . "yyyy-mm-dd '$y-$m-$d')"); $query.=" date='$date'"; } if (isset($_REQUEST['batch'])) { $batch=$_REQUEST['batch']; if (strlen($batch) > 32) die("batch field too long (>32)"); $query.=", batch='$batch'"; } if (isset($_REQUEST['type'])) { $type=$_REQUEST['type']; if (!in_array($type, $type_vals)) die("Invalid type ($type) specified"); $query.=", type='$type'"; } if (isset($_REQUEST['rev'])) { $rev=$_REQUEST['rev']; if (($rev = intval($rev)) <= 0 || $rev > 255) die("Revision number is invalid ($rev)"); $query.=sprintf(", rev=%d", $rev); } if (isset($_REQUEST['location'])) { $location=$_REQUEST['location']; if (strlen($location) > 64) die("location field too long (>64)"); $query.=", location='$location'"; } if (isset($_REQUEST['comments'])) $comments=$_REQUEST['comments']; $query.=", comments='" . rawurlencode($comments) . "'"; $query.=gather_enum_multi_query("sdram", 4); $query.=gather_enum_multi_query("flash", 4); $query.=gather_enum_multi_query("zbt", 16); $query.=gather_enum_multi_query("xlxtyp", 4); $nxlx = count_enum_multi("xlxtyp", 4); $query.=gather_enum_multi_query("xlxspd", 4); if (count_enum_multi("xlxspd", 4) != $nxlx) die("number of xilinx speeds not same as number of types"); $query.=gather_enum_multi_query("xlxtmp", 4); if (count_enum_multi("xlxtmp", 4) != $nxlx) die("number of xilinx temps. not same as number of types"); $query.=gather_enum_multi_query("xlxgrd", 4); if (count_enum_multi("xlxgrd", 4) != $nxlx) die("number of xilinx grades not same as number of types"); if (isset($_REQUEST['cputyp'])) { $cputyp=$_REQUEST['cputyp']; $query.=", cputyp='$cputyp'"; if (!isset($_REQUEST['cpuspd']) || $_REQUEST['cpuspd'] == '') die("must specify cpu speed if cpu type is defined"); $cpuspd=$_REQUEST['cpuspd']; $query.=", cpuspd='$cpuspd'"; if (!isset($_REQUEST['cpmspd']) || $_REQUEST['cpmspd'] == '') die("must specify cpm speed if cpu type is defined"); $cpmspd=$_REQUEST['cpmspd']; $query.=", cpmspd='$cpmspd'"; if (!isset($_REQUEST['busspd']) || $_REQUEST['busspd'] == '') die("must specify bus speed if cpu type is defined"); $busspd=$_REQUEST['busspd']; $query.=", busspd='$busspd'"; } else { if (isset($_REQUEST['cpuspd'])) die("can't specify cpu speed if there is no cpu"); if (isset($_REQUEST['cpmspd'])) die("can't specify cpm speed if there is no cpu"); if (isset($_REQUEST['busspd'])) die("can't specify bus speed if there is no cpu"); } if (isset($_REQUEST['hschin'])) { $hschin=$_REQUEST['hschin']; if (($hschin = intval($hschin)) < 0 || $hschin > 4) die("Invalid number of hs input chans ($hschin)"); } else $hschin = 0; if (isset($_REQUEST['hschout'])) { $hschout=$_REQUEST['hschout']; if (($hschout = intval($hschout)) < 0 || $hschout > 4) die("Invalid number of hs output chans ($hschout)"); } else $hschout = 0; if (isset($_REQUEST['hstype'])) { $hstype=$_REQUEST['hstype']; $query.=", hstype='$hstype'"; } else { if ($_REQUEST['hschin'] != 0) die("number of high-speed input channels must be zero" . " if high-speed chip is not present"); if ($_REQUEST['hschout'] != 0) die("number of high-speed output channels must be zero" . " if high-speed chip is not present"); } $query.=", hschin='$hschin'"; $query.=", hschout='$hschout'"; $query.=" where serno=$serno"; mysql_query($query); if(mysql_errno()) { $errstr = mysql_error(); echo "\t<font size=+4>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe following error was encountered:\n"; echo "\t\t</p>\n"; echo "\t\t<center>\n"; printf("\t\t\t<b>%s</b>\n", $errstr); echo "\t\t</center>\n"; echo "\t</font>\n"; } else { $sernos = array($serno); $nsernos = 1; write_eeprom_cfg_file(); echo "\t<font size=+2>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe board with serial number <b>$serno</b> was" . " successfully updated"; if ($numerrs > 0) { $errstr = $cfgerrs[0]; echo "<br>\n\t\t\t"; echo "(but the cfg file update failed: $errstr)"; } echo "\n"; echo "\t\t</p>\n"; echo "\t</font>\n"; } ?> <p> <table align=center width="100%"> <tr> <td align=center><a href="browse.php">Back to Browse</a></td> <td align=center><a href="index.php">Back to Start</a></td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/doedit.php
PHP
gpl3
5,206
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // doedit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Edit Log Entry Results"); if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '') die("the board serial number was not specified"); $serno=intval($_REQUEST['serno']); if (!isset($_REQUEST['logno']) || $_REQUEST['logno'] == '') die("log number not specified!"); $logno=intval($_REQUEST['logno']); $query="update log set"; if (isset($_REQUEST['date'])) { $date=$_REQUEST['date']; list($y, $m, $d) = split("-", $date); if (!checkdate($m, $d, $y) || $y < 1999) die("date is invalid (input '$date', " . "yyyy-mm-dd '$y-$m-$d')"); $query.=" date='$date'"; } if (isset($_REQUEST['who'])) { $who=$_REQUEST['who']; $query.=", who='" . $who . "'"; } if (isset($_REQUEST['details'])) { $details=$_REQUEST['details']; $query.=", details='" . rawurlencode($details) . "'"; } $query.=" where serno=$serno and logno=$logno"; mysql_query($query); if(mysql_errno()) { $errstr = mysql_error(); echo "\t<font size=+4>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe following error was encountered:\n"; echo "\t\t</p>\n"; echo "\t\t<center>\n"; printf("\t\t\t<b>%s</b>\n", $errstr); echo "\t\t</center>\n"; echo "\t</font>\n"; } else { echo "\t<font size=+2>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe log entry with log number <b>$logno</b> and\n"; echo "\t\t\tserial number <b>$serno</b> "; echo "was successfully updated\n"; echo "\t\t</p>\n"; echo "\t</font>\n"; } ?> <p> <table align=center width="100%"> <tr> <td align=center><a href="brlog.php?serno=<?php echo "$serno"; ?>">Back to Log</a></td> <td align=center><a href="index.php">Back to Start</a></td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/doedlog.php
PHP
gpl3
1,953
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // edit page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Edit Board Log Entry"); if (!isset($_REQUEST['serno']) || $_REQUEST['serno'] == '') die("serial number not specified!"); $serno=intval($_REQUEST['serno']); if (!isset($_REQUEST['logno']) || $_REQUEST['logno'] == '') die("log number not specified!"); $logno=intval($_REQUEST['logno']); $pserno = sprintf("%010d", $serno); $plogno = sprintf("%010d", $logno); echo "<center><b><font size=+2>"; echo "Board Serial Number: $pserno, Log Number: $plogno"; echo "</font></b></center>\n"; ?> <p> <form action=doedlog.php method=POST> <?php echo "<input type=hidden name=serno value=$serno>\n"; echo "<input type=hidden name=logno value=$logno>\n"; $r=mysql_query("select * from log where serno=$serno and logno=$logno"); $row=mysql_fetch_array($r); if(!$row) die("no record of log entry with serial number '$serno' " . "and log number '$logno' in database"); begin_table(3); // date date print_field("date", $row); // who char(20) print_field("who", $row); // details text print_field_multiline("details", $row, 60, 10, 'text_filter'); end_table(); echo "<p>\n"; echo "<center><b>"; echo "<font color=#ff0000>WARNING: NO UNDO ON DELETE!</font>"; echo "<br></br>\n"; echo "<tt>[ <a href=\"dodellog.php?serno=$serno&logno=$logno\">delete</a> ]</tt>"; echo "</b></center>\n"; echo "</p>\n"; ?> <p> <table align=center width="100%"> <tr> <td align=center> <input type=submit value=Edit> </td> <td> &nbsp; </td> <td align=center> <input type=reset value=Reset> </td> <td> &nbsp; </td> <td align=center> <a href="index.php">Back to Start</a> </td> </tr> </table> </p> </form> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/edlog.php
PHP
gpl3
1,965
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // dodelete page (hymod_bddb / boards) require("defs.php"); pg_head("$bddb_label - Delete Board Results"); if (!isset($_REQUEST['serno'])) die("the board serial number was not specified"); $serno=intval($_REQUEST['serno']); mysql_query("delete from boards where serno=$serno"); if(mysql_errno()) { $errstr = mysql_error(); echo "\t<font size=+4>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe following error was encountered:\n"; echo "\t\t</p>\n"; echo "\t\t<center>\n"; printf("\t\t\t<b>%s</b>\n", $errstr); echo "\t\t</center>\n"; echo "\t</font>\n"; } else { echo "\t<font size=+2>\n"; echo "\t\t<p>\n"; echo "\t\t\tThe board with serial number <b>$serno</b> was" . " successfully deleted\n"; mysql_query("delete from log where serno=$serno"); if (mysql_errno()) { $errstr = mysql_error(); echo "\t\t\t<font size=+4>\n"; echo "\t\t\t\t<p>\n"; echo "\t\t\t\t\tBut the following error occurred " . "when deleting the log entries:\n"; echo "\t\t\t\t</p>\n"; echo "\t\t\t\t<center>\n"; printf("\t\t\t\t\t<b>%s</b>\n", $errstr); echo "\t\t\t\t</center>\n"; echo "\t\t\t</font>\n"; } echo "\t\t</p>\n"; echo "\t</font>\n"; } ?> <p> <table width="100%"> <tr> <td align=center> <a href="browse.php">Back to Browse</a> </td> <td align=center> <a href="index.php">Back to Start</a> </td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/dodelete.php
PHP
gpl3
1,619
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // list page (hymod_bddb / boards) require("defs.php"); $serno=isset($_REQUEST['serno'])?$_REQUEST['serno']:''; $verbose=isset($_REQUEST['verbose'])?intval($_REQUEST['verbose']):0; pg_head("$bddb_label - Browse database" . ($verbose?" (verbose)":"")); ?> <p></p> <?php $limit=isset($_REQUEST['limit'])?abs(intval($_REQUEST['limit'])):20; $offset=isset($_REQUEST['offset'])?abs(intval($_REQUEST['offset'])):0; if ($serno == '') { $lr=mysql_query("select count(*) as n from boards"); $lrow=mysql_fetch_array($lr); if($lrow['n']>$limit){ $preoffset=max(0,$offset-$limit); $postoffset=$offset+$limit; echo "<table width=\"100%\">\n<tr>\n"; printf("<td align=left><%sa href=\"%s?submit=Browse&offset=%d&verbose=%d\"><img border=0 alt=\"&lt;\" src=\"/icons/left.gif\"></a></td>\n", $offset>0?"":"no", $PHP_SELF, $preoffset, $verbose); printf("<td align=right><%sa href=\"%s?submit=Browse&offset=%d&verbose=%d\"><img border=0 alt=\"&gt;\" src=\"/icons/right.gif\"></a></td>\n", $postoffset<$lrow['n']?"":"no", $PHP_SELF, $postoffset, $offset); echo "</tr>\n</table>\n"; } mysql_free_result($lr); } ?> <table align=center border=1 cellpadding=10> <tr> <th></th> <th>serno / edit</th> <th>ethaddr</th> <th>date</th> <th>batch</th> <th>type</th> <th>rev</th> <th>location</th> <?php if ($verbose) { echo "<th>comments</th>\n"; echo "<th>sdram</th>\n"; echo "<th>flash</th>\n"; echo "<th>zbt</th>\n"; echo "<th>xlxtyp</th>\n"; echo "<th>xlxspd</th>\n"; echo "<th>xlxtmp</th>\n"; echo "<th>xlxgrd</th>\n"; echo "<th>cputyp</th>\n"; echo "<th>cpuspd</th>\n"; echo "<th>cpmspd</th>\n"; echo "<th>busspd</th>\n"; echo "<th>hstype</th>\n"; echo "<th>hschin</th>\n"; echo "<th>hschout</th>\n"; } ?> </tr> <?php $query = "select * from boards"; if ($serno != '') { $pre = " where "; foreach (preg_split("/[\s,]+/", $serno) as $s) { if (preg_match('/^[0-9]+$/',$s)) $query .= $pre . "serno=" . $s; else if (preg_match('/^([0-9]+)-([0-9]+)$/',$s,$m)) { $m1 = intval($m[1]); $m2 = intval($m[2]); if ($m2 <= $m1) die("bad serial number range ($s)"); $query .= $pre . "(serno>=$m[1] and serno<=$m[2])"; } else die("illegal serial number ($s)"); $pre = " or "; } } $query .= " order by serno"; if ($serno == '') $query .= " limit $offset,$limit"; $r = mysql_query($query); function print_cell($str) { if ($str == '') $str = '&nbsp;'; echo "\t<td>$str</td>\n"; } while($row=mysql_fetch_array($r)){ foreach ($columns as $key) { if (!key_in_array($key, $row)) $row[$key] = ''; } echo "<tr>\n"; print_cell("<a href=\"brlog.php?serno=$row[serno]\">Log</a>"); print_cell("<a href=\"edit.php?serno=$row[serno]\">$row[serno]</a>"); print_cell($row['ethaddr']); print_cell($row['date']); print_cell($row['batch']); print_cell($row['type']); print_cell($row['rev']); print_cell($row['location']); if ($verbose) { print_cell("<pre>\n" . urldecode($row['comments']) . "\n\t</pre>"); print_cell(gather_enum_multi_print("sdram", 4, $row)); print_cell(gather_enum_multi_print("flash", 4, $row)); print_cell(gather_enum_multi_print("zbt", 16, $row)); print_cell(gather_enum_multi_print("xlxtyp", 4, $row)); print_cell(gather_enum_multi_print("xlxspd", 4, $row)); print_cell(gather_enum_multi_print("xlxtmp", 4, $row)); print_cell(gather_enum_multi_print("xlxgrd", 4, $row)); print_cell($row['cputyp']); print_cell($row['cpuspd']); print_cell($row['cpmspd']); print_cell($row['busspd']); print_cell($row['hstype']); print_cell($row['hschin']); print_cell($row['hschout']); } echo "</tr>\n"; } ?> </table> <p></p> <table width="100%"> <tr> <td align=center><?php printf("<a href=\"%s?submit=Browse&offset=%d&verbose=%d%s\">%s Listing</a>\n", $PHP_SELF, $offset, $verbose?0:1, $serno!=''?"&serno=$serno":'', $verbose?"Terse":"Verbose"); ?></td> <td align=center><a href="index.php">Back to Start</a></td> </tr> </table> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/browse.php
PHP
gpl3
4,244
<?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab // mysql database access info $mysql_user="fred"; $mysql_pw="apassword"; $mysql_db="mydbname"; // where to put the eeprom config files $bddb_cfgdir = '/tftpboot/bddb'; // what this database is called $bddb_label = 'Hymod Board Database'; ?>
1001-study-uboot
tools/bddb/config.php
PHP
gpl3
384
BODY { background: #e0ffff; color: #000000; font-family: Arial, Verdana, Helvetica; } H1 { font-family: "Copperplate Gothic Bold"; background: transparent; color: #993300; text-align: center; } H2, H3, H4, H5 { background: transparent; color: #993300; margin-top: 4%; text-align: center; } Body.Plain Div.Abstract, Body.Plain P.Abstract { background: #cccc99; color: #333300; border: white; padding: 3%; font-family: Times, Verdana; } TH.Nav { background: #0000cc; color: #ff9900; } TH.Menu { background: #3366cc; color: #ff9900; } A:hover { color: #ff6600; } A.Menu:hover { color: #ff6600; } A.HoMe:hover { color: #ff6600; } A.Menu { background: transparent; color: #ffcc33; font-family: Verdana, Helvetica, Arial; font-size: smaller; text-decoration: none; } A.Menu:visited { background: transparent; color: #ffcc99; } A.HoMe { background: transparent; color: #ffcc33; font-family: Verdana, Helvetica, Arial; text-decoration:none; } A.HoMe:visited { background: transparent; color: #ffcc99; } TH.Xmp { background: #eeeeee; color: #330066; font-family: courier; font-weight: normal; } TH.LuT { background: #cccccc; color: #000000; } TD.LuT { background: #ffffcc; color: #000000; font-size: 85%; } TH.Info, TD.Info { background: #ffffcc; color: #660000; font-family: "Comic Sans MS", Cursive, Verdana; font-size: smaller; } Div.Info, P.Info { background: #ffff99; color: #990033; text-align: left; padding: 2%; font-family: "Comic Sans MS", Cursive, Verdana; font-size: 85%; } Div.Info A { background: transparent; color: #ff6600; } .HL { background: #ffff99; color: #000000; } TD.HL { background: #ccffff; color: #000000; } Div.Margins { width: 512px; text-align: center; } TD.Plain { background: #ffffcc; color: #000033; } .Type { background: #cccccc; color: #660000; } .Name { background: #eeeeee; color: #660000; vertical-align: top; text-align: right; } .Value { background: #ffffee; color: #000066; } .Drop { background: #333366; color: #ffcc33; font-family: "Copperplate Gothic Light", Helvetica, Verdana, Arial; } A.Button:hover { color: #ff6600; } A.Button { text-decoration:none; color: #003366; background: #ffcc66; } .Button { font-size: 9pt; text-align: center; text-decoration:none; color: #003366; background: #ffcc66; margin-bottom: 2pt; border-top: 2px solid #ffff99; border-left: 2px solid #ffff99; border-right: 2px solid #cc9933; border-bottom: 2px solid #cc9933; font-family: Verdana, Arial, "Comic Sans MS"; } .Banner { width: 468; font-size: 12pt; text-align: center; text-decoration:none; color: #003366; background: #ffcc66; border-top: 4px solid #ffff99; border-left: 4px solid #ffff99; border-right: 4px solid #cc9933; border-bottom: 4px solid #cc9933; font-family: Verdana, Arial, "Comic Sans MS"; } TD.Nova, Body.Nova { background: #000000; font-family: "Times New Roman"; font-weight: light; color: #ffcc00; } Body.Nova A.Button { background: gold; color: #003366; } Body.Nova A.Banner { background: transparent; color: #003366; } Body.Nova A { background: transparent; text-decoration:none; color: #ffd766; } Body.Nova H1, Body.Nova H2, Body.Nova H3, Body.Nova H4 { background: transparent; color: white; margin-top: 4%; text-align: center; filter: Blur(Add=1, Direction=0, Strength=8); } Body.Nova Div.Abstract { background: #000000; color: #ffffff; font-family: Times, Verdana; } Body.Nova A.Abstract { background: transparent; color: #ffeedd; } Body.Nova TH.LuT { background: black; color: #ffff99; } Body.Nova TD.LuT { background: navy; color: #ffff99; }
1001-study-uboot
tools/bddb/bddb.css
CSS
gpl3
3,660
<?php // php pages made with phpMyBuilder <http://kyber.dk/phpMyBuilder> ?> <?php // (C) Copyright 2001 // Murray Jensen <Murray.Jensen@csiro.au> // CSIRO Manufacturing Science and Technology, Preston Lab require("defs.php"); pg_head("$bddb_label"); ?> <font size="+4"> <form action=execute.php method=POST> <table width="100%" cellspacing=10 cellpadding=10> <tr> <td align=center> <input type=submit name=submit value="New"></input> </td> <td align=center> <input type=submit name=submit value="Edit"></input> </td> <td align=center> <input type=submit name=submit value="Browse"></input> </td> <td align=center> <input type=submit name=submit value="Log"></input> </td> </tr> <tr> <td align=center colspan=4> <b>Serial Number:</b> <input type=text name=serno size=10 maxsize=10 value=""></input> </td> </tr> </table> </form> </font> <?php pg_foot(); ?>
1001-study-uboot
tools/bddb/index.php
PHP
gpl3
926
/* * (C) Copyright 2008 Semihalf * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef __FDT_HOST_H__ #define __FDT_HOST_H__ /* Make sure to include u-boot version of libfdt include files */ #include "../include/fdt.h" #include "../include/libfdt.h" #include "../include/fdt_support.h" #endif /* __FDT_HOST_H__ */
1001-study-uboot
tools/fdt_host.h
C
gpl3
993
/* * (C) Copyright 2010 * Linaro LTD, www.linaro.org * Author: John Rigby <john.rigby@linaro.org> * Based on TI's signGP.c * * (C) Copyright 2009 * Stefano Babic, DENX Software Engineering, sbabic@denx.de. * * (C) Copyright 2008 * Marvell Semiconductor <www.marvell.com> * Written-by: Prafulla Wadaskar <prafulla@marvell.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* Required to obtain the getline prototype from stdio.h */ #define _GNU_SOURCE #include "mkimage.h" #include <image.h> #include "omapimage.h" /* Header size is CH header rounded up to 512 bytes plus GP header */ #define OMAP_CH_HDR_SIZE 512 #define OMAP_GP_HDR_SIZE (sizeof(struct gp_header)) #define OMAP_FILE_HDR_SIZE (OMAP_CH_HDR_SIZE+OMAP_GP_HDR_SIZE) static uint8_t omapimage_header[OMAP_FILE_HDR_SIZE]; static int omapimage_check_image_types(uint8_t type) { if (type == IH_TYPE_OMAPIMAGE) return EXIT_SUCCESS; else { return EXIT_FAILURE; } } /* * Only the simplest image type is currently supported: * TOC pointing to CHSETTINGS * TOC terminator * CHSETTINGS * * padding to OMAP_CH_HDR_SIZE bytes * * gp header * size * load_addr */ static int valid_gph_size(uint32_t size) { return size; } static int valid_gph_load_addr(uint32_t load_addr) { return load_addr; } static int omapimage_verify_header(unsigned char *ptr, int image_size, struct mkimage_params *params) { struct ch_toc *toc = (struct ch_toc *)ptr; struct gp_header *gph = (struct gp_header *)(ptr+OMAP_CH_HDR_SIZE); uint32_t offset, size; while (toc->section_offset != 0xffffffff && toc->section_size != 0xffffffff) { offset = toc->section_offset; size = toc->section_size; if (!offset || !size) return -1; if (offset >= OMAP_CH_HDR_SIZE || offset+size >= OMAP_CH_HDR_SIZE) return -1; toc++; } if (!valid_gph_size(gph->size)) return -1; if (!valid_gph_load_addr(gph->load_addr)) return -1; return 0; } static void omapimage_print_section(struct ch_settings *chs) { const char *section_name; if (chs->section_key) section_name = "CHSETTINGS"; else section_name = "UNKNOWNKEY"; printf("%s (%x) " "valid:%x " "version:%x " "reserved:%x " "flags:%x\n", section_name, chs->section_key, chs->valid, chs->version, chs->reserved, chs->flags); } static void omapimage_print_header(const void *ptr) { const struct ch_toc *toc = (struct ch_toc *)ptr; const struct gp_header *gph = (struct gp_header *)(ptr+OMAP_CH_HDR_SIZE); uint32_t offset, size; while (toc->section_offset != 0xffffffff && toc->section_size != 0xffffffff) { offset = toc->section_offset; size = toc->section_size; if (offset >= OMAP_CH_HDR_SIZE || offset+size >= OMAP_CH_HDR_SIZE) exit(EXIT_FAILURE); printf("Section %s offset %x length %x\n", toc->section_name, toc->section_offset, toc->section_size); omapimage_print_section((struct ch_settings *)(ptr+offset)); toc++; } if (!valid_gph_size(gph->size)) { fprintf(stderr, "Error: invalid image size %x\n", gph->size); exit(EXIT_FAILURE); } if (!valid_gph_load_addr(gph->load_addr)) { fprintf(stderr, "Error: invalid image load address %x\n", gph->size); exit(EXIT_FAILURE); } printf("GP Header: Size %x LoadAddr %x\n", gph->size, gph->load_addr); } static int toc_offset(void *hdr, void *member) { return member - hdr; } static void omapimage_set_header(void *ptr, struct stat *sbuf, int ifd, struct mkimage_params *params) { struct ch_toc *toc = (struct ch_toc *)ptr; struct ch_settings *chs = (struct ch_settings *) (ptr + 2 * sizeof(*toc)); struct gp_header *gph = (struct gp_header *)(ptr + OMAP_CH_HDR_SIZE); toc->section_offset = toc_offset(ptr, chs); toc->section_size = sizeof(struct ch_settings); strcpy((char *)toc->section_name, "CHSETTINGS"); chs->section_key = KEY_CHSETTINGS; chs->valid = 0; chs->version = 1; chs->reserved = 0; chs->flags = 0; toc++; memset(toc, 0xff, sizeof(*toc)); gph->size = sbuf->st_size - OMAP_FILE_HDR_SIZE; gph->load_addr = params->addr; } int omapimage_check_params(struct mkimage_params *params) { return (params->dflag && (params->fflag || params->lflag)) || (params->fflag && (params->dflag || params->lflag)) || (params->lflag && (params->dflag || params->fflag)); } /* * omapimage parameters */ static struct image_type_params omapimage_params = { .name = "TI OMAP CH/GP Boot Image support", .header_size = OMAP_FILE_HDR_SIZE, .hdr = (void *)&omapimage_header, .check_image_type = omapimage_check_image_types, .verify_header = omapimage_verify_header, .print_header = omapimage_print_header, .set_header = omapimage_set_header, .check_params = omapimage_check_params, }; void init_omap_image_type(void) { mkimage_register(&omapimage_params); }
1001-study-uboot
tools/omapimage.c
C
gpl3
5,539
/* * (C) Copyright 2001 * Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <errno.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifndef __ASSEMBLY__ #define __ASSEMBLY__ /* Dirty trick to get only #defines */ #endif #define __ASM_STUB_PROCESSOR_H__ /* don't include asm/processor. */ #include <config.h> #undef __ASSEMBLY__ #if defined(CONFIG_ENV_IS_IN_FLASH) # ifndef CONFIG_ENV_ADDR # define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + CONFIG_ENV_OFFSET) # endif # ifndef CONFIG_ENV_OFFSET # define CONFIG_ENV_OFFSET (CONFIG_ENV_ADDR - CONFIG_SYS_FLASH_BASE) # endif # if !defined(CONFIG_ENV_ADDR_REDUND) && defined(CONFIG_ENV_OFFSET_REDUND) # define CONFIG_ENV_ADDR_REDUND (CONFIG_SYS_FLASH_BASE + CONFIG_ENV_OFFSET_REDUND) # endif # ifndef CONFIG_ENV_SIZE # define CONFIG_ENV_SIZE CONFIG_ENV_SECT_SIZE # endif # if defined(CONFIG_ENV_ADDR_REDUND) && !defined(CONFIG_ENV_SIZE_REDUND) # define CONFIG_ENV_SIZE_REDUND CONFIG_ENV_SIZE # endif # if (CONFIG_ENV_ADDR >= CONFIG_SYS_MONITOR_BASE) && \ ((CONFIG_ENV_ADDR + CONFIG_ENV_SIZE) <= (CONFIG_SYS_MONITOR_BASE + CONFIG_SYS_MONITOR_LEN)) # define ENV_IS_EMBEDDED 1 # endif # if defined(CONFIG_ENV_ADDR_REDUND) || defined(CONFIG_ENV_OFFSET_REDUND) # define CONFIG_SYS_REDUNDAND_ENVIRONMENT 1 # endif #endif /* CONFIG_ENV_IS_IN_FLASH */ #if defined(ENV_IS_EMBEDDED) && !defined(CONFIG_BUILD_ENVCRC) # define CONFIG_BUILD_ENVCRC 1 #endif #ifdef CONFIG_SYS_REDUNDAND_ENVIRONMENT # define ENV_HEADER_SIZE (sizeof(uint32_t) + 1) #else # define ENV_HEADER_SIZE (sizeof(uint32_t)) #endif #define ENV_SIZE (CONFIG_ENV_SIZE - ENV_HEADER_SIZE) #ifdef CONFIG_BUILD_ENVCRC # include <environment.h> extern unsigned int env_size; extern env_t environment; #endif /* CONFIG_BUILD_ENVCRC */ extern uint32_t crc32 (uint32_t, const unsigned char *, unsigned int); int main (int argc, char **argv) { #ifdef CONFIG_BUILD_ENVCRC unsigned char pad = 0x00; uint32_t crc; unsigned char *envptr = (unsigned char *)&environment, *dataptr = envptr + ENV_HEADER_SIZE; unsigned int datasize = ENV_SIZE; unsigned int eoe; if (argv[1] && !strncmp(argv[1], "--binary", 8)) { int ipad = 0xff; if (argv[1][8] == '=') sscanf(argv[1] + 9, "%i", &ipad); pad = ipad; } if (pad) { /* find the end of env */ for (eoe = 0; eoe < datasize - 1; ++eoe) if (!dataptr[eoe] && !dataptr[eoe+1]) { eoe += 2; break; } if (eoe < datasize - 1) memset(dataptr + eoe, pad, datasize - eoe); } crc = crc32 (0, dataptr, datasize); /* Check if verbose mode is activated passing a parameter to the program */ if (argc > 1) { if (!strncmp(argv[1], "--binary", 8)) { int le = (argc > 2 ? !strcmp(argv[2], "le") : 1); size_t i, start, end, step; if (le) { start = 0; end = ENV_HEADER_SIZE; step = 1; } else { start = ENV_HEADER_SIZE - 1; end = -1; step = -1; } for (i = start; i != end; i += step) printf("%c", (crc & (0xFF << (i * 8))) >> (i * 8)); if (fwrite(dataptr, 1, datasize, stdout) != datasize) fprintf(stderr, "fwrite() failed: %s\n", strerror(errno)); } else { printf("CRC32 from offset %08X to %08X of environment = %08X\n", (unsigned int) (dataptr - envptr), (unsigned int) (dataptr - envptr) + datasize, crc); } } else { printf ("0x%08X\n", crc); } #else printf ("0\n"); #endif return EXIT_SUCCESS; }
1001-study-uboot
tools/envcrc.c
C
gpl3
4,244
/* * Freescale i.MX28 image generator * * Copyright (C) 2011 Marek Vasut <marek.vasut@gmail.com> * on behalf of DENX Software Engineering GmbH * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "compiler.h" /* * Default BCB layout. * * TWEAK this if you have blown any OCOTP fuses. */ #define STRIDE_PAGES 64 #define STRIDE_COUNT 4 /* * Layout for 256Mb big NAND with 2048b page size, 64b OOB size and * 128kb erase size. * * TWEAK this if you have different kind of NAND chip. */ uint32_t nand_writesize = 2048; uint32_t nand_oobsize = 64; uint32_t nand_erasesize = 128 * 1024; /* * Sector on which the SigmaTel boot partition (0x53) starts. */ uint32_t sd_sector = 2048; /* * Each of the U-Boot bootstreams is at maximum 1MB big. * * TWEAK this if, for some wild reason, you need to boot bigger image. */ #define MAX_BOOTSTREAM_SIZE (1 * 1024 * 1024) /* i.MX28 NAND controller-specific constants. DO NOT TWEAK! */ #define MXS_NAND_DMA_DESCRIPTOR_COUNT 4 #define MXS_NAND_CHUNK_DATA_CHUNK_SIZE 512 #define MXS_NAND_METADATA_SIZE 10 #define MXS_NAND_COMMAND_BUFFER_SIZE 32 struct mx28_nand_fcb { uint32_t checksum; uint32_t fingerprint; uint32_t version; struct { uint8_t data_setup; uint8_t data_hold; uint8_t address_setup; uint8_t dsample_time; uint8_t nand_timing_state; uint8_t rea; uint8_t rloh; uint8_t rhoh; } timing; uint32_t page_data_size; uint32_t total_page_size; uint32_t sectors_per_block; uint32_t number_of_nands; /* Ignored */ uint32_t total_internal_die; /* Ignored */ uint32_t cell_type; /* Ignored */ uint32_t ecc_block_n_ecc_type; uint32_t ecc_block_0_size; uint32_t ecc_block_n_size; uint32_t ecc_block_0_ecc_type; uint32_t metadata_bytes; uint32_t num_ecc_blocks_per_page; uint32_t ecc_block_n_ecc_level_sdk; /* Ignored */ uint32_t ecc_block_0_size_sdk; /* Ignored */ uint32_t ecc_block_n_size_sdk; /* Ignored */ uint32_t ecc_block_0_ecc_level_sdk; /* Ignored */ uint32_t num_ecc_blocks_per_page_sdk; /* Ignored */ uint32_t metadata_bytes_sdk; /* Ignored */ uint32_t erase_threshold; uint32_t boot_patch; uint32_t patch_sectors; uint32_t firmware1_starting_sector; uint32_t firmware2_starting_sector; uint32_t sectors_in_firmware1; uint32_t sectors_in_firmware2; uint32_t dbbt_search_area_start_address; uint32_t badblock_marker_byte; uint32_t badblock_marker_start_bit; uint32_t bb_marker_physical_offset; }; struct mx28_nand_dbbt { uint32_t checksum; uint32_t fingerprint; uint32_t version; uint32_t number_bb; uint32_t number_2k_pages_bb; }; struct mx28_nand_bbt { uint32_t nand; uint32_t number_bb; uint32_t badblock[510]; }; struct mx28_sd_drive_info { uint32_t chip_num; uint32_t drive_type; uint32_t tag; uint32_t first_sector_number; uint32_t sector_count; }; struct mx28_sd_config_block { uint32_t signature; uint32_t primary_boot_tag; uint32_t secondary_boot_tag; uint32_t num_copies; struct mx28_sd_drive_info drv_info[1]; }; static inline uint32_t mx28_nand_ecc_size_in_bits(uint32_t ecc_strength) { return ecc_strength * 13; } static inline uint32_t mx28_nand_get_ecc_strength(uint32_t page_data_size, uint32_t page_oob_size) { if (page_data_size == 2048) return 8; if (page_data_size == 4096) { if (page_oob_size == 128) return 8; if (page_oob_size == 218) return 16; } return 0; } static inline uint32_t mx28_nand_get_mark_offset(uint32_t page_data_size, uint32_t ecc_strength) { uint32_t chunk_data_size_in_bits; uint32_t chunk_ecc_size_in_bits; uint32_t chunk_total_size_in_bits; uint32_t block_mark_chunk_number; uint32_t block_mark_chunk_bit_offset; uint32_t block_mark_bit_offset; chunk_data_size_in_bits = MXS_NAND_CHUNK_DATA_CHUNK_SIZE * 8; chunk_ecc_size_in_bits = mx28_nand_ecc_size_in_bits(ecc_strength); chunk_total_size_in_bits = chunk_data_size_in_bits + chunk_ecc_size_in_bits; /* Compute the bit offset of the block mark within the physical page. */ block_mark_bit_offset = page_data_size * 8; /* Subtract the metadata bits. */ block_mark_bit_offset -= MXS_NAND_METADATA_SIZE * 8; /* * Compute the chunk number (starting at zero) in which the block mark * appears. */ block_mark_chunk_number = block_mark_bit_offset / chunk_total_size_in_bits; /* * Compute the bit offset of the block mark within its chunk, and * validate it. */ block_mark_chunk_bit_offset = block_mark_bit_offset - (block_mark_chunk_number * chunk_total_size_in_bits); if (block_mark_chunk_bit_offset > chunk_data_size_in_bits) return 1; /* * Now that we know the chunk number in which the block mark appears, * we can subtract all the ECC bits that appear before it. */ block_mark_bit_offset -= block_mark_chunk_number * chunk_ecc_size_in_bits; return block_mark_bit_offset; } static inline uint32_t mx28_nand_mark_byte_offset(void) { uint32_t ecc_strength; ecc_strength = mx28_nand_get_ecc_strength(nand_writesize, nand_oobsize); return mx28_nand_get_mark_offset(nand_writesize, ecc_strength) >> 3; } static inline uint32_t mx28_nand_mark_bit_offset(void) { uint32_t ecc_strength; ecc_strength = mx28_nand_get_ecc_strength(nand_writesize, nand_oobsize); return mx28_nand_get_mark_offset(nand_writesize, ecc_strength) & 0x7; } static uint32_t mx28_nand_block_csum(uint8_t *block, uint32_t size) { uint32_t csum = 0; int i; for (i = 0; i < size; i++) csum += block[i]; return csum ^ 0xffffffff; } static struct mx28_nand_fcb *mx28_nand_get_fcb(uint32_t size) { struct mx28_nand_fcb *fcb; uint32_t bcb_size_bytes; uint32_t stride_size_bytes; uint32_t bootstream_size_pages; uint32_t fw1_start_page; uint32_t fw2_start_page; fcb = malloc(nand_writesize); if (!fcb) { printf("MX28 NAND: Unable to allocate FCB\n"); return NULL; } memset(fcb, 0, nand_writesize); fcb->fingerprint = 0x20424346; fcb->version = 0x01000000; /* * FIXME: These here are default values as found in kobs-ng. We should * probably retrieve the data from NAND or something. */ fcb->timing.data_setup = 80; fcb->timing.data_hold = 60; fcb->timing.address_setup = 25; fcb->timing.dsample_time = 6; fcb->page_data_size = nand_writesize; fcb->total_page_size = nand_writesize + nand_oobsize; fcb->sectors_per_block = nand_erasesize / nand_writesize; fcb->num_ecc_blocks_per_page = (nand_writesize / 512) - 1; fcb->ecc_block_0_size = 512; fcb->ecc_block_n_size = 512; fcb->metadata_bytes = 10; if (nand_writesize == 2048) { fcb->ecc_block_n_ecc_type = 4; fcb->ecc_block_0_ecc_type = 4; } else if (nand_writesize == 4096) { if (nand_oobsize == 128) { fcb->ecc_block_n_ecc_type = 4; fcb->ecc_block_0_ecc_type = 4; } else if (nand_oobsize == 218) { fcb->ecc_block_n_ecc_type = 8; fcb->ecc_block_0_ecc_type = 8; } } if (fcb->ecc_block_n_ecc_type == 0) { printf("MX28 NAND: Unsupported NAND geometry\n"); goto err; } fcb->boot_patch = 0; fcb->patch_sectors = 0; fcb->badblock_marker_byte = mx28_nand_mark_byte_offset(); fcb->badblock_marker_start_bit = mx28_nand_mark_bit_offset(); fcb->bb_marker_physical_offset = nand_writesize; stride_size_bytes = STRIDE_PAGES * nand_writesize; bcb_size_bytes = stride_size_bytes * STRIDE_COUNT; bootstream_size_pages = (size + (nand_writesize - 1)) / nand_writesize; fw1_start_page = 2 * bcb_size_bytes / nand_writesize; fw2_start_page = (2 * bcb_size_bytes + MAX_BOOTSTREAM_SIZE) / nand_writesize; fcb->firmware1_starting_sector = fw1_start_page; fcb->firmware2_starting_sector = fw2_start_page; fcb->sectors_in_firmware1 = bootstream_size_pages; fcb->sectors_in_firmware2 = bootstream_size_pages; fcb->dbbt_search_area_start_address = STRIDE_PAGES * STRIDE_COUNT; return fcb; err: free(fcb); return NULL; } static struct mx28_nand_dbbt *mx28_nand_get_dbbt(void) { struct mx28_nand_dbbt *dbbt; dbbt = malloc(nand_writesize); if (!dbbt) { printf("MX28 NAND: Unable to allocate DBBT\n"); return NULL; } memset(dbbt, 0, nand_writesize); dbbt->fingerprint = 0x54424244; dbbt->version = 0x1; return dbbt; } static inline uint8_t mx28_nand_parity_13_8(const uint8_t b) { uint32_t parity = 0, tmp; tmp = ((b >> 6) ^ (b >> 5) ^ (b >> 3) ^ (b >> 2)) & 1; parity |= tmp << 0; tmp = ((b >> 7) ^ (b >> 5) ^ (b >> 4) ^ (b >> 2) ^ (b >> 1)) & 1; parity |= tmp << 1; tmp = ((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ (b >> 1) ^ (b >> 0)) & 1; parity |= tmp << 2; tmp = ((b >> 7) ^ (b >> 4) ^ (b >> 3) ^ (b >> 0)) & 1; parity |= tmp << 3; tmp = ((b >> 6) ^ (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ (b >> 1) ^ (b >> 0)) & 1; parity |= tmp << 4; return parity; } static uint8_t *mx28_nand_fcb_block(struct mx28_nand_fcb *fcb) { uint8_t *block; uint8_t *ecc; int i; block = malloc(nand_writesize + nand_oobsize); if (!block) { printf("MX28 NAND: Unable to allocate FCB block\n"); return NULL; } memset(block, 0, nand_writesize + nand_oobsize); /* Update the FCB checksum */ fcb->checksum = mx28_nand_block_csum(((uint8_t *)fcb) + 4, 508); /* Figure 12-11. in iMX28RM, rev. 1, says FCB is at offset 12 */ memcpy(block + 12, fcb, sizeof(struct mx28_nand_fcb)); /* ECC is at offset 12 + 512 */ ecc = block + 12 + 512; /* Compute the ECC parity */ for (i = 0; i < sizeof(struct mx28_nand_fcb); i++) ecc[i] = mx28_nand_parity_13_8(block[i + 12]); return block; } static int mx28_nand_write_fcb(struct mx28_nand_fcb *fcb, char *buf) { uint32_t offset; uint8_t *fcbblock; int ret = 0; int i; fcbblock = mx28_nand_fcb_block(fcb); if (!fcbblock) return -1; for (i = 0; i < STRIDE_PAGES * STRIDE_COUNT; i += STRIDE_PAGES) { offset = i * nand_writesize; memcpy(buf + offset, fcbblock, nand_writesize + nand_oobsize); } free(fcbblock); return ret; } static int mx28_nand_write_dbbt(struct mx28_nand_dbbt *dbbt, char *buf) { uint32_t offset; int i = STRIDE_PAGES * STRIDE_COUNT; for (; i < 2 * STRIDE_PAGES * STRIDE_COUNT; i += STRIDE_PAGES) { offset = i * nand_writesize; memcpy(buf + offset, dbbt, sizeof(struct mx28_nand_dbbt)); } return 0; } static int mx28_nand_write_firmware(struct mx28_nand_fcb *fcb, int infd, char *buf) { int ret; off_t size; uint32_t offset1, offset2; size = lseek(infd, 0, SEEK_END); lseek(infd, 0, SEEK_SET); offset1 = fcb->firmware1_starting_sector * nand_writesize; offset2 = fcb->firmware2_starting_sector * nand_writesize; ret = read(infd, buf + offset1, size); if (ret != size) return -1; memcpy(buf + offset2, buf + offset1, size); return 0; } void usage(void) { printf( "Usage: mx28image [ops] <type> <infile> <outfile>\n" "Augment BootStream file with a proper header for i.MX28 boot\n" "\n" " <type> type of image:\n" " \"nand\" for NAND image\n" " \"sd\" for SD image\n" " <infile> input file, the u-boot.sb bootstream\n" " <outfile> output file, the bootable image\n" "\n"); printf( "For NAND boot, these options are accepted:\n" " -w <size> NAND page size\n" " -o <size> NAND OOB size\n" " -e <size> NAND erase size\n" "\n" "For SD boot, these options are accepted:\n" " -p <sector> Sector where the SGTL partition starts\n" ); } static int mx28_create_nand_image(int infd, int outfd) { struct mx28_nand_fcb *fcb; struct mx28_nand_dbbt *dbbt; int ret = -1; char *buf; int size; ssize_t wr_size; size = nand_writesize * 512 + 2 * MAX_BOOTSTREAM_SIZE; buf = malloc(size); if (!buf) { printf("Can not allocate output buffer of %d bytes\n", size); goto err0; } memset(buf, 0, size); fcb = mx28_nand_get_fcb(MAX_BOOTSTREAM_SIZE); if (!fcb) { printf("Unable to compile FCB\n"); goto err1; } dbbt = mx28_nand_get_dbbt(); if (!dbbt) { printf("Unable to compile DBBT\n"); goto err2; } ret = mx28_nand_write_fcb(fcb, buf); if (ret) { printf("Unable to write FCB to buffer\n"); goto err3; } ret = mx28_nand_write_dbbt(dbbt, buf); if (ret) { printf("Unable to write DBBT to buffer\n"); goto err3; } ret = mx28_nand_write_firmware(fcb, infd, buf); if (ret) { printf("Unable to write firmware to buffer\n"); goto err3; } wr_size = write(outfd, buf, size); if (wr_size != size) { ret = -1; goto err3; } ret = 0; err3: free(dbbt); err2: free(fcb); err1: free(buf); err0: return ret; } static int mx28_create_sd_image(int infd, int outfd) { int ret = -1; uint32_t *buf; int size; off_t fsize; ssize_t wr_size; struct mx28_sd_config_block *cb; fsize = lseek(infd, 0, SEEK_END); lseek(infd, 0, SEEK_SET); size = fsize + 512; buf = malloc(size); if (!buf) { printf("Can not allocate output buffer of %d bytes\n", size); goto err0; } ret = read(infd, (uint8_t *)buf + 512, fsize); if (ret != fsize) { ret = -1; goto err1; } cb = (struct mx28_sd_config_block *)buf; cb->signature = 0x00112233; cb->primary_boot_tag = 0x1; cb->secondary_boot_tag = 0x1; cb->num_copies = 1; cb->drv_info[0].chip_num = 0x0; cb->drv_info[0].drive_type = 0x0; cb->drv_info[0].tag = 0x1; cb->drv_info[0].first_sector_number = sd_sector + 1; cb->drv_info[0].sector_count = (size - 1) / 512; wr_size = write(outfd, buf, size); if (wr_size != size) { ret = -1; goto err1; } ret = 0; err1: free(buf); err0: return ret; } int parse_ops(int argc, char **argv) { int i; int tmp; char *end; enum param { PARAM_WRITE, PARAM_OOB, PARAM_ERASE, PARAM_PART, PARAM_SD, PARAM_NAND }; int type; for (i = 1; i < argc; i++) { if (!strncmp(argv[i], "-w", 2)) type = PARAM_WRITE; else if (!strncmp(argv[i], "-o", 2)) type = PARAM_OOB; else if (!strncmp(argv[i], "-e", 2)) type = PARAM_ERASE; else if (!strncmp(argv[i], "-p", 2)) type = PARAM_PART; else /* SD/MMC */ break; tmp = strtol(argv[++i], &end, 10); if (tmp % 2) return -1; if (tmp <= 0) return -1; if (type == PARAM_WRITE) nand_writesize = tmp; if (type == PARAM_OOB) nand_oobsize = tmp; if (type == PARAM_ERASE) nand_erasesize = tmp; if (type == PARAM_PART) sd_sector = tmp; } if (strcmp(argv[i], "sd") && strcmp(argv[i], "nand")) return -1; if (i + 3 != argc) return -1; return i; } int main(int argc, char **argv) { int infd, outfd; int ret = 0; int offset; offset = parse_ops(argc, argv); if (offset < 0) { usage(); ret = 1; goto err1; } infd = open(argv[offset + 1], O_RDONLY); if (infd < 0) { printf("Input BootStream file can not be opened\n"); ret = 2; goto err1; } outfd = open(argv[offset + 2], O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR); if (outfd < 0) { printf("Output file can not be created\n"); ret = 3; goto err2; } if (!strcmp(argv[offset], "sd")) ret = mx28_create_sd_image(infd, outfd); else if (!strcmp(argv[offset], "nand")) ret = mx28_create_nand_image(infd, outfd); close(outfd); err2: close(infd); err1: return ret; }
1001-study-uboot
tools/mxsboot.c
C
gpl3
15,810
/* * (C) Copyright 2010 * Linaro LTD, www.linaro.org * Author John Rigby <john.rigby@linaro.org> * Based on TI's signGP.c * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef _OMAPIMAGE_H_ #define _OMAPIMAGE_H_ struct ch_toc { uint32_t section_offset; uint32_t section_size; uint8_t unused[12]; uint8_t section_name[12]; }; struct ch_settings { uint32_t section_key; uint8_t valid; uint8_t version; uint16_t reserved; uint32_t flags; }; struct gp_header { uint32_t size; uint32_t load_addr; }; #define KEY_CHSETTINGS 0xC0C0C0C1 #endif /* _OMAPIMAGE_H_ */
1001-study-uboot
tools/omapimage.h
C
gpl3
1,329
/* * (C) Copyright 2008 Semihalf * * (C) Copyright 2000-2004 * DENX Software Engineering * Wolfgang Denk, wd@denx.de * * Updated-by: Prafulla Wadaskar <prafulla@marvell.com> * default_image specific code abstracted from mkimage.c * some functions added to address abstraction * * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include "mkimage.h" #include <image.h> #include <u-boot/crc.h> static image_header_t header; static int image_check_image_types(uint8_t type) { if (((type > IH_TYPE_INVALID) && (type < IH_TYPE_FLATDT)) || (type == IH_TYPE_KERNEL_NOLOAD)) return EXIT_SUCCESS; else return EXIT_FAILURE; } static int image_check_params(struct mkimage_params *params) { return ((params->dflag && (params->fflag || params->lflag)) || (params->fflag && (params->dflag || params->lflag)) || (params->lflag && (params->dflag || params->fflag))); } static int image_verify_header(unsigned char *ptr, int image_size, struct mkimage_params *params) { uint32_t len; const unsigned char *data; uint32_t checksum; image_header_t header; image_header_t *hdr = &header; /* * create copy of header so that we can blank out the * checksum field for checking - this can't be done * on the PROT_READ mapped data. */ memcpy(hdr, ptr, sizeof(image_header_t)); if (be32_to_cpu(hdr->ih_magic) != IH_MAGIC) { fprintf(stderr, "%s: Bad Magic Number: \"%s\" is no valid image\n", params->cmdname, params->imagefile); return -FDT_ERR_BADMAGIC; } data = (const unsigned char *)hdr; len = sizeof(image_header_t); checksum = be32_to_cpu(hdr->ih_hcrc); hdr->ih_hcrc = cpu_to_be32(0); /* clear for re-calculation */ if (crc32(0, data, len) != checksum) { fprintf(stderr, "%s: ERROR: \"%s\" has bad header checksum!\n", params->cmdname, params->imagefile); return -FDT_ERR_BADSTATE; } data = (const unsigned char *)ptr + sizeof(image_header_t); len = image_size - sizeof(image_header_t) ; checksum = be32_to_cpu(hdr->ih_dcrc); if (crc32(0, data, len) != checksum) { fprintf(stderr, "%s: ERROR: \"%s\" has corrupted data!\n", params->cmdname, params->imagefile); return -FDT_ERR_BADSTRUCTURE; } return 0; } static void image_set_header(void *ptr, struct stat *sbuf, int ifd, struct mkimage_params *params) { uint32_t checksum; image_header_t * hdr = (image_header_t *)ptr; checksum = crc32(0, (const unsigned char *)(ptr + sizeof(image_header_t)), sbuf->st_size - sizeof(image_header_t)); /* Build new header */ image_set_magic(hdr, IH_MAGIC); image_set_time(hdr, sbuf->st_mtime); image_set_size(hdr, sbuf->st_size - sizeof(image_header_t)); image_set_load(hdr, params->addr); image_set_ep(hdr, params->ep); image_set_dcrc(hdr, checksum); image_set_os(hdr, params->os); image_set_arch(hdr, params->arch); image_set_type(hdr, params->type); image_set_comp(hdr, params->comp); image_set_name(hdr, params->imagename); checksum = crc32(0, (const unsigned char *)hdr, sizeof(image_header_t)); image_set_hcrc(hdr, checksum); } /* * Default image type parameters definition */ static struct image_type_params defimage_params = { .name = "Default Image support", .header_size = sizeof(image_header_t), .hdr = (void*)&header, .check_image_type = image_check_image_types, .verify_header = image_verify_header, .print_header = image_print_contents, .set_header = image_set_header, .check_params = image_check_params, }; void init_default_image_type(void) { mkimage_register(&defimage_params); }
1001-study-uboot
tools/default_image.c
C
gpl3
4,215
/* * (C) Copyright 2009 * Stefano Babic, DENX Software Engineering, sbabic@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef _IMXIMAGE_H_ #define _IMXIMAGE_H_ #define MAX_HW_CFG_SIZE_V2 121 /* Max number of registers imx can set for v2 */ #define MAX_HW_CFG_SIZE_V1 60 /* Max number of registers imx can set for v1 */ #define APP_CODE_BARKER 0xB1 #define DCD_BARKER 0xB17219E9 #define HEADER_OFFSET 0x400 #define CMD_DATA_STR "DATA" #define FLASH_OFFSET_STANDARD 0x400 #define FLASH_OFFSET_NAND FLASH_OFFSET_STANDARD #define FLASH_OFFSET_SD FLASH_OFFSET_STANDARD #define FLASH_OFFSET_SPI FLASH_OFFSET_STANDARD #define FLASH_OFFSET_ONENAND 0x100 #define IVT_HEADER_TAG 0xD1 #define IVT_VERSION 0x40 #define DCD_HEADER_TAG 0xD2 #define DCD_COMMAND_TAG 0xCC #define DCD_VERSION 0x40 #define DCD_COMMAND_PARAM 0x4 enum imximage_cmd { CMD_INVALID, CMD_IMAGE_VERSION, CMD_BOOT_FROM, CMD_DATA }; enum imximage_fld_types { CFG_INVALID = -1, CFG_COMMAND, CFG_REG_SIZE, CFG_REG_ADDRESS, CFG_REG_VALUE }; enum imximage_version { IMXIMAGE_VER_INVALID = -1, IMXIMAGE_V1 = 1, IMXIMAGE_V2 }; typedef struct { uint32_t type; /* Type of pointer (byte, halfword, word, wait/read) */ uint32_t addr; /* Address to write to */ uint32_t value; /* Data to write */ } dcd_type_addr_data_t; typedef struct { uint32_t barker; /* Barker for sanity check */ uint32_t length; /* Device configuration length (without preamble) */ } dcd_preamble_t; typedef struct { dcd_preamble_t preamble; dcd_type_addr_data_t addr_data[MAX_HW_CFG_SIZE_V1]; } dcd_v1_t; typedef struct { uint32_t app_code_jump_vector; uint32_t app_code_barker; uint32_t app_code_csf; uint32_t dcd_ptr_ptr; uint32_t super_root_key; uint32_t dcd_ptr; uint32_t app_dest_ptr; } flash_header_v1_t; typedef struct { uint32_t length; /* Length of data to be read from flash */ } flash_cfg_parms_t; typedef struct { flash_header_v1_t fhdr; dcd_v1_t dcd_table; flash_cfg_parms_t ext_header; } imx_header_v1_t; typedef struct { uint32_t addr; uint32_t value; } dcd_addr_data_t; typedef struct { uint8_t tag; uint16_t length; uint8_t version; } __attribute__((packed)) ivt_header_t; typedef struct { uint8_t tag; uint16_t length; uint8_t param; } __attribute__((packed)) write_dcd_command_t; typedef struct { ivt_header_t header; write_dcd_command_t write_dcd_command; dcd_addr_data_t addr_data[MAX_HW_CFG_SIZE_V2]; } dcd_v2_t; typedef struct { uint32_t start; uint32_t size; uint32_t plugin; } boot_data_t; typedef struct { ivt_header_t header; uint32_t entry; uint32_t reserved1; uint32_t dcd_ptr; uint32_t boot_data_ptr; uint32_t self; uint32_t csf; uint32_t reserved2; } flash_header_v2_t; typedef struct { flash_header_v2_t fhdr; boot_data_t boot_data; dcd_v2_t dcd_table; } imx_header_v2_t; struct imx_header { union { imx_header_v1_t hdr_v1; imx_header_v2_t hdr_v2; } header; uint32_t flash_offset; }; typedef void (*set_dcd_val_t)(struct imx_header *imxhdr, char *name, int lineno, int fld, uint32_t value, uint32_t off); typedef void (*set_dcd_rst_t)(struct imx_header *imxhdr, uint32_t dcd_len, char *name, int lineno); typedef void (*set_imx_hdr_t)(struct imx_header *imxhdr, uint32_t dcd_len, struct stat *sbuf, struct mkimage_params *params); #endif /* _IMXIMAGE_H_ */
1001-study-uboot
tools/imximage.h
C
gpl3
4,107
/* * (C) Copyright 2011 * Heiko Schocher, DENX Software Engineering, hs@denx.de. * * Vased on: * (C) Copyright 2009 * Stefano Babic, DENX Software Engineering, sbabic@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef _UBLIMAGE_H_ #define _UBLIMAGE_H_ enum ublimage_cmd { CMD_INVALID, CMD_BOOT_MODE, CMD_ENTRY, CMD_PAGE, CMD_ST_BLOCK, CMD_ST_PAGE, CMD_LD_ADDR }; enum ublimage_fld_types { CFG_INVALID = -1, CFG_COMMAND, CFG_REG_VALUE }; /* * from sprufg5a.pdf Table 110 * Used by RBL when doing NAND boot */ #define UBL_MAGIC_BASE (0xA1ACED00) /* Safe boot mode */ #define UBL_MAGIC_SAFE (0x00) /* DMA boot mode */ #define UBL_MAGIC_DMA (0x11) /* I Cache boot mode */ #define UBL_MAGIC_IC (0x22) /* Fast EMIF boot mode */ #define UBL_MAGIC_FAST (0x33) /* DMA + ICache boot mode */ #define UBL_MAGIC_DMA_IC (0x44) /* DMA + ICache + Fast EMIF boot mode */ #define UBL_MAGIC_DMA_IC_FAST (0x55) /* Define max UBL image size */ #define UBL_IMAGE_SIZE (0x00003800u) /* one NAND block */ #define UBL_BLOCK_SIZE 2048 /* from sprufg5a.pdf Table 109 */ struct ubl_header { uint32_t magic; /* Magic Number, see UBL_* defines */ uint32_t entry; /* entry point address for bootloader */ uint32_t pages; /* number of pages (size of bootloader) */ uint32_t block; /* * blocknumber where user bootloader is * present */ uint32_t page; /* * page number where user bootloader is * present. */ uint32_t pll_m; /* * PLL setting -Multiplier (only valid if * Magic Number indicates PLL enable). */ uint32_t pll_n; /* * PLL setting -Divider (only valid if * Magic Number indicates PLL enable). */ uint32_t emif; /* * fast EMIF setting (only valid if * Magic Number indicates fast EMIF boot). */ /* to fit in one nand block */ unsigned char res[UBL_BLOCK_SIZE - 8 * 4]; }; #endif /* _UBLIMAGE_H_ */
1001-study-uboot
tools/ublimage.h
C
gpl3
2,750
/* * Copyright 2009 Extreme Engineering Solutions, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this software; if not, write to the * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * Include additional files required for supporting different operating systems */ #include "compiler.h" #ifdef __MINGW32__ #include "mingw_support.c" #endif #if defined(__APPLE__) && __DARWIN_C_LEVEL < 200809L #include "getline.c" #endif
1001-study-uboot
tools/os_support.c
C
gpl3
1,034
/* * (C) Copyright 2003 Intracom S.A. * Pantelis Antoniou <panto@intracom.gr> * * This little program makes an exhaustive search for the * correct terms of pdf, mfi, mfn, mfd, s, dbrmo, in PLPRCR. * The goal is to produce a gclk2 from a xin input, while respecting * all the restrictions on their combination. * * Generaly you select the first row of the produced table. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #define DPREF_MIN 10000000 #define DPREF_MAX 32000000 #define DPGDCK_MAX 320000000 #define DPGDCK_MIN 160000000 #define S_MIN 0 #define S_MAX 2 #define MFI_MIN 5 #define MFI_MAX 15 #define MFN_MIN 0 #define MFN_MAX 15 #define MFD_MIN 0 #define MFD_MAX 31 #define MF_MIN 5 #define MF_MAX 15 #define PDF_MIN 0 #define PDF_MAX 15 #define GCLK2_MAX 150000000 static int calculate (int xin, int target_clock, int ppm, int pdf, int mfi, int mfn, int mfd, int s, int *dprefp, int *dpgdckp, int *jdbckp, int *gclk2p, int *dbrmop) { unsigned int dpref, dpgdck, jdbck, gclk2, t1, t2, dbrmo; /* valid MFI? */ if (mfi < MFI_MIN) return -1; /* valid num, denum? */ if (mfn > 0 && mfn >= mfd) return -1; dpref = xin / (pdf + 1); /* valid dpef? */ if (dpref < DPREF_MIN || dpref > DPREF_MAX) return -1; if (mfn == 0) { dpgdck = (2 * mfi * xin) / (pdf + 1) ; dbrmo = 0; } else { /* 5 <= mfi + (mfn / mfd + 1) <= 15 */ t1 = mfd + 1; t2 = mfi * t1 + mfn; if ( MF_MIN * t1 > t2 || MF_MAX * t1 < t2) return -1; dpgdck = (unsigned int)(2 * (mfi * mfd + mfi + mfn) * (unsigned int)xin) / ((mfd + 1) * (pdf + 1)); dbrmo = 10 * mfn < (mfd + 1); } /* valid dpgclk? */ if (dpgdck < DPGDCK_MIN || dpgdck > DPGDCK_MAX) return -1; jdbck = dpgdck >> s; gclk2 = jdbck / 2; /* valid gclk2 */ if (gclk2 > GCLK2_MAX) return -1; t1 = abs(gclk2 - target_clock); /* XXX max 1MHz dev. in clock */ if (t1 > 1000000) return -1; /* dev within range (XXX gclk2 scaled to avoid overflow) */ if (t1 * 1000 > (unsigned int)ppm * (gclk2 / 1000)) return -1; *dprefp = dpref; *dpgdckp = dpgdck; *jdbckp = jdbck; *gclk2p = gclk2; *dbrmop = dbrmo; return gclk2; } int conf_clock(int xin, int target_clock, int ppm) { int pdf, s, mfn, mfd, mfi; int dpref, dpgdck, jdbck, gclk2, xout, dbrmo; int found = 0; /* integer multipliers */ for (pdf = PDF_MIN; pdf <= PDF_MAX; pdf++) { for (mfi = MFI_MIN; mfi <= MFI_MAX; mfi++) { for (s = 0; s <= S_MAX; s++) { xout = calculate(xin, target_clock, ppm, pdf, mfi, 0, 0, s, &dpref, &dpgdck, &jdbck, &gclk2, &dbrmo); if (xout < 0) continue; if (found == 0) { printf("pdf mfi mfn mfd s dbrmo dpref dpgdck jdbck gclk2 exact?\n"); printf("--- --- --- --- - ----- ----- ------ ----- ----- ------\n"); } printf("%3d %3d --- --- %1d %5d %9d %9d %9d %9d%s\n", pdf, mfi, s, dbrmo, dpref, dpgdck, jdbck, gclk2, gclk2 == target_clock ? " YES" : ""); found++; } } } /* fractional multipliers */ for (pdf = PDF_MIN; pdf <= PDF_MAX; pdf++) { for (mfi = MFI_MIN; mfi <= MFI_MAX; mfi++) { for (mfn = 1; mfn <= MFN_MAX; mfn++) { for (mfd = 1; mfd <= MFD_MAX; mfd++) { for (s = 0; s <= S_MAX; s++) { xout = calculate(xin, target_clock, ppm, pdf, mfi, mfn, mfd, s, &dpref, &dpgdck, &jdbck, &gclk2, &dbrmo); if (xout < 0) continue; if (found == 0) { printf("pdf mfi mfn mfd s dbrmo dpref dpgdck jdbck gclk2 exact?\n"); printf("--- --- --- --- - ----- ----- ------ ----- ----- ------\n"); } printf("%3d %3d %3d %3d %1d %5d %9d %9d %9d %9d%s\n", pdf, mfi, mfn, mfd, s, dbrmo, dpref, dpgdck, jdbck, gclk2, gclk2 == target_clock ? " YES" : ""); found++; } } } } } return found; } int main(int argc, char *argv[]) { int xin, want_gclk2, found, ppm = 100; if (argc < 3) { fprintf(stderr, "usage: mpc86x_clk <xin> <want_gclk2> [ppm]\n"); fprintf(stderr, " default ppm is 100\n"); return 10; } xin = atoi(argv[1]); want_gclk2 = atoi(argv[2]); if (argc >= 4) ppm = atoi(argv[3]); found = conf_clock(xin, want_gclk2, ppm); if (found <= 0) { fprintf(stderr, "cannot produce gclk2 %d from xin %d\n", want_gclk2, xin); return EXIT_FAILURE; } return EXIT_SUCCESS; }
1001-study-uboot
tools/mpc86x_clk.c
C
gpl3
5,222
int getline(char **lineptr, size_t *n, FILE *stream);
1001-study-uboot
tools/getline.h
C
gpl3
54
/* * (C) Copyright 2011 * Stefano Babic, DENX Software Engineering, sbabic@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef _AISIMAGE_H_ #define _AISIMAGE_H_ /* all values are for little endian systems */ #define AIS_MAGIC_WORD 0x41504954 #define AIS_FCN_MAX 8 enum { AIS_CMD_LOAD = 0x58535901, AIS_CMD_VALCRC = 0x58535902, AIS_CMD_ENCRC = 0x58535903, AIS_CMD_DISCRC = 0x58535904, AIS_CMD_JMP = 0x58535905, AIS_CMD_JMPCLOSE = 0x58535906, AIS_CMD_BOOTTBL = 0x58535907, AIS_CMD_FILL = 0x5853590A, AIS_CMD_FNLOAD = 0x5853590D, AIS_CMD_SEQREAD = 0x58535963, }; struct ais_cmd_load { uint32_t cmd; uint32_t addr; uint32_t size; uint32_t data[1]; }; struct ais_cmd_func { uint32_t cmd; uint32_t func_args; uint32_t parms[AIS_FCN_MAX]; }; struct ais_cmd_jmpclose { uint32_t cmd; uint32_t addr; }; #define CMD_DATA_STR "DATA" enum ais_file_cmd { CMD_INVALID, CMD_FILL, CMD_CRCON, CMD_CRCOFF, CMD_CRCCHECK, CMD_JMPCLOSE, CMD_JMP, CMD_SEQREAD, CMD_DATA, CMD_PLL0, CMD_PLL1, CMD_CLK, CMD_DDR2, CMD_EMIFA, CMD_EMIFA_ASYNC, CMD_PLL, CMD_PSC, CMD_PINMUX, CMD_BOOTTABLE }; enum aisimage_fld_types { CFG_INVALID = -1, CFG_COMMAND, CFG_VALUE, }; struct ais_header { uint32_t magic; char data[1]; }; #endif /* _AISIMAGE_H_ */
1001-study-uboot
tools/aisimage.h
C
gpl3
2,031
/* * Copyright 2009 Extreme Engineering Solutions, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this software; if not, write to the * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __OS_SUPPORT_H_ #define __OS_SUPPORT_H_ #include "compiler.h" /* * Include additional files required for supporting different operating systems */ #ifdef __MINGW32__ #include "mingw_support.h" #endif #if defined(__APPLE__) && __DARWIN_C_LEVEL < 200809L #include "getline.h" #endif #endif /* __OS_SUPPORT_H_ */
1001-study-uboot
tools/os_support.h
C
gpl3
1,115
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifndef BUFSIZ # define BUFSIZ 4096 #endif #undef BUFSIZ # define BUFSIZ 64 int main (void) { short ibuff[BUFSIZ], obuff[BUFSIZ]; int rc, i, len; while ((rc = read (0, ibuff, sizeof (ibuff))) > 0) { memset (obuff, 0, sizeof (obuff)); for (i = 0; i < (rc + 1) / 2; i++) { obuff[i] = ibuff[i ^ 1]; } len = (rc + 1) & ~1; if (write (1, obuff, len) != len) { perror ("read error"); return (EXIT_FAILURE); } memset (ibuff, 0, sizeof (ibuff)); } if (rc < 0) { perror ("read error"); return (EXIT_FAILURE); } return (EXIT_SUCCESS); }
1001-study-uboot
tools/xway-swap-bytes.c
C
gpl3
647
/* * Program for finding M & N values for DPLLs * To be run on Host PC * * (C) Copyright 2010 * Texas Instruments, <www.ti.com> * * Aneesh V <aneesh@ti.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdlib.h> #include <stdio.h> typedef unsigned int u32; #define MAX_N 127 /* * get_m_n_optimized() - Finds optimal DPLL multiplier(M) and divider(N) * values based on the reference frequency, required output frequency, * maximum tolerance for output frequency etc. * * target_freq_khz - output frequency required in KHz * ref_freq_khz - reference(input) frequency in KHz * m - pointer to computed M value * n - pointer to computed N value * tolerance_khz - tolerance for the output frequency. When the algorithm * succeeds in finding vialble M and N values the corresponding output * frequency will be in the range: * [target_freq_khz - tolerance_khz, target_freq_khz] * * Formula: * Fdpll = (2 * M * Fref) / (N + 1) * * Considerations for lock-time: * - Smaller the N, better lock-time, especially lock-time will be * - For acceptable lock-times: * Fref / (M + 1) >= 1 MHz * * Considerations for power: * - The difference in power for different N values giving the same * output is negligible. So, we optimize for lock-time * * Hard-constraints: * - N can not be greater than 127(7 bit field for representing N) * * Usage: * $ gcc clocks_get_m_n.c * $ ./a.out */ int get_m_n_optimized(u32 target_freq_khz, u32 ref_freq_khz, u32 *M, u32 *N) { u32 freq = target_freq_khz; u32 m_optimal, n_optimal, freq_optimal = 0, freq_old; u32 m, n; n = 1; while (1) { m = target_freq_khz / ref_freq_khz / 2 * n; freq_old = 0; while (1) { freq = ref_freq_khz * 2 * m / n; if (freq > target_freq_khz) { freq = freq_old; m--; break; } m++; freq_old = freq; } if (freq > freq_optimal) { freq_optimal = freq; m_optimal = m; n_optimal = n; } n++; if ((freq_optimal == target_freq_khz) || ((ref_freq_khz / n) < 1000)) { break; } } n--; *M = m_optimal; *N = n_optimal - 1; printf("ref %d m %d n %d target %d locked %d\n", ref_freq_khz, m_optimal, n_optimal - 1, target_freq_khz, freq_optimal); return 0; } void main(void) { u32 m, n; printf("\nMPU - 2000000\n"); get_m_n_optimized(2000000, 12000, &m, &n); get_m_n_optimized(2000000, 13000, &m, &n); get_m_n_optimized(2000000, 16800, &m, &n); get_m_n_optimized(2000000, 19200, &m, &n); get_m_n_optimized(2000000, 26000, &m, &n); get_m_n_optimized(2000000, 27000, &m, &n); get_m_n_optimized(2000000, 38400, &m, &n); printf("\nMPU - 1200000\n"); get_m_n_optimized(1200000, 12000, &m, &n); get_m_n_optimized(1200000, 13000, &m, &n); get_m_n_optimized(1200000, 16800, &m, &n); get_m_n_optimized(1200000, 19200, &m, &n); get_m_n_optimized(1200000, 26000, &m, &n); get_m_n_optimized(1200000, 27000, &m, &n); get_m_n_optimized(1200000, 38400, &m, &n); printf("\nMPU - 1584000\n"); get_m_n_optimized(1584000, 12000, &m, &n); get_m_n_optimized(1584000, 13000, &m, &n); get_m_n_optimized(1584000, 16800, &m, &n); get_m_n_optimized(1584000, 19200, &m, &n); get_m_n_optimized(1584000, 26000, &m, &n); get_m_n_optimized(1584000, 27000, &m, &n); get_m_n_optimized(1584000, 38400, &m, &n); printf("\nCore 1600000\n"); get_m_n_optimized(1600000, 12000, &m, &n); get_m_n_optimized(1600000, 13000, &m, &n); get_m_n_optimized(1600000, 16800, &m, &n); get_m_n_optimized(1600000, 19200, &m, &n); get_m_n_optimized(1600000, 26000, &m, &n); get_m_n_optimized(1600000, 27000, &m, &n); get_m_n_optimized(1600000, 38400, &m, &n); printf("\nPER 1536000\n"); get_m_n_optimized(1536000, 12000, &m, &n); get_m_n_optimized(1536000, 13000, &m, &n); get_m_n_optimized(1536000, 16800, &m, &n); get_m_n_optimized(1536000, 19200, &m, &n); get_m_n_optimized(1536000, 26000, &m, &n); get_m_n_optimized(1536000, 27000, &m, &n); get_m_n_optimized(1536000, 38400, &m, &n); printf("\nIVA 1862000\n"); get_m_n_optimized(1862000, 12000, &m, &n); get_m_n_optimized(1862000, 13000, &m, &n); get_m_n_optimized(1862000, 16800, &m, &n); get_m_n_optimized(1862000, 19200, &m, &n); get_m_n_optimized(1862000, 26000, &m, &n); get_m_n_optimized(1862000, 27000, &m, &n); get_m_n_optimized(1862000, 38400, &m, &n); printf("\nIVA Nitro - 1290000\n"); get_m_n_optimized(1290000, 12000, &m, &n); get_m_n_optimized(1290000, 13000, &m, &n); get_m_n_optimized(1290000, 16800, &m, &n); get_m_n_optimized(1290000, 19200, &m, &n); get_m_n_optimized(1290000, 26000, &m, &n); get_m_n_optimized(1290000, 27000, &m, &n); get_m_n_optimized(1290000, 38400, &m, &n); printf("\nABE 196608 sys clk\n"); get_m_n_optimized(196608, 12000, &m, &n); get_m_n_optimized(196608, 13000, &m, &n); get_m_n_optimized(196608, 16800, &m, &n); get_m_n_optimized(196608, 19200, &m, &n); get_m_n_optimized(196608, 26000, &m, &n); get_m_n_optimized(196608, 27000, &m, &n); get_m_n_optimized(196608, 38400, &m, &n); printf("\nABE 196608 32K\n"); get_m_n_optimized(196608000/4, 32768, &m, &n); printf("\nUSB 1920000\n"); get_m_n_optimized(1920000, 12000, &m, &n); get_m_n_optimized(1920000, 13000, &m, &n); get_m_n_optimized(1920000, 16800, &m, &n); get_m_n_optimized(1920000, 19200, &m, &n); get_m_n_optimized(1920000, 26000, &m, &n); get_m_n_optimized(1920000, 27000, &m, &n); get_m_n_optimized(1920000, 38400, &m, &n); printf("\nCore ES1 1523712\n"); get_m_n_optimized(1524000, 12000, &m, &n); get_m_n_optimized(1524000, 13000, &m, &n); get_m_n_optimized(1524000, 16800, &m, &n); get_m_n_optimized(1524000, 19200, &m, &n); get_m_n_optimized(1524000, 26000, &m, &n); get_m_n_optimized(1524000, 27000, &m, &n); /* exact recommendation for SDPs */ get_m_n_optimized(1523712, 38400, &m, &n); }
1001-study-uboot
tools/omap/clocks_get_m_n.c
C
gpl3
6,504
/* * Copyright 2008 Extreme Engineering Solutions, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this software; if not, write to the * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __MINGW_SUPPORT_H_ #define __WINGW_SUPPORT_H_ 1 /* Defining __INSIDE_MSYS__ helps to prevent u-boot/mingw overlap */ #define __INSIDE_MSYS__ 1 #include <windows.h> /* mmap protections */ #define PROT_READ 0x1 /* Page can be read */ #define PROT_WRITE 0x2 /* Page can be written */ #define PROT_EXEC 0x4 /* Page can be executed */ #define PROT_NONE 0x0 /* Page can not be accessed */ /* Sharing types (must choose one and only one of these) */ #define MAP_SHARED 0x01 /* Share changes */ #define MAP_PRIVATE 0x02 /* Changes are private */ /* Windows 64-bit access macros */ #define LODWORD(x) ((DWORD)((DWORDLONG)(x))) #define HIDWORD(x) ((DWORD)(((DWORDLONG)(x) >> 32) & 0xffffffff)) typedef UINT uint; typedef ULONG ulong; int fsync(int fd); void *mmap(void *, size_t, int, int, int, int); int munmap(void *, size_t); char *strtok_r(char *s, const char *delim, char **save_ptr); #include "getline.h" #endif /* __MINGW_SUPPORT_H_ */
1001-study-uboot
tools/mingw_support.h
C
gpl3
1,746
#!/bin/sh # # This scripts adds local version information from the version # control systems git, mercurial (hg) and subversion (svn). # # It was originally copied from the Linux kernel v3.2.0-rc4 and modified # to support the U-Boot build-system. # usage() { echo "Usage: $0 [--save-scmversion] [srctree]" >&2 exit 1 } scm_only=false srctree=. if test "$1" = "--save-scmversion"; then scm_only=true shift fi if test $# -gt 0; then srctree=$1 shift fi if test $# -gt 0 -o ! -d "$srctree"; then usage fi scm_version() { local short short=false cd "$srctree" if test -e .scmversion; then cat .scmversion return fi if test "$1" = "--short"; then short=true fi # Check for git and a git repo. if test -e .git && head=`git rev-parse --verify --short HEAD 2>/dev/null`; then # If we are at a tagged commit (like "v2.6.30-rc6"), we ignore # it, because this version is defined in the top level Makefile. if [ -z "`git describe --exact-match 2>/dev/null`" ]; then # If only the short version is requested, don't bother # running further git commands if $short; then echo "+" return fi # If we are past a tagged commit (like # "v2.6.30-rc5-302-g72357d5"), we pretty print it. if atag="`git describe 2>/dev/null`"; then echo "$atag" | awk -F- '{printf("-%05d-%s", $(NF-1),$(NF))}' # If we don't have a tag at all we print -g{commitish}. else printf '%s%s' -g $head fi fi # Is this git on svn? if git config --get svn-remote.svn.url >/dev/null; then printf -- '-svn%s' "`git svn find-rev $head`" fi # Update index only on r/w media [ -w . ] && git update-index --refresh --unmerged > /dev/null # Check for uncommitted changes if git diff-index --name-only HEAD | grep -v "^scripts/package" \ | read dummy; then printf '%s' -dirty fi # All done with git return fi # Check for mercurial and a mercurial repo. if test -d .hg && hgid=`hg id 2>/dev/null`; then # Do we have an tagged version? If so, latesttagdistance == 1 if [ "`hg log -r . --template '{latesttagdistance}'`" == "1" ]; then id=`hg log -r . --template '{latesttag}'` printf '%s%s' -hg "$id" else tag=`printf '%s' "$hgid" | cut -d' ' -f2` if [ -z "$tag" -o "$tag" = tip ]; then id=`printf '%s' "$hgid" | sed 's/[+ ].*//'` printf '%s%s' -hg "$id" fi fi # Are there uncommitted changes? # These are represented by + after the changeset id. case "$hgid" in *+|*+\ *) printf '%s' -dirty ;; esac # All done with mercurial return fi # Check for svn and a svn repo. if rev=`svn info 2>/dev/null | grep '^Last Changed Rev'`; then rev=`echo $rev | awk '{print $NF}'` printf -- '-svn%s' "$rev" # All done with svn return fi } collect_files() { local file res for file; do case "$file" in *\~*) continue ;; esac if test -e "$file"; then res="$res$(cat "$file")" fi done echo "$res" } if $scm_only; then if test ! -e .scmversion; then res=$(scm_version) echo "$res" >.scmversion fi exit fi #if test -e include/config/auto.conf; then # . include/config/auto.conf #else # echo "Error: kernelrelease not valid - run 'make prepare' to update it" # exit 1 #fi CONFIG_LOCALVERSION= CONFIG_LOCALVERSION_AUTO=y # localversion* files in the build and source directory res="$(collect_files localversion*)" if test ! "$srctree" -ef .; then res="$res$(collect_files "$srctree"/localversion*)" fi # CONFIG_LOCALVERSION and LOCALVERSION (if set) res="${res}${CONFIG_LOCALVERSION}${LOCALVERSION}" # scm version string if not at a tagged commit if test "$CONFIG_LOCALVERSION_AUTO" = "y"; then # full scm version string res="$res$(scm_version)" else # append a plus sign if the repository is not in a clean # annotated or signed tagged state (as git describe only # looks at signed or annotated tags - git tag -a/-s) and # LOCALVERSION= is not specified if test "${LOCALVERSION+set}" != "set"; then scm=$(scm_version --short) res="$res${scm:++}" fi fi echo "$res"
1001-study-uboot
tools/setlocalversion
Shell
gpl3
4,023
/* * (C) Copyright 2011 * Heiko Schocher, DENX Software Engineering, hs@denx.de. * * Based on: * (C) Copyright 2009 * Stefano Babic, DENX Software Engineering, sbabic@denx.de. * * (C) Copyright 2008 * Marvell Semiconductor <www.marvell.com> * Written-by: Prafulla Wadaskar <prafulla@marvell.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* Required to obtain the getline prototype from stdio.h */ #define _GNU_SOURCE #include "mkimage.h" #include <image.h> #include "ublimage.h" /* * Supported commands for configuration file */ static table_entry_t ublimage_cmds[] = { {CMD_BOOT_MODE, "MODE", "UBL special modes", }, {CMD_ENTRY, "ENTRY", "Entry point addr for bootloader", }, {CMD_PAGE, "PAGES", "number of pages (size of bootloader)", }, {CMD_ST_BLOCK, "START_BLOCK", "block number where bootloader is present", }, {CMD_ST_PAGE, "START_PAGE", "page number where bootloader is present", }, {CMD_LD_ADDR, "LD_ADDR", "load addr", }, {-1, "", "", }, }; /* * Supported Boot options for configuration file * this is needed to set the correct flash offset */ static table_entry_t ublimage_bootops[] = { {UBL_MAGIC_SAFE, "safe", "Safe boot mode", }, {-1, "", "Invalid", }, }; static struct ubl_header ublimage_header; static uint32_t get_cfg_value(char *token, char *name, int linenr) { char *endptr; uint32_t value; errno = 0; value = strtoul(token, &endptr, 16); if (errno || (token == endptr)) { fprintf(stderr, "Error: %s[%d] - Invalid hex data(%s)\n", name, linenr, token); exit(EXIT_FAILURE); } return value; } static void print_hdr(struct ubl_header *ubl_hdr) { printf("Image Type : Davinci UBL Boot Image\n"); printf("UBL magic : %08x\n", ubl_hdr->magic); printf("Entry Point: %08x\n", ubl_hdr->entry); printf("nr of pages: %08x\n", ubl_hdr->pages); printf("start block: %08x\n", ubl_hdr->block); printf("start page : %08x\n", ubl_hdr->page); } static void parse_cfg_cmd(struct ubl_header *ublhdr, int32_t cmd, char *token, char *name, int lineno, int fld, int dcd_len) { static int cmd_ver_first = ~0; switch (cmd) { case CMD_BOOT_MODE: ublhdr->magic = get_table_entry_id(ublimage_bootops, "ublimage special boot mode", token); if (ublhdr->magic == -1) { fprintf(stderr, "Error: %s[%d] -Invalid boot mode" "(%s)\n", name, lineno, token); exit(EXIT_FAILURE); } ublhdr->magic += UBL_MAGIC_BASE; if (unlikely(cmd_ver_first != 1)) cmd_ver_first = 0; break; case CMD_ENTRY: ublhdr->entry = get_cfg_value(token, name, lineno); break; case CMD_PAGE: ublhdr->pages = get_cfg_value(token, name, lineno); break; case CMD_ST_BLOCK: ublhdr->block = get_cfg_value(token, name, lineno); break; case CMD_ST_PAGE: ublhdr->page = get_cfg_value(token, name, lineno); break; case CMD_LD_ADDR: ublhdr->pll_m = get_cfg_value(token, name, lineno); break; } } static void parse_cfg_fld(struct ubl_header *ublhdr, int32_t *cmd, char *token, char *name, int lineno, int fld, int *dcd_len) { switch (fld) { case CFG_COMMAND: *cmd = get_table_entry_id(ublimage_cmds, "ublimage commands", token); if (*cmd < 0) { fprintf(stderr, "Error: %s[%d] - Invalid command" "(%s)\n", name, lineno, token); exit(EXIT_FAILURE); } break; case CFG_REG_VALUE: parse_cfg_cmd(ublhdr, *cmd, token, name, lineno, fld, *dcd_len); break; default: break; } } static uint32_t parse_cfg_file(struct ubl_header *ublhdr, char *name) { FILE *fd = NULL; char *line = NULL; char *token, *saveptr1, *saveptr2; int lineno = 0; int i; char *ptr = (char *)ublhdr; int fld; size_t len; int dcd_len = 0; int32_t cmd; int ublhdrlen = sizeof(struct ubl_header); fd = fopen(name, "r"); if (fd == 0) { fprintf(stderr, "Error: %s - Can't open DCD file\n", name); exit(EXIT_FAILURE); } /* Fill header with 0xff */ for (i = 0; i < ublhdrlen; i++) { *ptr = 0xff; ptr++; } /* * Very simple parsing, line starting with # are comments * and are dropped */ while ((getline(&line, &len, fd)) > 0) { lineno++; token = strtok_r(line, "\r\n", &saveptr1); if (token == NULL) continue; /* Check inside the single line */ for (fld = CFG_COMMAND, cmd = CMD_INVALID, line = token; ; line = NULL, fld++) { token = strtok_r(line, " \t", &saveptr2); if (token == NULL) break; /* Drop all text starting with '#' as comments */ if (token[0] == '#') break; parse_cfg_fld(ublhdr, &cmd, token, name, lineno, fld, &dcd_len); } } fclose(fd); return dcd_len; } static int ublimage_check_image_types(uint8_t type) { if (type == IH_TYPE_UBLIMAGE) return EXIT_SUCCESS; else return EXIT_FAILURE; } static int ublimage_verify_header(unsigned char *ptr, int image_size, struct mkimage_params *params) { struct ubl_header *ubl_hdr = (struct ubl_header *)ptr; if ((ubl_hdr->magic & 0xFFFFFF00) != UBL_MAGIC_BASE) return -1; return 0; } static void ublimage_print_header(const void *ptr) { struct ubl_header *ubl_hdr = (struct ubl_header *) ptr; print_hdr(ubl_hdr); } static void ublimage_set_header(void *ptr, struct stat *sbuf, int ifd, struct mkimage_params *params) { struct ubl_header *ublhdr = (struct ubl_header *)ptr; /* Parse configuration file */ parse_cfg_file(ublhdr, params->imagename); } int ublimage_check_params(struct mkimage_params *params) { if (!params) return CFG_INVALID; if (!strlen(params->imagename)) { fprintf(stderr, "Error: %s - Configuration file not" "specified, it is needed for ublimage generation\n", params->cmdname); return CFG_INVALID; } /* * Check parameters: * XIP is not allowed and verify that incompatible * parameters are not sent at the same time * For example, if list is required a data image must not be provided */ return (params->dflag && (params->fflag || params->lflag)) || (params->fflag && (params->dflag || params->lflag)) || (params->lflag && (params->dflag || params->fflag)) || (params->xflag) || !(strlen(params->imagename)); } /* * ublimage parameters */ static struct image_type_params ublimage_params = { .name = "Davinci UBL boot support", .header_size = sizeof(struct ubl_header), .hdr = (void *)&ublimage_header, .check_image_type = ublimage_check_image_types, .verify_header = ublimage_verify_header, .print_header = ublimage_print_header, .set_header = ublimage_set_header, .check_params = ublimage_check_params, }; void init_ubl_image_type(void) { mkimage_register(&ublimage_params); }
1001-study-uboot
tools/ublimage.c
C
gpl3
7,248
/* * cramfs.c * * Copyright (C) 1999 Linus Torvalds * * Copyright (C) 2000-2002 Transmeta Corporation * * Copyright (C) 2003 Kai-Uwe Bloem, * Auerswald GmbH & Co KG, <linux-development@auerswald.de> * - adapted from the www.tuxbox.org u-boot tree, added "ls" command * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (Version 2) as * published by the Free Software Foundation. * * Compressed ROM filesystem for Linux. * * TODO: * add support for resolving symbolic links */ /* * These are the VFS interfaces to the compressed ROM filesystem. * The actual compression is based on zlib, see the other files. */ #include <common.h> #include <malloc.h> #include <asm/byteorder.h> #include <linux/stat.h> #include <jffs2/jffs2.h> #include <jffs2/load_kernel.h> #include <cramfs/cramfs_fs.h> /* These two macros may change in future, to provide better st_ino semantics. */ #define CRAMINO(x) (CRAMFS_GET_OFFSET(x) ? CRAMFS_GET_OFFSET(x)<<2 : 1) #define OFFSET(x) ((x)->i_ino) struct cramfs_super super; /* CPU address space offset calculation macro, struct part_info offset is * device address space offset, so we need to shift it by a device start address. */ #if !defined(CONFIG_SYS_NO_FLASH) extern flash_info_t flash_info[]; #define PART_OFFSET(x) (x->offset + flash_info[x->dev->id->num].start[0]) #else #define PART_OFFSET(x) (x->offset) #endif static int cramfs_read_super (struct part_info *info) { unsigned long root_offset; /* Read the first block and get the superblock from it */ memcpy (&super, (void *) PART_OFFSET(info), sizeof (super)); /* Do sanity checks on the superblock */ if (super.magic != CRAMFS_32 (CRAMFS_MAGIC)) { /* check at 512 byte offset */ memcpy (&super, (void *) PART_OFFSET(info) + 512, sizeof (super)); if (super.magic != CRAMFS_32 (CRAMFS_MAGIC)) { printf ("cramfs: wrong magic\n"); return -1; } } /* flags is reused several times, so swab it once */ super.flags = CRAMFS_32 (super.flags); super.size = CRAMFS_32 (super.size); /* get feature flags first */ if (super.flags & ~CRAMFS_SUPPORTED_FLAGS) { printf ("cramfs: unsupported filesystem features\n"); return -1; } /* Check that the root inode is in a sane state */ if (!S_ISDIR (CRAMFS_16 (super.root.mode))) { printf ("cramfs: root is not a directory\n"); return -1; } root_offset = CRAMFS_GET_OFFSET (&(super.root)) << 2; if (root_offset == 0) { printf ("cramfs: empty filesystem"); } else if (!(super.flags & CRAMFS_FLAG_SHIFTED_ROOT_OFFSET) && ((root_offset != sizeof (struct cramfs_super)) && (root_offset != 512 + sizeof (struct cramfs_super)))) { printf ("cramfs: bad root offset %lu\n", root_offset); return -1; } return 0; } static unsigned long cramfs_resolve (unsigned long begin, unsigned long offset, unsigned long size, int raw, char *filename) { unsigned long inodeoffset = 0, nextoffset; while (inodeoffset < size) { struct cramfs_inode *inode; char *name; int namelen; inode = (struct cramfs_inode *) (begin + offset + inodeoffset); /* * Namelengths on disk are shifted by two * and the name padded out to 4-byte boundaries * with zeroes. */ namelen = CRAMFS_GET_NAMELEN (inode) << 2; name = (char *) inode + sizeof (struct cramfs_inode); nextoffset = inodeoffset + sizeof (struct cramfs_inode) + namelen; for (;;) { if (!namelen) return -1; if (name[namelen - 1]) break; namelen--; } if (!strncmp (filename, name, namelen)) { char *p = strtok (NULL, "/"); if (raw && (p == NULL || *p == '\0')) return offset + inodeoffset; if (S_ISDIR (CRAMFS_16 (inode->mode))) { return cramfs_resolve (begin, CRAMFS_GET_OFFSET (inode) << 2, CRAMFS_24 (inode-> size), raw, p); } else if (S_ISREG (CRAMFS_16 (inode->mode))) { return offset + inodeoffset; } else { printf ("%*.*s: unsupported file type (%x)\n", namelen, namelen, name, CRAMFS_16 (inode->mode)); return 0; } } inodeoffset = nextoffset; } printf ("can't find corresponding entry\n"); return 0; } static int cramfs_uncompress (unsigned long begin, unsigned long offset, unsigned long loadoffset) { struct cramfs_inode *inode = (struct cramfs_inode *) (begin + offset); unsigned long *block_ptrs = (unsigned long *) (begin + (CRAMFS_GET_OFFSET (inode) << 2)); unsigned long curr_block = (CRAMFS_GET_OFFSET (inode) + (((CRAMFS_24 (inode->size)) + 4095) >> 12)) << 2; int size, total_size = 0; int i; cramfs_uncompress_init (); for (i = 0; i < ((CRAMFS_24 (inode->size) + 4095) >> 12); i++) { size = cramfs_uncompress_block ((void *) loadoffset, (void *) (begin + curr_block), (CRAMFS_32 (block_ptrs[i]) - curr_block)); if (size < 0) return size; loadoffset += size; total_size += size; curr_block = CRAMFS_32 (block_ptrs[i]); } cramfs_uncompress_exit (); return total_size; } int cramfs_load (char *loadoffset, struct part_info *info, char *filename) { unsigned long offset; if (cramfs_read_super (info)) return -1; offset = cramfs_resolve (PART_OFFSET(info), CRAMFS_GET_OFFSET (&(super.root)) << 2, CRAMFS_24 (super.root.size), 0, strtok (filename, "/")); if (offset <= 0) return offset; return cramfs_uncompress (PART_OFFSET(info), offset, (unsigned long) loadoffset); } static int cramfs_list_inode (struct part_info *info, unsigned long offset) { struct cramfs_inode *inode = (struct cramfs_inode *) (PART_OFFSET(info) + offset); char *name, str[20]; int namelen, nextoff; /* * Namelengths on disk are shifted by two * and the name padded out to 4-byte boundaries * with zeroes. */ namelen = CRAMFS_GET_NAMELEN (inode) << 2; name = (char *) inode + sizeof (struct cramfs_inode); nextoff = namelen; for (;;) { if (!namelen) return namelen; if (name[namelen - 1]) break; namelen--; } printf (" %s %8d %*.*s", mkmodestr (CRAMFS_16 (inode->mode), str), CRAMFS_24 (inode->size), namelen, namelen, name); if ((CRAMFS_16 (inode->mode) & S_IFMT) == S_IFLNK) { /* symbolic link. * Unpack the link target, trusting in the inode's size field. */ unsigned long size = CRAMFS_24 (inode->size); char *link = malloc (size); if (link != NULL && cramfs_uncompress (PART_OFFSET(info), offset, (unsigned long) link) == size) printf (" -> %*.*s\n", (int) size, (int) size, link); else printf (" [Error reading link]\n"); if (link) free (link); } else printf ("\n"); return nextoff; } int cramfs_ls (struct part_info *info, char *filename) { struct cramfs_inode *inode; unsigned long inodeoffset = 0, nextoffset; unsigned long offset, size; if (cramfs_read_super (info)) return -1; if (strlen (filename) == 0 || !strcmp (filename, "/")) { /* Root directory. Use root inode in super block */ offset = CRAMFS_GET_OFFSET (&(super.root)) << 2; size = CRAMFS_24 (super.root.size); } else { /* Resolve the path */ offset = cramfs_resolve (PART_OFFSET(info), CRAMFS_GET_OFFSET (&(super.root)) << 2, CRAMFS_24 (super.root.size), 1, strtok (filename, "/")); if (offset <= 0) return offset; /* Resolving was successful. Examine the inode */ inode = (struct cramfs_inode *) (PART_OFFSET(info) + offset); if (!S_ISDIR (CRAMFS_16 (inode->mode))) { /* It's not a directory - list it, and that's that */ return (cramfs_list_inode (info, offset) > 0); } /* It's a directory. List files within */ offset = CRAMFS_GET_OFFSET (inode) << 2; size = CRAMFS_24 (inode->size); } /* List the given directory */ while (inodeoffset < size) { inode = (struct cramfs_inode *) (PART_OFFSET(info) + offset + inodeoffset); nextoffset = cramfs_list_inode (info, offset + inodeoffset); if (nextoffset == 0) break; inodeoffset += sizeof (struct cramfs_inode) + nextoffset; } return 1; } int cramfs_info (struct part_info *info) { if (cramfs_read_super (info)) return 0; printf ("size: 0x%x (%u)\n", super.size, super.size); if (super.flags != 0) { printf ("flags:\n"); if (super.flags & CRAMFS_FLAG_FSID_VERSION_2) printf ("\tFSID version 2\n"); if (super.flags & CRAMFS_FLAG_SORTED_DIRS) printf ("\tsorted dirs\n"); if (super.flags & CRAMFS_FLAG_HOLES) printf ("\tholes\n"); if (super.flags & CRAMFS_FLAG_SHIFTED_ROOT_OFFSET) printf ("\tshifted root offset\n"); } printf ("fsid:\n\tcrc: 0x%x\n\tedition: 0x%x\n", super.fsid.crc, super.fsid.edition); printf ("name: %16s\n", super.name); return 1; } int cramfs_check (struct part_info *info) { struct cramfs_super *sb; if (info->dev->id->type != MTD_DEV_TYPE_NOR) return 0; sb = (struct cramfs_super *) PART_OFFSET(info); if (sb->magic != CRAMFS_32 (CRAMFS_MAGIC)) { /* check at 512 byte offset */ sb = (struct cramfs_super *) (PART_OFFSET(info) + 512); if (sb->magic != CRAMFS_32 (CRAMFS_MAGIC)) return 0; } return 1; }
1001-study-uboot
fs/cramfs/cramfs.c
C
gpl3
9,104
/* * uncompress.c * * Copyright (C) 1999 Linus Torvalds * Copyright (C) 2000-2002 Transmeta Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (Version 2) as * published by the Free Software Foundation. * * cramfs interfaces to the uncompression library. There's really just * three entrypoints: * * - cramfs_uncompress_init() - called to initialize the thing. * - cramfs_uncompress_exit() - tell me when you're done * - cramfs_uncompress_block() - uncompress a block. * * NOTE NOTE NOTE! The uncompression is entirely single-threaded. We * only have one stream, and we'll initialize it only once even if it * then is used by multiple filesystems. */ #include <common.h> #include <malloc.h> #include <watchdog.h> #include <u-boot/zlib.h> static z_stream stream; void *zalloc(void *, unsigned, unsigned); void zfree(void *, void *, unsigned); /* Returns length of decompressed data. */ int cramfs_uncompress_block (void *dst, void *src, int srclen) { int err; inflateReset (&stream); stream.next_in = src; stream.avail_in = srclen; stream.next_out = dst; stream.avail_out = 4096 * 2; err = inflate (&stream, Z_FINISH); if (err != Z_STREAM_END) goto err; return stream.total_out; err: /*printf ("Error %d while decompressing!\n", err); */ /*printf ("%p(%d)->%p\n", src, srclen, dst); */ return -1; } int cramfs_uncompress_init (void) { int err; stream.zalloc = zalloc; stream.zfree = zfree; stream.next_in = 0; stream.avail_in = 0; #if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) stream.outcb = (cb_func) WATCHDOG_RESET; #else stream.outcb = Z_NULL; #endif /* CONFIG_HW_WATCHDOG */ err = inflateInit (&stream); if (err != Z_OK) { printf ("Error: inflateInit2() returned %d\n", err); return -1; } return 0; } int cramfs_uncompress_exit (void) { inflateEnd (&stream); return 0; }
1001-study-uboot
fs/cramfs/uncompress.c
C
gpl3
1,953
# # (C) Copyright 2000-2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk LIB = $(obj)libcramfs.o AOBJS = COBJS-$(CONFIG_CMD_CRAMFS) := cramfs.o COBJS-$(CONFIG_CMD_CRAMFS) += uncompress.o SRCS := $(AOBJS:.o=.S) $(COBJS-y:.o=.c) OBJS := $(addprefix $(obj),$(AOBJS) $(COBJS-y)) #CPPFLAGS += all: $(LIB) $(AOBJS) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
fs/cramfs/Makefile
Makefile
gpl3
1,435
# # (C) Copyright 2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # (C) Copyright 2003 # Pavel Bartusek, Sysgo Real-Time Solutions AG, pba@sysgo.de # # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk LIB = $(obj)libext2fs.o AOBJS = COBJS-$(CONFIG_CMD_EXT2) := ext2fs.o dev.o SRCS := $(AOBJS:.o=.S) $(COBJS-y:.o=.c) OBJS := $(addprefix $(obj),$(AOBJS) $(COBJS-y)) #CPPFLAGS += all: $(LIB) $(AOBJS) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
fs/ext2/Makefile
Makefile
gpl3
1,476
/* * (C) Copyright 2004 * esd gmbh <www.esd-electronics.com> * Reinhard Arlt <reinhard.arlt@esd-electronics.com> * * based on code of fs/reiserfs/dev.c by * * (C) Copyright 2003 - 2004 * Sysgo AG, <www.elinos.com>, Pavel Bartusek <pba@sysgo.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <common.h> #include <config.h> #include <ext2fs.h> static block_dev_desc_t *ext2fs_block_dev_desc; static disk_partition_t part_info; int ext2fs_set_blk_dev(block_dev_desc_t *rbdd, int part) { ext2fs_block_dev_desc = rbdd; if (part == 0) { /* disk doesn't use partition table */ part_info.start = 0; part_info.size = rbdd->lba; part_info.blksz = rbdd->blksz; } else { if (get_partition_info (ext2fs_block_dev_desc, part, &part_info)) { return 0; } } return part_info.size; } int ext2fs_devread(int sector, int byte_offset, int byte_len, char *buf) { ALLOC_CACHE_ALIGN_BUFFER(char, sec_buf, SECTOR_SIZE); unsigned sectors; /* * Check partition boundaries */ if ((sector < 0) || ((sector + ((byte_offset + byte_len - 1) >> SECTOR_BITS)) >= part_info.size)) { /* errnum = ERR_OUTSIDE_PART; */ printf(" ** %s read outside partition sector %d\n", __func__, sector); return 0; } /* * Get the read to the beginning of a partition. */ sector += byte_offset >> SECTOR_BITS; byte_offset &= SECTOR_SIZE - 1; debug(" <%d, %d, %d>\n", sector, byte_offset, byte_len); if (ext2fs_block_dev_desc == NULL) { printf(" ** %s Invalid Block Device Descriptor (NULL)\n", __func__); return 0; } if (byte_offset != 0) { /* read first part which isn't aligned with start of sector */ if (ext2fs_block_dev_desc-> block_read(ext2fs_block_dev_desc->dev, part_info.start + sector, 1, (unsigned long *) sec_buf) != 1) { printf(" ** %s read error **\n", __func__); return 0; } memcpy(buf, sec_buf + byte_offset, min(SECTOR_SIZE - byte_offset, byte_len)); buf += min(SECTOR_SIZE - byte_offset, byte_len); byte_len -= min(SECTOR_SIZE - byte_offset, byte_len); sector++; } /* read sector aligned part */ sectors = byte_len / SECTOR_SIZE; if (sectors > 0) { if (ext2fs_block_dev_desc->block_read( ext2fs_block_dev_desc->dev, part_info.start + sector, sectors, (unsigned long *) buf) != sectors) { printf(" ** %s read error - block\n", __func__); return 0; } buf += sectors * SECTOR_SIZE; byte_len -= sectors * SECTOR_SIZE; sector += sectors; } if (byte_len != 0) { /* read rest of data which are not in whole sector */ if (ext2fs_block_dev_desc-> block_read(ext2fs_block_dev_desc->dev, part_info.start + sector, 1, (unsigned long *) sec_buf) != 1) { printf(" ** %s read error - last part\n", __func__); return 0; } memcpy(buf, sec_buf, byte_len); } return 1; }
1001-study-uboot
fs/ext2/dev.c
C
gpl3
3,549
/* * (C) Copyright 2004 * esd gmbh <www.esd-electronics.com> * Reinhard Arlt <reinhard.arlt@esd-electronics.com> * * based on code from grub2 fs/ext2.c and fs/fshelp.c by * * GRUB -- GRand Unified Bootloader * Copyright (C) 2003, 2004 Free Software Foundation, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <common.h> #include <ext2fs.h> #include <malloc.h> #include <asm/byteorder.h> extern int ext2fs_devread (int sector, int byte_offset, int byte_len, char *buf); /* Magic value used to identify an ext2 filesystem. */ #define EXT2_MAGIC 0xEF53 /* Amount of indirect blocks in an inode. */ #define INDIRECT_BLOCKS 12 /* Maximum lenght of a pathname. */ #define EXT2_PATH_MAX 4096 /* Maximum nesting of symlinks, used to prevent a loop. */ #define EXT2_MAX_SYMLINKCNT 8 /* Filetype used in directory entry. */ #define FILETYPE_UNKNOWN 0 #define FILETYPE_REG 1 #define FILETYPE_DIRECTORY 2 #define FILETYPE_SYMLINK 7 /* Filetype information as used in inodes. */ #define FILETYPE_INO_MASK 0170000 #define FILETYPE_INO_REG 0100000 #define FILETYPE_INO_DIRECTORY 0040000 #define FILETYPE_INO_SYMLINK 0120000 /* Bits used as offset in sector */ #define DISK_SECTOR_BITS 9 /* Log2 size of ext2 block in 512 blocks. */ #define LOG2_EXT2_BLOCK_SIZE(data) (__le32_to_cpu (data->sblock.log2_block_size) + 1) /* Log2 size of ext2 block in bytes. */ #define LOG2_BLOCK_SIZE(data) (__le32_to_cpu (data->sblock.log2_block_size) + 10) /* The size of an ext2 block in bytes. */ #define EXT2_BLOCK_SIZE(data) (1 << LOG2_BLOCK_SIZE(data)) /* The ext2 superblock. */ struct ext2_sblock { uint32_t total_inodes; uint32_t total_blocks; uint32_t reserved_blocks; uint32_t free_blocks; uint32_t free_inodes; uint32_t first_data_block; uint32_t log2_block_size; uint32_t log2_fragment_size; uint32_t blocks_per_group; uint32_t fragments_per_group; uint32_t inodes_per_group; uint32_t mtime; uint32_t utime; uint16_t mnt_count; uint16_t max_mnt_count; uint16_t magic; uint16_t fs_state; uint16_t error_handling; uint16_t minor_revision_level; uint32_t lastcheck; uint32_t checkinterval; uint32_t creator_os; uint32_t revision_level; uint16_t uid_reserved; uint16_t gid_reserved; uint32_t first_inode; uint16_t inode_size; uint16_t block_group_number; uint32_t feature_compatibility; uint32_t feature_incompat; uint32_t feature_ro_compat; uint32_t unique_id[4]; char volume_name[16]; char last_mounted_on[64]; uint32_t compression_info; }; /* The ext2 blockgroup. */ struct ext2_block_group { uint32_t block_id; uint32_t inode_id; uint32_t inode_table_id; uint16_t free_blocks; uint16_t free_inodes; uint16_t used_dir_cnt; uint32_t reserved[3]; }; /* The ext2 inode. */ struct ext2_inode { uint16_t mode; uint16_t uid; uint32_t size; uint32_t atime; uint32_t ctime; uint32_t mtime; uint32_t dtime; uint16_t gid; uint16_t nlinks; uint32_t blockcnt; /* Blocks of 512 bytes!! */ uint32_t flags; uint32_t osd1; union { struct datablocks { uint32_t dir_blocks[INDIRECT_BLOCKS]; uint32_t indir_block; uint32_t double_indir_block; uint32_t tripple_indir_block; } blocks; char symlink[60]; } b; uint32_t version; uint32_t acl; uint32_t dir_acl; uint32_t fragment_addr; uint32_t osd2[3]; }; /* The header of an ext2 directory entry. */ struct ext2_dirent { uint32_t inode; uint16_t direntlen; uint8_t namelen; uint8_t filetype; }; struct ext2fs_node { struct ext2_data *data; struct ext2_inode inode; int ino; int inode_read; }; /* Information about a "mounted" ext2 filesystem. */ struct ext2_data { struct ext2_sblock sblock; struct ext2_inode *inode; struct ext2fs_node diropen; }; typedef struct ext2fs_node *ext2fs_node_t; struct ext2_data *ext2fs_root = NULL; ext2fs_node_t ext2fs_file = NULL; int symlinknest = 0; uint32_t *indir1_block = NULL; int indir1_size = 0; int indir1_blkno = -1; uint32_t *indir2_block = NULL; int indir2_size = 0; int indir2_blkno = -1; static unsigned int inode_size; static int ext2fs_blockgroup (struct ext2_data *data, int group, struct ext2_block_group *blkgrp) { unsigned int blkno; unsigned int blkoff; unsigned int desc_per_blk; desc_per_blk = EXT2_BLOCK_SIZE(data) / sizeof(struct ext2_block_group); blkno = __le32_to_cpu(data->sblock.first_data_block) + 1 + group / desc_per_blk; blkoff = (group % desc_per_blk) * sizeof(struct ext2_block_group); #ifdef DEBUG printf ("ext2fs read %d group descriptor (blkno %d blkoff %d)\n", group, blkno, blkoff); #endif return (ext2fs_devread (blkno << LOG2_EXT2_BLOCK_SIZE(data), blkoff, sizeof(struct ext2_block_group), (char *)blkgrp)); } static int ext2fs_read_inode (struct ext2_data *data, int ino, struct ext2_inode *inode) { struct ext2_block_group blkgrp; struct ext2_sblock *sblock = &data->sblock; int inodes_per_block; int status; unsigned int blkno; unsigned int blkoff; #ifdef DEBUG printf ("ext2fs read inode %d, inode_size %d\n", ino, inode_size); #endif /* It is easier to calculate if the first inode is 0. */ ino--; status = ext2fs_blockgroup (data, ino / __le32_to_cpu (sblock->inodes_per_group), &blkgrp); if (status == 0) { return (0); } inodes_per_block = EXT2_BLOCK_SIZE(data) / inode_size; blkno = __le32_to_cpu (blkgrp.inode_table_id) + (ino % __le32_to_cpu (sblock->inodes_per_group)) / inodes_per_block; blkoff = (ino % inodes_per_block) * inode_size; #ifdef DEBUG printf ("ext2fs read inode blkno %d blkoff %d\n", blkno, blkoff); #endif /* Read the inode. */ status = ext2fs_devread (blkno << LOG2_EXT2_BLOCK_SIZE (data), blkoff, sizeof (struct ext2_inode), (char *) inode); if (status == 0) { return (0); } return (1); } void ext2fs_free_node (ext2fs_node_t node, ext2fs_node_t currroot) { if ((node != &ext2fs_root->diropen) && (node != currroot)) { free (node); } } static int ext2fs_read_block (ext2fs_node_t node, int fileblock) { struct ext2_data *data = node->data; struct ext2_inode *inode = &node->inode; int blknr; int blksz = EXT2_BLOCK_SIZE (data); int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); int status; /* Direct blocks. */ if (fileblock < INDIRECT_BLOCKS) { blknr = __le32_to_cpu (inode->b.blocks.dir_blocks[fileblock]); } /* Indirect. */ else if (fileblock < (INDIRECT_BLOCKS + (blksz / 4))) { if (indir1_block == NULL) { indir1_block = (uint32_t *) malloc (blksz); if (indir1_block == NULL) { printf ("** ext2fs read block (indir 1) malloc failed. **\n"); return (-1); } indir1_size = blksz; indir1_blkno = -1; } if (blksz != indir1_size) { free (indir1_block); indir1_block = NULL; indir1_size = 0; indir1_blkno = -1; indir1_block = (uint32_t *) malloc (blksz); if (indir1_block == NULL) { printf ("** ext2fs read block (indir 1) malloc failed. **\n"); return (-1); } indir1_size = blksz; } if ((__le32_to_cpu (inode->b.blocks.indir_block) << log2_blksz) != indir1_blkno) { status = ext2fs_devread (__le32_to_cpu(inode->b.blocks.indir_block) << log2_blksz, 0, blksz, (char *) indir1_block); if (status == 0) { printf ("** ext2fs read block (indir 1) failed. **\n"); return (0); } indir1_blkno = __le32_to_cpu (inode->b.blocks. indir_block) << log2_blksz; } blknr = __le32_to_cpu (indir1_block [fileblock - INDIRECT_BLOCKS]); } /* Double indirect. */ else if (fileblock < (INDIRECT_BLOCKS + (blksz / 4 * (blksz / 4 + 1)))) { unsigned int perblock = blksz / 4; unsigned int rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4); if (indir1_block == NULL) { indir1_block = (uint32_t *) malloc (blksz); if (indir1_block == NULL) { printf ("** ext2fs read block (indir 2 1) malloc failed. **\n"); return (-1); } indir1_size = blksz; indir1_blkno = -1; } if (blksz != indir1_size) { free (indir1_block); indir1_block = NULL; indir1_size = 0; indir1_blkno = -1; indir1_block = (uint32_t *) malloc (blksz); if (indir1_block == NULL) { printf ("** ext2fs read block (indir 2 1) malloc failed. **\n"); return (-1); } indir1_size = blksz; } if ((__le32_to_cpu (inode->b.blocks.double_indir_block) << log2_blksz) != indir1_blkno) { status = ext2fs_devread (__le32_to_cpu(inode->b.blocks.double_indir_block) << log2_blksz, 0, blksz, (char *) indir1_block); if (status == 0) { printf ("** ext2fs read block (indir 2 1) failed. **\n"); return (-1); } indir1_blkno = __le32_to_cpu (inode->b.blocks.double_indir_block) << log2_blksz; } if (indir2_block == NULL) { indir2_block = (uint32_t *) malloc (blksz); if (indir2_block == NULL) { printf ("** ext2fs read block (indir 2 2) malloc failed. **\n"); return (-1); } indir2_size = blksz; indir2_blkno = -1; } if (blksz != indir2_size) { free (indir2_block); indir2_block = NULL; indir2_size = 0; indir2_blkno = -1; indir2_block = (uint32_t *) malloc (blksz); if (indir2_block == NULL) { printf ("** ext2fs read block (indir 2 2) malloc failed. **\n"); return (-1); } indir2_size = blksz; } if ((__le32_to_cpu (indir1_block[rblock / perblock]) << log2_blksz) != indir2_blkno) { status = ext2fs_devread (__le32_to_cpu(indir1_block[rblock / perblock]) << log2_blksz, 0, blksz, (char *) indir2_block); if (status == 0) { printf ("** ext2fs read block (indir 2 2) failed. **\n"); return (-1); } indir2_blkno = __le32_to_cpu (indir1_block[rblock / perblock]) << log2_blksz; } blknr = __le32_to_cpu (indir2_block[rblock % perblock]); } /* Tripple indirect. */ else { printf ("** ext2fs doesn't support tripple indirect blocks. **\n"); return (-1); } #ifdef DEBUG printf ("ext2fs_read_block %08x\n", blknr); #endif return (blknr); } int ext2fs_read_file (ext2fs_node_t node, int pos, unsigned int len, char *buf) { int i; int blockcnt; int log2blocksize = LOG2_EXT2_BLOCK_SIZE (node->data); int blocksize = 1 << (log2blocksize + DISK_SECTOR_BITS); unsigned int filesize = __le32_to_cpu(node->inode.size); /* Adjust len so it we can't read past the end of the file. */ if (len > filesize) { len = filesize; } blockcnt = ((len + pos) + blocksize - 1) / blocksize; for (i = pos / blocksize; i < blockcnt; i++) { int blknr; int blockoff = pos % blocksize; int blockend = blocksize; int skipfirst = 0; blknr = ext2fs_read_block (node, i); if (blknr < 0) { return (-1); } blknr = blknr << log2blocksize; /* Last block. */ if (i == blockcnt - 1) { blockend = (len + pos) % blocksize; /* The last portion is exactly blocksize. */ if (!blockend) { blockend = blocksize; } } /* First block. */ if (i == pos / blocksize) { skipfirst = blockoff; blockend -= skipfirst; } /* If the block number is 0 this block is not stored on disk but is zero filled instead. */ if (blknr) { int status; status = ext2fs_devread (blknr, skipfirst, blockend, buf); if (status == 0) { return (-1); } } else { memset (buf, 0, blocksize - skipfirst); } buf += blocksize - skipfirst; } return (len); } static int ext2fs_iterate_dir (ext2fs_node_t dir, char *name, ext2fs_node_t * fnode, int *ftype) { unsigned int fpos = 0; int status; struct ext2fs_node *diro = (struct ext2fs_node *) dir; #ifdef DEBUG if (name != NULL) printf ("Iterate dir %s\n", name); #endif /* of DEBUG */ if (!diro->inode_read) { status = ext2fs_read_inode (diro->data, diro->ino, &diro->inode); if (status == 0) { return (0); } } /* Search the file. */ while (fpos < __le32_to_cpu (diro->inode.size)) { struct ext2_dirent dirent; status = ext2fs_read_file (diro, fpos, sizeof (struct ext2_dirent), (char *) &dirent); if (status < 1) { return (0); } if (dirent.namelen != 0) { char filename[dirent.namelen + 1]; ext2fs_node_t fdiro; int type = FILETYPE_UNKNOWN; status = ext2fs_read_file (diro, fpos + sizeof (struct ext2_dirent), dirent.namelen, filename); if (status < 1) { return (0); } fdiro = malloc (sizeof (struct ext2fs_node)); if (!fdiro) { return (0); } fdiro->data = diro->data; fdiro->ino = __le32_to_cpu (dirent.inode); filename[dirent.namelen] = '\0'; if (dirent.filetype != FILETYPE_UNKNOWN) { fdiro->inode_read = 0; if (dirent.filetype == FILETYPE_DIRECTORY) { type = FILETYPE_DIRECTORY; } else if (dirent.filetype == FILETYPE_SYMLINK) { type = FILETYPE_SYMLINK; } else if (dirent.filetype == FILETYPE_REG) { type = FILETYPE_REG; } } else { /* The filetype can not be read from the dirent, get it from inode */ status = ext2fs_read_inode (diro->data, __le32_to_cpu(dirent.inode), &fdiro->inode); if (status == 0) { free (fdiro); return (0); } fdiro->inode_read = 1; if ((__le16_to_cpu (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY) { type = FILETYPE_DIRECTORY; } else if ((__le16_to_cpu (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK) { type = FILETYPE_SYMLINK; } else if ((__le16_to_cpu (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_REG) { type = FILETYPE_REG; } } #ifdef DEBUG printf ("iterate >%s<\n", filename); #endif /* of DEBUG */ if ((name != NULL) && (fnode != NULL) && (ftype != NULL)) { if (strcmp (filename, name) == 0) { *ftype = type; *fnode = fdiro; return (1); } } else { if (fdiro->inode_read == 0) { status = ext2fs_read_inode (diro->data, __le32_to_cpu (dirent.inode), &fdiro->inode); if (status == 0) { free (fdiro); return (0); } fdiro->inode_read = 1; } switch (type) { case FILETYPE_DIRECTORY: printf ("<DIR> "); break; case FILETYPE_SYMLINK: printf ("<SYM> "); break; case FILETYPE_REG: printf (" "); break; default: printf ("< ? > "); break; } printf ("%10d %s\n", __le32_to_cpu (fdiro->inode.size), filename); } free (fdiro); } fpos += __le16_to_cpu (dirent.direntlen); } return (0); } static char *ext2fs_read_symlink (ext2fs_node_t node) { char *symlink; struct ext2fs_node *diro = node; int status; if (!diro->inode_read) { status = ext2fs_read_inode (diro->data, diro->ino, &diro->inode); if (status == 0) { return (0); } } symlink = malloc (__le32_to_cpu (diro->inode.size) + 1); if (!symlink) { return (0); } /* If the filesize of the symlink is bigger than 60 the symlink is stored in a separate block, otherwise it is stored in the inode. */ if (__le32_to_cpu (diro->inode.size) <= 60) { strncpy (symlink, diro->inode.b.symlink, __le32_to_cpu (diro->inode.size)); } else { status = ext2fs_read_file (diro, 0, __le32_to_cpu (diro->inode.size), symlink); if (status == 0) { free (symlink); return (0); } } symlink[__le32_to_cpu (diro->inode.size)] = '\0'; return (symlink); } int ext2fs_find_file1 (const char *currpath, ext2fs_node_t currroot, ext2fs_node_t * currfound, int *foundtype) { char fpath[strlen (currpath) + 1]; char *name = fpath; char *next; int status; int type = FILETYPE_DIRECTORY; ext2fs_node_t currnode = currroot; ext2fs_node_t oldnode = currroot; strncpy (fpath, currpath, strlen (currpath) + 1); /* Remove all leading slashes. */ while (*name == '/') { name++; } if (!*name) { *currfound = currnode; return (1); } for (;;) { int found; /* Extract the actual part from the pathname. */ next = strchr (name, '/'); if (next) { /* Remove all leading slashes. */ while (*next == '/') { *(next++) = '\0'; } } /* At this point it is expected that the current node is a directory, check if this is true. */ if (type != FILETYPE_DIRECTORY) { ext2fs_free_node (currnode, currroot); return (0); } oldnode = currnode; /* Iterate over the directory. */ found = ext2fs_iterate_dir (currnode, name, &currnode, &type); if (found == 0) { return (0); } if (found == -1) { break; } /* Read in the symlink and follow it. */ if (type == FILETYPE_SYMLINK) { char *symlink; /* Test if the symlink does not loop. */ if (++symlinknest == 8) { ext2fs_free_node (currnode, currroot); ext2fs_free_node (oldnode, currroot); return (0); } symlink = ext2fs_read_symlink (currnode); ext2fs_free_node (currnode, currroot); if (!symlink) { ext2fs_free_node (oldnode, currroot); return (0); } #ifdef DEBUG printf ("Got symlink >%s<\n", symlink); #endif /* of DEBUG */ /* The symlink is an absolute path, go back to the root inode. */ if (symlink[0] == '/') { ext2fs_free_node (oldnode, currroot); oldnode = &ext2fs_root->diropen; } /* Lookup the node the symlink points to. */ status = ext2fs_find_file1 (symlink, oldnode, &currnode, &type); free (symlink); if (status == 0) { ext2fs_free_node (oldnode, currroot); return (0); } } ext2fs_free_node (oldnode, currroot); /* Found the node! */ if (!next || *next == '\0') { *currfound = currnode; *foundtype = type; return (1); } name = next; } return (-1); } int ext2fs_find_file (const char *path, ext2fs_node_t rootnode, ext2fs_node_t * foundnode, int expecttype) { int status; int foundtype = FILETYPE_DIRECTORY; symlinknest = 0; if (!path) { return (0); } status = ext2fs_find_file1 (path, rootnode, foundnode, &foundtype); if (status == 0) { return (0); } /* Check if the node that was found was of the expected type. */ if ((expecttype == FILETYPE_REG) && (foundtype != expecttype)) { return (0); } else if ((expecttype == FILETYPE_DIRECTORY) && (foundtype != expecttype)) { return (0); } return (1); } int ext2fs_ls (const char *dirname) { ext2fs_node_t dirnode; int status; if (ext2fs_root == NULL) { return (0); } status = ext2fs_find_file (dirname, &ext2fs_root->diropen, &dirnode, FILETYPE_DIRECTORY); if (status != 1) { printf ("** Can not find directory. **\n"); return (1); } ext2fs_iterate_dir (dirnode, NULL, NULL, NULL); ext2fs_free_node (dirnode, &ext2fs_root->diropen); return (0); } int ext2fs_open (const char *filename) { ext2fs_node_t fdiro = NULL; int status; int len; if (ext2fs_root == NULL) { return (-1); } ext2fs_file = NULL; status = ext2fs_find_file (filename, &ext2fs_root->diropen, &fdiro, FILETYPE_REG); if (status == 0) { goto fail; } if (!fdiro->inode_read) { status = ext2fs_read_inode (fdiro->data, fdiro->ino, &fdiro->inode); if (status == 0) { goto fail; } } len = __le32_to_cpu (fdiro->inode.size); ext2fs_file = fdiro; return (len); fail: ext2fs_free_node (fdiro, &ext2fs_root->diropen); return (-1); } int ext2fs_close (void ) { if ((ext2fs_file != NULL) && (ext2fs_root != NULL)) { ext2fs_free_node (ext2fs_file, &ext2fs_root->diropen); ext2fs_file = NULL; } if (ext2fs_root != NULL) { free (ext2fs_root); ext2fs_root = NULL; } if (indir1_block != NULL) { free (indir1_block); indir1_block = NULL; indir1_size = 0; indir1_blkno = -1; } if (indir2_block != NULL) { free (indir2_block); indir2_block = NULL; indir2_size = 0; indir2_blkno = -1; } return (0); } int ext2fs_read (char *buf, unsigned len) { int status; if (ext2fs_root == NULL) { return (0); } if (ext2fs_file == NULL) { return (0); } status = ext2fs_read_file (ext2fs_file, 0, len, buf); return (status); } int ext2fs_mount (unsigned part_length) { struct ext2_data *data; int status; data = malloc (sizeof (struct ext2_data)); if (!data) { return (0); } /* Read the superblock. */ status = ext2fs_devread (1 * 2, 0, sizeof (struct ext2_sblock), (char *) &data->sblock); if (status == 0) { goto fail; } /* Make sure this is an ext2 filesystem. */ if (__le16_to_cpu (data->sblock.magic) != EXT2_MAGIC) { goto fail; } if (__le32_to_cpu(data->sblock.revision_level == 0)) { inode_size = 128; } else { inode_size = __le16_to_cpu(data->sblock.inode_size); } #ifdef DEBUG printf("EXT2 rev %d, inode_size %d\n", __le32_to_cpu(data->sblock.revision_level), inode_size); #endif data->diropen.data = data; data->diropen.ino = 2; data->diropen.inode_read = 1; data->inode = &data->diropen.inode; status = ext2fs_read_inode (data, 2, data->inode); if (status == 0) { goto fail; } ext2fs_root = data; return (1); fail: printf ("Failed to mount ext2 filesystem...\n"); free (data); ext2fs_root = NULL; return (0); }
1001-study-uboot
fs/ext2/ext2fs.c
C
gpl3
21,595
#include <common.h> #include <malloc.h> #include <linux/stat.h> #include <linux/time.h> #include <jffs2/jffs2.h> #include <jffs2/jffs2_1pass.h> #include <nand.h> #include "jffs2_nand_private.h" #define NODE_CHUNK 1024 /* size of memory allocation chunk in b_nodes */ /* Debugging switches */ #undef DEBUG_DIRENTS /* print directory entry list after scan */ #undef DEBUG_FRAGMENTS /* print fragment list after scan */ #undef DEBUG /* enable debugging messages */ #ifdef DEBUG # define DEBUGF(fmt,args...) printf(fmt ,##args) #else # define DEBUGF(fmt,args...) #endif static nand_info_t *nand; /* Compression names */ static char *compr_names[] = { "NONE", "ZERO", "RTIME", "RUBINMIPS", "COPY", "DYNRUBIN", "ZLIB", #if defined(CONFIG_JFFS2_LZO) "LZO", #endif }; /* Spinning wheel */ static char spinner[] = { '|', '/', '-', '\\' }; /* Memory management */ struct mem_block { unsigned index; struct mem_block *next; char nodes[0]; }; static void free_nodes(struct b_list *list) { while (list->listMemBase != NULL) { struct mem_block *next = list->listMemBase->next; free(list->listMemBase); list->listMemBase = next; } } static struct b_node * add_node(struct b_list *list, int size) { u32 index = 0; struct mem_block *memBase; struct b_node *b; memBase = list->listMemBase; if (memBase != NULL) index = memBase->index; if (memBase == NULL || index >= NODE_CHUNK) { /* we need more space before we continue */ memBase = mmalloc(sizeof(struct mem_block) + NODE_CHUNK * size); if (memBase == NULL) { putstr("add_node: malloc failed\n"); return NULL; } memBase->next = list->listMemBase; index = 0; } /* now we have room to add it. */ b = (struct b_node *)&memBase->nodes[size * index]; index ++; memBase->index = index; list->listMemBase = memBase; list->listCount++; return b; } static struct b_node * insert_node(struct b_list *list, struct b_node *new) { #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS struct b_node *b, *prev; if (list->listTail != NULL && list->listCompare(new, list->listTail)) prev = list->listTail; else if (list->listLast != NULL && list->listCompare(new, list->listLast)) prev = list->listLast; else prev = NULL; for (b = (prev ? prev->next : list->listHead); b != NULL && list->listCompare(new, b); prev = b, b = b->next) { list->listLoops++; } if (b != NULL) list->listLast = prev; if (b != NULL) { new->next = b; if (prev != NULL) prev->next = new; else list->listHead = new; } else #endif { new->next = (struct b_node *) NULL; if (list->listTail != NULL) { list->listTail->next = new; list->listTail = new; } else { list->listTail = list->listHead = new; } } return new; } static struct b_node * insert_inode(struct b_list *list, struct jffs2_raw_inode *node, u32 offset) { struct b_inode *new; if (!(new = (struct b_inode *)add_node(list, sizeof(struct b_inode)))) { putstr("add_node failed!\r\n"); return NULL; } new->offset = offset; new->version = node->version; new->ino = node->ino; new->isize = node->isize; new->csize = node->csize; return insert_node(list, (struct b_node *)new); } static struct b_node * insert_dirent(struct b_list *list, struct jffs2_raw_dirent *node, u32 offset) { struct b_dirent *new; if (!(new = (struct b_dirent *)add_node(list, sizeof(struct b_dirent)))) { putstr("add_node failed!\r\n"); return NULL; } new->offset = offset; new->version = node->version; new->pino = node->pino; new->ino = node->ino; new->nhash = full_name_hash(node->name, node->nsize); new->nsize = node->nsize; new->type = node->type; return insert_node(list, (struct b_node *)new); } #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS /* Sort data entries with the latest version last, so that if there * is overlapping data the latest version will be used. */ static int compare_inodes(struct b_node *new, struct b_node *old) { struct jffs2_raw_inode ojNew; struct jffs2_raw_inode ojOld; struct jffs2_raw_inode *jNew = (struct jffs2_raw_inode *)get_fl_mem(new->offset, sizeof(ojNew), &ojNew); struct jffs2_raw_inode *jOld = (struct jffs2_raw_inode *)get_fl_mem(old->offset, sizeof(ojOld), &ojOld); return jNew->version > jOld->version; } /* Sort directory entries so all entries in the same directory * with the same name are grouped together, with the latest version * last. This makes it easy to eliminate all but the latest version * by marking the previous version dead by setting the inode to 0. */ static int compare_dirents(struct b_node *new, struct b_node *old) { struct jffs2_raw_dirent ojNew; struct jffs2_raw_dirent ojOld; struct jffs2_raw_dirent *jNew = (struct jffs2_raw_dirent *)get_fl_mem(new->offset, sizeof(ojNew), &ojNew); struct jffs2_raw_dirent *jOld = (struct jffs2_raw_dirent *)get_fl_mem(old->offset, sizeof(ojOld), &ojOld); int cmp; /* ascending sort by pino */ if (jNew->pino != jOld->pino) return jNew->pino > jOld->pino; /* pino is the same, so use ascending sort by nsize, so * we don't do strncmp unless we really must. */ if (jNew->nsize != jOld->nsize) return jNew->nsize > jOld->nsize; /* length is also the same, so use ascending sort by name */ cmp = strncmp(jNew->name, jOld->name, jNew->nsize); if (cmp != 0) return cmp > 0; /* we have duplicate names in this directory, so use ascending * sort by version */ if (jNew->version > jOld->version) { /* since jNew is newer, we know jOld is not valid, so * mark it with inode 0 and it will not be used */ jOld->ino = 0; return 1; } return 0; } #endif static u32 jffs_init_1pass_list(struct part_info *part) { struct b_lists *pL; if (part->jffs2_priv != NULL) { pL = (struct b_lists *)part->jffs2_priv; free_nodes(&pL->frag); free_nodes(&pL->dir); free(pL); } if (NULL != (part->jffs2_priv = malloc(sizeof(struct b_lists)))) { pL = (struct b_lists *)part->jffs2_priv; memset(pL, 0, sizeof(*pL)); #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS pL->dir.listCompare = compare_dirents; pL->frag.listCompare = compare_inodes; #endif } return 0; } /* find the inode from the slashless name given a parent */ static long jffs2_1pass_read_inode(struct b_lists *pL, u32 ino, char *dest, struct stat *stat) { struct b_inode *jNode; u32 totalSize = 0; u32 latestVersion = 0; long ret; #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS /* Find file size before loading any data, so fragments that * start past the end of file can be ignored. A fragment * that is partially in the file is loaded, so extra data may * be loaded up to the next 4K boundary above the file size. * This shouldn't cause trouble when loading kernel images, so * we will live with it. */ for (jNode = (struct b_inode *)pL->frag.listHead; jNode; jNode = jNode->next) { if ((ino == jNode->ino)) { /* get actual file length from the newest node */ if (jNode->version >= latestVersion) { totalSize = jNode->isize; latestVersion = jNode->version; } } } #endif for (jNode = (struct b_inode *)pL->frag.listHead; jNode; jNode = jNode->next) { if ((ino != jNode->ino)) continue; #ifndef CONFIG_SYS_JFFS2_SORT_FRAGMENTS /* get actual file length from the newest node */ if (jNode->version >= latestVersion) { totalSize = jNode->isize; latestVersion = jNode->version; } #endif if (dest || stat) { char *src, *dst; char data[4096 + sizeof(struct jffs2_raw_inode)]; struct jffs2_raw_inode *inode; size_t len; inode = (struct jffs2_raw_inode *)&data; len = sizeof(struct jffs2_raw_inode); if (dest) len += jNode->csize; nand_read(nand, jNode->offset, &len, inode); /* ignore data behind latest known EOF */ if (inode->offset > totalSize) continue; if (stat) { stat->st_mtime = inode->mtime; stat->st_mode = inode->mode; stat->st_ino = inode->ino; stat->st_size = totalSize; } if (!dest) continue; src = ((char *) inode) + sizeof(struct jffs2_raw_inode); dst = (char *) (dest + inode->offset); switch (inode->compr) { case JFFS2_COMPR_NONE: ret = 0; memcpy(dst, src, inode->dsize); break; case JFFS2_COMPR_ZERO: ret = 0; memset(dst, 0, inode->dsize); break; case JFFS2_COMPR_RTIME: ret = 0; rtime_decompress(src, dst, inode->csize, inode->dsize); break; case JFFS2_COMPR_DYNRUBIN: /* this is slow but it works */ ret = 0; dynrubin_decompress(src, dst, inode->csize, inode->dsize); break; case JFFS2_COMPR_ZLIB: ret = zlib_decompress(src, dst, inode->csize, inode->dsize); break; #if defined(CONFIG_JFFS2_LZO) case JFFS2_COMPR_LZO: ret = lzo_decompress(src, dst, inode->csize, inode->dsize); break; #endif default: /* unknown */ putLabeledWord("UNKNOWN COMPRESSION METHOD = ", inode->compr); return -1; } } } return totalSize; } /* find the inode from the slashless name given a parent */ static u32 jffs2_1pass_find_inode(struct b_lists * pL, const char *name, u32 pino) { struct b_dirent *jDir; int len = strlen(name); /* name is assumed slash free */ unsigned int nhash = full_name_hash(name, len); u32 version = 0; u32 inode = 0; /* we need to search all and return the inode with the highest version */ for (jDir = (struct b_dirent *)pL->dir.listHead; jDir; jDir = jDir->next) { if ((pino == jDir->pino) && (jDir->ino) && /* 0 for unlink */ (len == jDir->nsize) && (nhash == jDir->nhash)) { /* TODO: compare name */ if (jDir->version < version) continue; if (jDir->version == version && inode != 0) { /* I'm pretty sure this isn't legal */ putstr(" ** ERROR ** "); /* putnstr(jDir->name, jDir->nsize); */ /* putLabeledWord(" has dup version =", version); */ } inode = jDir->ino; version = jDir->version; } } return inode; } char *mkmodestr(unsigned long mode, char *str) { static const char *l = "xwr"; int mask = 1, i; char c; switch (mode & S_IFMT) { case S_IFDIR: str[0] = 'd'; break; case S_IFBLK: str[0] = 'b'; break; case S_IFCHR: str[0] = 'c'; break; case S_IFIFO: str[0] = 'f'; break; case S_IFLNK: str[0] = 'l'; break; case S_IFSOCK: str[0] = 's'; break; case S_IFREG: str[0] = '-'; break; default: str[0] = '?'; } for(i = 0; i < 9; i++) { c = l[i%3]; str[9-i] = (mode & mask)?c:'-'; mask = mask<<1; } if(mode & S_ISUID) str[3] = (mode & S_IXUSR)?'s':'S'; if(mode & S_ISGID) str[6] = (mode & S_IXGRP)?'s':'S'; if(mode & S_ISVTX) str[9] = (mode & S_IXOTH)?'t':'T'; str[10] = '\0'; return str; } static inline void dump_stat(struct stat *st, const char *name) { char str[20]; char s[64], *p; if (st->st_mtime == (time_t)(-1)) /* some ctimes really hate -1 */ st->st_mtime = 1; ctime_r(&st->st_mtime, s/*,64*/); /* newlib ctime doesn't have buflen */ if ((p = strchr(s,'\n')) != NULL) *p = '\0'; if ((p = strchr(s,'\r')) != NULL) *p = '\0'; /* printf("%6lo %s %8ld %s %s\n", st->st_mode, mkmodestr(st->st_mode, str), st->st_size, s, name); */ printf(" %s %8ld %s %s", mkmodestr(st->st_mode,str), st->st_size, s, name); } static inline int dump_inode(struct b_lists *pL, struct b_dirent *d, struct b_inode *i) { char fname[JFFS2_MAX_NAME_LEN + 1]; struct stat st; size_t len; if(!d || !i) return -1; len = d->nsize; nand_read(nand, d->offset + sizeof(struct jffs2_raw_dirent), &len, &fname); fname[d->nsize] = '\0'; memset(&st, 0, sizeof(st)); jffs2_1pass_read_inode(pL, i->ino, NULL, &st); dump_stat(&st, fname); /* FIXME if (d->type == DT_LNK) { unsigned char *src = (unsigned char *) (&i[1]); putstr(" -> "); putnstr(src, (int)i->dsize); } */ putstr("\r\n"); return 0; } /* list inodes with the given pino */ static u32 jffs2_1pass_list_inodes(struct b_lists * pL, u32 pino) { struct b_dirent *jDir; u32 i_version = 0; for (jDir = (struct b_dirent *)pL->dir.listHead; jDir; jDir = jDir->next) { if ((pino == jDir->pino) && (jDir->ino)) { /* ino=0 -> unlink */ struct b_inode *jNode = (struct b_inode *)pL->frag.listHead; struct b_inode *i = NULL; while (jNode) { if (jNode->ino == jDir->ino && jNode->version >= i_version) { i_version = jNode->version; i = jNode; } jNode = jNode->next; } dump_inode(pL, jDir, i); } } return pino; } static u32 jffs2_1pass_search_inode(struct b_lists * pL, const char *fname, u32 pino) { int i; char tmp[256]; char working_tmp[256]; char *c; /* discard any leading slash */ i = 0; while (fname[i] == '/') i++; strcpy(tmp, &fname[i]); while ((c = (char *) strchr(tmp, '/'))) /* we are still dired searching */ { strncpy(working_tmp, tmp, c - tmp); working_tmp[c - tmp] = '\0'; #if 0 putstr("search_inode: tmp = "); putstr(tmp); putstr("\r\n"); putstr("search_inode: wtmp = "); putstr(working_tmp); putstr("\r\n"); putstr("search_inode: c = "); putstr(c); putstr("\r\n"); #endif for (i = 0; i < strlen(c) - 1; i++) tmp[i] = c[i + 1]; tmp[i] = '\0'; #if 0 putstr("search_inode: post tmp = "); putstr(tmp); putstr("\r\n"); #endif if (!(pino = jffs2_1pass_find_inode(pL, working_tmp, pino))) { putstr("find_inode failed for name="); putstr(working_tmp); putstr("\r\n"); return 0; } } /* this is for the bare filename, directories have already been mapped */ if (!(pino = jffs2_1pass_find_inode(pL, tmp, pino))) { putstr("find_inode failed for name="); putstr(tmp); putstr("\r\n"); return 0; } return pino; } static u32 jffs2_1pass_resolve_inode(struct b_lists * pL, u32 ino) { struct b_dirent *jDir; struct b_inode *jNode; u8 jDirFoundType = 0; u32 jDirFoundIno = 0; u32 jDirFoundPino = 0; char tmp[JFFS2_MAX_NAME_LEN + 1]; u32 version = 0; u32 pino; /* we need to search all and return the inode with the highest version */ for (jDir = (struct b_dirent *)pL->dir.listHead; jDir; jDir = jDir->next) { if (ino == jDir->ino) { if (jDir->version < version) continue; if (jDir->version == version && jDirFoundType) { /* I'm pretty sure this isn't legal */ putstr(" ** ERROR ** "); /* putnstr(jDir->name, jDir->nsize); */ /* putLabeledWord(" has dup version (resolve) = ", */ /* version); */ } jDirFoundType = jDir->type; jDirFoundIno = jDir->ino; jDirFoundPino = jDir->pino; version = jDir->version; } } /* now we found the right entry again. (shoulda returned inode*) */ if (jDirFoundType != DT_LNK) return jDirFoundIno; /* it's a soft link so we follow it again. */ for (jNode = (struct b_inode *)pL->frag.listHead; jNode; jNode = jNode->next) { if (jNode->ino == jDirFoundIno) { size_t len = jNode->csize; nand_read(nand, jNode->offset + sizeof(struct jffs2_raw_inode), &len, &tmp); tmp[jNode->csize] = '\0'; break; } } /* ok so the name of the new file to find is in tmp */ /* if it starts with a slash it is root based else shared dirs */ if (tmp[0] == '/') pino = 1; else pino = jDirFoundPino; return jffs2_1pass_search_inode(pL, tmp, pino); } static u32 jffs2_1pass_search_list_inodes(struct b_lists * pL, const char *fname, u32 pino) { int i; char tmp[256]; char working_tmp[256]; char *c; /* discard any leading slash */ i = 0; while (fname[i] == '/') i++; strcpy(tmp, &fname[i]); working_tmp[0] = '\0'; while ((c = (char *) strchr(tmp, '/'))) /* we are still dired searching */ { strncpy(working_tmp, tmp, c - tmp); working_tmp[c - tmp] = '\0'; for (i = 0; i < strlen(c) - 1; i++) tmp[i] = c[i + 1]; tmp[i] = '\0'; /* only a failure if we arent looking at top level */ if (!(pino = jffs2_1pass_find_inode(pL, working_tmp, pino)) && (working_tmp[0])) { putstr("find_inode failed for name="); putstr(working_tmp); putstr("\r\n"); return 0; } } if (tmp[0] && !(pino = jffs2_1pass_find_inode(pL, tmp, pino))) { putstr("find_inode failed for name="); putstr(tmp); putstr("\r\n"); return 0; } /* this is for the bare filename, directories have already been mapped */ if (!(pino = jffs2_1pass_list_inodes(pL, pino))) { putstr("find_inode failed for name="); putstr(tmp); putstr("\r\n"); return 0; } return pino; } unsigned char jffs2_1pass_rescan_needed(struct part_info *part) { struct b_node *b; struct jffs2_unknown_node onode; struct jffs2_unknown_node *node; struct b_lists *pL = (struct b_lists *)part->jffs2_priv; if (part->jffs2_priv == 0){ DEBUGF ("rescan: First time in use\n"); return 1; } /* if we have no list, we need to rescan */ if (pL->frag.listCount == 0) { DEBUGF ("rescan: fraglist zero\n"); return 1; } /* or if we are scanning a new partition */ if (pL->partOffset != part->offset) { DEBUGF ("rescan: different partition\n"); return 1; } /* FIXME */ #if 0 /* but suppose someone reflashed a partition at the same offset... */ b = pL->dir.listHead; while (b) { node = (struct jffs2_unknown_node *) get_fl_mem(b->offset, sizeof(onode), &onode); if (node->nodetype != JFFS2_NODETYPE_DIRENT) { DEBUGF ("rescan: fs changed beneath me? (%lx)\n", (unsigned long) b->offset); return 1; } b = b->next; } #endif return 0; } #ifdef DEBUG_FRAGMENTS static void dump_fragments(struct b_lists *pL) { struct b_node *b; struct jffs2_raw_inode ojNode; struct jffs2_raw_inode *jNode; putstr("\r\n\r\n******The fragment Entries******\r\n"); b = pL->frag.listHead; while (b) { jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset, sizeof(ojNode), &ojNode); putLabeledWord("\r\n\tbuild_list: FLASH_OFFSET = ", b->offset); putLabeledWord("\tbuild_list: totlen = ", jNode->totlen); putLabeledWord("\tbuild_list: inode = ", jNode->ino); putLabeledWord("\tbuild_list: version = ", jNode->version); putLabeledWord("\tbuild_list: isize = ", jNode->isize); putLabeledWord("\tbuild_list: atime = ", jNode->atime); putLabeledWord("\tbuild_list: offset = ", jNode->offset); putLabeledWord("\tbuild_list: csize = ", jNode->csize); putLabeledWord("\tbuild_list: dsize = ", jNode->dsize); putLabeledWord("\tbuild_list: compr = ", jNode->compr); putLabeledWord("\tbuild_list: usercompr = ", jNode->usercompr); putLabeledWord("\tbuild_list: flags = ", jNode->flags); putLabeledWord("\tbuild_list: offset = ", b->offset); /* FIXME: ? [RS] */ b = b->next; } } #endif #ifdef DEBUG_DIRENTS static void dump_dirents(struct b_lists *pL) { struct b_node *b; struct jffs2_raw_dirent *jDir; putstr("\r\n\r\n******The directory Entries******\r\n"); b = pL->dir.listHead; while (b) { jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset); putstr("\r\n"); putnstr(jDir->name, jDir->nsize); putLabeledWord("\r\n\tbuild_list: magic = ", jDir->magic); putLabeledWord("\tbuild_list: nodetype = ", jDir->nodetype); putLabeledWord("\tbuild_list: hdr_crc = ", jDir->hdr_crc); putLabeledWord("\tbuild_list: pino = ", jDir->pino); putLabeledWord("\tbuild_list: version = ", jDir->version); putLabeledWord("\tbuild_list: ino = ", jDir->ino); putLabeledWord("\tbuild_list: mctime = ", jDir->mctime); putLabeledWord("\tbuild_list: nsize = ", jDir->nsize); putLabeledWord("\tbuild_list: type = ", jDir->type); putLabeledWord("\tbuild_list: node_crc = ", jDir->node_crc); putLabeledWord("\tbuild_list: name_crc = ", jDir->name_crc); putLabeledWord("\tbuild_list: offset = ", b->offset); /* FIXME: ? [RS] */ b = b->next; put_fl_mem(jDir); } } #endif static int jffs2_fill_scan_buf(nand_info_t *nand, unsigned char *buf, unsigned ofs, unsigned len) { int ret; unsigned olen; olen = len; ret = nand_read(nand, ofs, &olen, buf); if (ret) { printf("nand_read(0x%x bytes from 0x%x) returned %d\n", len, ofs, ret); return ret; } if (olen < len) { printf("Read at 0x%x gave only 0x%x bytes\n", ofs, olen); return -1; } return 0; } #define EMPTY_SCAN_SIZE 1024 static u32 jffs2_1pass_build_lists(struct part_info * part) { struct b_lists *pL; struct jffs2_unknown_node *node; unsigned nr_blocks, sectorsize, ofs, offset; char *buf; int i; u32 counter = 0; u32 counter4 = 0; u32 counterF = 0; u32 counterN = 0; struct mtdids *id = part->dev->id; nand = nand_info + id->num; /* if we are building a list we need to refresh the cache. */ jffs_init_1pass_list(part); pL = (struct b_lists *)part->jffs2_priv; pL->partOffset = part->offset; puts ("Scanning JFFS2 FS: "); sectorsize = nand->erasesize; nr_blocks = part->size / sectorsize; buf = malloc(sectorsize); if (!buf) return 0; for (i = 0; i < nr_blocks; i++) { printf("\b\b%c ", spinner[counter++ % sizeof(spinner)]); offset = part->offset + i * sectorsize; if (nand_block_isbad(nand, offset)) continue; if (jffs2_fill_scan_buf(nand, buf, offset, EMPTY_SCAN_SIZE)) return 0; ofs = 0; /* Scan only 4KiB of 0xFF before declaring it's empty */ while (ofs < EMPTY_SCAN_SIZE && *(uint32_t *)(&buf[ofs]) == 0xFFFFFFFF) ofs += 4; if (ofs == EMPTY_SCAN_SIZE) continue; if (jffs2_fill_scan_buf(nand, buf + EMPTY_SCAN_SIZE, offset + EMPTY_SCAN_SIZE, sectorsize - EMPTY_SCAN_SIZE)) return 0; offset += ofs; while (ofs < sectorsize - sizeof(struct jffs2_unknown_node)) { node = (struct jffs2_unknown_node *)&buf[ofs]; if (node->magic != JFFS2_MAGIC_BITMASK || !hdr_crc(node)) { offset += 4; ofs += 4; counter4++; continue; } /* if its a fragment add it */ if (node->nodetype == JFFS2_NODETYPE_INODE && inode_crc((struct jffs2_raw_inode *) node)) { if (insert_inode(&pL->frag, (struct jffs2_raw_inode *) node, offset) == NULL) { return 0; } } else if (node->nodetype == JFFS2_NODETYPE_DIRENT && dirent_crc((struct jffs2_raw_dirent *) node) && dirent_name_crc((struct jffs2_raw_dirent *) node)) { if (! (counterN%100)) puts ("\b\b. "); if (insert_dirent(&pL->dir, (struct jffs2_raw_dirent *) node, offset) == NULL) { return 0; } counterN++; } else if (node->nodetype == JFFS2_NODETYPE_CLEANMARKER) { if (node->totlen != sizeof(struct jffs2_unknown_node)) printf("OOPS Cleanmarker has bad size " "%d != %zu\n", node->totlen, sizeof(struct jffs2_unknown_node)); } else if (node->nodetype == JFFS2_NODETYPE_PADDING) { if (node->totlen < sizeof(struct jffs2_unknown_node)) printf("OOPS Padding has bad size " "%d < %zu\n", node->totlen, sizeof(struct jffs2_unknown_node)); } else { printf("Unknown node type: %x len %d offset 0x%x\n", node->nodetype, node->totlen, offset); } offset += ((node->totlen + 3) & ~3); ofs += ((node->totlen + 3) & ~3); counterF++; } } putstr("\b\b done.\r\n"); /* close off the dots */ #if 0 putLabeledWord("dir entries = ", pL->dir.listCount); putLabeledWord("frag entries = ", pL->frag.listCount); putLabeledWord("+4 increments = ", counter4); putLabeledWord("+file_offset increments = ", counterF); #endif #ifdef DEBUG_DIRENTS dump_dirents(pL); #endif #ifdef DEBUG_FRAGMENTS dump_fragments(pL); #endif /* give visual feedback that we are done scanning the flash */ led_blink(0x0, 0x0, 0x1, 0x1); /* off, forever, on 100ms, off 100ms */ free(buf); return 1; } static u32 jffs2_1pass_fill_info(struct b_lists * pL, struct b_jffs2_info * piL) { struct b_node *b; struct jffs2_raw_inode ojNode; struct jffs2_raw_inode *jNode; int i; for (i = 0; i < JFFS2_NUM_COMPR; i++) { piL->compr_info[i].num_frags = 0; piL->compr_info[i].compr_sum = 0; piL->compr_info[i].decompr_sum = 0; } /* FIXME b = pL->frag.listHead; while (b) { jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset, sizeof(ojNode), &ojNode); if (jNode->compr < JFFS2_NUM_COMPR) { piL->compr_info[jNode->compr].num_frags++; piL->compr_info[jNode->compr].compr_sum += jNode->csize; piL->compr_info[jNode->compr].decompr_sum += jNode->dsize; } b = b->next; } */ return 0; } static struct b_lists * jffs2_get_list(struct part_info * part, const char *who) { if (jffs2_1pass_rescan_needed(part)) { if (!jffs2_1pass_build_lists(part)) { printf("%s: Failed to scan JFFSv2 file structure\n", who); return NULL; } } return (struct b_lists *)part->jffs2_priv; } /* Print directory / file contents */ u32 jffs2_1pass_ls(struct part_info * part, const char *fname) { struct b_lists *pl; long ret = 0; u32 inode; if (! (pl = jffs2_get_list(part, "ls"))) return 0; if (! (inode = jffs2_1pass_search_list_inodes(pl, fname, 1))) { putstr("ls: Failed to scan jffs2 file structure\r\n"); return 0; } #if 0 putLabeledWord("found file at inode = ", inode); putLabeledWord("read_inode returns = ", ret); #endif return ret; } /* Load a file from flash into memory. fname can be a full path */ u32 jffs2_1pass_load(char *dest, struct part_info * part, const char *fname) { struct b_lists *pl; long ret = 0; u32 inode; if (! (pl = jffs2_get_list(part, "load"))) return 0; if (! (inode = jffs2_1pass_search_inode(pl, fname, 1))) { putstr("load: Failed to find inode\r\n"); return 0; } /* Resolve symlinks */ if (! (inode = jffs2_1pass_resolve_inode(pl, inode))) { putstr("load: Failed to resolve inode structure\r\n"); return 0; } if ((ret = jffs2_1pass_read_inode(pl, inode, dest, NULL)) < 0) { putstr("load: Failed to read inode\r\n"); return 0; } DEBUGF ("load: loaded '%s' to 0x%lx (%ld bytes)\n", fname, (unsigned long) dest, ret); return ret; } /* Return information about the fs on this partition */ u32 jffs2_1pass_info(struct part_info * part) { struct b_jffs2_info info; struct b_lists *pl; int i; if (! (pl = jffs2_get_list(part, "info"))) return 0; jffs2_1pass_fill_info(pl, &info); for (i = 0; i < JFFS2_NUM_COMPR; i++) { printf ("Compression: %s\n" "\tfrag count: %d\n" "\tcompressed sum: %d\n" "\tuncompressed sum: %d\n", compr_names[i], info.compr_info[i].num_frags, info.compr_info[i].compr_sum, info.compr_info[i].decompr_sum); } return 1; }
1001-study-uboot
fs/jffs2/jffs2_nand_1pass.c
C
gpl3
26,002
/*------------------------------------------------------------------------- * Filename: mini_inflate.c * Version: $Id: mini_inflate.c,v 1.3 2002/01/24 22:58:42 rfeany Exp $ * Copyright: Copyright (C) 2001, Russ Dill * Author: Russ Dill <Russ.Dill@asu.edu> * Description: Mini inflate implementation (RFC 1951) *-----------------------------------------------------------------------*/ /* * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <config.h> #include <jffs2/mini_inflate.h> /* The order that the code lengths in section 3.2.7 are in */ static unsigned char huffman_order[] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; inline void cramfs_memset(int *s, const int c, size n) { n--; for (;n > 0; n--) s[n] = c; s[0] = c; } /* associate a stream with a block of data and reset the stream */ static void init_stream(struct bitstream *stream, unsigned char *data, void *(*inflate_memcpy)(void *, const void *, size)) { stream->error = NO_ERROR; stream->memcpy = inflate_memcpy; stream->decoded = 0; stream->data = data; stream->bit = 0; /* The first bit of the stream is the lsb of the * first byte */ /* really sorry about all this initialization, think of a better way, * let me know and it will get cleaned up */ stream->codes.bits = 8; stream->codes.num_symbols = 19; stream->codes.lengths = stream->code_lengths; stream->codes.symbols = stream->code_symbols; stream->codes.count = stream->code_count; stream->codes.first = stream->code_first; stream->codes.pos = stream->code_pos; stream->lengths.bits = 16; stream->lengths.num_symbols = 288; stream->lengths.lengths = stream->length_lengths; stream->lengths.symbols = stream->length_symbols; stream->lengths.count = stream->length_count; stream->lengths.first = stream->length_first; stream->lengths.pos = stream->length_pos; stream->distance.bits = 16; stream->distance.num_symbols = 32; stream->distance.lengths = stream->distance_lengths; stream->distance.symbols = stream->distance_symbols; stream->distance.count = stream->distance_count; stream->distance.first = stream->distance_first; stream->distance.pos = stream->distance_pos; } /* pull 'bits' bits out of the stream. The last bit pulled it returned as the * msb. (section 3.1.1) */ inline unsigned long pull_bits(struct bitstream *stream, const unsigned int bits) { unsigned long ret; int i; ret = 0; for (i = 0; i < bits; i++) { ret += ((*(stream->data) >> stream->bit) & 1) << i; /* if, before incrementing, we are on bit 7, * go to the lsb of the next byte */ if (stream->bit++ == 7) { stream->bit = 0; stream->data++; } } return ret; } inline int pull_bit(struct bitstream *stream) { int ret = ((*(stream->data) >> stream->bit) & 1); if (stream->bit++ == 7) { stream->bit = 0; stream->data++; } return ret; } /* discard bits up to the next whole byte */ static void discard_bits(struct bitstream *stream) { if (stream->bit != 0) { stream->bit = 0; stream->data++; } } /* No decompression, the data is all literals (section 3.2.4) */ static void decompress_none(struct bitstream *stream, unsigned char *dest) { unsigned int length; discard_bits(stream); length = *(stream->data++); length += *(stream->data++) << 8; pull_bits(stream, 16); /* throw away the inverse of the size */ stream->decoded += length; stream->memcpy(dest, stream->data, length); stream->data += length; } /* Read in a symbol from the stream (section 3.2.2) */ static int read_symbol(struct bitstream *stream, struct huffman_set *set) { int bits = 0; int code = 0; while (!(set->count[bits] && code < set->first[bits] + set->count[bits])) { code = (code << 1) + pull_bit(stream); if (++bits > set->bits) { /* error decoding (corrupted data?) */ stream->error = CODE_NOT_FOUND; return -1; } } return set->symbols[set->pos[bits] + code - set->first[bits]]; } /* decompress a stream of data encoded with the passed length and distance * huffman codes */ static void decompress_huffman(struct bitstream *stream, unsigned char *dest) { struct huffman_set *lengths = &(stream->lengths); struct huffman_set *distance = &(stream->distance); int symbol, length, dist, i; do { if ((symbol = read_symbol(stream, lengths)) < 0) return; if (symbol < 256) { *(dest++) = symbol; /* symbol is a literal */ stream->decoded++; } else if (symbol > 256) { /* Determine the length of the repitition * (section 3.2.5) */ if (symbol < 265) length = symbol - 254; else if (symbol == 285) length = 258; else { length = pull_bits(stream, (symbol - 261) >> 2); length += (4 << ((symbol - 261) >> 2)) + 3; length += ((symbol - 1) % 4) << ((symbol - 261) >> 2); } /* Determine how far back to go */ if ((symbol = read_symbol(stream, distance)) < 0) return; if (symbol < 4) dist = symbol + 1; else { dist = pull_bits(stream, (symbol - 2) >> 1); dist += (2 << ((symbol - 2) >> 1)) + 1; dist += (symbol % 2) << ((symbol - 2) >> 1); } stream->decoded += length; for (i = 0; i < length; i++) { *dest = dest[-dist]; dest++; } } } while (symbol != 256); /* 256 is the end of the data block */ } /* Fill the lookup tables (section 3.2.2) */ static void fill_code_tables(struct huffman_set *set) { int code = 0, i, length; /* fill in the first code of each bit length, and the pos pointer */ set->pos[0] = 0; for (i = 1; i < set->bits; i++) { code = (code + set->count[i - 1]) << 1; set->first[i] = code; set->pos[i] = set->pos[i - 1] + set->count[i - 1]; } /* Fill in the table of symbols in order of their huffman code */ for (i = 0; i < set->num_symbols; i++) { if ((length = set->lengths[i])) set->symbols[set->pos[length]++] = i; } /* reset the pos pointer */ for (i = 1; i < set->bits; i++) set->pos[i] -= set->count[i]; } static void init_code_tables(struct huffman_set *set) { cramfs_memset(set->lengths, 0, set->num_symbols); cramfs_memset(set->count, 0, set->bits); cramfs_memset(set->first, 0, set->bits); } /* read in the huffman codes for dynamic decoding (section 3.2.7) */ static void decompress_dynamic(struct bitstream *stream, unsigned char *dest) { /* I tried my best to minimize the memory footprint here, while still * keeping up performance. I really dislike the _lengths[] tables, but * I see no way of eliminating them without a sizable performance * impact. The first struct table keeps track of stats on each bit * length. The _length table keeps a record of the bit length of each * symbol. The _symbols table is for looking up symbols by the huffman * code (the pos element points to the first place in the symbol table * where that bit length occurs). I also hate the initization of these * structs, if someone knows how to compact these, lemme know. */ struct huffman_set *codes = &(stream->codes); struct huffman_set *lengths = &(stream->lengths); struct huffman_set *distance = &(stream->distance); int hlit = pull_bits(stream, 5) + 257; int hdist = pull_bits(stream, 5) + 1; int hclen = pull_bits(stream, 4) + 4; int length, curr_code, symbol, i, last_code; last_code = 0; init_code_tables(codes); init_code_tables(lengths); init_code_tables(distance); /* fill in the count of each bit length' as well as the lengths * table */ for (i = 0; i < hclen; i++) { length = pull_bits(stream, 3); codes->lengths[huffman_order[i]] = length; if (length) codes->count[length]++; } fill_code_tables(codes); /* Do the same for the length codes, being carefull of wrap through * to the distance table */ curr_code = 0; while (curr_code < hlit) { if ((symbol = read_symbol(stream, codes)) < 0) return; if (symbol == 0) { curr_code++; last_code = 0; } else if (symbol < 16) { /* Literal length */ lengths->lengths[curr_code] = last_code = symbol; lengths->count[symbol]++; curr_code++; } else if (symbol == 16) { /* repeat the last symbol 3 - 6 * times */ length = 3 + pull_bits(stream, 2); for (;length; length--, curr_code++) if (curr_code < hlit) { lengths->lengths[curr_code] = last_code; lengths->count[last_code]++; } else { /* wrap to the distance table */ distance->lengths[curr_code - hlit] = last_code; distance->count[last_code]++; } } else if (symbol == 17) { /* repeat a bit length 0 */ curr_code += 3 + pull_bits(stream, 3); last_code = 0; } else { /* same, but more times */ curr_code += 11 + pull_bits(stream, 7); last_code = 0; } } fill_code_tables(lengths); /* Fill the distance table, don't need to worry about wrapthrough * here */ curr_code -= hlit; while (curr_code < hdist) { if ((symbol = read_symbol(stream, codes)) < 0) return; if (symbol == 0) { curr_code++; last_code = 0; } else if (symbol < 16) { distance->lengths[curr_code] = last_code = symbol; distance->count[symbol]++; curr_code++; } else if (symbol == 16) { length = 3 + pull_bits(stream, 2); for (;length; length--, curr_code++) { distance->lengths[curr_code] = last_code; distance->count[last_code]++; } } else if (symbol == 17) { curr_code += 3 + pull_bits(stream, 3); last_code = 0; } else { curr_code += 11 + pull_bits(stream, 7); last_code = 0; } } fill_code_tables(distance); decompress_huffman(stream, dest); } /* fill in the length and distance huffman codes for fixed encoding * (section 3.2.6) */ static void decompress_fixed(struct bitstream *stream, unsigned char *dest) { /* let gcc fill in the initial values */ struct huffman_set *lengths = &(stream->lengths); struct huffman_set *distance = &(stream->distance); cramfs_memset(lengths->count, 0, 16); cramfs_memset(lengths->first, 0, 16); cramfs_memset(lengths->lengths, 8, 144); cramfs_memset(lengths->lengths + 144, 9, 112); cramfs_memset(lengths->lengths + 256, 7, 24); cramfs_memset(lengths->lengths + 280, 8, 8); lengths->count[7] = 24; lengths->count[8] = 152; lengths->count[9] = 112; cramfs_memset(distance->count, 0, 16); cramfs_memset(distance->first, 0, 16); cramfs_memset(distance->lengths, 5, 32); distance->count[5] = 32; fill_code_tables(lengths); fill_code_tables(distance); decompress_huffman(stream, dest); } /* returns the number of bytes decoded, < 0 if there was an error. Note that * this function assumes that the block starts on a byte boundry * (non-compliant, but I don't see where this would happen). section 3.2.3 */ long decompress_block(unsigned char *dest, unsigned char *source, void *(*inflate_memcpy)(void *, const void *, size)) { int bfinal, btype; struct bitstream stream; init_stream(&stream, source, inflate_memcpy); do { bfinal = pull_bit(&stream); btype = pull_bits(&stream, 2); if (btype == NO_COMP) decompress_none(&stream, dest + stream.decoded); else if (btype == DYNAMIC_COMP) decompress_dynamic(&stream, dest + stream.decoded); else if (btype == FIXED_COMP) decompress_fixed(&stream, dest + stream.decoded); else stream.error = COMP_UNKNOWN; } while (!bfinal && !stream.error); #if 0 putstr("decompress_block start\r\n"); putLabeledWord("stream.error = ",stream.error); putLabeledWord("stream.decoded = ",stream.decoded); putLabeledWord("dest = ",dest); putstr("decompress_block end\r\n"); #endif return stream.error ? -stream.error : stream.decoded; }
1001-study-uboot
fs/jffs2/mini_inflate.c
C
gpl3
12,155
/* ------------------------------------------------------------------------- * Filename: jffs2.c * Version: $Id: jffs2_1pass.c,v 1.7 2002/01/25 01:56:47 nyet Exp $ * Copyright: Copyright (C) 2001, Russ Dill * Author: Russ Dill <Russ.Dill@asu.edu> * Description: Module to load kernel from jffs2 *-----------------------------------------------------------------------*/ /* * some portions of this code are taken from jffs2, and as such, the * following copyright notice is included. * * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2001 Red Hat, Inc. * * Created by David Woodhouse <dwmw2@cambridge.redhat.com> * * The original JFFS, from which the design for JFFS2 was derived, * was designed and implemented by Axis Communications AB. * * The contents of this file are subject to the Red Hat eCos Public * License Version 1.1 (the "Licence"); you may not use this file * except in compliance with the Licence. You may obtain a copy of * the Licence at http://www.redhat.com/ * * Software distributed under the Licence is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the Licence for the specific language governing rights and * limitations under the Licence. * * The Original Code is JFFS2 - Journalling Flash File System, version 2 * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License version 2 (the "GPL"), in * which case the provisions of the GPL are applicable instead of the * above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the RHEPL, indicate your decision by * deleting the provisions above and replace them with the notice and * other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file * under either the RHEPL or the GPL. * * $Id: jffs2_1pass.c,v 1.7 2002/01/25 01:56:47 nyet Exp $ * */ /* Ok, so anyone who knows the jffs2 code will probably want to get a papar * bag to throw up into before reading this code. I looked through the jffs2 * code, the caching scheme is very elegant. I tried to keep the version * for a bootloader as small and simple as possible. Instead of worring about * unneccesary data copies, node scans, etc, I just optimized for the known * common case, a kernel, which looks like: * (1) most pages are 4096 bytes * (2) version numbers are somewhat sorted in acsending order * (3) multiple compressed blocks making up one page is uncommon * * So I create a linked list of decending version numbers (insertions at the * head), and then for each page, walk down the list, until a matching page * with 4096 bytes is found, and then decompress the watching pages in * reverse order. * */ /* * Adapted by Nye Liu <nyet@zumanetworks.com> and * Rex Feany <rfeany@zumanetworks.com> * on Jan/2002 for U-Boot. * * Clipped out all the non-1pass functions, cleaned up warnings, * wrappers, etc. No major changes to the code. * Please, he really means it when he said have a paper bag * handy. We needed it ;). * */ /* * Bugfixing by Kai-Uwe Bloem <kai-uwe.bloem@auerswald.de>, (C) Mar/2003 * * - overhaul of the memory management. Removed much of the "paper-bagging" * in that part of the code, fixed several bugs, now frees memory when * partition is changed. * It's still ugly :-( * - fixed a bug in jffs2_1pass_read_inode where the file length calculation * was incorrect. Removed a bit of the paper-bagging as well. * - removed double crc calculation for fragment headers in jffs2_private.h * for speedup. * - scan_empty rewritten in a more "standard" manner (non-paperbag, that is). * - spinning wheel now spins depending on how much memory has been scanned * - lots of small changes all over the place to "improve" readability. * - implemented fragment sorting to ensure that the newest data is copied * if there are multiple copies of fragments for a certain file offset. * * The fragment sorting feature must be enabled by CONFIG_SYS_JFFS2_SORT_FRAGMENTS. * Sorting is done while adding fragments to the lists, which is more or less a * bubble sort. This takes a lot of time, and is most probably not an issue if * the boot filesystem is always mounted readonly. * * You should define it if the boot filesystem is mounted writable, and updates * to the boot files are done by copying files to that filesystem. * * * There's a big issue left: endianess is completely ignored in this code. Duh! * * * You still should have paper bags at hand :-(. The code lacks more or less * any comment, and is still arcane and difficult to read in places. As this * might be incompatible with any new code from the jffs2 maintainers anyway, * it should probably be dumped and replaced by something like jffs2reader! */ #include <common.h> #include <config.h> #include <malloc.h> #include <linux/stat.h> #include <linux/time.h> #include <watchdog.h> #include <jffs2/jffs2.h> #include <jffs2/jffs2_1pass.h> #include <linux/mtd/compat.h> #include <asm/errno.h> #include "jffs2_private.h" #define NODE_CHUNK 1024 /* size of memory allocation chunk in b_nodes */ #define SPIN_BLKSIZE 18 /* spin after having scanned 1<<BLKSIZE bytes */ /* Debugging switches */ #undef DEBUG_DIRENTS /* print directory entry list after scan */ #undef DEBUG_FRAGMENTS /* print fragment list after scan */ #undef DEBUG /* enable debugging messages */ #ifdef DEBUG # define DEBUGF(fmt,args...) printf(fmt ,##args) #else # define DEBUGF(fmt,args...) #endif #include "summary.h" /* keeps pointer to currentlu processed partition */ static struct part_info *current_part; #if (defined(CONFIG_JFFS2_NAND) && \ defined(CONFIG_CMD_NAND) ) #include <nand.h> /* * Support for jffs2 on top of NAND-flash * * NAND memory isn't mapped in processor's address space, * so data should be fetched from flash before * being processed. This is exactly what functions declared * here do. * */ #define NAND_PAGE_SIZE 512 #define NAND_PAGE_SHIFT 9 #define NAND_PAGE_MASK (~(NAND_PAGE_SIZE-1)) #ifndef NAND_CACHE_PAGES #define NAND_CACHE_PAGES 16 #endif #define NAND_CACHE_SIZE (NAND_CACHE_PAGES*NAND_PAGE_SIZE) static u8* nand_cache = NULL; static u32 nand_cache_off = (u32)-1; static int read_nand_cached(u32 off, u32 size, u_char *buf) { struct mtdids *id = current_part->dev->id; u32 bytes_read = 0; size_t retlen; int cpy_bytes; while (bytes_read < size) { if ((off + bytes_read < nand_cache_off) || (off + bytes_read >= nand_cache_off+NAND_CACHE_SIZE)) { nand_cache_off = (off + bytes_read) & NAND_PAGE_MASK; if (!nand_cache) { /* This memory never gets freed but 'cause it's a bootloader, nobody cares */ nand_cache = malloc(NAND_CACHE_SIZE); if (!nand_cache) { printf("read_nand_cached: can't alloc cache size %d bytes\n", NAND_CACHE_SIZE); return -1; } } retlen = NAND_CACHE_SIZE; if (nand_read(&nand_info[id->num], nand_cache_off, &retlen, nand_cache) != 0 || retlen != NAND_CACHE_SIZE) { printf("read_nand_cached: error reading nand off %#x size %d bytes\n", nand_cache_off, NAND_CACHE_SIZE); return -1; } } cpy_bytes = nand_cache_off + NAND_CACHE_SIZE - (off + bytes_read); if (cpy_bytes > size - bytes_read) cpy_bytes = size - bytes_read; memcpy(buf + bytes_read, nand_cache + off + bytes_read - nand_cache_off, cpy_bytes); bytes_read += cpy_bytes; } return bytes_read; } static void *get_fl_mem_nand(u32 off, u32 size, void *ext_buf) { u_char *buf = ext_buf ? (u_char*)ext_buf : (u_char*)malloc(size); if (NULL == buf) { printf("get_fl_mem_nand: can't alloc %d bytes\n", size); return NULL; } if (read_nand_cached(off, size, buf) < 0) { if (!ext_buf) free(buf); return NULL; } return buf; } static void *get_node_mem_nand(u32 off, void *ext_buf) { struct jffs2_unknown_node node; void *ret = NULL; if (NULL == get_fl_mem_nand(off, sizeof(node), &node)) return NULL; if (!(ret = get_fl_mem_nand(off, node.magic == JFFS2_MAGIC_BITMASK ? node.totlen : sizeof(node), ext_buf))) { printf("off = %#x magic %#x type %#x node.totlen = %d\n", off, node.magic, node.nodetype, node.totlen); } return ret; } static void put_fl_mem_nand(void *buf) { free(buf); } #endif #if defined(CONFIG_CMD_ONENAND) #include <linux/mtd/mtd.h> #include <linux/mtd/onenand.h> #include <onenand_uboot.h> #define ONENAND_PAGE_SIZE 2048 #define ONENAND_PAGE_SHIFT 11 #define ONENAND_PAGE_MASK (~(ONENAND_PAGE_SIZE-1)) #ifndef ONENAND_CACHE_PAGES #define ONENAND_CACHE_PAGES 4 #endif #define ONENAND_CACHE_SIZE (ONENAND_CACHE_PAGES*ONENAND_PAGE_SIZE) static u8* onenand_cache; static u32 onenand_cache_off = (u32)-1; static int read_onenand_cached(u32 off, u32 size, u_char *buf) { u32 bytes_read = 0; size_t retlen; int cpy_bytes; while (bytes_read < size) { if ((off + bytes_read < onenand_cache_off) || (off + bytes_read >= onenand_cache_off + ONENAND_CACHE_SIZE)) { onenand_cache_off = (off + bytes_read) & ONENAND_PAGE_MASK; if (!onenand_cache) { /* This memory never gets freed but 'cause it's a bootloader, nobody cares */ onenand_cache = malloc(ONENAND_CACHE_SIZE); if (!onenand_cache) { printf("read_onenand_cached: can't alloc cache size %d bytes\n", ONENAND_CACHE_SIZE); return -1; } } retlen = ONENAND_CACHE_SIZE; if (onenand_read(&onenand_mtd, onenand_cache_off, retlen, &retlen, onenand_cache) != 0 || retlen != ONENAND_CACHE_SIZE) { printf("read_onenand_cached: error reading nand off %#x size %d bytes\n", onenand_cache_off, ONENAND_CACHE_SIZE); return -1; } } cpy_bytes = onenand_cache_off + ONENAND_CACHE_SIZE - (off + bytes_read); if (cpy_bytes > size - bytes_read) cpy_bytes = size - bytes_read; memcpy(buf + bytes_read, onenand_cache + off + bytes_read - onenand_cache_off, cpy_bytes); bytes_read += cpy_bytes; } return bytes_read; } static void *get_fl_mem_onenand(u32 off, u32 size, void *ext_buf) { u_char *buf = ext_buf ? (u_char *)ext_buf : (u_char *)malloc(size); if (NULL == buf) { printf("get_fl_mem_onenand: can't alloc %d bytes\n", size); return NULL; } if (read_onenand_cached(off, size, buf) < 0) { if (!ext_buf) free(buf); return NULL; } return buf; } static void *get_node_mem_onenand(u32 off, void *ext_buf) { struct jffs2_unknown_node node; void *ret = NULL; if (NULL == get_fl_mem_onenand(off, sizeof(node), &node)) return NULL; ret = get_fl_mem_onenand(off, node.magic == JFFS2_MAGIC_BITMASK ? node.totlen : sizeof(node), ext_buf); if (!ret) { printf("off = %#x magic %#x type %#x node.totlen = %d\n", off, node.magic, node.nodetype, node.totlen); } return ret; } static void put_fl_mem_onenand(void *buf) { free(buf); } #endif #if defined(CONFIG_CMD_FLASH) /* * Support for jffs2 on top of NOR-flash * * NOR flash memory is mapped in processor's address space, * just return address. */ static inline void *get_fl_mem_nor(u32 off, u32 size, void *ext_buf) { u32 addr = off; struct mtdids *id = current_part->dev->id; extern flash_info_t flash_info[]; flash_info_t *flash = &flash_info[id->num]; addr += flash->start[0]; if (ext_buf) { memcpy(ext_buf, (void *)addr, size); return ext_buf; } return (void*)addr; } static inline void *get_node_mem_nor(u32 off, void *ext_buf) { struct jffs2_unknown_node *pNode; /* pNode will point directly to flash - don't provide external buffer and don't care about size */ pNode = get_fl_mem_nor(off, 0, NULL); return (void *)get_fl_mem_nor(off, pNode->magic == JFFS2_MAGIC_BITMASK ? pNode->totlen : sizeof(*pNode), ext_buf); } #endif /* * Generic jffs2 raw memory and node read routines. * */ static inline void *get_fl_mem(u32 off, u32 size, void *ext_buf) { struct mtdids *id = current_part->dev->id; switch(id->type) { #if defined(CONFIG_CMD_FLASH) case MTD_DEV_TYPE_NOR: return get_fl_mem_nor(off, size, ext_buf); break; #endif #if defined(CONFIG_JFFS2_NAND) && defined(CONFIG_CMD_NAND) case MTD_DEV_TYPE_NAND: return get_fl_mem_nand(off, size, ext_buf); break; #endif #if defined(CONFIG_CMD_ONENAND) case MTD_DEV_TYPE_ONENAND: return get_fl_mem_onenand(off, size, ext_buf); break; #endif default: printf("get_fl_mem: unknown device type, " \ "using raw offset!\n"); } return (void*)off; } static inline void *get_node_mem(u32 off, void *ext_buf) { struct mtdids *id = current_part->dev->id; switch(id->type) { #if defined(CONFIG_CMD_FLASH) case MTD_DEV_TYPE_NOR: return get_node_mem_nor(off, ext_buf); break; #endif #if defined(CONFIG_JFFS2_NAND) && \ defined(CONFIG_CMD_NAND) case MTD_DEV_TYPE_NAND: return get_node_mem_nand(off, ext_buf); break; #endif #if defined(CONFIG_CMD_ONENAND) case MTD_DEV_TYPE_ONENAND: return get_node_mem_onenand(off, ext_buf); break; #endif default: printf("get_fl_mem: unknown device type, " \ "using raw offset!\n"); } return (void*)off; } static inline void put_fl_mem(void *buf, void *ext_buf) { struct mtdids *id = current_part->dev->id; /* If buf is the same as ext_buf, it was provided by the caller - we shouldn't free it then. */ if (buf == ext_buf) return; switch (id->type) { #if defined(CONFIG_JFFS2_NAND) && defined(CONFIG_CMD_NAND) case MTD_DEV_TYPE_NAND: return put_fl_mem_nand(buf); #endif #if defined(CONFIG_CMD_ONENAND) case MTD_DEV_TYPE_ONENAND: return put_fl_mem_onenand(buf); #endif } } /* Compression names */ static char *compr_names[] = { "NONE", "ZERO", "RTIME", "RUBINMIPS", "COPY", "DYNRUBIN", "ZLIB", #if defined(CONFIG_JFFS2_LZO) "LZO", #endif }; /* Memory management */ struct mem_block { u32 index; struct mem_block *next; struct b_node nodes[NODE_CHUNK]; }; static void free_nodes(struct b_list *list) { while (list->listMemBase != NULL) { struct mem_block *next = list->listMemBase->next; free( list->listMemBase ); list->listMemBase = next; } } static struct b_node * add_node(struct b_list *list) { u32 index = 0; struct mem_block *memBase; struct b_node *b; memBase = list->listMemBase; if (memBase != NULL) index = memBase->index; #if 0 putLabeledWord("add_node: index = ", index); putLabeledWord("add_node: memBase = ", list->listMemBase); #endif if (memBase == NULL || index >= NODE_CHUNK) { /* we need more space before we continue */ memBase = mmalloc(sizeof(struct mem_block)); if (memBase == NULL) { putstr("add_node: malloc failed\n"); return NULL; } memBase->next = list->listMemBase; index = 0; #if 0 putLabeledWord("add_node: alloced a new membase at ", *memBase); #endif } /* now we have room to add it. */ b = &memBase->nodes[index]; index ++; memBase->index = index; list->listMemBase = memBase; list->listCount++; return b; } static struct b_node * insert_node(struct b_list *list, u32 offset) { struct b_node *new; #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS struct b_node *b, *prev; #endif if (!(new = add_node(list))) { putstr("add_node failed!\r\n"); return NULL; } new->offset = offset; #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS if (list->listTail != NULL && list->listCompare(new, list->listTail)) prev = list->listTail; else if (list->listLast != NULL && list->listCompare(new, list->listLast)) prev = list->listLast; else prev = NULL; for (b = (prev ? prev->next : list->listHead); b != NULL && list->listCompare(new, b); prev = b, b = b->next) { list->listLoops++; } if (b != NULL) list->listLast = prev; if (b != NULL) { new->next = b; if (prev != NULL) prev->next = new; else list->listHead = new; } else #endif { new->next = (struct b_node *) NULL; if (list->listTail != NULL) { list->listTail->next = new; list->listTail = new; } else { list->listTail = list->listHead = new; } } return new; } #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS /* Sort data entries with the latest version last, so that if there * is overlapping data the latest version will be used. */ static int compare_inodes(struct b_node *new, struct b_node *old) { struct jffs2_raw_inode ojNew; struct jffs2_raw_inode ojOld; struct jffs2_raw_inode *jNew = (struct jffs2_raw_inode *)get_fl_mem(new->offset, sizeof(ojNew), &ojNew); struct jffs2_raw_inode *jOld = (struct jffs2_raw_inode *)get_fl_mem(old->offset, sizeof(ojOld), &ojOld); return jNew->version > jOld->version; } /* Sort directory entries so all entries in the same directory * with the same name are grouped together, with the latest version * last. This makes it easy to eliminate all but the latest version * by marking the previous version dead by setting the inode to 0. */ static int compare_dirents(struct b_node *new, struct b_node *old) { struct jffs2_raw_dirent ojNew; struct jffs2_raw_dirent ojOld; struct jffs2_raw_dirent *jNew = (struct jffs2_raw_dirent *)get_fl_mem(new->offset, sizeof(ojNew), &ojNew); struct jffs2_raw_dirent *jOld = (struct jffs2_raw_dirent *)get_fl_mem(old->offset, sizeof(ojOld), &ojOld); int cmp; /* ascending sort by pino */ if (jNew->pino != jOld->pino) return jNew->pino > jOld->pino; /* pino is the same, so use ascending sort by nsize, so * we don't do strncmp unless we really must. */ if (jNew->nsize != jOld->nsize) return jNew->nsize > jOld->nsize; /* length is also the same, so use ascending sort by name */ cmp = strncmp((char *)jNew->name, (char *)jOld->name, jNew->nsize); if (cmp != 0) return cmp > 0; /* we have duplicate names in this directory, so use ascending * sort by version */ if (jNew->version > jOld->version) { /* since jNew is newer, we know jOld is not valid, so * mark it with inode 0 and it will not be used */ jOld->ino = 0; return 1; } return 0; } #endif void jffs2_free_cache(struct part_info *part) { struct b_lists *pL; if (part->jffs2_priv != NULL) { pL = (struct b_lists *)part->jffs2_priv; free_nodes(&pL->frag); free_nodes(&pL->dir); free(pL->readbuf); free(pL); } } static u32 jffs_init_1pass_list(struct part_info *part) { struct b_lists *pL; jffs2_free_cache(part); if (NULL != (part->jffs2_priv = malloc(sizeof(struct b_lists)))) { pL = (struct b_lists *)part->jffs2_priv; memset(pL, 0, sizeof(*pL)); #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS pL->dir.listCompare = compare_dirents; pL->frag.listCompare = compare_inodes; #endif } return 0; } /* find the inode from the slashless name given a parent */ static long jffs2_1pass_read_inode(struct b_lists *pL, u32 inode, char *dest) { struct b_node *b; struct jffs2_raw_inode *jNode; u32 totalSize = 0; u32 latestVersion = 0; uchar *lDest; uchar *src; int i; u32 counter = 0; #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS /* Find file size before loading any data, so fragments that * start past the end of file can be ignored. A fragment * that is partially in the file is loaded, so extra data may * be loaded up to the next 4K boundary above the file size. * This shouldn't cause trouble when loading kernel images, so * we will live with it. */ for (b = pL->frag.listHead; b != NULL; b = b->next) { jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset, sizeof(struct jffs2_raw_inode), pL->readbuf); if ((inode == jNode->ino)) { /* get actual file length from the newest node */ if (jNode->version >= latestVersion) { totalSize = jNode->isize; latestVersion = jNode->version; } } put_fl_mem(jNode, pL->readbuf); } #endif for (b = pL->frag.listHead; b != NULL; b = b->next) { jNode = (struct jffs2_raw_inode *) get_node_mem(b->offset, pL->readbuf); if ((inode == jNode->ino)) { #if 0 putLabeledWord("\r\n\r\nread_inode: totlen = ", jNode->totlen); putLabeledWord("read_inode: inode = ", jNode->ino); putLabeledWord("read_inode: version = ", jNode->version); putLabeledWord("read_inode: isize = ", jNode->isize); putLabeledWord("read_inode: offset = ", jNode->offset); putLabeledWord("read_inode: csize = ", jNode->csize); putLabeledWord("read_inode: dsize = ", jNode->dsize); putLabeledWord("read_inode: compr = ", jNode->compr); putLabeledWord("read_inode: usercompr = ", jNode->usercompr); putLabeledWord("read_inode: flags = ", jNode->flags); #endif #ifndef CONFIG_SYS_JFFS2_SORT_FRAGMENTS /* get actual file length from the newest node */ if (jNode->version >= latestVersion) { totalSize = jNode->isize; latestVersion = jNode->version; } #endif if(dest) { src = ((uchar *) jNode) + sizeof(struct jffs2_raw_inode); /* ignore data behind latest known EOF */ if (jNode->offset > totalSize) { put_fl_mem(jNode, pL->readbuf); continue; } if (b->datacrc == CRC_UNKNOWN) b->datacrc = data_crc(jNode) ? CRC_OK : CRC_BAD; if (b->datacrc == CRC_BAD) { put_fl_mem(jNode, pL->readbuf); continue; } lDest = (uchar *) (dest + jNode->offset); #if 0 putLabeledWord("read_inode: src = ", src); putLabeledWord("read_inode: dest = ", lDest); #endif switch (jNode->compr) { case JFFS2_COMPR_NONE: ldr_memcpy(lDest, src, jNode->dsize); break; case JFFS2_COMPR_ZERO: for (i = 0; i < jNode->dsize; i++) *(lDest++) = 0; break; case JFFS2_COMPR_RTIME: rtime_decompress(src, lDest, jNode->csize, jNode->dsize); break; case JFFS2_COMPR_DYNRUBIN: /* this is slow but it works */ dynrubin_decompress(src, lDest, jNode->csize, jNode->dsize); break; case JFFS2_COMPR_ZLIB: zlib_decompress(src, lDest, jNode->csize, jNode->dsize); break; #if defined(CONFIG_JFFS2_LZO) case JFFS2_COMPR_LZO: lzo_decompress(src, lDest, jNode->csize, jNode->dsize); break; #endif default: /* unknown */ putLabeledWord("UNKNOWN COMPRESSION METHOD = ", jNode->compr); put_fl_mem(jNode, pL->readbuf); return -1; break; } } #if 0 putLabeledWord("read_inode: totalSize = ", totalSize); #endif } counter++; put_fl_mem(jNode, pL->readbuf); } #if 0 putLabeledWord("read_inode: returning = ", totalSize); #endif return totalSize; } /* find the inode from the slashless name given a parent */ static u32 jffs2_1pass_find_inode(struct b_lists * pL, const char *name, u32 pino) { struct b_node *b; struct jffs2_raw_dirent *jDir; int len; u32 counter; u32 version = 0; u32 inode = 0; /* name is assumed slash free */ len = strlen(name); counter = 0; /* we need to search all and return the inode with the highest version */ for(b = pL->dir.listHead; b; b = b->next, counter++) { jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset, pL->readbuf); if ((pino == jDir->pino) && (len == jDir->nsize) && (jDir->ino) && /* 0 for unlink */ (!strncmp((char *)jDir->name, name, len))) { /* a match */ if (jDir->version < version) { put_fl_mem(jDir, pL->readbuf); continue; } if (jDir->version == version && inode != 0) { /* I'm pretty sure this isn't legal */ putstr(" ** ERROR ** "); putnstr(jDir->name, jDir->nsize); putLabeledWord(" has dup version =", version); } inode = jDir->ino; version = jDir->version; } #if 0 putstr("\r\nfind_inode:p&l ->"); putnstr(jDir->name, jDir->nsize); putstr("\r\n"); putLabeledWord("pino = ", jDir->pino); putLabeledWord("nsize = ", jDir->nsize); putLabeledWord("b = ", (u32) b); putLabeledWord("counter = ", counter); #endif put_fl_mem(jDir, pL->readbuf); } return inode; } char *mkmodestr(unsigned long mode, char *str) { static const char *l = "xwr"; int mask = 1, i; char c; switch (mode & S_IFMT) { case S_IFDIR: str[0] = 'd'; break; case S_IFBLK: str[0] = 'b'; break; case S_IFCHR: str[0] = 'c'; break; case S_IFIFO: str[0] = 'f'; break; case S_IFLNK: str[0] = 'l'; break; case S_IFSOCK: str[0] = 's'; break; case S_IFREG: str[0] = '-'; break; default: str[0] = '?'; } for(i = 0; i < 9; i++) { c = l[i%3]; str[9-i] = (mode & mask)?c:'-'; mask = mask<<1; } if(mode & S_ISUID) str[3] = (mode & S_IXUSR)?'s':'S'; if(mode & S_ISGID) str[6] = (mode & S_IXGRP)?'s':'S'; if(mode & S_ISVTX) str[9] = (mode & S_IXOTH)?'t':'T'; str[10] = '\0'; return str; } static inline void dump_stat(struct stat *st, const char *name) { char str[20]; char s[64], *p; if (st->st_mtime == (time_t)(-1)) /* some ctimes really hate -1 */ st->st_mtime = 1; ctime_r((time_t *)&st->st_mtime, s/*,64*/); /* newlib ctime doesn't have buflen */ if ((p = strchr(s,'\n')) != NULL) *p = '\0'; if ((p = strchr(s,'\r')) != NULL) *p = '\0'; /* printf("%6lo %s %8ld %s %s\n", st->st_mode, mkmodestr(st->st_mode, str), st->st_size, s, name); */ printf(" %s %8ld %s %s", mkmodestr(st->st_mode,str), st->st_size, s, name); } static inline u32 dump_inode(struct b_lists * pL, struct jffs2_raw_dirent *d, struct jffs2_raw_inode *i) { char fname[256]; struct stat st; if(!d || !i) return -1; strncpy(fname, (char *)d->name, d->nsize); fname[d->nsize] = '\0'; memset(&st,0,sizeof(st)); st.st_mtime = i->mtime; st.st_mode = i->mode; st.st_ino = i->ino; st.st_size = i->isize; dump_stat(&st, fname); if (d->type == DT_LNK) { unsigned char *src = (unsigned char *) (&i[1]); putstr(" -> "); putnstr(src, (int)i->dsize); } putstr("\r\n"); return 0; } /* list inodes with the given pino */ static u32 jffs2_1pass_list_inodes(struct b_lists * pL, u32 pino) { struct b_node *b; struct jffs2_raw_dirent *jDir; for (b = pL->dir.listHead; b; b = b->next) { jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset, pL->readbuf); if ((pino == jDir->pino) && (jDir->ino)) { /* ino=0 -> unlink */ u32 i_version = 0; struct jffs2_raw_inode ojNode; struct jffs2_raw_inode *jNode, *i = NULL; struct b_node *b2 = pL->frag.listHead; while (b2) { jNode = (struct jffs2_raw_inode *) get_fl_mem(b2->offset, sizeof(ojNode), &ojNode); if (jNode->ino == jDir->ino && jNode->version >= i_version) { i_version = jNode->version; if (i) put_fl_mem(i, NULL); if (jDir->type == DT_LNK) i = get_node_mem(b2->offset, NULL); else i = get_fl_mem(b2->offset, sizeof(*i), NULL); } b2 = b2->next; } dump_inode(pL, jDir, i); put_fl_mem(i, NULL); } put_fl_mem(jDir, pL->readbuf); } return pino; } static u32 jffs2_1pass_search_inode(struct b_lists * pL, const char *fname, u32 pino) { int i; char tmp[256]; char working_tmp[256]; char *c; /* discard any leading slash */ i = 0; while (fname[i] == '/') i++; strcpy(tmp, &fname[i]); while ((c = (char *) strchr(tmp, '/'))) /* we are still dired searching */ { strncpy(working_tmp, tmp, c - tmp); working_tmp[c - tmp] = '\0'; #if 0 putstr("search_inode: tmp = "); putstr(tmp); putstr("\r\n"); putstr("search_inode: wtmp = "); putstr(working_tmp); putstr("\r\n"); putstr("search_inode: c = "); putstr(c); putstr("\r\n"); #endif for (i = 0; i < strlen(c) - 1; i++) tmp[i] = c[i + 1]; tmp[i] = '\0'; #if 0 putstr("search_inode: post tmp = "); putstr(tmp); putstr("\r\n"); #endif if (!(pino = jffs2_1pass_find_inode(pL, working_tmp, pino))) { putstr("find_inode failed for name="); putstr(working_tmp); putstr("\r\n"); return 0; } } /* this is for the bare filename, directories have already been mapped */ if (!(pino = jffs2_1pass_find_inode(pL, tmp, pino))) { putstr("find_inode failed for name="); putstr(tmp); putstr("\r\n"); return 0; } return pino; } static u32 jffs2_1pass_resolve_inode(struct b_lists * pL, u32 ino) { struct b_node *b; struct b_node *b2; struct jffs2_raw_dirent *jDir; struct jffs2_raw_inode *jNode; u8 jDirFoundType = 0; u32 jDirFoundIno = 0; u32 jDirFoundPino = 0; char tmp[256]; u32 version = 0; u32 pino; unsigned char *src; /* we need to search all and return the inode with the highest version */ for(b = pL->dir.listHead; b; b = b->next) { jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset, pL->readbuf); if (ino == jDir->ino) { if (jDir->version < version) { put_fl_mem(jDir, pL->readbuf); continue; } if (jDir->version == version && jDirFoundType) { /* I'm pretty sure this isn't legal */ putstr(" ** ERROR ** "); putnstr(jDir->name, jDir->nsize); putLabeledWord(" has dup version (resolve) = ", version); } jDirFoundType = jDir->type; jDirFoundIno = jDir->ino; jDirFoundPino = jDir->pino; version = jDir->version; } put_fl_mem(jDir, pL->readbuf); } /* now we found the right entry again. (shoulda returned inode*) */ if (jDirFoundType != DT_LNK) return jDirFoundIno; /* it's a soft link so we follow it again. */ b2 = pL->frag.listHead; while (b2) { jNode = (struct jffs2_raw_inode *) get_node_mem(b2->offset, pL->readbuf); if (jNode->ino == jDirFoundIno) { src = (unsigned char *)jNode + sizeof(struct jffs2_raw_inode); #if 0 putLabeledWord("\t\t dsize = ", jNode->dsize); putstr("\t\t target = "); putnstr(src, jNode->dsize); putstr("\r\n"); #endif strncpy(tmp, (char *)src, jNode->dsize); tmp[jNode->dsize] = '\0'; put_fl_mem(jNode, pL->readbuf); break; } b2 = b2->next; put_fl_mem(jNode, pL->readbuf); } /* ok so the name of the new file to find is in tmp */ /* if it starts with a slash it is root based else shared dirs */ if (tmp[0] == '/') pino = 1; else pino = jDirFoundPino; return jffs2_1pass_search_inode(pL, tmp, pino); } static u32 jffs2_1pass_search_list_inodes(struct b_lists * pL, const char *fname, u32 pino) { int i; char tmp[256]; char working_tmp[256]; char *c; /* discard any leading slash */ i = 0; while (fname[i] == '/') i++; strcpy(tmp, &fname[i]); working_tmp[0] = '\0'; while ((c = (char *) strchr(tmp, '/'))) /* we are still dired searching */ { strncpy(working_tmp, tmp, c - tmp); working_tmp[c - tmp] = '\0'; for (i = 0; i < strlen(c) - 1; i++) tmp[i] = c[i + 1]; tmp[i] = '\0'; /* only a failure if we arent looking at top level */ if (!(pino = jffs2_1pass_find_inode(pL, working_tmp, pino)) && (working_tmp[0])) { putstr("find_inode failed for name="); putstr(working_tmp); putstr("\r\n"); return 0; } } if (tmp[0] && !(pino = jffs2_1pass_find_inode(pL, tmp, pino))) { putstr("find_inode failed for name="); putstr(tmp); putstr("\r\n"); return 0; } /* this is for the bare filename, directories have already been mapped */ if (!(pino = jffs2_1pass_list_inodes(pL, pino))) { putstr("find_inode failed for name="); putstr(tmp); putstr("\r\n"); return 0; } return pino; } unsigned char jffs2_1pass_rescan_needed(struct part_info *part) { struct b_node *b; struct jffs2_unknown_node onode; struct jffs2_unknown_node *node; struct b_lists *pL = (struct b_lists *)part->jffs2_priv; if (part->jffs2_priv == 0){ DEBUGF ("rescan: First time in use\n"); return 1; } /* if we have no list, we need to rescan */ if (pL->frag.listCount == 0) { DEBUGF ("rescan: fraglist zero\n"); return 1; } /* but suppose someone reflashed a partition at the same offset... */ b = pL->dir.listHead; while (b) { node = (struct jffs2_unknown_node *) get_fl_mem(b->offset, sizeof(onode), &onode); if (node->nodetype != JFFS2_NODETYPE_DIRENT) { DEBUGF ("rescan: fs changed beneath me? (%lx)\n", (unsigned long) b->offset); return 1; } b = b->next; } return 0; } #ifdef CONFIG_JFFS2_SUMMARY static u32 sum_get_unaligned32(u32 *ptr) { u32 val; u8 *p = (u8 *)ptr; val = *p | (*(p + 1) << 8) | (*(p + 2) << 16) | (*(p + 3) << 24); return __le32_to_cpu(val); } static u16 sum_get_unaligned16(u16 *ptr) { u16 val; u8 *p = (u8 *)ptr; val = *p | (*(p + 1) << 8); return __le16_to_cpu(val); } #define dbg_summary(...) do {} while (0); /* * Process the stored summary information - helper function for * jffs2_sum_scan_sumnode() */ static int jffs2_sum_process_sum_data(struct part_info *part, uint32_t offset, struct jffs2_raw_summary *summary, struct b_lists *pL) { void *sp; int i, pass; void *ret; for (pass = 0; pass < 2; pass++) { sp = summary->sum; for (i = 0; i < summary->sum_num; i++) { struct jffs2_sum_unknown_flash *spu = sp; dbg_summary("processing summary index %d\n", i); switch (sum_get_unaligned16(&spu->nodetype)) { case JFFS2_NODETYPE_INODE: { struct jffs2_sum_inode_flash *spi; if (pass) { spi = sp; ret = insert_node(&pL->frag, (u32)part->offset + offset + sum_get_unaligned32( &spi->offset)); if (ret == NULL) return -1; } sp += JFFS2_SUMMARY_INODE_SIZE; break; } case JFFS2_NODETYPE_DIRENT: { struct jffs2_sum_dirent_flash *spd; spd = sp; if (pass) { ret = insert_node(&pL->dir, (u32) part->offset + offset + sum_get_unaligned32( &spd->offset)); if (ret == NULL) return -1; } sp += JFFS2_SUMMARY_DIRENT_SIZE( spd->nsize); break; } default : { uint16_t nodetype = sum_get_unaligned16( &spu->nodetype); printf("Unsupported node type %x found" " in summary!\n", nodetype); if ((nodetype & JFFS2_COMPAT_MASK) == JFFS2_FEATURE_INCOMPAT) return -EIO; return -EBADMSG; } } } } return 0; } /* Process the summary node - called from jffs2_scan_eraseblock() */ int jffs2_sum_scan_sumnode(struct part_info *part, uint32_t offset, struct jffs2_raw_summary *summary, uint32_t sumsize, struct b_lists *pL) { struct jffs2_unknown_node crcnode; int ret, ofs; uint32_t crc; ofs = part->sector_size - sumsize; dbg_summary("summary found for 0x%08x at 0x%08x (0x%x bytes)\n", offset, offset + ofs, sumsize); /* OK, now check for node validity and CRC */ crcnode.magic = JFFS2_MAGIC_BITMASK; crcnode.nodetype = JFFS2_NODETYPE_SUMMARY; crcnode.totlen = summary->totlen; crc = crc32_no_comp(0, (uchar *)&crcnode, sizeof(crcnode)-4); if (summary->hdr_crc != crc) { dbg_summary("Summary node header is corrupt (bad CRC or " "no summary at all)\n"); goto crc_err; } if (summary->totlen != sumsize) { dbg_summary("Summary node is corrupt (wrong erasesize?)\n"); goto crc_err; } crc = crc32_no_comp(0, (uchar *)summary, sizeof(struct jffs2_raw_summary)-8); if (summary->node_crc != crc) { dbg_summary("Summary node is corrupt (bad CRC)\n"); goto crc_err; } crc = crc32_no_comp(0, (uchar *)summary->sum, sumsize - sizeof(struct jffs2_raw_summary)); if (summary->sum_crc != crc) { dbg_summary("Summary node data is corrupt (bad CRC)\n"); goto crc_err; } if (summary->cln_mkr) dbg_summary("Summary : CLEANMARKER node \n"); ret = jffs2_sum_process_sum_data(part, offset, summary, pL); if (ret == -EBADMSG) return 0; if (ret) return ret; /* real error */ return 1; crc_err: putstr("Summary node crc error, skipping summary information.\n"); return 0; } #endif /* CONFIG_JFFS2_SUMMARY */ #ifdef DEBUG_FRAGMENTS static void dump_fragments(struct b_lists *pL) { struct b_node *b; struct jffs2_raw_inode ojNode; struct jffs2_raw_inode *jNode; putstr("\r\n\r\n******The fragment Entries******\r\n"); b = pL->frag.listHead; while (b) { jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset, sizeof(ojNode), &ojNode); putLabeledWord("\r\n\tbuild_list: FLASH_OFFSET = ", b->offset); putLabeledWord("\tbuild_list: totlen = ", jNode->totlen); putLabeledWord("\tbuild_list: inode = ", jNode->ino); putLabeledWord("\tbuild_list: version = ", jNode->version); putLabeledWord("\tbuild_list: isize = ", jNode->isize); putLabeledWord("\tbuild_list: atime = ", jNode->atime); putLabeledWord("\tbuild_list: offset = ", jNode->offset); putLabeledWord("\tbuild_list: csize = ", jNode->csize); putLabeledWord("\tbuild_list: dsize = ", jNode->dsize); putLabeledWord("\tbuild_list: compr = ", jNode->compr); putLabeledWord("\tbuild_list: usercompr = ", jNode->usercompr); putLabeledWord("\tbuild_list: flags = ", jNode->flags); putLabeledWord("\tbuild_list: offset = ", b->offset); /* FIXME: ? [RS] */ b = b->next; } } #endif #ifdef DEBUG_DIRENTS static void dump_dirents(struct b_lists *pL) { struct b_node *b; struct jffs2_raw_dirent *jDir; putstr("\r\n\r\n******The directory Entries******\r\n"); b = pL->dir.listHead; while (b) { jDir = (struct jffs2_raw_dirent *) get_node_mem(b->offset, pL->readbuf); putstr("\r\n"); putnstr(jDir->name, jDir->nsize); putLabeledWord("\r\n\tbuild_list: magic = ", jDir->magic); putLabeledWord("\tbuild_list: nodetype = ", jDir->nodetype); putLabeledWord("\tbuild_list: hdr_crc = ", jDir->hdr_crc); putLabeledWord("\tbuild_list: pino = ", jDir->pino); putLabeledWord("\tbuild_list: version = ", jDir->version); putLabeledWord("\tbuild_list: ino = ", jDir->ino); putLabeledWord("\tbuild_list: mctime = ", jDir->mctime); putLabeledWord("\tbuild_list: nsize = ", jDir->nsize); putLabeledWord("\tbuild_list: type = ", jDir->type); putLabeledWord("\tbuild_list: node_crc = ", jDir->node_crc); putLabeledWord("\tbuild_list: name_crc = ", jDir->name_crc); putLabeledWord("\tbuild_list: offset = ", b->offset); /* FIXME: ? [RS] */ b = b->next; put_fl_mem(jDir, pL->readbuf); } } #endif #define DEFAULT_EMPTY_SCAN_SIZE 4096 static inline uint32_t EMPTY_SCAN_SIZE(uint32_t sector_size) { if (sector_size < DEFAULT_EMPTY_SCAN_SIZE) return sector_size; else return DEFAULT_EMPTY_SCAN_SIZE; } static u32 jffs2_1pass_build_lists(struct part_info * part) { struct b_lists *pL; struct jffs2_unknown_node *node; u32 nr_sectors = part->size/part->sector_size; u32 i; u32 counter4 = 0; u32 counterF = 0; u32 counterN = 0; u32 max_totlen = 0; u32 buf_size = DEFAULT_EMPTY_SCAN_SIZE; char *buf; /* turn off the lcd. Refreshing the lcd adds 50% overhead to the */ /* jffs2 list building enterprise nope. in newer versions the overhead is */ /* only about 5 %. not enough to inconvenience people for. */ /* lcd_off(); */ /* if we are building a list we need to refresh the cache. */ jffs_init_1pass_list(part); pL = (struct b_lists *)part->jffs2_priv; buf = malloc(buf_size); puts ("Scanning JFFS2 FS: "); /* start at the beginning of the partition */ for (i = 0; i < nr_sectors; i++) { uint32_t sector_ofs = i * part->sector_size; uint32_t buf_ofs = sector_ofs; uint32_t buf_len; uint32_t ofs, prevofs; #ifdef CONFIG_JFFS2_SUMMARY struct jffs2_sum_marker *sm; void *sumptr = NULL; uint32_t sumlen; int ret; #endif WATCHDOG_RESET(); #ifdef CONFIG_JFFS2_SUMMARY buf_len = sizeof(*sm); /* Read as much as we want into the _end_ of the preallocated * buffer */ get_fl_mem(part->offset + sector_ofs + part->sector_size - buf_len, buf_len, buf + buf_size - buf_len); sm = (void *)buf + buf_size - sizeof(*sm); if (sm->magic == JFFS2_SUM_MAGIC) { sumlen = part->sector_size - sm->offset; sumptr = buf + buf_size - sumlen; /* Now, make sure the summary itself is available */ if (sumlen > buf_size) { /* Need to kmalloc for this. */ sumptr = malloc(sumlen); if (!sumptr) { putstr("Can't get memory for summary " "node!\n"); free(buf); jffs2_free_cache(part); return 0; } memcpy(sumptr + sumlen - buf_len, buf + buf_size - buf_len, buf_len); } if (buf_len < sumlen) { /* Need to read more so that the entire summary * node is present */ get_fl_mem(part->offset + sector_ofs + part->sector_size - sumlen, sumlen - buf_len, sumptr); } } if (sumptr) { ret = jffs2_sum_scan_sumnode(part, sector_ofs, sumptr, sumlen, pL); if (buf_size && sumlen > buf_size) free(sumptr); if (ret < 0) { free(buf); jffs2_free_cache(part); return 0; } if (ret) continue; } #endif /* CONFIG_JFFS2_SUMMARY */ buf_len = EMPTY_SCAN_SIZE(part->sector_size); get_fl_mem((u32)part->offset + buf_ofs, buf_len, buf); /* We temporarily use 'ofs' as a pointer into the buffer/jeb */ ofs = 0; /* Scan only 4KiB of 0xFF before declaring it's empty */ while (ofs < EMPTY_SCAN_SIZE(part->sector_size) && *(uint32_t *)(&buf[ofs]) == 0xFFFFFFFF) ofs += 4; if (ofs == EMPTY_SCAN_SIZE(part->sector_size)) continue; ofs += sector_ofs; prevofs = ofs - 1; scan_more: while (ofs < sector_ofs + part->sector_size) { if (ofs == prevofs) { printf("offset %08x already seen, skip\n", ofs); ofs += 4; counter4++; continue; } prevofs = ofs; if (sector_ofs + part->sector_size < ofs + sizeof(*node)) break; if (buf_ofs + buf_len < ofs + sizeof(*node)) { buf_len = min_t(uint32_t, buf_size, sector_ofs + part->sector_size - ofs); get_fl_mem((u32)part->offset + ofs, buf_len, buf); buf_ofs = ofs; } node = (struct jffs2_unknown_node *)&buf[ofs-buf_ofs]; if (*(uint32_t *)(&buf[ofs-buf_ofs]) == 0xffffffff) { uint32_t inbuf_ofs; uint32_t scan_end; ofs += 4; scan_end = min_t(uint32_t, EMPTY_SCAN_SIZE( part->sector_size)/8, buf_len); more_empty: inbuf_ofs = ofs - buf_ofs; while (inbuf_ofs < scan_end) { if (*(uint32_t *)(&buf[inbuf_ofs]) != 0xffffffff) goto scan_more; inbuf_ofs += 4; ofs += 4; } /* Ran off end. */ /* See how much more there is to read in this * eraseblock... */ buf_len = min_t(uint32_t, buf_size, sector_ofs + part->sector_size - ofs); if (!buf_len) { /* No more to read. Break out of main * loop without marking this range of * empty space as dirty (because it's * not) */ break; } scan_end = buf_len; get_fl_mem((u32)part->offset + ofs, buf_len, buf); buf_ofs = ofs; goto more_empty; } if (node->magic != JFFS2_MAGIC_BITMASK || !hdr_crc(node)) { ofs += 4; counter4++; continue; } if (ofs + node->totlen > sector_ofs + part->sector_size) { ofs += 4; counter4++; continue; } /* if its a fragment add it */ switch (node->nodetype) { case JFFS2_NODETYPE_INODE: if (buf_ofs + buf_len < ofs + sizeof(struct jffs2_raw_inode)) { get_fl_mem((u32)part->offset + ofs, buf_len, buf); buf_ofs = ofs; node = (void *)buf; } if (!inode_crc((struct jffs2_raw_inode *) node)) break; if (insert_node(&pL->frag, (u32) part->offset + ofs) == NULL) { free(buf); jffs2_free_cache(part); return 0; } if (max_totlen < node->totlen) max_totlen = node->totlen; break; case JFFS2_NODETYPE_DIRENT: if (buf_ofs + buf_len < ofs + sizeof(struct jffs2_raw_dirent) + ((struct jffs2_raw_dirent *) node)->nsize) { get_fl_mem((u32)part->offset + ofs, buf_len, buf); buf_ofs = ofs; node = (void *)buf; } if (!dirent_crc((struct jffs2_raw_dirent *) node) || !dirent_name_crc( (struct jffs2_raw_dirent *) node)) break; if (! (counterN%100)) puts ("\b\b. "); if (insert_node(&pL->dir, (u32) part->offset + ofs) == NULL) { free(buf); jffs2_free_cache(part); return 0; } if (max_totlen < node->totlen) max_totlen = node->totlen; counterN++; break; case JFFS2_NODETYPE_CLEANMARKER: if (node->totlen != sizeof(struct jffs2_unknown_node)) printf("OOPS Cleanmarker has bad size " "%d != %zu\n", node->totlen, sizeof(struct jffs2_unknown_node)); break; case JFFS2_NODETYPE_PADDING: if (node->totlen < sizeof(struct jffs2_unknown_node)) printf("OOPS Padding has bad size " "%d < %zu\n", node->totlen, sizeof(struct jffs2_unknown_node)); break; case JFFS2_NODETYPE_SUMMARY: break; default: printf("Unknown node type: %x len %d offset 0x%x\n", node->nodetype, node->totlen, ofs); } ofs += ((node->totlen + 3) & ~3); counterF++; } } free(buf); putstr("\b\b done.\r\n"); /* close off the dots */ /* We don't care if malloc failed - then each read operation will * allocate its own buffer as necessary (NAND) or will read directly * from flash (NOR). */ pL->readbuf = malloc(max_totlen); /* turn the lcd back on. */ /* splash(); */ #if 0 putLabeledWord("dir entries = ", pL->dir.listCount); putLabeledWord("frag entries = ", pL->frag.listCount); putLabeledWord("+4 increments = ", counter4); putLabeledWord("+file_offset increments = ", counterF); #endif #ifdef DEBUG_DIRENTS dump_dirents(pL); #endif #ifdef DEBUG_FRAGMENTS dump_fragments(pL); #endif /* give visual feedback that we are done scanning the flash */ led_blink(0x0, 0x0, 0x1, 0x1); /* off, forever, on 100ms, off 100ms */ return 1; } static u32 jffs2_1pass_fill_info(struct b_lists * pL, struct b_jffs2_info * piL) { struct b_node *b; struct jffs2_raw_inode ojNode; struct jffs2_raw_inode *jNode; int i; for (i = 0; i < JFFS2_NUM_COMPR; i++) { piL->compr_info[i].num_frags = 0; piL->compr_info[i].compr_sum = 0; piL->compr_info[i].decompr_sum = 0; } b = pL->frag.listHead; while (b) { jNode = (struct jffs2_raw_inode *) get_fl_mem(b->offset, sizeof(ojNode), &ojNode); if (jNode->compr < JFFS2_NUM_COMPR) { piL->compr_info[jNode->compr].num_frags++; piL->compr_info[jNode->compr].compr_sum += jNode->csize; piL->compr_info[jNode->compr].decompr_sum += jNode->dsize; } b = b->next; } return 0; } static struct b_lists * jffs2_get_list(struct part_info * part, const char *who) { /* copy requested part_info struct pointer to global location */ current_part = part; if (jffs2_1pass_rescan_needed(part)) { if (!jffs2_1pass_build_lists(part)) { printf("%s: Failed to scan JFFSv2 file structure\n", who); return NULL; } } return (struct b_lists *)part->jffs2_priv; } /* Print directory / file contents */ u32 jffs2_1pass_ls(struct part_info * part, const char *fname) { struct b_lists *pl; long ret = 1; u32 inode; if (! (pl = jffs2_get_list(part, "ls"))) return 0; if (! (inode = jffs2_1pass_search_list_inodes(pl, fname, 1))) { putstr("ls: Failed to scan jffs2 file structure\r\n"); return 0; } #if 0 putLabeledWord("found file at inode = ", inode); putLabeledWord("read_inode returns = ", ret); #endif return ret; } /* Load a file from flash into memory. fname can be a full path */ u32 jffs2_1pass_load(char *dest, struct part_info * part, const char *fname) { struct b_lists *pl; long ret = 1; u32 inode; if (! (pl = jffs2_get_list(part, "load"))) return 0; if (! (inode = jffs2_1pass_search_inode(pl, fname, 1))) { putstr("load: Failed to find inode\r\n"); return 0; } /* Resolve symlinks */ if (! (inode = jffs2_1pass_resolve_inode(pl, inode))) { putstr("load: Failed to resolve inode structure\r\n"); return 0; } if ((ret = jffs2_1pass_read_inode(pl, inode, dest)) < 0) { putstr("load: Failed to read inode\r\n"); return 0; } DEBUGF ("load: loaded '%s' to 0x%lx (%ld bytes)\n", fname, (unsigned long) dest, ret); return ret; } /* Return information about the fs on this partition */ u32 jffs2_1pass_info(struct part_info * part) { struct b_jffs2_info info; struct b_lists *pl; int i; if (! (pl = jffs2_get_list(part, "info"))) return 0; jffs2_1pass_fill_info(pl, &info); for (i = 0; i < JFFS2_NUM_COMPR; i++) { printf ("Compression: %s\n" "\tfrag count: %d\n" "\tcompressed sum: %d\n" "\tuncompressed sum: %d\n", compr_names[i], info.compr_info[i].num_frags, info.compr_info[i].compr_sum, info.compr_info[i].decompr_sum); } return 1; }
1001-study-uboot
fs/jffs2/jffs2_1pass.c
C
gpl3
48,158
#ifndef jffs2_private_h #define jffs2_private_h #include <jffs2/jffs2.h> struct b_node { u32 offset; struct b_node *next; enum { CRC_UNKNOWN = 0, CRC_OK, CRC_BAD } datacrc; }; struct b_list { struct b_node *listTail; struct b_node *listHead; #ifdef CONFIG_SYS_JFFS2_SORT_FRAGMENTS struct b_node *listLast; int (*listCompare)(struct b_node *new, struct b_node *node); u32 listLoops; #endif u32 listCount; struct mem_block *listMemBase; }; struct b_lists { struct b_list dir; struct b_list frag; void *readbuf; }; struct b_compr_info { u32 num_frags; u32 compr_sum; u32 decompr_sum; }; struct b_jffs2_info { struct b_compr_info compr_info[JFFS2_NUM_COMPR]; }; static inline int hdr_crc(struct jffs2_unknown_node *node) { #if 1 u32 crc = crc32_no_comp(0, (unsigned char *)node, sizeof(struct jffs2_unknown_node) - 4); #else /* what's the semantics of this? why is this here? */ u32 crc = crc32_no_comp(~0, (unsigned char *)node, sizeof(struct jffs2_unknown_node) - 4); crc ^= ~0; #endif if (node->hdr_crc != crc) { return 0; } else { return 1; } } static inline int dirent_crc(struct jffs2_raw_dirent *node) { if (node->node_crc != crc32_no_comp(0, (unsigned char *)node, sizeof(struct jffs2_raw_dirent) - 8)) { return 0; } else { return 1; } } static inline int dirent_name_crc(struct jffs2_raw_dirent *node) { if (node->name_crc != crc32_no_comp(0, (unsigned char *)&(node->name), node->nsize)) { return 0; } else { return 1; } } static inline int inode_crc(struct jffs2_raw_inode *node) { if (node->node_crc != crc32_no_comp(0, (unsigned char *)node, sizeof(struct jffs2_raw_inode) - 8)) { return 0; } else { return 1; } } static inline int data_crc(struct jffs2_raw_inode *node) { if (node->data_crc != crc32_no_comp(0, (unsigned char *) ((int) &node->node_crc + sizeof (node->node_crc)), node->csize)) { return 0; } else { return 1; } } #endif /* jffs2_private.h */
1001-study-uboot
fs/jffs2/jffs2_private.h
C
gpl3
1,957
# # (C) Copyright 2000-2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk LIB = $(obj)libjffs2.o AOBJS = ifdef CONFIG_CMD_JFFS2 COBJS-$(CONFIG_JFFS2_LZO) += compr_lzo.o COBJS-y += compr_rtime.o COBJS-y += compr_rubin.o COBJS-y += compr_zlib.o COBJS-y += jffs2_1pass.o COBJS-y += mini_inflate.o endif COBJS := $(COBJS-y) SRCS := $(AOBJS:.o=.S) $(COBJS:.o=.c) OBJS := $(addprefix $(obj),$(AOBJS) $(COBJS)) #CPPFLAGS += all: $(LIB) $(AOBJS) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
fs/jffs2/Makefile
Makefile
gpl3
1,563
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2001 Red Hat, Inc. * * Created by David Woodhouse <dwmw2@cambridge.redhat.com> * * The original JFFS, from which the design for JFFS2 was derived, * was designed and implemented by Axis Communications AB. * * The contents of this file are subject to the Red Hat eCos Public * License Version 1.1 (the "Licence"); you may not use this file * except in compliance with the Licence. You may obtain a copy of * the Licence at http://www.redhat.com/ * * Software distributed under the Licence is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the Licence for the specific language governing rights and * limitations under the Licence. * * The Original Code is JFFS2 - Journalling Flash File System, version 2 * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License version 2 (the "GPL"), in * which case the provisions of the GPL are applicable instead of the * above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the RHEPL, indicate your decision by * deleting the provisions above and replace them with the notice and * other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file * under either the RHEPL or the GPL. * * $Id: compr_zlib.c,v 1.2 2002/01/24 22:58:42 rfeany Exp $ * */ #include <common.h> #include <config.h> #include <jffs2/jffs2.h> #include <jffs2/mini_inflate.h> long zlib_decompress(unsigned char *data_in, unsigned char *cpage_out, __u32 srclen, __u32 destlen) { return (decompress_block(cpage_out, data_in + 2, (void *) ldr_memcpy)); }
1001-study-uboot
fs/jffs2/compr_zlib.c
C
gpl3
1,865
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2004 Patrik Kluba, * University of Szeged, Hungary * * For licensing information, see the file 'LICENCE' in the * jffs2 directory. * * $Id: compr_lzo.c,v 1.3 2004/06/23 16:34:39 havasi Exp $ * */ /* LZO1X-1 (and -999) compression module for jffs2 based on the original LZO sources */ /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ /* Original copyright notice follows: lzo1x_9x.c -- implementation of the LZO1X-999 compression algorithm lzo_ptr.h -- low-level pointer constructs lzo_swd.ch -- sliding window dictionary lzoconf.h -- configuration for the LZO real-time data compression library lzo_mchw.ch -- matching functions using a window minilzo.c -- mini subset of the LZO real-time data compression library config1x.h -- configuration for the LZO1X algorithm lzo1x.h -- public interface of the LZO1X compression algorithm These files are part of the LZO real-time data compression library. Copyright (C) 1996-2002 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Markus F.X.J. Oberhumer <markus@oberhumer.com> */ /* 2004-02-16 pajko <pajko(AT)halom(DOT)u-szeged(DOT)hu> Initial release -removed all 16 bit code -all sensitive data will be on 4 byte boundary -removed check parts for library use -removed all but LZO1X-* compression */ #include <config.h> #include <linux/stddef.h> #include <jffs2/jffs2.h> #include <jffs2/compr_rubin.h> /* Integral types that have *exactly* the same number of bits as a lzo_voidp */ typedef unsigned long lzo_ptr_t; typedef long lzo_sptr_t; /* data type definitions */ #define U32 unsigned long #define S32 signed long #define I32 long #define U16 unsigned short #define S16 signed short #define I16 short #define U8 unsigned char #define S8 signed char #define I8 char #define M1_MAX_OFFSET 0x0400 #define M2_MAX_OFFSET 0x0800 #define M3_MAX_OFFSET 0x4000 #define M4_MAX_OFFSET 0xbfff #define __COPY4(dst,src) * (lzo_uint32p)(dst) = * (const lzo_uint32p)(src) #define COPY4(dst,src) __COPY4((lzo_ptr_t)(dst),(lzo_ptr_t)(src)) #define TEST_IP (ip < ip_end) #define TEST_OP (op <= op_end) #define NEED_IP(x) \ if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun #define NEED_OP(x) \ if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun #define TEST_LOOKBEHIND(m_pos,out) if (m_pos < out) goto lookbehind_overrun typedef U32 lzo_uint32; typedef I32 lzo_int32; typedef U32 lzo_uint; typedef I32 lzo_int; typedef int lzo_bool; #define lzo_byte U8 #define lzo_bytep U8 * #define lzo_charp char * #define lzo_voidp void * #define lzo_shortp short * #define lzo_ushortp unsigned short * #define lzo_uint32p lzo_uint32 * #define lzo_int32p lzo_int32 * #define lzo_uintp lzo_uint * #define lzo_intp lzo_int * #define lzo_voidpp lzo_voidp * #define lzo_bytepp lzo_bytep * #define lzo_sizeof_dict_t sizeof(lzo_bytep) #define LZO_E_OK 0 #define LZO_E_ERROR (-1) #define LZO_E_OUT_OF_MEMORY (-2) /* not used right now */ #define LZO_E_NOT_COMPRESSIBLE (-3) /* not used right now */ #define LZO_E_INPUT_OVERRUN (-4) #define LZO_E_OUTPUT_OVERRUN (-5) #define LZO_E_LOOKBEHIND_OVERRUN (-6) #define LZO_E_EOF_NOT_FOUND (-7) #define LZO_E_INPUT_NOT_CONSUMED (-8) #define PTR(a) ((lzo_ptr_t) (a)) #define PTR_LINEAR(a) PTR(a) #define PTR_ALIGNED_4(a) ((PTR_LINEAR(a) & 3) == 0) #define PTR_ALIGNED_8(a) ((PTR_LINEAR(a) & 7) == 0) #define PTR_ALIGNED2_4(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 3) == 0) #define PTR_ALIGNED2_8(a,b) (((PTR_LINEAR(a) | PTR_LINEAR(b)) & 7) == 0) #define PTR_LT(a,b) (PTR(a) < PTR(b)) #define PTR_GE(a,b) (PTR(a) >= PTR(b)) #define PTR_DIFF(a,b) ((lzo_ptrdiff_t) (PTR(a) - PTR(b))) #define pd(a,b) ((lzo_uint) ((a)-(b))) typedef ptrdiff_t lzo_ptrdiff_t; static int lzo1x_decompress (const lzo_byte * in, lzo_uint in_len, lzo_byte * out, lzo_uintp out_len, lzo_voidp wrkmem) { register lzo_byte *op; register const lzo_byte *ip; register lzo_uint t; register const lzo_byte *m_pos; const lzo_byte *const ip_end = in + in_len; lzo_byte *const op_end = out + *out_len; *out_len = 0; op = out; ip = in; if (*ip > 17) { t = *ip++ - 17; if (t < 4) goto match_next; NEED_OP (t); NEED_IP (t + 1); do *op++ = *ip++; while (--t > 0); goto first_literal_run; } while (TEST_IP && TEST_OP) { t = *ip++; if (t >= 16) goto match; if (t == 0) { NEED_IP (1); while (*ip == 0) { t += 255; ip++; NEED_IP (1); } t += 15 + *ip++; } NEED_OP (t + 3); NEED_IP (t + 4); if (PTR_ALIGNED2_4 (op, ip)) { COPY4 (op, ip); op += 4; ip += 4; if (--t > 0) { if (t >= 4) { do { COPY4 (op, ip); op += 4; ip += 4; t -= 4; } while (t >= 4); if (t > 0) do *op++ = *ip++; while (--t > 0); } else do *op++ = *ip++; while (--t > 0); } } else { *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; do *op++ = *ip++; while (--t > 0); } first_literal_run: t = *ip++; if (t >= 16) goto match; m_pos = op - (1 + M2_MAX_OFFSET); m_pos -= t >> 2; m_pos -= *ip++ << 2; TEST_LOOKBEHIND (m_pos, out); NEED_OP (3); *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; goto match_done; while (TEST_IP && TEST_OP) { match: if (t >= 64) { m_pos = op - 1; m_pos -= (t >> 2) & 7; m_pos -= *ip++ << 3; t = (t >> 5) - 1; TEST_LOOKBEHIND (m_pos, out); NEED_OP (t + 3 - 1); goto copy_match; } else if (t >= 32) { t &= 31; if (t == 0) { NEED_IP (1); while (*ip == 0) { t += 255; ip++; NEED_IP (1); } t += 31 + *ip++; } m_pos = op - 1; m_pos -= (ip[0] >> 2) + (ip[1] << 6); ip += 2; } else if (t >= 16) { m_pos = op; m_pos -= (t & 8) << 11; t &= 7; if (t == 0) { NEED_IP (1); while (*ip == 0) { t += 255; ip++; NEED_IP (1); } t += 7 + *ip++; } m_pos -= (ip[0] >> 2) + (ip[1] << 6); ip += 2; if (m_pos == op) goto eof_found; m_pos -= 0x4000; } else { m_pos = op - 1; m_pos -= t >> 2; m_pos -= *ip++ << 2; TEST_LOOKBEHIND (m_pos, out); NEED_OP (2); *op++ = *m_pos++; *op++ = *m_pos; goto match_done; } TEST_LOOKBEHIND (m_pos, out); NEED_OP (t + 3 - 1); if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4 (op, m_pos)) { COPY4 (op, m_pos); op += 4; m_pos += 4; t -= 4 - (3 - 1); do { COPY4 (op, m_pos); op += 4; m_pos += 4; t -= 4; } while (t >= 4); if (t > 0) do *op++ = *m_pos++; while (--t > 0); } else { copy_match: *op++ = *m_pos++; *op++ = *m_pos++; do *op++ = *m_pos++; while (--t > 0); } match_done: t = ip[-2] & 3; if (t == 0) break; match_next: NEED_OP (t); NEED_IP (t + 1); do *op++ = *ip++; while (--t > 0); t = *ip++; } } *out_len = op - out; return LZO_E_EOF_NOT_FOUND; eof_found: *out_len = op - out; return (ip == ip_end ? LZO_E_OK : (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); input_overrun: *out_len = op - out; return LZO_E_INPUT_OVERRUN; output_overrun: *out_len = op - out; return LZO_E_OUTPUT_OVERRUN; lookbehind_overrun: *out_len = op - out; return LZO_E_LOOKBEHIND_OVERRUN; } int lzo_decompress(unsigned char *data_in, unsigned char *cpage_out, u32 srclen, u32 destlen) { lzo_uint outlen = destlen; return lzo1x_decompress (data_in, srclen, cpage_out, &outlen, NULL); }
1001-study-uboot
fs/jffs2/compr_lzo.c
C
gpl3
8,646
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2001 Red Hat, Inc. * * Created by Arjan van de Ven <arjanv@redhat.com> * * The original JFFS, from which the design for JFFS2 was derived, * was designed and implemented by Axis Communications AB. * * The contents of this file are subject to the Red Hat eCos Public * License Version 1.1 (the "Licence"); you may not use this file * except in compliance with the Licence. You may obtain a copy of * the Licence at http://www.redhat.com/ * * Software distributed under the Licence is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the Licence for the specific language governing rights and * limitations under the Licence. * * The Original Code is JFFS2 - Journalling Flash File System, version 2 * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License version 2 (the "GPL"), in * which case the provisions of the GPL are applicable instead of the * above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the RHEPL, indicate your decision by * deleting the provisions above and replace them with the notice and * other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file * under either the RHEPL or the GPL. * * $Id: compr_rtime.c,v 1.2 2002/01/24 22:58:42 rfeany Exp $ * * * Very simple lz77-ish encoder. * * Theory of operation: Both encoder and decoder have a list of "last * occurances" for every possible source-value; after sending the * first source-byte, the second byte indicated the "run" length of * matches * * The algorithm is intended to only send "whole bytes", no bit-messing. * */ #include <config.h> #include <jffs2/jffs2.h> void rtime_decompress(unsigned char *data_in, unsigned char *cpage_out, u32 srclen, u32 destlen) { int positions[256]; int outpos; int pos; int i; outpos = pos = 0; for (i = 0; i < 256; positions[i++] = 0); while (outpos<destlen) { unsigned char value; int backoffs; int repeat; value = data_in[pos++]; cpage_out[outpos++] = value; /* first the verbatim copied byte */ repeat = data_in[pos++]; backoffs = positions[value]; positions[value]=outpos; if (repeat) { if (backoffs + repeat >= outpos) { while(repeat) { cpage_out[outpos++] = cpage_out[backoffs++]; repeat--; } } else { for (i = 0; i < repeat; i++) *(cpage_out + outpos + i) = *(cpage_out + backoffs + i); outpos+=repeat; } } } }
1001-study-uboot
fs/jffs2/compr_rtime.c
C
gpl3
2,720
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2001 Red Hat, Inc. * * Created by Arjan van de Ven <arjanv@redhat.com> * * Heavily modified by Russ Dill <Russ.Dill@asu.edu> in an attempt at * a little more speed. * * The original JFFS, from which the design for JFFS2 was derived, * was designed and implemented by Axis Communications AB. * * The contents of this file are subject to the Red Hat eCos Public * License Version 1.1 (the "Licence"); you may not use this file * except in compliance with the Licence. You may obtain a copy of * the Licence at http://www.redhat.com/ * * Software distributed under the Licence is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the Licence for the specific language governing rights and * limitations under the Licence. * * The Original Code is JFFS2 - Journalling Flash File System, version 2 * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License version 2 (the "GPL"), in * which case the provisions of the GPL are applicable instead of the * above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the RHEPL, indicate your decision by * deleting the provisions above and replace them with the notice and * other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file * under either the RHEPL or the GPL. * * $Id: compr_rubin.c,v 1.2 2002/01/24 22:58:42 rfeany Exp $ * */ #include <config.h> #include <jffs2/jffs2.h> #include <jffs2/compr_rubin.h> void rubin_do_decompress(unsigned char *bits, unsigned char *in, unsigned char *page_out, __u32 destlen) { register char *curr = (char *)page_out; char *end = (char *)(page_out + destlen); register unsigned long temp; register unsigned long result; register unsigned long p; register unsigned long q; register unsigned long rec_q; register unsigned long bit; register long i0; unsigned long i; /* init_pushpull */ temp = *(u32 *) in; bit = 16; /* init_rubin */ q = 0; p = (long) (2 * UPPER_BIT_RUBIN); /* init_decode */ rec_q = (in[0] << 8) | in[1]; while (curr < end) { /* in byte */ result = 0; for (i = 0; i < 8; i++) { /* decode */ while ((q & UPPER_BIT_RUBIN) || ((p + q) <= UPPER_BIT_RUBIN)) { q &= ~UPPER_BIT_RUBIN; q <<= 1; p <<= 1; rec_q &= ~UPPER_BIT_RUBIN; rec_q <<= 1; rec_q |= (temp >> (bit++ ^ 7)) & 1; if (bit > 31) { u32 *p = (u32 *)in; bit = 0; temp = *(++p); in = (unsigned char *)p; } } i0 = (bits[i] * p) >> 8; if (i0 <= 0) i0 = 1; /* if it fails, it fails, we have our crc if (i0 >= p) i0 = p - 1; */ result >>= 1; if (rec_q < q + i0) { /* result |= 0x00; */ p = i0; } else { result |= 0x80; p -= i0; q += i0; } } *(curr++) = result; } } void dynrubin_decompress(unsigned char *data_in, unsigned char *cpage_out, unsigned long sourcelen, unsigned long dstlen) { unsigned char bits[8]; int c; for (c=0; c<8; c++) bits[c] = (256 - data_in[c]); rubin_do_decompress(bits, data_in+8, cpage_out, dstlen); }
1001-study-uboot
fs/jffs2/compr_rubin.c
C
gpl3
3,330
#ifndef jffs2_private_h #define jffs2_private_h #include <jffs2/jffs2.h> struct b_node { struct b_node *next; }; struct b_inode { struct b_inode *next; u32 offset; /* physical offset to beginning of real inode */ u32 version; u32 ino; u32 isize; u32 csize; }; struct b_dirent { struct b_dirent *next; u32 offset; /* physical offset to beginning of real dirent */ u32 version; u32 pino; u32 ino; unsigned int nhash; unsigned char nsize; unsigned char type; }; struct b_list { struct b_node *listTail; struct b_node *listHead; unsigned int listCount; struct mem_block *listMemBase; }; struct b_lists { char *partOffset; struct b_list dir; struct b_list frag; }; struct b_compr_info { u32 num_frags; u32 compr_sum; u32 decompr_sum; }; struct b_jffs2_info { struct b_compr_info compr_info[JFFS2_NUM_COMPR]; }; static inline int hdr_crc(struct jffs2_unknown_node *node) { #if 1 u32 crc = crc32_no_comp(0, (unsigned char *)node, sizeof(struct jffs2_unknown_node) - 4); #else /* what's the semantics of this? why is this here? */ u32 crc = crc32_no_comp(~0, (unsigned char *)node, sizeof(struct jffs2_unknown_node) - 4); crc ^= ~0; #endif if (node->hdr_crc != crc) { return 0; } else { return 1; } } static inline int dirent_crc(struct jffs2_raw_dirent *node) { if (node->node_crc != crc32_no_comp(0, (unsigned char *)node, sizeof(struct jffs2_raw_dirent) - 8)) { return 0; } else { return 1; } } static inline int dirent_name_crc(struct jffs2_raw_dirent *node) { if (node->name_crc != crc32_no_comp(0, (unsigned char *)&(node->name), node->nsize)) { return 0; } else { return 1; } } static inline int inode_crc(struct jffs2_raw_inode *node) { if (node->node_crc != crc32_no_comp(0, (unsigned char *)node, sizeof(struct jffs2_raw_inode) - 8)) { return 0; } else { return 1; } } /* Borrowed from include/linux/dcache.h */ /* Name hashing routines. Initial hash value */ /* Hash courtesy of the R5 hash in reiserfs modulo sign bits */ #define init_name_hash() 0 /* partial hash update function. Assume roughly 4 bits per character */ static inline unsigned long partial_name_hash(unsigned long c, unsigned long prevhash) { return (prevhash + (c << 4) + (c >> 4)) * 11; } /* * Finally: cut down the number of bits to a int value (and try to avoid * losing bits) */ static inline unsigned long end_name_hash(unsigned long hash) { return (unsigned int) hash; } /* Compute the hash for a name string. */ static inline unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long hash = init_name_hash(); while (len--) hash = partial_name_hash(*name++, hash); return end_name_hash(hash); } #endif /* jffs2_private.h */
1001-study-uboot
fs/jffs2/jffs2_nand_private.h
C
gpl3
2,721
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright © 2004 Ferenc Havasi <havasi@inf.u-szeged.hu>, * Zoltan Sogor <weth@inf.u-szeged.hu>, * Patrik Kluba <pajko@halom.u-szeged.hu>, * University of Szeged, Hungary * * For licensing information, see the file 'LICENCE' in this directory. * */ #ifndef JFFS2_SUMMARY_H #define JFFS2_SUMMARY_H #define BLK_STATE_ALLFF 0 #define BLK_STATE_CLEAN 1 #define BLK_STATE_PARTDIRTY 2 #define BLK_STATE_CLEANMARKER 3 #define BLK_STATE_ALLDIRTY 4 #define BLK_STATE_BADBLOCK 5 #define JFFS2_SUMMARY_NOSUM_SIZE 0xffffffff #define JFFS2_SUMMARY_INODE_SIZE (sizeof(struct jffs2_sum_inode_flash)) #define JFFS2_SUMMARY_DIRENT_SIZE(x) (sizeof(struct jffs2_sum_dirent_flash) + (x)) #define JFFS2_SUMMARY_XATTR_SIZE (sizeof(struct jffs2_sum_xattr_flash)) #define JFFS2_SUMMARY_XREF_SIZE (sizeof(struct jffs2_sum_xref_flash)) /* Summary structures used on flash */ struct jffs2_sum_unknown_flash { __u16 nodetype; /* node type */ }; struct jffs2_sum_inode_flash { __u16 nodetype; /* node type */ __u32 inode; /* inode number */ __u32 version; /* inode version */ __u32 offset; /* offset on jeb */ __u32 totlen; /* record length */ } __attribute__((packed)); struct jffs2_sum_dirent_flash { __u16 nodetype; /* == JFFS_NODETYPE_DIRENT */ __u32 totlen; /* record length */ __u32 offset; /* offset on jeb */ __u32 pino; /* parent inode */ __u32 version; /* dirent version */ __u32 ino; /* == zero for unlink */ uint8_t nsize; /* dirent name size */ uint8_t type; /* dirent type */ uint8_t name[0]; /* dirent name */ } __attribute__((packed)); struct jffs2_sum_xattr_flash { __u16 nodetype; /* == JFFS2_NODETYPE_XATR */ __u32 xid; /* xattr identifier */ __u32 version; /* version number */ __u32 offset; /* offset on jeb */ __u32 totlen; /* node length */ } __attribute__((packed)); struct jffs2_sum_xref_flash { __u16 nodetype; /* == JFFS2_NODETYPE_XREF */ __u32 offset; /* offset on jeb */ } __attribute__((packed)); union jffs2_sum_flash { struct jffs2_sum_unknown_flash u; struct jffs2_sum_inode_flash i; struct jffs2_sum_dirent_flash d; struct jffs2_sum_xattr_flash x; struct jffs2_sum_xref_flash r; }; /* Summary structures used in the memory */ struct jffs2_sum_unknown_mem { union jffs2_sum_mem *next; __u16 nodetype; /* node type */ }; struct jffs2_sum_inode_mem { union jffs2_sum_mem *next; __u16 nodetype; /* node type */ __u32 inode; /* inode number */ __u32 version; /* inode version */ __u32 offset; /* offset on jeb */ __u32 totlen; /* record length */ } __attribute__((packed)); struct jffs2_sum_dirent_mem { union jffs2_sum_mem *next; __u16 nodetype; /* == JFFS_NODETYPE_DIRENT */ __u32 totlen; /* record length */ __u32 offset; /* ofset on jeb */ __u32 pino; /* parent inode */ __u32 version; /* dirent version */ __u32 ino; /* == zero for unlink */ uint8_t nsize; /* dirent name size */ uint8_t type; /* dirent type */ uint8_t name[0]; /* dirent name */ } __attribute__((packed)); struct jffs2_sum_xattr_mem { union jffs2_sum_mem *next; __u16 nodetype; __u32 xid; __u32 version; __u32 offset; __u32 totlen; } __attribute__((packed)); struct jffs2_sum_xref_mem { union jffs2_sum_mem *next; __u16 nodetype; __u32 offset; } __attribute__((packed)); union jffs2_sum_mem { struct jffs2_sum_unknown_mem u; struct jffs2_sum_inode_mem i; struct jffs2_sum_dirent_mem d; struct jffs2_sum_xattr_mem x; struct jffs2_sum_xref_mem r; }; /* Summary related information stored in superblock */ struct jffs2_summary { uint32_t sum_size; /* collected summary information for nextblock */ uint32_t sum_num; uint32_t sum_padded; union jffs2_sum_mem *sum_list_head; union jffs2_sum_mem *sum_list_tail; __u32 *sum_buf; /* buffer for writing out summary */ }; /* Summary marker is stored at the end of every sumarized erase block */ struct jffs2_sum_marker { __u32 offset; /* offset of the summary node in the jeb */ __u32 magic; /* == JFFS2_SUM_MAGIC */ }; #define JFFS2_SUMMARY_FRAME_SIZE (sizeof(struct jffs2_raw_summary) + sizeof(struct jffs2_sum_marker)) #endif /* JFFS2_SUMMARY_H */
1001-study-uboot
fs/jffs2/summary.h
C
gpl3
4,167
# # (C) Copyright 2000-2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # # subdirs-$(CONFIG_CMD_CRAMFS) := cramfs subdirs-$(CONFIG_CMD_EXT2) += ext2 subdirs-$(CONFIG_CMD_FAT) += fat subdirs-$(CONFIG_CMD_FDOS) += fdos subdirs-$(CONFIG_CMD_JFFS2) += jffs2 subdirs-$(CONFIG_CMD_REISER) += reiserfs subdirs-$(CONFIG_YAFFS2) += yaffs2 subdirs-$(CONFIG_CMD_UBIFS) += ubifs SUBDIRS := $(subdirs-y) $(obj).depend all: @for dir in $(SUBDIRS) ; do \ $(MAKE) -C $$dir $@ ; done
1001-study-uboot
fs/Makefile
Makefile
gpl3
1,263
/* * Copyright 2000-2002 by Hans Reiser, licensing governed by reiserfs/README * * GRUB -- GRand Unified Bootloader * Copyright (C) 2000, 2001 Free Software Foundation, Inc. * * (C) Copyright 2003 - 2004 * Sysgo AG, <www.elinos.com>, Pavel Bartusek <pba@sysgo.com> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* An implementation for the ReiserFS filesystem ported from GRUB. * Some parts of this code (mainly the structures and defines) are * from the original reiser fs code, as found in the linux kernel. */ #include <common.h> #include <malloc.h> #include <linux/ctype.h> #include <linux/time.h> #include <asm/byteorder.h> #include <reiserfs.h> #include "reiserfs_private.h" #undef REISERDEBUG /* Some parts of this code (mainly the structures and defines) are * from the original reiser fs code, as found in the linux kernel. */ static char fsys_buf[FSYS_BUFLEN]; static reiserfs_error_t errnum = ERR_NONE; static int print_possibilities; static unsigned int filepos, filemax; static int substring (const char *s1, const char *s2) { while (*s1 == *s2) { /* The strings match exactly. */ if (! *(s1++)) return 0; s2 ++; } /* S1 is a substring of S2. */ if (*s1 == 0) return -1; /* S1 isn't a substring. */ return 1; } static void sd_print_item (struct item_head * ih, char * item) { char filetime[30]; time_t ttime; if (stat_data_v1 (ih)) { struct stat_data_v1 * sd = (struct stat_data_v1 *)item; ttime = sd_v1_mtime(sd); ctime_r(&ttime, filetime); printf ("%-10s %4hd %6d %6d %9d %24.24s", bb_mode_string(sd_v1_mode(sd)), sd_v1_nlink(sd),sd_v1_uid(sd), sd_v1_gid(sd), sd_v1_size(sd), filetime); } else { struct stat_data * sd = (struct stat_data *)item; ttime = sd_v2_mtime(sd); ctime_r(&ttime, filetime); printf ("%-10s %4d %6d %6d %9d %24.24s", bb_mode_string(sd_v2_mode(sd)), sd_v2_nlink(sd),sd_v2_uid(sd),sd_v2_gid(sd), (__u32) sd_v2_size(sd), filetime); } } static int journal_read (int block, int len, char *buffer) { return reiserfs_devread ((INFO->journal_block + block) << INFO->blocksize_shift, 0, len, buffer); } /* Read a block from ReiserFS file system, taking the journal into * account. If the block nr is in the journal, the block from the * journal taken. */ static int block_read (unsigned int blockNr, int start, int len, char *buffer) { int transactions = INFO->journal_transactions; int desc_block = INFO->journal_first_desc; int journal_mask = INFO->journal_block_count - 1; int translatedNr = blockNr; __u32 *journal_table = JOURNAL_START; while (transactions-- > 0) { int i = 0; int j_len; if (__le32_to_cpu(*journal_table) != 0xffffffff) { /* Search for the blockNr in cached journal */ j_len = __le32_to_cpu(*journal_table++); while (i++ < j_len) { if (__le32_to_cpu(*journal_table++) == blockNr) { journal_table += j_len - i; goto found; } } } else { /* This is the end of cached journal marker. The remaining * transactions are still on disk. */ struct reiserfs_journal_desc desc; struct reiserfs_journal_commit commit; if (! journal_read (desc_block, sizeof (desc), (char *) &desc)) return 0; j_len = __le32_to_cpu(desc.j_len); while (i < j_len && i < JOURNAL_TRANS_HALF) if (__le32_to_cpu(desc.j_realblock[i++]) == blockNr) goto found; if (j_len >= JOURNAL_TRANS_HALF) { int commit_block = (desc_block + 1 + j_len) & journal_mask; if (! journal_read (commit_block, sizeof (commit), (char *) &commit)) return 0; while (i < j_len) if (__le32_to_cpu(commit.j_realblock[i++ - JOURNAL_TRANS_HALF]) == blockNr) goto found; } } goto not_found; found: translatedNr = INFO->journal_block + ((desc_block + i) & journal_mask); #ifdef REISERDEBUG printf ("block_read: block %d is mapped to journal block %d.\n", blockNr, translatedNr - INFO->journal_block); #endif /* We must continue the search, as this block may be overwritten * in later transactions. */ not_found: desc_block = (desc_block + 2 + j_len) & journal_mask; } return reiserfs_devread (translatedNr << INFO->blocksize_shift, start, len, buffer); } /* Init the journal data structure. We try to cache as much as * possible in the JOURNAL_START-JOURNAL_END space, but if it is full * we can still read the rest from the disk on demand. * * The first number of valid transactions and the descriptor block of the * first valid transaction are held in INFO. The transactions are all * adjacent, but we must take care of the journal wrap around. */ static int journal_init (void) { unsigned int block_count = INFO->journal_block_count; unsigned int desc_block; unsigned int commit_block; unsigned int next_trans_id; struct reiserfs_journal_header header; struct reiserfs_journal_desc desc; struct reiserfs_journal_commit commit; __u32 *journal_table = JOURNAL_START; journal_read (block_count, sizeof (header), (char *) &header); desc_block = __le32_to_cpu(header.j_first_unflushed_offset); if (desc_block >= block_count) return 0; INFO->journal_first_desc = desc_block; next_trans_id = __le32_to_cpu(header.j_last_flush_trans_id) + 1; #ifdef REISERDEBUG printf ("journal_init: last flushed %d\n", __le32_to_cpu(header.j_last_flush_trans_id)); #endif while (1) { journal_read (desc_block, sizeof (desc), (char *) &desc); if (substring (JOURNAL_DESC_MAGIC, desc.j_magic) > 0 || __le32_to_cpu(desc.j_trans_id) != next_trans_id || __le32_to_cpu(desc.j_mount_id) != __le32_to_cpu(header.j_mount_id)) /* no more valid transactions */ break; commit_block = (desc_block + __le32_to_cpu(desc.j_len) + 1) & (block_count - 1); journal_read (commit_block, sizeof (commit), (char *) &commit); if (__le32_to_cpu(desc.j_trans_id) != commit.j_trans_id || __le32_to_cpu(desc.j_len) != __le32_to_cpu(commit.j_len)) /* no more valid transactions */ break; #ifdef REISERDEBUG printf ("Found valid transaction %d/%d at %d.\n", __le32_to_cpu(desc.j_trans_id), __le32_to_cpu(desc.j_mount_id), desc_block); #endif next_trans_id++; if (journal_table < JOURNAL_END) { if ((journal_table + 1 + __le32_to_cpu(desc.j_len)) >= JOURNAL_END) { /* The table is almost full; mark the end of the cached * journal.*/ *journal_table = __cpu_to_le32(0xffffffff); journal_table = JOURNAL_END; } else { unsigned int i; /* Cache the length and the realblock numbers in the table. * The block number of descriptor can easily be computed. * and need not to be stored here. */ /* both are in the little endian format */ *journal_table++ = desc.j_len; for (i = 0; i < __le32_to_cpu(desc.j_len) && i < JOURNAL_TRANS_HALF; i++) { /* both are in the little endian format */ *journal_table++ = desc.j_realblock[i]; #ifdef REISERDEBUG printf ("block %d is in journal %d.\n", __le32_to_cpu(desc.j_realblock[i]), desc_block); #endif } for ( ; i < __le32_to_cpu(desc.j_len); i++) { /* both are in the little endian format */ *journal_table++ = commit.j_realblock[i-JOURNAL_TRANS_HALF]; #ifdef REISERDEBUG printf ("block %d is in journal %d.\n", __le32_to_cpu(commit.j_realblock[i-JOURNAL_TRANS_HALF]), desc_block); #endif } } } desc_block = (commit_block + 1) & (block_count - 1); } #ifdef REISERDEBUG printf ("Transaction %d/%d at %d isn't valid.\n", __le32_to_cpu(desc.j_trans_id), __le32_to_cpu(desc.j_mount_id), desc_block); #endif INFO->journal_transactions = next_trans_id - __le32_to_cpu(header.j_last_flush_trans_id) - 1; return errnum == 0; } /* check filesystem types and read superblock into memory buffer */ int reiserfs_mount (unsigned part_length) { struct reiserfs_super_block super; int superblock = REISERFS_DISK_OFFSET_IN_BYTES >> SECTOR_BITS; char *cache; if (part_length < superblock + (sizeof (super) >> SECTOR_BITS) || ! reiserfs_devread (superblock, 0, sizeof (struct reiserfs_super_block), (char *) &super) || (substring (REISER3FS_SUPER_MAGIC_STRING, super.s_magic) > 0 && substring (REISER2FS_SUPER_MAGIC_STRING, super.s_magic) > 0 && substring (REISERFS_SUPER_MAGIC_STRING, super.s_magic) > 0) || (/* check that this is not a copy inside the journal log */ sb_journal_block(&super) * sb_blocksize(&super) <= REISERFS_DISK_OFFSET_IN_BYTES)) { /* Try old super block position */ superblock = REISERFS_OLD_DISK_OFFSET_IN_BYTES >> SECTOR_BITS; if (part_length < superblock + (sizeof (super) >> SECTOR_BITS) || ! reiserfs_devread (superblock, 0, sizeof (struct reiserfs_super_block), (char *) &super)) return 0; if (substring (REISER2FS_SUPER_MAGIC_STRING, super.s_magic) > 0 && substring (REISERFS_SUPER_MAGIC_STRING, super.s_magic) > 0) { /* pre journaling super block ? */ if (substring (REISERFS_SUPER_MAGIC_STRING, (char*) ((int) &super + 20)) > 0) return 0; set_sb_blocksize(&super, REISERFS_OLD_BLOCKSIZE); set_sb_journal_block(&super, 0); set_sb_version(&super, 0); } } /* check the version number. */ if (sb_version(&super) > REISERFS_MAX_SUPPORTED_VERSION) return 0; INFO->version = sb_version(&super); INFO->blocksize = sb_blocksize(&super); INFO->fullblocksize_shift = log2 (sb_blocksize(&super)); INFO->blocksize_shift = INFO->fullblocksize_shift - SECTOR_BITS; INFO->cached_slots = (FSYSREISER_CACHE_SIZE >> INFO->fullblocksize_shift) - 1; #ifdef REISERDEBUG printf ("reiserfs_mount: version=%d, blocksize=%d\n", INFO->version, INFO->blocksize); #endif /* REISERDEBUG */ /* Clear node cache. */ memset (INFO->blocks, 0, sizeof (INFO->blocks)); if (sb_blocksize(&super) < FSYSREISER_MIN_BLOCKSIZE || sb_blocksize(&super) > FSYSREISER_MAX_BLOCKSIZE || (SECTOR_SIZE << INFO->blocksize_shift) != sb_blocksize(&super)) return 0; /* Initialize journal code. If something fails we end with zero * journal_transactions, so we don't access the journal at all. */ INFO->journal_transactions = 0; if (sb_journal_block(&super) != 0 && super.s_journal_dev == 0) { INFO->journal_block = sb_journal_block(&super); INFO->journal_block_count = sb_journal_size(&super); if (is_power_of_two (INFO->journal_block_count)) journal_init (); /* Read in super block again, maybe it is in the journal */ block_read (superblock >> INFO->blocksize_shift, 0, sizeof (struct reiserfs_super_block), (char *) &super); } if (! block_read (sb_root_block(&super), 0, INFO->blocksize, (char*) ROOT)) return 0; cache = ROOT; INFO->tree_depth = __le16_to_cpu(BLOCKHEAD (cache)->blk_level); #ifdef REISERDEBUG printf ("root read_in: block=%d, depth=%d\n", sb_root_block(&super), INFO->tree_depth); #endif /* REISERDEBUG */ if (INFO->tree_depth >= MAX_HEIGHT) return 0; if (INFO->tree_depth == DISK_LEAF_NODE_LEVEL) { /* There is only one node in the whole filesystem, * which is simultanously leaf and root */ memcpy (LEAF, ROOT, INFO->blocksize); } return 1; } /***************** TREE ACCESSING METHODS *****************************/ /* I assume you are familiar with the ReiserFS tree, if not go to * http://www.namesys.com/content_table.html * * My tree node cache is organized as following * 0 ROOT node * 1 LEAF node (if the ROOT is also a LEAF it is copied here * 2-n other nodes on current path from bottom to top. * if there is not enough space in the cache, the top most are * omitted. * * I have only two methods to find a key in the tree: * search_stat(dir_id, objectid) searches for the stat entry (always * the first entry) of an object. * next_key() gets the next key in tree order. * * This means, that I can only sequential reads of files are * efficient, but this really doesn't hurt for grub. */ /* Read in the node at the current path and depth into the node cache. * You must set INFO->blocks[depth] before. */ static char * read_tree_node (unsigned int blockNr, int depth) { char* cache = CACHE(depth); int num_cached = INFO->cached_slots; if (depth < num_cached) { /* This is the cached part of the path. Check if same block is * needed. */ if (blockNr == INFO->blocks[depth]) return cache; } else cache = CACHE(num_cached); #ifdef REISERDEBUG printf (" next read_in: block=%d (depth=%d)\n", blockNr, depth); #endif /* REISERDEBUG */ if (! block_read (blockNr, 0, INFO->blocksize, cache)) return 0; /* Make sure it has the right node level */ if (__le16_to_cpu(BLOCKHEAD (cache)->blk_level) != depth) { errnum = ERR_FSYS_CORRUPT; return 0; } INFO->blocks[depth] = blockNr; return cache; } /* Get the next key, i.e. the key following the last retrieved key in * tree order. INFO->current_ih and * INFO->current_info are adapted accordingly. */ static int next_key (void) { int depth; struct item_head *ih = INFO->current_ih + 1; char *cache; #ifdef REISERDEBUG printf ("next_key:\n old ih: key %d:%d:%d:%d version:%d\n", __le32_to_cpu(INFO->current_ih->ih_key.k_dir_id), __le32_to_cpu(INFO->current_ih->ih_key.k_objectid), __le32_to_cpu(INFO->current_ih->ih_key.u.v1.k_offset), __le32_to_cpu(INFO->current_ih->ih_key.u.v1.k_uniqueness), __le16_to_cpu(INFO->current_ih->ih_version)); #endif /* REISERDEBUG */ if (ih == &ITEMHEAD[__le16_to_cpu(BLOCKHEAD (LEAF)->blk_nr_item)]) { depth = DISK_LEAF_NODE_LEVEL; /* The last item, was the last in the leaf node. * Read in the next block */ do { if (depth == INFO->tree_depth) { /* There are no more keys at all. * Return a dummy item with MAX_KEY */ ih = (struct item_head *) &BLOCKHEAD (LEAF)->blk_right_delim_key; goto found; } depth++; #ifdef REISERDEBUG printf (" depth=%d, i=%d\n", depth, INFO->next_key_nr[depth]); #endif /* REISERDEBUG */ } while (INFO->next_key_nr[depth] == 0); if (depth == INFO->tree_depth) cache = ROOT; else if (depth <= INFO->cached_slots) cache = CACHE (depth); else { cache = read_tree_node (INFO->blocks[depth], depth); if (! cache) return 0; } do { int nr_item = __le16_to_cpu(BLOCKHEAD (cache)->blk_nr_item); int key_nr = INFO->next_key_nr[depth]++; #ifdef REISERDEBUG printf (" depth=%d, i=%d/%d\n", depth, key_nr, nr_item); #endif /* REISERDEBUG */ if (key_nr == nr_item) /* This is the last item in this block, set the next_key_nr to 0 */ INFO->next_key_nr[depth] = 0; cache = read_tree_node (dc_block_number(&(DC (cache)[key_nr])), --depth); if (! cache) return 0; } while (depth > DISK_LEAF_NODE_LEVEL); ih = ITEMHEAD; } found: INFO->current_ih = ih; INFO->current_item = &LEAF[__le16_to_cpu(ih->ih_item_location)]; #ifdef REISERDEBUG printf (" new ih: key %d:%d:%d:%d version:%d\n", __le32_to_cpu(INFO->current_ih->ih_key.k_dir_id), __le32_to_cpu(INFO->current_ih->ih_key.k_objectid), __le32_to_cpu(INFO->current_ih->ih_key.u.v1.k_offset), __le32_to_cpu(INFO->current_ih->ih_key.u.v1.k_uniqueness), __le16_to_cpu(INFO->current_ih->ih_version)); #endif /* REISERDEBUG */ return 1; } /* preconditions: reiserfs_mount already executed, therefore * INFO block is valid * returns: 0 if error (errnum is set), * nonzero iff we were able to find the key successfully. * postconditions: on a nonzero return, the current_ih and * current_item fields describe the key that equals the * searched key. INFO->next_key contains the next key after * the searched key. * side effects: messes around with the cache. */ static int search_stat (__u32 dir_id, __u32 objectid) { char *cache; int depth; int nr_item; int i; struct item_head *ih; #ifdef REISERDEBUG printf ("search_stat:\n key %d:%d:0:0\n", dir_id, objectid); #endif /* REISERDEBUG */ depth = INFO->tree_depth; cache = ROOT; while (depth > DISK_LEAF_NODE_LEVEL) { struct key *key; nr_item = __le16_to_cpu(BLOCKHEAD (cache)->blk_nr_item); key = KEY (cache); for (i = 0; i < nr_item; i++) { if (__le32_to_cpu(key->k_dir_id) > dir_id || (__le32_to_cpu(key->k_dir_id) == dir_id && (__le32_to_cpu(key->k_objectid) > objectid || (__le32_to_cpu(key->k_objectid) == objectid && (__le32_to_cpu(key->u.v1.k_offset) | __le32_to_cpu(key->u.v1.k_uniqueness)) > 0)))) break; key++; } #ifdef REISERDEBUG printf (" depth=%d, i=%d/%d\n", depth, i, nr_item); #endif /* REISERDEBUG */ INFO->next_key_nr[depth] = (i == nr_item) ? 0 : i+1; cache = read_tree_node (dc_block_number(&(DC (cache)[i])), --depth); if (! cache) return 0; } /* cache == LEAF */ nr_item = __le16_to_cpu(BLOCKHEAD (LEAF)->blk_nr_item); ih = ITEMHEAD; for (i = 0; i < nr_item; i++) { if (__le32_to_cpu(ih->ih_key.k_dir_id) == dir_id && __le32_to_cpu(ih->ih_key.k_objectid) == objectid && __le32_to_cpu(ih->ih_key.u.v1.k_offset) == 0 && __le32_to_cpu(ih->ih_key.u.v1.k_uniqueness) == 0) { #ifdef REISERDEBUG printf (" depth=%d, i=%d/%d\n", depth, i, nr_item); #endif /* REISERDEBUG */ INFO->current_ih = ih; INFO->current_item = &LEAF[__le16_to_cpu(ih->ih_item_location)]; return 1; } ih++; } errnum = ERR_FSYS_CORRUPT; return 0; } int reiserfs_read (char *buf, unsigned len) { unsigned int blocksize; unsigned int offset; unsigned int to_read; char *prev_buf = buf; #ifdef REISERDEBUG printf ("reiserfs_read: filepos=%d len=%d, offset=%Lx\n", filepos, len, (__u64) IH_KEY_OFFSET (INFO->current_ih) - 1); #endif /* REISERDEBUG */ if (__le32_to_cpu(INFO->current_ih->ih_key.k_objectid) != INFO->fileinfo.k_objectid || IH_KEY_OFFSET (INFO->current_ih) > filepos + 1) { search_stat (INFO->fileinfo.k_dir_id, INFO->fileinfo.k_objectid); goto get_next_key; } while (! errnum) { if (__le32_to_cpu(INFO->current_ih->ih_key.k_objectid) != INFO->fileinfo.k_objectid) { break; } offset = filepos - IH_KEY_OFFSET (INFO->current_ih) + 1; blocksize = __le16_to_cpu(INFO->current_ih->ih_item_len); #ifdef REISERDEBUG printf (" loop: filepos=%d len=%d, offset=%d blocksize=%d\n", filepos, len, offset, blocksize); #endif /* REISERDEBUG */ if (IH_KEY_ISTYPE(INFO->current_ih, TYPE_DIRECT) && offset < blocksize) { #ifdef REISERDEBUG printf ("direct_read: offset=%d, blocksize=%d\n", offset, blocksize); #endif /* REISERDEBUG */ to_read = blocksize - offset; if (to_read > len) to_read = len; memcpy (buf, INFO->current_item + offset, to_read); goto update_buf_len; } else if (IH_KEY_ISTYPE(INFO->current_ih, TYPE_INDIRECT)) { blocksize = (blocksize >> 2) << INFO->fullblocksize_shift; #ifdef REISERDEBUG printf ("indirect_read: offset=%d, blocksize=%d\n", offset, blocksize); #endif /* REISERDEBUG */ while (offset < blocksize) { __u32 blocknr = __le32_to_cpu(((__u32 *) INFO->current_item) [offset >> INFO->fullblocksize_shift]); int blk_offset = offset & (INFO->blocksize-1); to_read = INFO->blocksize - blk_offset; if (to_read > len) to_read = len; /* Journal is only for meta data. Data blocks can be read * directly without using block_read */ reiserfs_devread (blocknr << INFO->blocksize_shift, blk_offset, to_read, buf); update_buf_len: len -= to_read; buf += to_read; offset += to_read; filepos += to_read; if (len == 0) goto done; } } get_next_key: next_key (); } done: return errnum ? 0 : buf - prev_buf; } /* preconditions: reiserfs_mount already executed, therefore * INFO block is valid * returns: 0 if error, nonzero iff we were able to find the file successfully * postconditions: on a nonzero return, INFO->fileinfo contains the info * of the file we were trying to look up, filepos is 0 and filemax is * the size of the file. */ static int reiserfs_dir (char *dirname) { struct reiserfs_de_head *de_head; char *rest, ch; __u32 dir_id, objectid, parent_dir_id = 0, parent_objectid = 0; #ifndef STAGE1_5 int do_possibilities = 0; #endif /* ! STAGE1_5 */ char linkbuf[PATH_MAX]; /* buffer for following symbolic links */ int link_count = 0; int mode; dir_id = REISERFS_ROOT_PARENT_OBJECTID; objectid = REISERFS_ROOT_OBJECTID; while (1) { #ifdef REISERDEBUG printf ("dirname=%s\n", dirname); #endif /* REISERDEBUG */ /* Search for the stat info first. */ if (! search_stat (dir_id, objectid)) return 0; #ifdef REISERDEBUG printf ("sd_mode=%x sd_size=%d\n", stat_data_v1(INFO->current_ih) ? sd_v1_mode((struct stat_data_v1 *) INFO->current_item) : sd_v2_mode((struct stat_data *) (INFO->current_item)), stat_data_v1(INFO->current_ih) ? sd_v1_size((struct stat_data_v1 *) INFO->current_item) : sd_v2_size((struct stat_data *) INFO->current_item) ); #endif /* REISERDEBUG */ mode = stat_data_v1(INFO->current_ih) ? sd_v1_mode((struct stat_data_v1 *) INFO->current_item) : sd_v2_mode((struct stat_data *) INFO->current_item); /* If we've got a symbolic link, then chase it. */ if (S_ISLNK (mode)) { unsigned int len; if (++link_count > MAX_LINK_COUNT) { errnum = ERR_SYMLINK_LOOP; return 0; } /* Get the symlink size. */ filemax = stat_data_v1(INFO->current_ih) ? sd_v1_size((struct stat_data_v1 *) INFO->current_item) : sd_v2_size((struct stat_data *) INFO->current_item); /* Find out how long our remaining name is. */ len = 0; while (dirname[len] && !isspace (dirname[len])) len++; if (filemax + len > sizeof (linkbuf) - 1) { errnum = ERR_FILELENGTH; return 0; } /* Copy the remaining name to the end of the symlink data. Note that DIRNAME and LINKBUF may overlap! */ memmove (linkbuf + filemax, dirname, len+1); INFO->fileinfo.k_dir_id = dir_id; INFO->fileinfo.k_objectid = objectid; filepos = 0; if (! next_key () || reiserfs_read (linkbuf, filemax) != filemax) { if (! errnum) errnum = ERR_FSYS_CORRUPT; return 0; } #ifdef REISERDEBUG printf ("symlink=%s\n", linkbuf); #endif /* REISERDEBUG */ dirname = linkbuf; if (*dirname == '/') { /* It's an absolute link, so look it up in root. */ dir_id = REISERFS_ROOT_PARENT_OBJECTID; objectid = REISERFS_ROOT_OBJECTID; } else { /* Relative, so look it up in our parent directory. */ dir_id = parent_dir_id; objectid = parent_objectid; } /* Now lookup the new name. */ continue; } /* if we have a real file (and we're not just printing possibilities), then this is where we want to exit */ if (! *dirname || isspace (*dirname)) { if (! S_ISREG (mode)) { errnum = ERR_BAD_FILETYPE; return 0; } filepos = 0; filemax = stat_data_v1(INFO->current_ih) ? sd_v1_size((struct stat_data_v1 *) INFO->current_item) : sd_v2_size((struct stat_data *) INFO->current_item); #if 0 /* If this is a new stat data and size is > 4GB set filemax to * maximum */ if (__le16_to_cpu(INFO->current_ih->ih_version) == ITEM_VERSION_2 && sd_size_hi((struct stat_data *) INFO->current_item) > 0) filemax = 0xffffffff; #endif INFO->fileinfo.k_dir_id = dir_id; INFO->fileinfo.k_objectid = objectid; return next_key (); } /* continue with the file/directory name interpretation */ while (*dirname == '/') dirname++; if (! S_ISDIR (mode)) { errnum = ERR_BAD_FILETYPE; return 0; } for (rest = dirname; (ch = *rest) && ! isspace (ch) && ch != '/'; rest++); *rest = 0; # ifndef STAGE1_5 if (print_possibilities && ch != '/') do_possibilities = 1; # endif /* ! STAGE1_5 */ while (1) { char *name_end; int num_entries; if (! next_key ()) return 0; #ifdef REISERDEBUG printf ("ih: key %d:%d:%d:%d version:%d\n", __le32_to_cpu(INFO->current_ih->ih_key.k_dir_id), __le32_to_cpu(INFO->current_ih->ih_key.k_objectid), __le32_to_cpu(INFO->current_ih->ih_key.u.v1.k_offset), __le32_to_cpu(INFO->current_ih->ih_key.u.v1.k_uniqueness), __le16_to_cpu(INFO->current_ih->ih_version)); #endif /* REISERDEBUG */ if (__le32_to_cpu(INFO->current_ih->ih_key.k_objectid) != objectid) break; name_end = INFO->current_item + __le16_to_cpu(INFO->current_ih->ih_item_len); de_head = (struct reiserfs_de_head *) INFO->current_item; num_entries = __le16_to_cpu(INFO->current_ih->u.ih_entry_count); while (num_entries > 0) { char *filename = INFO->current_item + deh_location(de_head); char tmp = *name_end; if ((deh_state(de_head) & DEH_Visible)) { int cmp; /* Directory names in ReiserFS are not null * terminated. We write a temporary 0 behind it. * NOTE: that this may overwrite the first block in * the tree cache. That doesn't hurt as long as we * don't call next_key () in between. */ *name_end = 0; cmp = substring (dirname, filename); *name_end = tmp; # ifndef STAGE1_5 if (do_possibilities) { if (cmp <= 0) { char fn[PATH_MAX]; struct fsys_reiser_info info_save; if (print_possibilities > 0) print_possibilities = -print_possibilities; *name_end = 0; strcpy(fn, filename); *name_end = tmp; /* If NAME is "." or "..", do not count it. */ if (strcmp (fn, ".") != 0 && strcmp (fn, "..") != 0) { memcpy(&info_save, INFO, sizeof(struct fsys_reiser_info)); search_stat (deh_dir_id(de_head), deh_objectid(de_head)); sd_print_item(INFO->current_ih, INFO->current_item); printf(" %s\n", fn); search_stat (dir_id, objectid); memcpy(INFO, &info_save, sizeof(struct fsys_reiser_info)); } } } else # endif /* ! STAGE1_5 */ if (cmp == 0) goto found; } /* The beginning of this name marks the end of the next name. */ name_end = filename; de_head++; num_entries--; } } # ifndef STAGE1_5 if (print_possibilities < 0) return 1; # endif /* ! STAGE1_5 */ errnum = ERR_FILE_NOT_FOUND; *rest = ch; return 0; found: *rest = ch; dirname = rest; parent_dir_id = dir_id; parent_objectid = objectid; dir_id = deh_dir_id(de_head); objectid = deh_objectid(de_head); } } /* * U-Boot interface functions */ /* * List given directory * * RETURN: 0 - OK, else grub_error_t errnum */ int reiserfs_ls (char *dirname) { char *dir_slash; int res; errnum = 0; dir_slash = malloc(strlen(dirname) + 1); if (dir_slash == NULL) { return ERR_NUMBER_OVERFLOW; } strcpy(dir_slash, dirname); /* add "/" to the directory name */ strcat(dir_slash, "/"); print_possibilities = 1; res = reiserfs_dir (dir_slash); free(dir_slash); if (!res || errnum) { return errnum; } return 0; } /* * Open file for reading * * RETURN: >0 - OK, size of opened file * <0 - ERROR -grub_error_t errnum */ int reiserfs_open (char *filename) { /* open the file */ errnum = 0; print_possibilities = 0; if (!reiserfs_dir (filename) || errnum) { return -errnum; } return filemax; }
1001-study-uboot
fs/reiserfs/reiserfs.c
C
gpl3
28,564
/* * Copyright 2000-2002 by Hans Reiser, licensing governed by reiserfs/README * * GRUB -- GRand Unified Bootloader * Copyright (C) 2000, 2001 Free Software Foundation, Inc. * * (C) Copyright 2003 - 2004 * Sysgo AG, <www.elinos.com>, Pavel Bartusek <pba@sysgo.com> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* An implementation for the ReiserFS filesystem ported from GRUB. * Some parts of this code (mainly the structures and defines) are * from the original reiser fs code, as found in the linux kernel. */ #ifndef __BYTE_ORDER #if defined(__LITTLE_ENDIAN) && !defined(__BIG_ENDIAN) #define __BYTE_ORDER __LITTLE_ENDIAN #elif defined(__BIG_ENDIAN) && !defined(__LITTLE_ENDIAN) #define __BYTE_ORDER __BIG_ENDIAN #else #error "unable to define __BYTE_ORDER" #endif #endif /* not __BYTE_ORDER */ #define FSYS_BUFLEN 0x8000 #define FSYS_BUF fsys_buf /* This is the new super block of a journaling reiserfs system */ struct reiserfs_super_block { __u32 s_block_count; /* blocks count */ __u32 s_free_blocks; /* free blocks count */ __u32 s_root_block; /* root block number */ __u32 s_journal_block; /* journal block number */ __u32 s_journal_dev; /* journal device number */ __u32 s_journal_size; /* size of the journal on FS creation. used to make sure they don't overflow it */ __u32 s_journal_trans_max; /* max number of blocks in a transaction. */ __u32 s_journal_magic; /* random value made on fs creation */ __u32 s_journal_max_batch; /* max number of blocks to batch into a trans */ __u32 s_journal_max_commit_age; /* in seconds, how old can an async commit be */ __u32 s_journal_max_trans_age; /* in seconds, how old can a transaction be */ __u16 s_blocksize; /* block size */ __u16 s_oid_maxsize; /* max size of object id array */ __u16 s_oid_cursize; /* current size of object id array */ __u16 s_state; /* valid or error */ char s_magic[16]; /* reiserfs magic string indicates that file system is reiserfs */ __u16 s_tree_height; /* height of disk tree */ __u16 s_bmap_nr; /* amount of bitmap blocks needed to address each block of file system */ __u16 s_version; char s_unused[128]; /* zero filled by mkreiserfs */ }; #define sb_root_block(sbp) (__le32_to_cpu((sbp)->s_root_block)) #define sb_journal_block(sbp) (__le32_to_cpu((sbp)->s_journal_block)) #define set_sb_journal_block(sbp,v) ((sbp)->s_journal_block = __cpu_to_le32(v)) #define sb_journal_size(sbp) (__le32_to_cpu((sbp)->s_journal_size)) #define sb_blocksize(sbp) (__le16_to_cpu((sbp)->s_blocksize)) #define set_sb_blocksize(sbp,v) ((sbp)->s_blocksize = __cpu_to_le16(v)) #define sb_version(sbp) (__le16_to_cpu((sbp)->s_version)) #define set_sb_version(sbp,v) ((sbp)->s_version = __cpu_to_le16(v)) #define REISERFS_MAX_SUPPORTED_VERSION 2 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs" #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs" #define REISER3FS_SUPER_MAGIC_STRING "ReIsEr3Fs" #define MAX_HEIGHT 7 /* must be correct to keep the desc and commit structs at 4k */ #define JOURNAL_TRANS_HALF 1018 /* first block written in a commit. */ struct reiserfs_journal_desc { __u32 j_trans_id; /* id of commit */ __u32 j_len; /* length of commit. len +1 is the commit block */ __u32 j_mount_id; /* mount id of this trans*/ __u32 j_realblock[JOURNAL_TRANS_HALF]; /* real locations for the first blocks */ char j_magic[12]; }; /* last block written in a commit */ struct reiserfs_journal_commit { __u32 j_trans_id; /* must match j_trans_id from the desc block */ __u32 j_len; /* ditto */ __u32 j_realblock[JOURNAL_TRANS_HALF]; /* real locations for the last blocks */ char j_digest[16]; /* md5 sum of all the blocks involved, including desc and commit. not used, kill it */ }; /* this header block gets written whenever a transaction is considered fully flushed, and is more recent than the last fully flushed transaction. fully flushed means all the log blocks and all the real blocks are on disk, and this transaction does not need to be replayed. */ struct reiserfs_journal_header { /* id of last fully flushed transaction */ __u32 j_last_flush_trans_id; /* offset in the log of where to start replay after a crash */ __u32 j_first_unflushed_offset; /* mount id to detect very old transactions */ __u32 j_mount_id; }; /* magic string to find desc blocks in the journal */ #define JOURNAL_DESC_MAGIC "ReIsErLB" /* * directories use this key as well as old files */ struct offset_v1 { /* * for regular files this is the offset to the first byte of the * body, contained in the object-item, as measured from the start of * the entire body of the object. * * for directory entries, k_offset consists of hash derived from * hashing the name and using few bits (23 or more) of the resulting * hash, and generation number that allows distinguishing names with * hash collisions. If number of collisions overflows generation * number, we return EEXIST. High order bit is 0 always */ __u32 k_offset; __u32 k_uniqueness; }; struct offset_v2 { /* * for regular files this is the offset to the first byte of the * body, contained in the object-item, as measured from the start of * the entire body of the object. * * for directory entries, k_offset consists of hash derived from * hashing the name and using few bits (23 or more) of the resulting * hash, and generation number that allows distinguishing names with * hash collisions. If number of collisions overflows generation * number, we return EEXIST. High order bit is 0 always */ #if defined(__LITTLE_ENDIAN_BITFIELD) /* little endian version */ __u64 k_offset:60; __u64 k_type: 4; #elif defined(__BIG_ENDIAN_BITFIELD) /* big endian version */ __u64 k_type: 4; __u64 k_offset:60; #else #error "__LITTLE_ENDIAN_BITFIELD or __BIG_ENDIAN_BITFIELD must be defined" #endif } __attribute__ ((__packed__)); #define TYPE_MAXTYPE 3 #define TYPE_ANY 15 #if (__BYTE_ORDER == __BIG_ENDIAN) typedef union { struct offset_v2 offset_v2; __u64 linear; } __attribute__ ((__packed__)) offset_v2_esafe_overlay; static inline __u16 offset_v2_k_type( const struct offset_v2 *v2 ) { offset_v2_esafe_overlay tmp = *(const offset_v2_esafe_overlay *)v2; tmp.linear = __le64_to_cpu( tmp.linear ); return (tmp.offset_v2.k_type <= TYPE_MAXTYPE)?tmp.offset_v2.k_type:TYPE_ANY; } static inline loff_t offset_v2_k_offset( const struct offset_v2 *v2 ) { offset_v2_esafe_overlay tmp = *(const offset_v2_esafe_overlay *)v2; tmp.linear = __le64_to_cpu( tmp.linear ); return tmp.offset_v2.k_offset; } #elif (__BYTE_ORDER == __LITTLE_ENDIAN) # define offset_v2_k_type(v2) ((v2)->k_type) # define offset_v2_k_offset(v2) ((v2)->k_offset) #else #error "__BYTE_ORDER must be __LITTLE_ENDIAN or __BIG_ENDIAN" #endif struct key { /* packing locality: by default parent directory object id */ __u32 k_dir_id; /* object identifier */ __u32 k_objectid; /* the offset and node type (old and new form) */ union { struct offset_v1 v1; struct offset_v2 v2; } u; }; #define KEY_SIZE (sizeof (struct key)) /* Header of a disk block. More precisely, header of a formatted leaf or internal node, and not the header of an unformatted node. */ struct block_head { __u16 blk_level; /* Level of a block in the tree. */ __u16 blk_nr_item; /* Number of keys/items in a block. */ __u16 blk_free_space; /* Block free space in bytes. */ struct key blk_right_delim_key; /* Right delimiting key for this block (supported for leaf level nodes only) */ }; #define BLKH_SIZE (sizeof (struct block_head)) #define DISK_LEAF_NODE_LEVEL 1 /* Leaf node level. */ struct item_head { /* Everything in the tree is found by searching for it based on * its key.*/ struct key ih_key; union { /* The free space in the last unformatted node of an indirect item if this is an indirect item. This equals 0xFFFF iff this is a direct item or stat data item. Note that the key, not this field, is used to determine the item type, and thus which field this union contains. */ __u16 ih_free_space; /* Iff this is a directory item, this field equals the number of directory entries in the directory item. */ __u16 ih_entry_count; } __attribute__ ((__packed__)) u; __u16 ih_item_len; /* total size of the item body */ __u16 ih_item_location; /* an offset to the item body * within the block */ __u16 ih_version; /* 0 for all old items, 2 for new ones. Highest bit is set by fsck temporary, cleaned after all done */ } __attribute__ ((__packed__)); /* size of item header */ #define IH_SIZE (sizeof (struct item_head)) #define ITEM_VERSION_1 0 #define ITEM_VERSION_2 1 #define ih_version(ih) (__le16_to_cpu((ih)->ih_version)) #define IH_KEY_OFFSET(ih) (ih_version(ih) == ITEM_VERSION_1 \ ? __le32_to_cpu((ih)->ih_key.u.v1.k_offset) \ : offset_v2_k_offset(&((ih)->ih_key.u.v2))) #define IH_KEY_ISTYPE(ih, type) (ih_version(ih) == ITEM_VERSION_1 \ ? __le32_to_cpu((ih)->ih_key.u.v1.k_uniqueness) == V1_##type \ : offset_v2_k_type(&((ih)->ih_key.u.v2)) == V2_##type) /***************************************************************************/ /* DISK CHILD */ /***************************************************************************/ /* Disk child pointer: The pointer from an internal node of the tree to a node that is on disk. */ struct disk_child { __u32 dc_block_number; /* Disk child's block number. */ __u16 dc_size; /* Disk child's used space. */ __u16 dc_reserved; }; #define DC_SIZE (sizeof(struct disk_child)) #define dc_block_number(dc_p) (__le32_to_cpu((dc_p)->dc_block_number)) /* * old stat data is 32 bytes long. We are going to distinguish new one by * different size */ struct stat_data_v1 { __u16 sd_mode; /* file type, permissions */ __u16 sd_nlink; /* number of hard links */ __u16 sd_uid; /* owner */ __u16 sd_gid; /* group */ __u32 sd_size; /* file size */ __u32 sd_atime; /* time of last access */ __u32 sd_mtime; /* time file was last modified */ __u32 sd_ctime; /* time inode (stat data) was last changed (except changes to sd_atime and sd_mtime) */ union { __u32 sd_rdev; __u32 sd_blocks; /* number of blocks file uses */ } __attribute__ ((__packed__)) u; __u32 sd_first_direct_byte; /* first byte of file which is stored in a direct item: except that if it equals 1 it is a symlink and if it equals ~(__u32)0 there is no direct item. The existence of this field really grates on me. Let's replace it with a macro based on sd_size and our tail suppression policy. Someday. -Hans */ } __attribute__ ((__packed__)); #define stat_data_v1(ih) (ih_version(ih) == ITEM_VERSION_1) #define sd_v1_mode(sdp) ((sdp)->sd_mode) #define sd_v1_nlink(sdp) (__le16_to_cpu((sdp)->sd_nlink)) #define sd_v1_uid(sdp) (__le16_to_cpu((sdp)->sd_uid)) #define sd_v1_gid(sdp) (__le16_to_cpu((sdp)->sd_gid)) #define sd_v1_size(sdp) (__le32_to_cpu((sdp)->sd_size)) #define sd_v1_mtime(sdp) (__le32_to_cpu((sdp)->sd_mtime)) /* Stat Data on disk (reiserfs version of UFS disk inode minus the address blocks) */ struct stat_data { __u16 sd_mode; /* file type, permissions */ __u16 sd_attrs; /* persistent inode flags */ __u32 sd_nlink; /* number of hard links */ __u64 sd_size; /* file size */ __u32 sd_uid; /* owner */ __u32 sd_gid; /* group */ __u32 sd_atime; /* time of last access */ __u32 sd_mtime; /* time file was last modified */ __u32 sd_ctime; /* time inode (stat data) was last changed (except changes to sd_atime and sd_mtime) */ __u32 sd_blocks; union { __u32 sd_rdev; __u32 sd_generation; /*__u32 sd_first_direct_byte; */ /* first byte of file which is stored in a direct item: except that if it equals 1 it is a symlink and if it equals ~(__u32)0 there is no direct item. The existence of this field really grates on me. Let's replace it with a macro based on sd_size and our tail suppression policy? */ } __attribute__ ((__packed__)) u; } __attribute__ ((__packed__)); #define stat_data_v2(ih) (ih_version(ih) == ITEM_VERSION_2) #define sd_v2_mode(sdp) (__le16_to_cpu((sdp)->sd_mode)) #define sd_v2_nlink(sdp) (__le32_to_cpu((sdp)->sd_nlink)) #define sd_v2_size(sdp) (__le64_to_cpu((sdp)->sd_size)) #define sd_v2_uid(sdp) (__le32_to_cpu((sdp)->sd_uid)) #define sd_v2_gid(sdp) (__le32_to_cpu((sdp)->sd_gid)) #define sd_v2_mtime(sdp) (__le32_to_cpu((sdp)->sd_mtime)) #define sd_mode(sdp) (__le16_to_cpu((sdp)->sd_mode)) #define sd_size(sdp) (__le32_to_cpu((sdp)->sd_size)) #define sd_size_hi(sdp) (__le32_to_cpu((sdp)->sd_size_hi)) struct reiserfs_de_head { __u32 deh_offset; /* third component of the directory entry key */ __u32 deh_dir_id; /* objectid of the parent directory of the object, that is referenced by directory entry */ __u32 deh_objectid;/* objectid of the object, that is referenced by directory entry */ __u16 deh_location;/* offset of name in the whole item */ __u16 deh_state; /* whether 1) entry contains stat data (for future), and 2) whether entry is hidden (unlinked) */ }; #define DEH_SIZE (sizeof (struct reiserfs_de_head)) #define deh_offset(p_deh) (__le32_to_cpu((p_deh)->deh_offset)) #define deh_dir_id(p_deh) (__le32_to_cpu((p_deh)->deh_dir_id)) #define deh_objectid(p_deh) (__le32_to_cpu((p_deh)->deh_objectid)) #define deh_location(p_deh) (__le16_to_cpu((p_deh)->deh_location)) #define deh_state(p_deh) (__le16_to_cpu((p_deh)->deh_state)) #define DEH_Statdata (1 << 0) /* not used now */ #define DEH_Visible (1 << 2) #define SD_OFFSET 0 #define SD_UNIQUENESS 0 #define DOT_OFFSET 1 #define DOT_DOT_OFFSET 2 #define DIRENTRY_UNIQUENESS 500 #define V1_TYPE_STAT_DATA 0x0 #define V1_TYPE_DIRECT 0xffffffff #define V1_TYPE_INDIRECT 0xfffffffe #define V1_TYPE_DIRECTORY_MAX 0xfffffffd #define V2_TYPE_STAT_DATA 0 #define V2_TYPE_INDIRECT 1 #define V2_TYPE_DIRECT 2 #define V2_TYPE_DIRENTRY 3 #define REISERFS_ROOT_OBJECTID 2 #define REISERFS_ROOT_PARENT_OBJECTID 1 #define REISERFS_DISK_OFFSET_IN_BYTES (64 * 1024) /* the spot for the super in versions 3.5 - 3.5.11 (inclusive) */ #define REISERFS_OLD_DISK_OFFSET_IN_BYTES (8 * 1024) #define REISERFS_OLD_BLOCKSIZE 4096 #define S_ISREG(mode) (((mode) & 0170000) == 0100000) #define S_ISDIR(mode) (((mode) & 0170000) == 0040000) #define S_ISLNK(mode) (((mode) & 0170000) == 0120000) #define PATH_MAX 1024 /* include/linux/limits.h */ #define MAX_LINK_COUNT 5 /* number of symbolic links to follow */ /* The size of the node cache */ #define FSYSREISER_CACHE_SIZE 24*1024 #define FSYSREISER_MIN_BLOCKSIZE SECTOR_SIZE #define FSYSREISER_MAX_BLOCKSIZE FSYSREISER_CACHE_SIZE / 3 /* Info about currently opened file */ struct fsys_reiser_fileinfo { __u32 k_dir_id; __u32 k_objectid; }; /* In memory info about the currently mounted filesystem */ struct fsys_reiser_info { /* The last read item head */ struct item_head *current_ih; /* The last read item */ char *current_item; /* The information for the currently opened file */ struct fsys_reiser_fileinfo fileinfo; /* The start of the journal */ __u32 journal_block; /* The size of the journal */ __u32 journal_block_count; /* The first valid descriptor block in journal (relative to journal_block) */ __u32 journal_first_desc; /* The ReiserFS version. */ __u16 version; /* The current depth of the reiser tree. */ __u16 tree_depth; /* SECTOR_SIZE << blocksize_shift == blocksize. */ __u8 blocksize_shift; /* 1 << full_blocksize_shift == blocksize. */ __u8 fullblocksize_shift; /* The reiserfs block size (must be a power of 2) */ __u16 blocksize; /* The number of cached tree nodes */ __u16 cached_slots; /* The number of valid transactions in journal */ __u16 journal_transactions; unsigned int blocks[MAX_HEIGHT]; unsigned int next_key_nr[MAX_HEIGHT]; }; /* The cached s+tree blocks in FSYS_BUF, see below * for a more detailed description. */ #define ROOT ((char *) ((int) FSYS_BUF)) #define CACHE(i) (ROOT + ((i) << INFO->fullblocksize_shift)) #define LEAF CACHE (DISK_LEAF_NODE_LEVEL) #define BLOCKHEAD(cache) ((struct block_head *) cache) #define ITEMHEAD ((struct item_head *) ((int) LEAF + BLKH_SIZE)) #define KEY(cache) ((struct key *) ((int) cache + BLKH_SIZE)) #define DC(cache) ((struct disk_child *) \ ((int) cache + BLKH_SIZE + KEY_SIZE * nr_item)) /* The fsys_reiser_info block. */ #define INFO \ ((struct fsys_reiser_info *) ((int) FSYS_BUF + FSYSREISER_CACHE_SIZE)) /* * The journal cache. For each transaction it contains the number of * blocks followed by the real block numbers of this transaction. * * If the block numbers of some transaction won't fit in this space, * this list is stopped with a 0xffffffff marker and the remaining * uncommitted transactions aren't cached. */ #define JOURNAL_START ((__u32 *) (INFO + 1)) #define JOURNAL_END ((__u32 *) (FSYS_BUF + FSYS_BUFLEN)) static __inline__ unsigned long log2 (unsigned long word) { #ifdef __I386__ __asm__ ("bsfl %1,%0" : "=r" (word) : "r" (word)); return word; #else int i; for(i=0; i<(8*sizeof(word)); i++) if ((1<<i) & word) return i; return 0; #endif } static __inline__ int is_power_of_two (unsigned long word) { return (word & -word) == word; } extern const char *bb_mode_string(int mode); extern int reiserfs_devread (int sector, int byte_offset, int byte_len, char *buf);
1001-study-uboot
fs/reiserfs/reiserfs_private.h
C
gpl3
18,568
/* * mode_string implementation for busybox * * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* Aug 13, 2003 * Fix a bug reported by junkio@cox.net involving the mode_chars index. */ #include <common.h> #include <linux/stat.h> #if ( S_ISUID != 04000 ) || ( S_ISGID != 02000 ) || ( S_ISVTX != 01000 ) \ || ( S_IRUSR != 00400 ) || ( S_IWUSR != 00200 ) || ( S_IXUSR != 00100 ) \ || ( S_IRGRP != 00040 ) || ( S_IWGRP != 00020 ) || ( S_IXGRP != 00010 ) \ || ( S_IROTH != 00004 ) || ( S_IWOTH != 00002 ) || ( S_IXOTH != 00001 ) #error permission bitflag value assumption(s) violated! #endif #if ( S_IFSOCK!= 0140000 ) || ( S_IFLNK != 0120000 ) \ || ( S_IFREG != 0100000 ) || ( S_IFBLK != 0060000 ) \ || ( S_IFDIR != 0040000 ) || ( S_IFCHR != 0020000 ) \ || ( S_IFIFO != 0010000 ) #warning mode type bitflag value assumption(s) violated! falling back to larger version #if (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX) == 07777 #undef mode_t #define mode_t unsigned short #endif static const mode_t mode_flags[] = { S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID, S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID, S_IROTH, S_IWOTH, S_IXOTH, S_ISVTX }; /* The static const char arrays below are duplicated for the two cases * because moving them ahead of the mode_flags declaration cause a text * size increase with the gcc version I'm using. */ /* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C', * and 'B' types don't appear to be available on linux. So I removed them. */ static const char type_chars[16] = "?pc?d?b?-?l?s???"; /* 0123456789abcdef */ static const char mode_chars[7] = "rwxSTst"; const char *bb_mode_string(int mode) { static char buf[12]; char *p = buf; int i, j, k; *p = type_chars[ (mode >> 12) & 0xf ]; i = 0; do { j = k = 0; do { *++p = '-'; if (mode & mode_flags[i+j]) { *p = mode_chars[j]; k = j; } } while (++j < 3); if (mode & mode_flags[i+j]) { *p = mode_chars[3 + (k & 2) + ((i&8) >> 3)]; } i += 4; } while (i < 12); /* Note: We don't bother with nul termination because bss initialization * should have taken care of that for us. If the user scribbled in buf * memory, they deserve whatever happens. But we'll at least assert. */ if (buf[10] != 0) return NULL; return buf; } #else /* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C', * and 'B' types don't appear to be available on linux. So I removed them. */ static const char type_chars[16] = "?pc?d?b?-?l?s???"; /* 0123456789abcdef */ static const char mode_chars[7] = "rwxSTst"; const char *bb_mode_string(int mode) { static char buf[12]; char *p = buf; int i, j, k, m; *p = type_chars[ (mode >> 12) & 0xf ]; i = 0; m = 0400; do { j = k = 0; do { *++p = '-'; if (mode & m) { *p = mode_chars[j]; k = j; } m >>= 1; } while (++j < 3); ++i; if (mode & (010000 >> i)) { *p = mode_chars[3 + (k & 2) + (i == 3)]; } } while (i < 3); /* Note: We don't bother with nul termination because bss initialization * should have taken care of that for us. If the user scribbled in buf * memory, they deserve whatever happens. But we'll at least assert. */ if (buf[10] != 0) return NULL; return buf; } #endif
1001-study-uboot
fs/reiserfs/mode_string.c
C
gpl3
4,038
# # (C) Copyright 2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # (C) Copyright 2003 # Pavel Bartusek, Sysgo Real-Time Solutions AG, pba@sysgo.de # # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk LIB = $(obj)libreiserfs.o AOBJS = COBJS-$(CONFIG_CMD_REISER) := reiserfs.o dev.o mode_string.o SRCS := $(AOBJS:.o=.S) $(COBJS-y:.o=.c) OBJS := $(addprefix $(obj),$(AOBJS) $(COBJS-y)) #CPPFLAGS += all: $(LIB) $(AOBJS) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
fs/reiserfs/Makefile
Makefile
gpl3
1,496
/* * (C) Copyright 2003 - 2004 * Sysgo AG, <www.elinos.com>, Pavel Bartusek <pba@sysgo.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <common.h> #include <config.h> #include <reiserfs.h> #include "reiserfs_private.h" static block_dev_desc_t *reiserfs_block_dev_desc; static disk_partition_t part_info; int reiserfs_set_blk_dev(block_dev_desc_t *rbdd, int part) { reiserfs_block_dev_desc = rbdd; if (part == 0) { /* disk doesn't use partition table */ part_info.start = 0; part_info.size = rbdd->lba; part_info.blksz = rbdd->blksz; } else { if (get_partition_info (reiserfs_block_dev_desc, part, &part_info)) { return 0; } } return (part_info.size); } int reiserfs_devread (int sector, int byte_offset, int byte_len, char *buf) { char sec_buf[SECTOR_SIZE]; unsigned block_len; /* unsigned len = byte_len; u8 *start = buf; */ /* * Check partition boundaries */ if (sector < 0 || ((sector + ((byte_offset + byte_len - 1) >> SECTOR_BITS)) >= part_info.size)) { /* errnum = ERR_OUTSIDE_PART; */ printf (" ** reiserfs_devread() read outside partition\n"); return 0; } /* * Get the read to the beginning of a partition. */ sector += byte_offset >> SECTOR_BITS; byte_offset &= SECTOR_SIZE - 1; #if defined(DEBUG) printf (" <%d, %d, %d> ", sector, byte_offset, byte_len); #endif if (reiserfs_block_dev_desc == NULL) return 0; if (byte_offset != 0) { /* read first part which isn't aligned with start of sector */ if (reiserfs_block_dev_desc->block_read(reiserfs_block_dev_desc->dev, part_info.start+sector, 1, (unsigned long *)sec_buf) != 1) { printf (" ** reiserfs_devread() read error\n"); return 0; } memcpy(buf, sec_buf+byte_offset, min(SECTOR_SIZE-byte_offset, byte_len)); buf+=min(SECTOR_SIZE-byte_offset, byte_len); byte_len-=min(SECTOR_SIZE-byte_offset, byte_len); sector++; } /* read sector aligned part */ block_len = byte_len & ~(SECTOR_SIZE-1); if (reiserfs_block_dev_desc->block_read(reiserfs_block_dev_desc->dev, part_info.start+sector, block_len/SECTOR_SIZE, (unsigned long *)buf) != block_len/SECTOR_SIZE) { printf (" ** reiserfs_devread() read error - block\n"); return 0; } buf+=block_len; byte_len-=block_len; sector+= block_len/SECTOR_SIZE; if ( byte_len != 0 ) { /* read rest of data which are not in whole sector */ if (reiserfs_block_dev_desc->block_read(reiserfs_block_dev_desc->dev, part_info.start+sector, 1, (unsigned long *)sec_buf) != 1) { printf (" ** reiserfs_devread() read error - last part\n"); return 0; } memcpy(buf, sec_buf, byte_len); } return 1; }
1001-study-uboot
fs/reiserfs/dev.c
C
gpl3
3,311
# # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk LIB = $(obj)libfat.o AOBJS = COBJS-$(CONFIG_CMD_FAT) := fat.o COBJS-$(CONFIG_FAT_WRITE):= fat_write.o ifndef CONFIG_SPL_BUILD COBJS-$(CONFIG_CMD_FAT) += file.o endif SRCS := $(AOBJS:.o=.S) $(COBJS-y:.o=.c) OBJS := $(addprefix $(obj),$(AOBJS) $(COBJS-y)) all: $(LIB) $(AOBJS) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
fs/fat/Makefile
Makefile
gpl3
1,392
/* * file.c * * Mini "VFS" by Marcus Sundberg * * 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6 * 2003-03-10 - kharris@nexus-tech.net - ported to uboot * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <config.h> #include <malloc.h> #include <fat.h> #include <linux/stat.h> #include <linux/time.h> /* Supported filesystems */ static const struct filesystem filesystems[] = { { file_fat_detectfs, file_fat_ls, file_fat_read, "FAT" }, }; #define NUM_FILESYS (sizeof(filesystems)/sizeof(struct filesystem)) /* The filesystem which was last detected */ static int current_filesystem = FSTYPE_NONE; /* The current working directory */ #define CWD_LEN 511 char file_cwd[CWD_LEN+1] = "/"; const char * file_getfsname(int idx) { if (idx < 0 || idx >= NUM_FILESYS) return NULL; return filesystems[idx].name; } static void pathcpy(char *dest, const char *src) { char *origdest = dest; do { if (dest-file_cwd >= CWD_LEN) { *dest = '\0'; return; } *(dest) = *(src); if (*src == '\0') { if (dest-- != origdest && ISDIRDELIM(*dest)) { *dest = '\0'; } return; } ++dest; if (ISDIRDELIM(*src)) while (ISDIRDELIM(*src)) src++; else src++; } while (1); } int file_cd(const char *path) { if (ISDIRDELIM(*path)) { while (ISDIRDELIM(*path)) path++; strncpy(file_cwd+1, path, CWD_LEN-1); } else { const char *origpath = path; char *tmpstr = file_cwd; int back = 0; while (*tmpstr != '\0') tmpstr++; do { tmpstr--; } while (ISDIRDELIM(*tmpstr)); while (*path == '.') { path++; while (*path == '.') { path++; back++; } if (*path != '\0' && !ISDIRDELIM(*path)) { path = origpath; back = 0; break; } while (ISDIRDELIM(*path)) path++; origpath = path; } while (back--) { /* Strip off path component */ while (!ISDIRDELIM(*tmpstr)) { tmpstr--; } if (tmpstr == file_cwd) { /* Incremented again right after the loop. */ tmpstr--; break; } /* Skip delimiters */ while (ISDIRDELIM(*tmpstr)) tmpstr--; } tmpstr++; if (*path == '\0') { if (tmpstr == file_cwd) { *tmpstr = '/'; tmpstr++; } *tmpstr = '\0'; return 0; } *tmpstr = '/'; pathcpy(tmpstr+1, path); } return 0; } int file_detectfs(void) { int i; current_filesystem = FSTYPE_NONE; for (i = 0; i < NUM_FILESYS; i++) { if (filesystems[i].detect() == 0) { strcpy(file_cwd, "/"); current_filesystem = i; break; } } return current_filesystem; } int file_ls(const char *dir) { char fullpath[1024]; const char *arg; if (current_filesystem == FSTYPE_NONE) { printf("Can't list files without a filesystem!\n"); return -1; } if (ISDIRDELIM(*dir)) { arg = dir; } else { sprintf(fullpath, "%s/%s", file_cwd, dir); arg = fullpath; } return filesystems[current_filesystem].ls(arg); } long file_read(const char *filename, void *buffer, unsigned long maxsize) { char fullpath[1024]; const char *arg; if (current_filesystem == FSTYPE_NONE) { printf("Can't load file without a filesystem!\n"); return -1; } if (ISDIRDELIM(*filename)) { arg = filename; } else { sprintf(fullpath, "%s/%s", file_cwd, filename); arg = fullpath; } return filesystems[current_filesystem].read(arg, buffer, maxsize); }
1001-study-uboot
fs/fat/file.c
C
gpl3
4,071
/* * fat_write.c * * R/W (V)FAT 12/16/32 filesystem implementation by Donggeun Kim * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <command.h> #include <config.h> #include <fat.h> #include <asm/byteorder.h> #include <part.h> #include "fat.c" static void uppercase(char *str, int len) { int i; for (i = 0; i < len; i++) { TOUPPER(*str); str++; } } static int total_sector; static int disk_write(__u32 startblock, __u32 getsize, __u8 *bufptr) { if (cur_dev == NULL) return -1; if (startblock + getsize > total_sector) { printf("error: overflow occurs\n"); return -1; } startblock += part_offset; if (cur_dev->block_read) { return cur_dev->block_write(cur_dev->dev, startblock, getsize, (unsigned long *) bufptr); } return -1; } /* * Set short name in directory entry */ static void set_name(dir_entry *dirent, const char *filename) { char s_name[VFAT_MAXLEN_BYTES]; char *period; int period_location, len, i, ext_num; if (filename == NULL) return; len = strlen(filename); if (len == 0) return; memcpy(s_name, filename, len); uppercase(s_name, len); period = strchr(s_name, '.'); if (period == NULL) { period_location = len; ext_num = 0; } else { period_location = period - s_name; ext_num = len - period_location - 1; } /* Pad spaces when the length of file name is shorter than eight */ if (period_location < 8) { memcpy(dirent->name, s_name, period_location); for (i = period_location; i < 8; i++) dirent->name[i] = ' '; } else if (period_location == 8) { memcpy(dirent->name, s_name, period_location); } else { memcpy(dirent->name, s_name, 6); dirent->name[6] = '~'; dirent->name[7] = '1'; } if (ext_num < 3) { memcpy(dirent->ext, s_name + period_location + 1, ext_num); for (i = ext_num; i < 3; i++) dirent->ext[i] = ' '; } else memcpy(dirent->ext, s_name + period_location + 1, 3); debug("name : %s\n", dirent->name); debug("ext : %s\n", dirent->ext); } /* * Write fat buffer into block device */ static int flush_fat_buffer(fsdata *mydata) { int getsize = FATBUFBLOCKS; __u32 fatlength = mydata->fatlength; __u8 *bufptr = mydata->fatbuf; __u32 startblock = mydata->fatbufnum * FATBUFBLOCKS; fatlength *= mydata->sect_size; startblock += mydata->fat_sect; if (getsize > fatlength) getsize = fatlength; /* Write FAT buf */ if (disk_write(startblock, getsize, bufptr) < 0) { debug("error: writing FAT blocks\n"); return -1; } return 0; } /* * Get the entry at index 'entry' in a FAT (12/16/32) table. * On failure 0x00 is returned. * When bufnum is changed, write back the previous fatbuf to the disk. */ static __u32 get_fatent_value(fsdata *mydata, __u32 entry) { __u32 bufnum; __u32 off16, offset; __u32 ret = 0x00; __u16 val1, val2; switch (mydata->fatsize) { case 32: bufnum = entry / FAT32BUFSIZE; offset = entry - bufnum * FAT32BUFSIZE; break; case 16: bufnum = entry / FAT16BUFSIZE; offset = entry - bufnum * FAT16BUFSIZE; break; case 12: bufnum = entry / FAT12BUFSIZE; offset = entry - bufnum * FAT12BUFSIZE; break; default: /* Unsupported FAT size */ return ret; } debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n", mydata->fatsize, entry, entry, offset, offset); /* Read a new block of FAT entries into the cache. */ if (bufnum != mydata->fatbufnum) { int getsize = FATBUFBLOCKS; __u8 *bufptr = mydata->fatbuf; __u32 fatlength = mydata->fatlength; __u32 startblock = bufnum * FATBUFBLOCKS; if (getsize > fatlength) getsize = fatlength; fatlength *= mydata->sect_size; /* We want it in bytes now */ startblock += mydata->fat_sect; /* Offset from start of disk */ /* Write back the fatbuf to the disk */ if (mydata->fatbufnum != -1) { if (flush_fat_buffer(mydata) < 0) return -1; } if (disk_read(startblock, getsize, bufptr) < 0) { debug("Error reading FAT blocks\n"); return ret; } mydata->fatbufnum = bufnum; } /* Get the actual entry from the table */ switch (mydata->fatsize) { case 32: ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]); break; case 16: ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]); break; case 12: off16 = (offset * 3) / 4; switch (offset & 0x3) { case 0: ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]); ret &= 0xfff; break; case 1: val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]); val1 &= 0xf000; val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]); val2 &= 0x00ff; ret = (val2 << 4) | (val1 >> 12); break; case 2: val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]); val1 &= 0xff00; val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]); val2 &= 0x000f; ret = (val2 << 8) | (val1 >> 8); break; case 3: ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]); ret = (ret & 0xfff0) >> 4; break; default: break; } break; } debug("FAT%d: ret: %08x, entry: %08x, offset: %04x\n", mydata->fatsize, ret, entry, offset); return ret; } #ifdef CONFIG_SUPPORT_VFAT /* * Set the file name information from 'name' into 'slotptr', */ static int str2slot(dir_slot *slotptr, const char *name, int *idx) { int j, end_idx = 0; for (j = 0; j <= 8; j += 2) { if (name[*idx] == 0x00) { slotptr->name0_4[j] = 0; slotptr->name0_4[j + 1] = 0; end_idx++; goto name0_4; } slotptr->name0_4[j] = name[*idx]; (*idx)++; end_idx++; } for (j = 0; j <= 10; j += 2) { if (name[*idx] == 0x00) { slotptr->name5_10[j] = 0; slotptr->name5_10[j + 1] = 0; end_idx++; goto name5_10; } slotptr->name5_10[j] = name[*idx]; (*idx)++; end_idx++; } for (j = 0; j <= 2; j += 2) { if (name[*idx] == 0x00) { slotptr->name11_12[j] = 0; slotptr->name11_12[j + 1] = 0; end_idx++; goto name11_12; } slotptr->name11_12[j] = name[*idx]; (*idx)++; end_idx++; } if (name[*idx] == 0x00) return 1; return 0; /* Not used characters are filled with 0xff 0xff */ name0_4: for (; end_idx < 5; end_idx++) { slotptr->name0_4[end_idx * 2] = 0xff; slotptr->name0_4[end_idx * 2 + 1] = 0xff; } end_idx = 5; name5_10: end_idx -= 5; for (; end_idx < 6; end_idx++) { slotptr->name5_10[end_idx * 2] = 0xff; slotptr->name5_10[end_idx * 2 + 1] = 0xff; } end_idx = 11; name11_12: end_idx -= 11; for (; end_idx < 2; end_idx++) { slotptr->name11_12[end_idx * 2] = 0xff; slotptr->name11_12[end_idx * 2 + 1] = 0xff; } return 1; } static int is_next_clust(fsdata *mydata, dir_entry *dentptr); static void flush_dir_table(fsdata *mydata, dir_entry **dentptr); /* * Fill dir_slot entries with appropriate name, id, and attr * The real directory entry is returned by 'dentptr' */ static void fill_dir_slot(fsdata *mydata, dir_entry **dentptr, const char *l_name) { dir_slot *slotptr = (dir_slot *)get_vfatname_block; __u8 counter = 0, checksum; int idx = 0, ret; char s_name[16]; /* Get short file name and checksum value */ strncpy(s_name, (*dentptr)->name, 16); checksum = mkcksum(s_name); do { memset(slotptr, 0x00, sizeof(dir_slot)); ret = str2slot(slotptr, l_name, &idx); slotptr->id = ++counter; slotptr->attr = ATTR_VFAT; slotptr->alias_checksum = checksum; slotptr++; } while (ret == 0); slotptr--; slotptr->id |= LAST_LONG_ENTRY_MASK; while (counter >= 1) { if (is_next_clust(mydata, *dentptr)) { /* A new cluster is allocated for directory table */ flush_dir_table(mydata, dentptr); } memcpy(*dentptr, slotptr, sizeof(dir_slot)); (*dentptr)++; slotptr--; counter--; } if (is_next_clust(mydata, *dentptr)) { /* A new cluster is allocated for directory table */ flush_dir_table(mydata, dentptr); } } static __u32 dir_curclust; /* * Extract the full long filename starting at 'retdent' (which is really * a slot) into 'l_name'. If successful also copy the real directory entry * into 'retdent' * If additional adjacent cluster for directory entries is read into memory, * then 'get_vfatname_block' is copied into 'get_dentfromdir_block' and * the location of the real directory entry is returned by 'retdent' * Return 0 on success, -1 otherwise. */ static int get_long_file_name(fsdata *mydata, int curclust, __u8 *cluster, dir_entry **retdent, char *l_name) { dir_entry *realdent; dir_slot *slotptr = (dir_slot *)(*retdent); dir_slot *slotptr2 = NULL; __u8 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ? PREFETCH_BLOCKS : mydata->clust_size); __u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff; int idx = 0, cur_position = 0; if (counter > VFAT_MAXSEQ) { debug("Error: VFAT name is too long\n"); return -1; } while ((__u8 *)slotptr < buflimit) { if (counter == 0) break; if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter) return -1; slotptr++; counter--; } if ((__u8 *)slotptr >= buflimit) { if (curclust == 0) return -1; curclust = get_fatent_value(mydata, dir_curclust); if (CHECK_CLUST(curclust, mydata->fatsize)) { debug("curclust: 0x%x\n", curclust); printf("Invalid FAT entry\n"); return -1; } dir_curclust = curclust; if (get_cluster(mydata, curclust, get_vfatname_block, mydata->clust_size * mydata->sect_size) != 0) { debug("Error: reading directory block\n"); return -1; } slotptr2 = (dir_slot *)get_vfatname_block; while (counter > 0) { if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter) return -1; slotptr2++; counter--; } /* Save the real directory entry */ realdent = (dir_entry *)slotptr2; while ((__u8 *)slotptr2 > get_vfatname_block) { slotptr2--; slot2str(slotptr2, l_name, &idx); } } else { /* Save the real directory entry */ realdent = (dir_entry *)slotptr; } do { slotptr--; if (slot2str(slotptr, l_name, &idx)) break; } while (!(slotptr->id & LAST_LONG_ENTRY_MASK)); l_name[idx] = '\0'; if (*l_name == DELETED_FLAG) *l_name = '\0'; else if (*l_name == aRING) *l_name = DELETED_FLAG; downcase(l_name); /* Return the real directory entry */ *retdent = realdent; if (slotptr2) { memcpy(get_dentfromdir_block, get_vfatname_block, mydata->clust_size * mydata->sect_size); cur_position = (__u8 *)realdent - get_vfatname_block; *retdent = (dir_entry *) &get_dentfromdir_block[cur_position]; } return 0; } #endif /* * Set the entry at index 'entry' in a FAT (16/32) table. */ static int set_fatent_value(fsdata *mydata, __u32 entry, __u32 entry_value) { __u32 bufnum, offset; switch (mydata->fatsize) { case 32: bufnum = entry / FAT32BUFSIZE; offset = entry - bufnum * FAT32BUFSIZE; break; case 16: bufnum = entry / FAT16BUFSIZE; offset = entry - bufnum * FAT16BUFSIZE; break; default: /* Unsupported FAT size */ return -1; } /* Read a new block of FAT entries into the cache. */ if (bufnum != mydata->fatbufnum) { int getsize = FATBUFBLOCKS; __u8 *bufptr = mydata->fatbuf; __u32 fatlength = mydata->fatlength; __u32 startblock = bufnum * FATBUFBLOCKS; fatlength *= mydata->sect_size; startblock += mydata->fat_sect; if (getsize > fatlength) getsize = fatlength; if (mydata->fatbufnum != -1) { if (flush_fat_buffer(mydata) < 0) return -1; } if (disk_read(startblock, getsize, bufptr) < 0) { debug("Error reading FAT blocks\n"); return -1; } mydata->fatbufnum = bufnum; } /* Set the actual entry */ switch (mydata->fatsize) { case 32: ((__u32 *) mydata->fatbuf)[offset] = cpu_to_le32(entry_value); break; case 16: ((__u16 *) mydata->fatbuf)[offset] = cpu_to_le16(entry_value); break; default: return -1; } return 0; } /* * Determine the entry value at index 'entry' in a FAT (16/32) table */ static __u32 determine_fatent(fsdata *mydata, __u32 entry) { __u32 next_fat, next_entry = entry + 1; while (1) { next_fat = get_fatent_value(mydata, next_entry); if (next_fat == 0) { set_fatent_value(mydata, entry, next_entry); break; } next_entry++; } debug("FAT%d: entry: %08x, entry_value: %04x\n", mydata->fatsize, entry, next_entry); return next_entry; } /* * Write at most 'size' bytes from 'buffer' into the specified cluster. * Return 0 on success, -1 otherwise. */ static int set_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size) { int idx = 0; __u32 startsect; if (clustnum > 0) startsect = mydata->data_begin + clustnum * mydata->clust_size; else startsect = mydata->rootdir_sect; debug("clustnum: %d, startsect: %d\n", clustnum, startsect); if (disk_write(startsect, size / mydata->sect_size, buffer) < 0) { debug("Error writing data\n"); return -1; } if (size % mydata->sect_size) { __u8 tmpbuf[mydata->sect_size]; idx = size / mydata->sect_size; buffer += idx * mydata->sect_size; memcpy(tmpbuf, buffer, size % mydata->sect_size); if (disk_write(startsect + idx, 1, tmpbuf) < 0) { debug("Error writing data\n"); return -1; } return 0; } return 0; } /* * Find the first empty cluster */ static int find_empty_cluster(fsdata *mydata) { __u32 fat_val, entry = 3; while (1) { fat_val = get_fatent_value(mydata, entry); if (fat_val == 0) break; entry++; } return entry; } /* * Write directory entries in 'get_dentfromdir_block' to block device */ static void flush_dir_table(fsdata *mydata, dir_entry **dentptr) { int dir_newclust = 0; if (set_cluster(mydata, dir_curclust, get_dentfromdir_block, mydata->clust_size * mydata->sect_size) != 0) { printf("error: wrinting directory entry\n"); return; } dir_newclust = find_empty_cluster(mydata); set_fatent_value(mydata, dir_curclust, dir_newclust); if (mydata->fatsize == 32) set_fatent_value(mydata, dir_newclust, 0xffffff8); else if (mydata->fatsize == 16) set_fatent_value(mydata, dir_newclust, 0xfff8); dir_curclust = dir_newclust; if (flush_fat_buffer(mydata) < 0) return; memset(get_dentfromdir_block, 0x00, mydata->clust_size * mydata->sect_size); *dentptr = (dir_entry *) get_dentfromdir_block; } /* * Set empty cluster from 'entry' to the end of a file */ static int clear_fatent(fsdata *mydata, __u32 entry) { __u32 fat_val; while (1) { fat_val = get_fatent_value(mydata, entry); if (fat_val != 0) set_fatent_value(mydata, entry, 0); else break; if (fat_val == 0xfffffff || fat_val == 0xffff) break; entry = fat_val; } /* Flush fat buffer */ if (flush_fat_buffer(mydata) < 0) return -1; return 0; } /* * Write at most 'maxsize' bytes from 'buffer' into * the file associated with 'dentptr' * Return the number of bytes read or -1 on fatal errors. */ static int set_contents(fsdata *mydata, dir_entry *dentptr, __u8 *buffer, unsigned long maxsize) { unsigned long filesize = FAT2CPU32(dentptr->size), gotsize = 0; unsigned int bytesperclust = mydata->clust_size * mydata->sect_size; __u32 curclust = START(dentptr); __u32 endclust = 0, newclust = 0; unsigned long actsize; debug("Filesize: %ld bytes\n", filesize); if (maxsize > 0 && filesize > maxsize) filesize = maxsize; debug("%ld bytes\n", filesize); actsize = bytesperclust; endclust = curclust; do { /* search for consecutive clusters */ while (actsize < filesize) { newclust = determine_fatent(mydata, endclust); if ((newclust - 1) != endclust) goto getit; if (CHECK_CLUST(newclust, mydata->fatsize)) { debug("curclust: 0x%x\n", newclust); debug("Invalid FAT entry\n"); return gotsize; } endclust = newclust; actsize += bytesperclust; } /* actsize >= file size */ actsize -= bytesperclust; /* set remaining clusters */ if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) { debug("error: writing cluster\n"); return -1; } /* set remaining bytes */ gotsize += (int)actsize; filesize -= actsize; buffer += actsize; actsize = filesize; if (set_cluster(mydata, endclust, buffer, (int)actsize) != 0) { debug("error: writing cluster\n"); return -1; } gotsize += actsize; /* Mark end of file in FAT */ if (mydata->fatsize == 16) newclust = 0xffff; else if (mydata->fatsize == 32) newclust = 0xfffffff; set_fatent_value(mydata, endclust, newclust); return gotsize; getit: if (set_cluster(mydata, curclust, buffer, (int)actsize) != 0) { debug("error: writing cluster\n"); return -1; } gotsize += (int)actsize; filesize -= actsize; buffer += actsize; if (CHECK_CLUST(curclust, mydata->fatsize)) { debug("curclust: 0x%x\n", curclust); debug("Invalid FAT entry\n"); return gotsize; } actsize = bytesperclust; curclust = endclust = newclust; } while (1); } /* * Fill dir_entry */ static void fill_dentry(fsdata *mydata, dir_entry *dentptr, const char *filename, __u32 start_cluster, __u32 size, __u8 attr) { if (mydata->fatsize == 32) dentptr->starthi = cpu_to_le16((start_cluster & 0xffff0000) >> 16); dentptr->start = cpu_to_le16(start_cluster & 0xffff); dentptr->size = cpu_to_le32(size); dentptr->attr = attr; set_name(dentptr, filename); } /* * Check whether adding a file makes the file system to * exceed the size of the block device * Return -1 when overflow occurs, otherwise return 0 */ static int check_overflow(fsdata *mydata, __u32 clustnum, unsigned long size) { __u32 startsect, sect_num; if (clustnum > 0) { startsect = mydata->data_begin + clustnum * mydata->clust_size; } else { startsect = mydata->rootdir_sect; } sect_num = size / mydata->sect_size; if (size % mydata->sect_size) sect_num++; if (startsect + sect_num > total_sector) return -1; return 0; } /* * Check if adding several entries exceed one cluster boundary */ static int is_next_clust(fsdata *mydata, dir_entry *dentptr) { int cur_position; cur_position = (__u8 *)dentptr - get_dentfromdir_block; if (cur_position >= mydata->clust_size * mydata->sect_size) return 1; else return 0; } static dir_entry *empty_dentptr; /* * Find a directory entry based on filename or start cluster number * If the directory entry is not found, * the new position for writing a directory entry will be returned */ static dir_entry *find_directory_entry(fsdata *mydata, int startsect, char *filename, dir_entry *retdent, __u32 start) { __u16 prevcksum = 0xffff; __u32 curclust = (startsect - mydata->data_begin) / mydata->clust_size; debug("get_dentfromdir: %s\n", filename); while (1) { dir_entry *dentptr; int i; if (get_cluster(mydata, curclust, get_dentfromdir_block, mydata->clust_size * mydata->sect_size) != 0) { printf("Error: reading directory block\n"); return NULL; } dentptr = (dir_entry *)get_dentfromdir_block; dir_curclust = curclust; for (i = 0; i < DIRENTSPERCLUST; i++) { char s_name[14], l_name[VFAT_MAXLEN_BYTES]; l_name[0] = '\0'; if (dentptr->name[0] == DELETED_FLAG) { dentptr++; if (is_next_clust(mydata, dentptr)) break; continue; } if ((dentptr->attr & ATTR_VOLUME)) { #ifdef CONFIG_SUPPORT_VFAT if ((dentptr->attr & ATTR_VFAT) && (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) { prevcksum = ((dir_slot *)dentptr)->alias_checksum; get_long_file_name(mydata, curclust, get_dentfromdir_block, &dentptr, l_name); debug("vfatname: |%s|\n", l_name); } else #endif { /* Volume label or VFAT entry */ dentptr++; if (is_next_clust(mydata, dentptr)) break; continue; } } if (dentptr->name[0] == 0) { debug("Dentname == NULL - %d\n", i); empty_dentptr = dentptr; return NULL; } get_name(dentptr, s_name); if (strcmp(filename, s_name) && strcmp(filename, l_name)) { debug("Mismatch: |%s|%s|\n", s_name, l_name); dentptr++; if (is_next_clust(mydata, dentptr)) break; continue; } memcpy(retdent, dentptr, sizeof(dir_entry)); debug("DentName: %s", s_name); debug(", start: 0x%x", START(dentptr)); debug(", size: 0x%x %s\n", FAT2CPU32(dentptr->size), (dentptr->attr & ATTR_DIR) ? "(DIR)" : ""); return dentptr; } curclust = get_fatent_value(mydata, dir_curclust); if ((curclust >= 0xffffff8) || (curclust >= 0xfff8)) { empty_dentptr = dentptr; return NULL; } if (CHECK_CLUST(curclust, mydata->fatsize)) { debug("curclust: 0x%x\n", curclust); debug("Invalid FAT entry\n"); return NULL; } } return NULL; } static int do_fat_write(const char *filename, void *buffer, unsigned long size) { dir_entry *dentptr, *retdent; dir_slot *slotptr; __u32 startsect; __u32 start_cluster; boot_sector bs; volume_info volinfo; fsdata datablock; fsdata *mydata = &datablock; int cursect; int root_cluster, ret = -1, name_len; char l_filename[VFAT_MAXLEN_BYTES]; int write_size = size; dir_curclust = 0; if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) { debug("error: reading boot sector\n"); return -1; } total_sector = bs.total_sect; if (total_sector == 0) total_sector = part_size; root_cluster = bs.root_cluster; if (mydata->fatsize == 32) mydata->fatlength = bs.fat32_length; else mydata->fatlength = bs.fat_length; mydata->fat_sect = bs.reserved; cursect = mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats; mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0]; mydata->clust_size = bs.cluster_size; if (mydata->fatsize == 32) { mydata->data_begin = mydata->rootdir_sect - (mydata->clust_size * 2); } else { int rootdir_size; rootdir_size = ((bs.dir_entries[1] * (int)256 + bs.dir_entries[0]) * sizeof(dir_entry)) / mydata->sect_size; mydata->data_begin = mydata->rootdir_sect + rootdir_size - (mydata->clust_size * 2); } mydata->fatbufnum = -1; mydata->fatbuf = malloc(FATBUFSIZE); if (mydata->fatbuf == NULL) { debug("Error: allocating memory\n"); return -1; } if (disk_read(cursect, (mydata->fatsize == 32) ? (mydata->clust_size) : PREFETCH_BLOCKS, do_fat_read_block) < 0) { debug("Error: reading rootdir block\n"); goto exit; } dentptr = (dir_entry *) do_fat_read_block; name_len = strlen(filename); if (name_len >= VFAT_MAXLEN_BYTES) name_len = VFAT_MAXLEN_BYTES - 1; memcpy(l_filename, filename, name_len); l_filename[name_len] = 0; /* terminate the string */ downcase(l_filename); startsect = mydata->rootdir_sect; retdent = find_directory_entry(mydata, startsect, l_filename, dentptr, 0); if (retdent) { /* Update file size and start_cluster in a directory entry */ retdent->size = cpu_to_le32(size); start_cluster = FAT2CPU16(retdent->start); if (mydata->fatsize == 32) start_cluster |= (FAT2CPU16(retdent->starthi) << 16); ret = check_overflow(mydata, start_cluster, size); if (ret) { printf("Error: %ld overflow\n", size); goto exit; } ret = clear_fatent(mydata, start_cluster); if (ret) { printf("Error: clearing FAT entries\n"); goto exit; } ret = set_contents(mydata, retdent, buffer, size); if (ret < 0) { printf("Error: writing contents\n"); goto exit; } write_size = ret; debug("attempt to write 0x%x bytes\n", write_size); /* Flush fat buffer */ ret = flush_fat_buffer(mydata); if (ret) { printf("Error: flush fat buffer\n"); goto exit; } /* Write directory table to device */ ret = set_cluster(mydata, dir_curclust, get_dentfromdir_block, mydata->clust_size * mydata->sect_size); if (ret) { printf("Error: writing directory entry\n"); goto exit; } } else { slotptr = (dir_slot *)empty_dentptr; /* Set short name to set alias checksum field in dir_slot */ set_name(empty_dentptr, filename); fill_dir_slot(mydata, &empty_dentptr, filename); ret = start_cluster = find_empty_cluster(mydata); if (ret < 0) { printf("Error: finding empty cluster\n"); goto exit; } ret = check_overflow(mydata, start_cluster, size); if (ret) { printf("Error: %ld overflow\n", size); goto exit; } /* Set attribute as archieve for regular file */ fill_dentry(mydata, empty_dentptr, filename, start_cluster, size, 0x20); ret = set_contents(mydata, empty_dentptr, buffer, size); if (ret < 0) { printf("Error: writing contents\n"); goto exit; } write_size = ret; debug("attempt to write 0x%x bytes\n", write_size); /* Flush fat buffer */ ret = flush_fat_buffer(mydata); if (ret) { printf("Error: flush fat buffer\n"); goto exit; } /* Write directory table to device */ ret = set_cluster(mydata, dir_curclust, get_dentfromdir_block, mydata->clust_size * mydata->sect_size); if (ret) { printf("Error: writing directory entry\n"); goto exit; } } exit: free(mydata->fatbuf); return ret < 0 ? ret : write_size; } int file_fat_write(const char *filename, void *buffer, unsigned long maxsize) { printf("writing %s\n", filename); return do_fat_write(filename, buffer, maxsize); }
1001-study-uboot
fs/fat/fat_write.c
C
gpl3
25,759
/* * fat.c * * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg * * 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6 * 2003-03-10 - kharris@nexus-tech.net - ported to uboot * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <config.h> #include <exports.h> #include <fat.h> #include <asm/byteorder.h> #include <part.h> /* * Convert a string to lowercase. */ static void downcase (char *str) { while (*str != '\0') { TOLOWER(*str); str++; } } static block_dev_desc_t *cur_dev = NULL; static unsigned long part_offset = 0; static int cur_part = 1; #define DOS_PART_TBL_OFFSET 0x1be #define DOS_PART_MAGIC_OFFSET 0x1fe #define DOS_FS_TYPE_OFFSET 0x36 #define DOS_FS32_TYPE_OFFSET 0x52 static int disk_read (__u32 startblock, __u32 getsize, __u8 * bufptr) { if (cur_dev == NULL) return -1; startblock += part_offset; if (cur_dev->block_read) { return cur_dev->block_read(cur_dev->dev, startblock, getsize, (unsigned long *) bufptr); } return -1; } int fat_register_device (block_dev_desc_t * dev_desc, int part_no) { unsigned char buffer[dev_desc->blksz]; if (!dev_desc->block_read) return -1; cur_dev = dev_desc; /* check if we have a MBR (on floppies we have only a PBR) */ if (dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *)buffer) != 1) { printf("** Can't read from device %d **\n", dev_desc->dev); return -1; } if (buffer[DOS_PART_MAGIC_OFFSET] != 0x55 || buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) { /* no signature found */ return -1; } #if (defined(CONFIG_CMD_IDE) || \ defined(CONFIG_CMD_MG_DISK) || \ defined(CONFIG_CMD_SATA) || \ defined(CONFIG_CMD_SCSI) || \ defined(CONFIG_CMD_USB) || \ defined(CONFIG_MMC) || \ defined(CONFIG_SYSTEMACE) ) { disk_partition_t info; /* First we assume there is a MBR */ if (!get_partition_info(dev_desc, part_no, &info)) { part_offset = info.start; cur_part = part_no; } else if ((strncmp((char *)&buffer[DOS_FS_TYPE_OFFSET], "FAT", 3) == 0) || (strncmp((char *)&buffer[DOS_FS32_TYPE_OFFSET], "FAT32", 5) == 0)) { /* ok, we assume we are on a PBR only */ cur_part = 1; part_offset = 0; } else { printf("** Partition %d not valid on device %d **\n", part_no, dev_desc->dev); return -1; } } #else if ((strncmp((char *)&buffer[DOS_FS_TYPE_OFFSET], "FAT", 3) == 0) || (strncmp((char *)&buffer[DOS_FS32_TYPE_OFFSET], "FAT32", 5) == 0)) { /* ok, we assume we are on a PBR only */ cur_part = 1; part_offset = 0; } else { /* FIXME we need to determine the start block of the * partition where the DOS FS resides. This can be done * by using the get_partition_info routine. For this * purpose the libpart must be included. */ part_offset = 32; cur_part = 1; } #endif return 0; } /* * Get the first occurence of a directory delimiter ('/' or '\') in a string. * Return index into string if found, -1 otherwise. */ static int dirdelim (char *str) { char *start = str; while (*str != '\0') { if (ISDIRDELIM(*str)) return str - start; str++; } return -1; } /* * Extract zero terminated short name from a directory entry. */ static void get_name (dir_entry *dirent, char *s_name) { char *ptr; memcpy(s_name, dirent->name, 8); s_name[8] = '\0'; ptr = s_name; while (*ptr && *ptr != ' ') ptr++; if (dirent->ext[0] && dirent->ext[0] != ' ') { *ptr = '.'; ptr++; memcpy(ptr, dirent->ext, 3); ptr[3] = '\0'; while (*ptr && *ptr != ' ') ptr++; } *ptr = '\0'; if (*s_name == DELETED_FLAG) *s_name = '\0'; else if (*s_name == aRING) *s_name = DELETED_FLAG; downcase(s_name); } /* * Get the entry at index 'entry' in a FAT (12/16/32) table. * On failure 0x00 is returned. */ static __u32 get_fatent (fsdata *mydata, __u32 entry) { __u32 bufnum; __u32 off16, offset; __u32 ret = 0x00; __u16 val1, val2; switch (mydata->fatsize) { case 32: bufnum = entry / FAT32BUFSIZE; offset = entry - bufnum * FAT32BUFSIZE; break; case 16: bufnum = entry / FAT16BUFSIZE; offset = entry - bufnum * FAT16BUFSIZE; break; case 12: bufnum = entry / FAT12BUFSIZE; offset = entry - bufnum * FAT12BUFSIZE; break; default: /* Unsupported FAT size */ return ret; } debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n", mydata->fatsize, entry, entry, offset, offset); /* Read a new block of FAT entries into the cache. */ if (bufnum != mydata->fatbufnum) { __u32 getsize = FATBUFBLOCKS; __u8 *bufptr = mydata->fatbuf; __u32 fatlength = mydata->fatlength; __u32 startblock = bufnum * FATBUFBLOCKS; if (getsize > fatlength) getsize = fatlength; fatlength *= mydata->sect_size; /* We want it in bytes now */ startblock += mydata->fat_sect; /* Offset from start of disk */ if (disk_read(startblock, getsize, bufptr) < 0) { debug("Error reading FAT blocks\n"); return ret; } mydata->fatbufnum = bufnum; } /* Get the actual entry from the table */ switch (mydata->fatsize) { case 32: ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]); break; case 16: ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]); break; case 12: off16 = (offset * 3) / 4; switch (offset & 0x3) { case 0: ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]); ret &= 0xfff; break; case 1: val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]); val1 &= 0xf000; val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]); val2 &= 0x00ff; ret = (val2 << 4) | (val1 >> 12); break; case 2: val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]); val1 &= 0xff00; val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]); val2 &= 0x000f; ret = (val2 << 8) | (val1 >> 8); break; case 3: ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]); ret = (ret & 0xfff0) >> 4; break; default: break; } break; } debug("FAT%d: ret: %08x, offset: %04x\n", mydata->fatsize, ret, offset); return ret; } /* * Read at most 'size' bytes from the specified cluster into 'buffer'. * Return 0 on success, -1 otherwise. */ static int get_cluster (fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size) { __u32 idx = 0; __u32 startsect; if (clustnum > 0) { startsect = mydata->data_begin + clustnum * mydata->clust_size; } else { startsect = mydata->rootdir_sect; } debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect); if (disk_read(startsect, size / mydata->sect_size, buffer) < 0) { debug("Error reading data\n"); return -1; } if (size % mydata->sect_size) { __u8 tmpbuf[mydata->sect_size]; idx = size / mydata->sect_size; if (disk_read(startsect + idx, 1, tmpbuf) < 0) { debug("Error reading data\n"); return -1; } buffer += idx * mydata->sect_size; memcpy(buffer, tmpbuf, size % mydata->sect_size); return 0; } return 0; } /* * Read at most 'maxsize' bytes from the file associated with 'dentptr' * into 'buffer'. * Return the number of bytes read or -1 on fatal errors. */ static long get_contents (fsdata *mydata, dir_entry *dentptr, __u8 *buffer, unsigned long maxsize) { unsigned long filesize = FAT2CPU32(dentptr->size), gotsize = 0; unsigned int bytesperclust = mydata->clust_size * mydata->sect_size; __u32 curclust = START(dentptr); __u32 endclust, newclust; unsigned long actsize; debug("Filesize: %ld bytes\n", filesize); if (maxsize > 0 && filesize > maxsize) filesize = maxsize; debug("%ld bytes\n", filesize); actsize = bytesperclust; endclust = curclust; do { /* search for consecutive clusters */ while (actsize < filesize) { newclust = get_fatent(mydata, endclust); if ((newclust - 1) != endclust) goto getit; if (CHECK_CLUST(newclust, mydata->fatsize)) { debug("curclust: 0x%x\n", newclust); debug("Invalid FAT entry\n"); return gotsize; } endclust = newclust; actsize += bytesperclust; } /* actsize >= file size */ actsize -= bytesperclust; /* get remaining clusters */ if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) { printf("Error reading cluster\n"); return -1; } /* get remaining bytes */ gotsize += (int)actsize; filesize -= actsize; buffer += actsize; actsize = filesize; if (get_cluster(mydata, endclust, buffer, (int)actsize) != 0) { printf("Error reading cluster\n"); return -1; } gotsize += actsize; return gotsize; getit: if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) { printf("Error reading cluster\n"); return -1; } gotsize += (int)actsize; filesize -= actsize; buffer += actsize; curclust = get_fatent(mydata, endclust); if (CHECK_CLUST(curclust, mydata->fatsize)) { debug("curclust: 0x%x\n", curclust); printf("Invalid FAT entry\n"); return gotsize; } actsize = bytesperclust; endclust = curclust; } while (1); } #ifdef CONFIG_SUPPORT_VFAT /* * Extract the file name information from 'slotptr' into 'l_name', * starting at l_name[*idx]. * Return 1 if terminator (zero byte) is found, 0 otherwise. */ static int slot2str (dir_slot *slotptr, char *l_name, int *idx) { int j; for (j = 0; j <= 8; j += 2) { l_name[*idx] = slotptr->name0_4[j]; if (l_name[*idx] == 0x00) return 1; (*idx)++; } for (j = 0; j <= 10; j += 2) { l_name[*idx] = slotptr->name5_10[j]; if (l_name[*idx] == 0x00) return 1; (*idx)++; } for (j = 0; j <= 2; j += 2) { l_name[*idx] = slotptr->name11_12[j]; if (l_name[*idx] == 0x00) return 1; (*idx)++; } return 0; } /* * Extract the full long filename starting at 'retdent' (which is really * a slot) into 'l_name'. If successful also copy the real directory entry * into 'retdent' * Return 0 on success, -1 otherwise. */ __attribute__ ((__aligned__ (__alignof__ (dir_entry)))) __u8 get_vfatname_block[MAX_CLUSTSIZE]; static int get_vfatname (fsdata *mydata, int curclust, __u8 *cluster, dir_entry *retdent, char *l_name) { dir_entry *realdent; dir_slot *slotptr = (dir_slot *)retdent; __u8 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ? PREFETCH_BLOCKS : mydata->clust_size); __u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff; int idx = 0; if (counter > VFAT_MAXSEQ) { debug("Error: VFAT name is too long\n"); return -1; } while ((__u8 *)slotptr < buflimit) { if (counter == 0) break; if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter) return -1; slotptr++; counter--; } if ((__u8 *)slotptr >= buflimit) { dir_slot *slotptr2; if (curclust == 0) return -1; curclust = get_fatent(mydata, curclust); if (CHECK_CLUST(curclust, mydata->fatsize)) { debug("curclust: 0x%x\n", curclust); printf("Invalid FAT entry\n"); return -1; } if (get_cluster(mydata, curclust, get_vfatname_block, mydata->clust_size * mydata->sect_size) != 0) { debug("Error: reading directory block\n"); return -1; } slotptr2 = (dir_slot *)get_vfatname_block; while (counter > 0) { if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter) return -1; slotptr2++; counter--; } /* Save the real directory entry */ realdent = (dir_entry *)slotptr2; while ((__u8 *)slotptr2 > get_vfatname_block) { slotptr2--; slot2str(slotptr2, l_name, &idx); } } else { /* Save the real directory entry */ realdent = (dir_entry *)slotptr; } do { slotptr--; if (slot2str(slotptr, l_name, &idx)) break; } while (!(slotptr->id & LAST_LONG_ENTRY_MASK)); l_name[idx] = '\0'; if (*l_name == DELETED_FLAG) *l_name = '\0'; else if (*l_name == aRING) *l_name = DELETED_FLAG; downcase(l_name); /* Return the real directory entry */ memcpy(retdent, realdent, sizeof(dir_entry)); return 0; } /* Calculate short name checksum */ static __u8 mkcksum (const char *str) { int i; __u8 ret = 0; for (i = 0; i < 11; i++) { ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + str[i]; } return ret; } #endif /* CONFIG_SUPPORT_VFAT */ /* * Get the directory entry associated with 'filename' from the directory * starting at 'startsect' */ __attribute__ ((__aligned__ (__alignof__ (dir_entry)))) __u8 get_dentfromdir_block[MAX_CLUSTSIZE]; static dir_entry *get_dentfromdir (fsdata *mydata, int startsect, char *filename, dir_entry *retdent, int dols) { __u16 prevcksum = 0xffff; __u32 curclust = START(retdent); int files = 0, dirs = 0; debug("get_dentfromdir: %s\n", filename); while (1) { dir_entry *dentptr; int i; if (get_cluster(mydata, curclust, get_dentfromdir_block, mydata->clust_size * mydata->sect_size) != 0) { debug("Error: reading directory block\n"); return NULL; } dentptr = (dir_entry *)get_dentfromdir_block; for (i = 0; i < DIRENTSPERCLUST; i++) { char s_name[14], l_name[VFAT_MAXLEN_BYTES]; l_name[0] = '\0'; if (dentptr->name[0] == DELETED_FLAG) { dentptr++; continue; } if ((dentptr->attr & ATTR_VOLUME)) { #ifdef CONFIG_SUPPORT_VFAT if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT && (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) { prevcksum = ((dir_slot *)dentptr)->alias_checksum; get_vfatname(mydata, curclust, get_dentfromdir_block, dentptr, l_name); if (dols) { int isdir; char dirc; int doit = 0; isdir = (dentptr->attr & ATTR_DIR); if (isdir) { dirs++; dirc = '/'; doit = 1; } else { dirc = ' '; if (l_name[0] != 0) { files++; doit = 1; } } if (doit) { if (dirc == ' ') { printf(" %8ld %s%c\n", (long)FAT2CPU32(dentptr->size), l_name, dirc); } else { printf(" %s%c\n", l_name, dirc); } } dentptr++; continue; } debug("vfatname: |%s|\n", l_name); } else #endif { /* Volume label or VFAT entry */ dentptr++; continue; } } if (dentptr->name[0] == 0) { if (dols) { printf("\n%d file(s), %d dir(s)\n\n", files, dirs); } debug("Dentname == NULL - %d\n", i); return NULL; } #ifdef CONFIG_SUPPORT_VFAT if (dols && mkcksum(dentptr->name) == prevcksum) { dentptr++; continue; } #endif get_name(dentptr, s_name); if (dols) { int isdir = (dentptr->attr & ATTR_DIR); char dirc; int doit = 0; if (isdir) { dirs++; dirc = '/'; doit = 1; } else { dirc = ' '; if (s_name[0] != 0) { files++; doit = 1; } } if (doit) { if (dirc == ' ') { printf(" %8ld %s%c\n", (long)FAT2CPU32(dentptr->size), s_name, dirc); } else { printf(" %s%c\n", s_name, dirc); } } dentptr++; continue; } if (strcmp(filename, s_name) && strcmp(filename, l_name)) { debug("Mismatch: |%s|%s|\n", s_name, l_name); dentptr++; continue; } memcpy(retdent, dentptr, sizeof(dir_entry)); debug("DentName: %s", s_name); debug(", start: 0x%x", START(dentptr)); debug(", size: 0x%x %s\n", FAT2CPU32(dentptr->size), (dentptr->attr & ATTR_DIR) ? "(DIR)" : ""); return retdent; } curclust = get_fatent(mydata, curclust); if (CHECK_CLUST(curclust, mydata->fatsize)) { debug("curclust: 0x%x\n", curclust); printf("Invalid FAT entry\n"); return NULL; } } return NULL; } /* * Read boot sector and volume info from a FAT filesystem */ static int read_bootsectandvi (boot_sector *bs, volume_info *volinfo, int *fatsize) { __u8 *block; volume_info *vistart; int ret = 0; if (cur_dev == NULL) { debug("Error: no device selected\n"); return -1; } block = malloc(cur_dev->blksz); if (block == NULL) { debug("Error: allocating block\n"); return -1; } if (disk_read (0, 1, block) < 0) { debug("Error: reading block\n"); goto fail; } memcpy(bs, block, sizeof(boot_sector)); bs->reserved = FAT2CPU16(bs->reserved); bs->fat_length = FAT2CPU16(bs->fat_length); bs->secs_track = FAT2CPU16(bs->secs_track); bs->heads = FAT2CPU16(bs->heads); bs->total_sect = FAT2CPU32(bs->total_sect); /* FAT32 entries */ if (bs->fat_length == 0) { /* Assume FAT32 */ bs->fat32_length = FAT2CPU32(bs->fat32_length); bs->flags = FAT2CPU16(bs->flags); bs->root_cluster = FAT2CPU32(bs->root_cluster); bs->info_sector = FAT2CPU16(bs->info_sector); bs->backup_boot = FAT2CPU16(bs->backup_boot); vistart = (volume_info *)(block + sizeof(boot_sector)); *fatsize = 32; } else { vistart = (volume_info *)&(bs->fat32_length); *fatsize = 0; } memcpy(volinfo, vistart, sizeof(volume_info)); if (*fatsize == 32) { if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0) goto exit; } else { if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) { *fatsize = 12; goto exit; } if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) { *fatsize = 16; goto exit; } } debug("Error: broken fs_type sign\n"); fail: ret = -1; exit: free(block); return ret; } __attribute__ ((__aligned__ (__alignof__ (dir_entry)))) __u8 do_fat_read_block[MAX_CLUSTSIZE]; long do_fat_read (const char *filename, void *buffer, unsigned long maxsize, int dols) { char fnamecopy[2048]; boot_sector bs; volume_info volinfo; fsdata datablock; fsdata *mydata = &datablock; dir_entry *dentptr; __u16 prevcksum = 0xffff; char *subname = ""; __u32 cursect; int idx, isdir = 0; int files = 0, dirs = 0; long ret = -1; int firsttime; __u32 root_cluster = 0; int rootdir_size = 0; int j; if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) { debug("Error: reading boot sector\n"); return -1; } if (mydata->fatsize == 32) { root_cluster = bs.root_cluster; mydata->fatlength = bs.fat32_length; } else { mydata->fatlength = bs.fat_length; } mydata->fat_sect = bs.reserved; cursect = mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats; mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0]; mydata->clust_size = bs.cluster_size; if (mydata->fatsize == 32) { mydata->data_begin = mydata->rootdir_sect - (mydata->clust_size * 2); } else { rootdir_size = ((bs.dir_entries[1] * (int)256 + bs.dir_entries[0]) * sizeof(dir_entry)) / mydata->sect_size; mydata->data_begin = mydata->rootdir_sect + rootdir_size - (mydata->clust_size * 2); } mydata->fatbufnum = -1; mydata->fatbuf = malloc(FATBUFSIZE); if (mydata->fatbuf == NULL) { debug("Error: allocating memory\n"); return -1; } #ifdef CONFIG_SUPPORT_VFAT debug("VFAT Support enabled\n"); #endif debug("FAT%d, fat_sect: %d, fatlength: %d\n", mydata->fatsize, mydata->fat_sect, mydata->fatlength); debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n" "Data begins at: %d\n", root_cluster, mydata->rootdir_sect, mydata->rootdir_sect * mydata->sect_size, mydata->data_begin); debug("Sector size: %d, cluster size: %d\n", mydata->sect_size, mydata->clust_size); /* "cwd" is always the root... */ while (ISDIRDELIM(*filename)) filename++; /* Make a copy of the filename and convert it to lowercase */ strcpy(fnamecopy, filename); downcase(fnamecopy); if (*fnamecopy == '\0') { if (!dols) goto exit; dols = LS_ROOT; } else if ((idx = dirdelim(fnamecopy)) >= 0) { isdir = 1; fnamecopy[idx] = '\0'; subname = fnamecopy + idx + 1; /* Handle multiple delimiters */ while (ISDIRDELIM(*subname)) subname++; } else if (dols) { isdir = 1; } j = 0; while (1) { int i; debug("FAT read sect=%d, clust_size=%d, DIRENTSPERBLOCK=%d\n", cursect, mydata->clust_size, DIRENTSPERBLOCK); if (disk_read(cursect, (mydata->fatsize == 32) ? (mydata->clust_size) : PREFETCH_BLOCKS, do_fat_read_block) < 0) { debug("Error: reading rootdir block\n"); goto exit; } dentptr = (dir_entry *) do_fat_read_block; for (i = 0; i < DIRENTSPERBLOCK; i++) { char s_name[14], l_name[VFAT_MAXLEN_BYTES]; l_name[0] = '\0'; if (dentptr->name[0] == DELETED_FLAG) { dentptr++; continue; } if ((dentptr->attr & ATTR_VOLUME)) { #ifdef CONFIG_SUPPORT_VFAT if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT && (dentptr->name[0] & LAST_LONG_ENTRY_MASK)) { prevcksum = ((dir_slot *)dentptr)->alias_checksum; get_vfatname(mydata, root_cluster, do_fat_read_block, dentptr, l_name); if (dols == LS_ROOT) { char dirc; int doit = 0; int isdir = (dentptr->attr & ATTR_DIR); if (isdir) { dirs++; dirc = '/'; doit = 1; } else { dirc = ' '; if (l_name[0] != 0) { files++; doit = 1; } } if (doit) { if (dirc == ' ') { printf(" %8ld %s%c\n", (long)FAT2CPU32(dentptr->size), l_name, dirc); } else { printf(" %s%c\n", l_name, dirc); } } dentptr++; continue; } debug("Rootvfatname: |%s|\n", l_name); } else #endif { /* Volume label or VFAT entry */ dentptr++; continue; } } else if (dentptr->name[0] == 0) { debug("RootDentname == NULL - %d\n", i); if (dols == LS_ROOT) { printf("\n%d file(s), %d dir(s)\n\n", files, dirs); ret = 0; } goto exit; } #ifdef CONFIG_SUPPORT_VFAT else if (dols == LS_ROOT && mkcksum(dentptr->name) == prevcksum) { dentptr++; continue; } #endif get_name(dentptr, s_name); if (dols == LS_ROOT) { int isdir = (dentptr->attr & ATTR_DIR); char dirc; int doit = 0; if (isdir) { dirc = '/'; if (s_name[0] != 0) { dirs++; doit = 1; } } else { dirc = ' '; if (s_name[0] != 0) { files++; doit = 1; } } if (doit) { if (dirc == ' ') { printf(" %8ld %s%c\n", (long)FAT2CPU32(dentptr->size), s_name, dirc); } else { printf(" %s%c\n", s_name, dirc); } } dentptr++; continue; } if (strcmp(fnamecopy, s_name) && strcmp(fnamecopy, l_name)) { debug("RootMismatch: |%s|%s|\n", s_name, l_name); dentptr++; continue; } if (isdir && !(dentptr->attr & ATTR_DIR)) goto exit; debug("RootName: %s", s_name); debug(", start: 0x%x", START(dentptr)); debug(", size: 0x%x %s\n", FAT2CPU32(dentptr->size), isdir ? "(DIR)" : ""); goto rootdir_done; /* We got a match */ } debug("END LOOP: j=%d clust_size=%d\n", j, mydata->clust_size); /* * On FAT32 we must fetch the FAT entries for the next * root directory clusters when a cluster has been * completely processed. */ ++j; int fat32_end = 0; if ((mydata->fatsize == 32) && (j == mydata->clust_size)) { int nxtsect = 0; int nxt_clust = 0; nxt_clust = get_fatent(mydata, root_cluster); fat32_end = CHECK_CLUST(nxt_clust, 32); nxtsect = mydata->data_begin + (nxt_clust * mydata->clust_size); root_cluster = nxt_clust; cursect = nxtsect; j = 0; } else { cursect++; } /* If end of rootdir reached */ if ((mydata->fatsize == 32 && fat32_end) || (mydata->fatsize != 32 && j == rootdir_size)) { if (dols == LS_ROOT) { printf("\n%d file(s), %d dir(s)\n\n", files, dirs); ret = 0; } goto exit; } } rootdir_done: firsttime = 1; while (isdir) { int startsect = mydata->data_begin + START(dentptr) * mydata->clust_size; dir_entry dent; char *nextname = NULL; dent = *dentptr; dentptr = &dent; idx = dirdelim(subname); if (idx >= 0) { subname[idx] = '\0'; nextname = subname + idx + 1; /* Handle multiple delimiters */ while (ISDIRDELIM(*nextname)) nextname++; if (dols && *nextname == '\0') firsttime = 0; } else { if (dols && firsttime) { firsttime = 0; } else { isdir = 0; } } if (get_dentfromdir(mydata, startsect, subname, dentptr, isdir ? 0 : dols) == NULL) { if (dols && !isdir) ret = 0; goto exit; } if (idx >= 0) { if (!(dentptr->attr & ATTR_DIR)) goto exit; subname = nextname; } } ret = get_contents(mydata, dentptr, buffer, maxsize); debug("Size: %d, got: %ld\n", FAT2CPU32(dentptr->size), ret); exit: free(mydata->fatbuf); return ret; } int file_fat_detectfs (void) { boot_sector bs; volume_info volinfo; int fatsize; char vol_label[12]; if (cur_dev == NULL) { printf("No current device\n"); return 1; } #if defined(CONFIG_CMD_IDE) || \ defined(CONFIG_CMD_MG_DISK) || \ defined(CONFIG_CMD_SATA) || \ defined(CONFIG_CMD_SCSI) || \ defined(CONFIG_CMD_USB) || \ defined(CONFIG_MMC) printf("Interface: "); switch (cur_dev->if_type) { case IF_TYPE_IDE: printf("IDE"); break; case IF_TYPE_SATA: printf("SATA"); break; case IF_TYPE_SCSI: printf("SCSI"); break; case IF_TYPE_ATAPI: printf("ATAPI"); break; case IF_TYPE_USB: printf("USB"); break; case IF_TYPE_DOC: printf("DOC"); break; case IF_TYPE_MMC: printf("MMC"); break; default: printf("Unknown"); } printf("\n Device %d: ", cur_dev->dev); dev_print(cur_dev); #endif if (read_bootsectandvi(&bs, &volinfo, &fatsize)) { printf("\nNo valid FAT fs found\n"); return 1; } memcpy(vol_label, volinfo.volume_label, 11); vol_label[11] = '\0'; volinfo.fs_type[5] = '\0'; printf("Partition %d: Filesystem: %s \"%s\"\n", cur_part, volinfo.fs_type, vol_label); return 0; } int file_fat_ls (const char *dir) { return do_fat_read(dir, NULL, 0, LS_YES); } long file_fat_read (const char *filename, void *buffer, unsigned long maxsize) { printf("reading %s\n", filename); return do_fat_read(filename, buffer, maxsize, LS_NO); }
1001-study-uboot
fs/fat/fat.c
C
gpl3
26,752
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Adrian Hunter * Artem Bityutskiy (Битюцкий Артём) */ /* * This file implements the scan which is a general-purpose function for * determining what nodes are in an eraseblock. The scan is used to replay the * journal, to do garbage collection. for the TNC in-the-gaps method, and by * debugging functions. */ #include "ubifs.h" /** * scan_padding_bytes - scan for padding bytes. * @buf: buffer to scan * @len: length of buffer * * This function returns the number of padding bytes on success and * %SCANNED_GARBAGE on failure. */ static int scan_padding_bytes(void *buf, int len) { int pad_len = 0, max_pad_len = min_t(int, UBIFS_PAD_NODE_SZ, len); uint8_t *p = buf; dbg_scan("not a node"); while (pad_len < max_pad_len && *p++ == UBIFS_PADDING_BYTE) pad_len += 1; if (!pad_len || (pad_len & 7)) return SCANNED_GARBAGE; dbg_scan("%d padding bytes", pad_len); return pad_len; } /** * ubifs_scan_a_node - scan for a node or padding. * @c: UBIFS file-system description object * @buf: buffer to scan * @len: length of buffer * @lnum: logical eraseblock number * @offs: offset within the logical eraseblock * @quiet: print no messages * * This function returns a scanning code to indicate what was scanned. */ int ubifs_scan_a_node(const struct ubifs_info *c, void *buf, int len, int lnum, int offs, int quiet) { struct ubifs_ch *ch = buf; uint32_t magic; magic = le32_to_cpu(ch->magic); if (magic == 0xFFFFFFFF) { dbg_scan("hit empty space"); return SCANNED_EMPTY_SPACE; } if (magic != UBIFS_NODE_MAGIC) return scan_padding_bytes(buf, len); if (len < UBIFS_CH_SZ) return SCANNED_GARBAGE; dbg_scan("scanning %s", dbg_ntype(ch->node_type)); if (ubifs_check_node(c, buf, lnum, offs, quiet, 1)) return SCANNED_A_CORRUPT_NODE; if (ch->node_type == UBIFS_PAD_NODE) { struct ubifs_pad_node *pad = buf; int pad_len = le32_to_cpu(pad->pad_len); int node_len = le32_to_cpu(ch->len); /* Validate the padding node */ if (pad_len < 0 || offs + node_len + pad_len > c->leb_size) { if (!quiet) { ubifs_err("bad pad node at LEB %d:%d", lnum, offs); dbg_dump_node(c, pad); } return SCANNED_A_BAD_PAD_NODE; } /* Make the node pads to 8-byte boundary */ if ((node_len + pad_len) & 7) { if (!quiet) { dbg_err("bad padding length %d - %d", offs, offs + node_len + pad_len); } return SCANNED_A_BAD_PAD_NODE; } dbg_scan("%d bytes padded, offset now %d", pad_len, ALIGN(offs + node_len + pad_len, 8)); return node_len + pad_len; } return SCANNED_A_NODE; } /** * ubifs_start_scan - create LEB scanning information at start of scan. * @c: UBIFS file-system description object * @lnum: logical eraseblock number * @offs: offset to start at (usually zero) * @sbuf: scan buffer (must be c->leb_size) * * This function returns %0 on success and a negative error code on failure. */ struct ubifs_scan_leb *ubifs_start_scan(const struct ubifs_info *c, int lnum, int offs, void *sbuf) { struct ubifs_scan_leb *sleb; int err; dbg_scan("scan LEB %d:%d", lnum, offs); sleb = kzalloc(sizeof(struct ubifs_scan_leb), GFP_NOFS); if (!sleb) return ERR_PTR(-ENOMEM); sleb->lnum = lnum; INIT_LIST_HEAD(&sleb->nodes); sleb->buf = sbuf; err = ubi_read(c->ubi, lnum, sbuf + offs, offs, c->leb_size - offs); if (err && err != -EBADMSG) { ubifs_err("cannot read %d bytes from LEB %d:%d," " error %d", c->leb_size - offs, lnum, offs, err); kfree(sleb); return ERR_PTR(err); } if (err == -EBADMSG) sleb->ecc = 1; return sleb; } /** * ubifs_end_scan - update LEB scanning information at end of scan. * @c: UBIFS file-system description object * @sleb: scanning information * @lnum: logical eraseblock number * @offs: offset to start at (usually zero) * * This function returns %0 on success and a negative error code on failure. */ void ubifs_end_scan(const struct ubifs_info *c, struct ubifs_scan_leb *sleb, int lnum, int offs) { lnum = lnum; dbg_scan("stop scanning LEB %d at offset %d", lnum, offs); ubifs_assert(offs % c->min_io_size == 0); sleb->endpt = ALIGN(offs, c->min_io_size); } /** * ubifs_add_snod - add a scanned node to LEB scanning information. * @c: UBIFS file-system description object * @sleb: scanning information * @buf: buffer containing node * @offs: offset of node on flash * * This function returns %0 on success and a negative error code on failure. */ int ubifs_add_snod(const struct ubifs_info *c, struct ubifs_scan_leb *sleb, void *buf, int offs) { struct ubifs_ch *ch = buf; struct ubifs_ino_node *ino = buf; struct ubifs_scan_node *snod; snod = kzalloc(sizeof(struct ubifs_scan_node), GFP_NOFS); if (!snod) return -ENOMEM; snod->sqnum = le64_to_cpu(ch->sqnum); snod->type = ch->node_type; snod->offs = offs; snod->len = le32_to_cpu(ch->len); snod->node = buf; switch (ch->node_type) { case UBIFS_INO_NODE: case UBIFS_DENT_NODE: case UBIFS_XENT_NODE: case UBIFS_DATA_NODE: case UBIFS_TRUN_NODE: /* * The key is in the same place in all keyed * nodes. */ key_read(c, &ino->key, &snod->key); break; } list_add_tail(&snod->list, &sleb->nodes); sleb->nodes_cnt += 1; return 0; } /** * ubifs_scanned_corruption - print information after UBIFS scanned corruption. * @c: UBIFS file-system description object * @lnum: LEB number of corruption * @offs: offset of corruption * @buf: buffer containing corruption */ void ubifs_scanned_corruption(const struct ubifs_info *c, int lnum, int offs, void *buf) { int len; ubifs_err("corrupted data at LEB %d:%d", lnum, offs); if (dbg_failure_mode) return; len = c->leb_size - offs; if (len > 4096) len = 4096; dbg_err("first %d bytes from LEB %d:%d", len, lnum, offs); print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 4, buf, len, 1); } /** * ubifs_scan - scan a logical eraseblock. * @c: UBIFS file-system description object * @lnum: logical eraseblock number * @offs: offset to start at (usually zero) * @sbuf: scan buffer (must be c->leb_size) * * This function scans LEB number @lnum and returns complete information about * its contents. Returns an error code in case of failure. */ struct ubifs_scan_leb *ubifs_scan(const struct ubifs_info *c, int lnum, int offs, void *sbuf) { void *buf = sbuf + offs; int err, len = c->leb_size - offs; struct ubifs_scan_leb *sleb; sleb = ubifs_start_scan(c, lnum, offs, sbuf); if (IS_ERR(sleb)) return sleb; while (len >= 8) { struct ubifs_ch *ch = buf; int node_len, ret; dbg_scan("look at LEB %d:%d (%d bytes left)", lnum, offs, len); cond_resched(); ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 0); if (ret > 0) { /* Padding bytes or a valid padding node */ offs += ret; buf += ret; len -= ret; continue; } if (ret == SCANNED_EMPTY_SPACE) /* Empty space is checked later */ break; switch (ret) { case SCANNED_GARBAGE: dbg_err("garbage"); goto corrupted; case SCANNED_A_NODE: break; case SCANNED_A_CORRUPT_NODE: case SCANNED_A_BAD_PAD_NODE: dbg_err("bad node"); goto corrupted; default: dbg_err("unknown"); goto corrupted; } err = ubifs_add_snod(c, sleb, buf, offs); if (err) goto error; node_len = ALIGN(le32_to_cpu(ch->len), 8); offs += node_len; buf += node_len; len -= node_len; } if (offs % c->min_io_size) goto corrupted; ubifs_end_scan(c, sleb, lnum, offs); for (; len > 4; offs += 4, buf = buf + 4, len -= 4) if (*(uint32_t *)buf != 0xffffffff) break; for (; len; offs++, buf++, len--) if (*(uint8_t *)buf != 0xff) { ubifs_err("corrupt empty space at LEB %d:%d", lnum, offs); goto corrupted; } return sleb; corrupted: ubifs_scanned_corruption(c, lnum, offs, buf); err = -EUCLEAN; error: ubifs_err("LEB %d scanning failed", lnum); ubifs_scan_destroy(sleb); return ERR_PTR(err); } /** * ubifs_scan_destroy - destroy LEB scanning information. * @sleb: scanning information to free */ void ubifs_scan_destroy(struct ubifs_scan_leb *sleb) { struct ubifs_scan_node *node; struct list_head *head; head = &sleb->nodes; while (!list_empty(head)) { node = list_entry(head->next, struct ubifs_scan_node, list); list_del(&node->list); kfree(node); } kfree(sleb); }
1001-study-uboot
fs/ubifs/scan.c
C
gpl3
9,083
/* * crc16.c * * This source code is licensed under the GNU General Public License, * Version 2. See the file COPYING for more details. */ #include <linux/types.h> #include "crc16.h" /** CRC table for the CRC-16. The poly is 0x8005 (x^16 + x^15 + x^2 + 1) */ u16 const crc16_table[256] = { 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040 }; /** * crc16 - compute the CRC-16 for the data buffer * @crc: previous CRC value * @buffer: data pointer * @len: number of bytes in the buffer * * Returns the updated CRC value. */ u16 crc16(u16 crc, u8 const *buffer, size_t len) { while (len--) crc = crc16_byte(crc, *buffer++); return crc; }
1001-study-uboot
fs/ubifs/crc16.c
C
gpl3
2,689
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter */ /* * This file implements UBIFS initialization and VFS superblock operations. Some * initialization stuff which is rather large and complex is placed at * corresponding subsystems, but most of it is here. */ #include "ubifs.h" #include <linux/math64.h> #define INODE_LOCKED_MAX 64 struct super_block *ubifs_sb; static struct inode *inodes_locked_down[INODE_LOCKED_MAX]; /* shrinker.c */ /* List of all UBIFS file-system instances */ struct list_head ubifs_infos; /* linux/fs/super.c */ static int sb_set(struct super_block *sb, void *data) { dev_t *dev = data; sb->s_dev = *dev; return 0; } /** * sget - find or create a superblock * @type: filesystem type superblock should belong to * @test: comparison callback * @set: setup callback * @data: argument to each of them */ struct super_block *sget(struct file_system_type *type, int (*test)(struct super_block *,void *), int (*set)(struct super_block *,void *), void *data) { struct super_block *s = NULL; int err; s = kzalloc(sizeof(struct super_block), GFP_USER); if (!s) { err = -ENOMEM; return ERR_PTR(err); } INIT_LIST_HEAD(&s->s_instances); INIT_LIST_HEAD(&s->s_inodes); s->s_time_gran = 1000000000; err = set(s, data); if (err) { return ERR_PTR(err); } s->s_type = type; strncpy(s->s_id, type->name, sizeof(s->s_id)); list_add(&s->s_instances, &type->fs_supers); return s; } /** * validate_inode - validate inode. * @c: UBIFS file-system description object * @inode: the inode to validate * * This is a helper function for 'ubifs_iget()' which validates various fields * of a newly built inode to make sure they contain sane values and prevent * possible vulnerabilities. Returns zero if the inode is all right and * a non-zero error code if not. */ static int validate_inode(struct ubifs_info *c, const struct inode *inode) { int err; const struct ubifs_inode *ui = ubifs_inode(inode); if (inode->i_size > c->max_inode_sz) { ubifs_err("inode is too large (%lld)", (long long)inode->i_size); return 1; } if (ui->compr_type < 0 || ui->compr_type >= UBIFS_COMPR_TYPES_CNT) { ubifs_err("unknown compression type %d", ui->compr_type); return 2; } if (ui->data_len < 0 || ui->data_len > UBIFS_MAX_INO_DATA) return 4; if (!ubifs_compr_present(ui->compr_type)) { ubifs_warn("inode %lu uses '%s' compression, but it was not " "compiled in", inode->i_ino, ubifs_compr_name(ui->compr_type)); } err = dbg_check_dir_size(c, inode); return err; } struct inode *iget_locked(struct super_block *sb, unsigned long ino) { struct inode *inode; inode = (struct inode *)malloc(sizeof(struct ubifs_inode)); if (inode) { inode->i_ino = ino; inode->i_sb = sb; list_add(&inode->i_sb_list, &sb->s_inodes); inode->i_state = I_LOCK | I_NEW; } return inode; } int ubifs_iput(struct inode *inode) { list_del_init(&inode->i_sb_list); free(inode); return 0; } /* * Lock (save) inode in inode array for readback after recovery */ void iput(struct inode *inode) { int i; struct inode *ino; /* * Search end of list */ for (i = 0; i < INODE_LOCKED_MAX; i++) { if (inodes_locked_down[i] == NULL) break; } if (i >= INODE_LOCKED_MAX) { ubifs_err("Error, can't lock (save) more inodes while recovery!!!"); return; } /* * Allocate and use new inode */ ino = (struct inode *)malloc(sizeof(struct ubifs_inode)); memcpy(ino, inode, sizeof(struct ubifs_inode)); /* * Finally save inode in array */ inodes_locked_down[i] = ino; } struct inode *ubifs_iget(struct super_block *sb, unsigned long inum) { int err; union ubifs_key key; struct ubifs_ino_node *ino; struct ubifs_info *c = sb->s_fs_info; struct inode *inode; struct ubifs_inode *ui; int i; dbg_gen("inode %lu", inum); /* * U-Boot special handling of locked down inodes via recovery * e.g. ubifs_recover_size() */ for (i = 0; i < INODE_LOCKED_MAX; i++) { /* * Exit on last entry (NULL), inode not found in list */ if (inodes_locked_down[i] == NULL) break; if (inodes_locked_down[i]->i_ino == inum) { /* * We found the locked down inode in our array, * so just return this pointer instead of creating * a new one. */ return inodes_locked_down[i]; } } inode = iget_locked(sb, inum); if (!inode) return ERR_PTR(-ENOMEM); if (!(inode->i_state & I_NEW)) return inode; ui = ubifs_inode(inode); ino = kmalloc(UBIFS_MAX_INO_NODE_SZ, GFP_NOFS); if (!ino) { err = -ENOMEM; goto out; } ino_key_init(c, &key, inode->i_ino); err = ubifs_tnc_lookup(c, &key, ino); if (err) goto out_ino; inode->i_flags |= (S_NOCMTIME | S_NOATIME); inode->i_nlink = le32_to_cpu(ino->nlink); inode->i_uid = le32_to_cpu(ino->uid); inode->i_gid = le32_to_cpu(ino->gid); inode->i_atime.tv_sec = (int64_t)le64_to_cpu(ino->atime_sec); inode->i_atime.tv_nsec = le32_to_cpu(ino->atime_nsec); inode->i_mtime.tv_sec = (int64_t)le64_to_cpu(ino->mtime_sec); inode->i_mtime.tv_nsec = le32_to_cpu(ino->mtime_nsec); inode->i_ctime.tv_sec = (int64_t)le64_to_cpu(ino->ctime_sec); inode->i_ctime.tv_nsec = le32_to_cpu(ino->ctime_nsec); inode->i_mode = le32_to_cpu(ino->mode); inode->i_size = le64_to_cpu(ino->size); ui->data_len = le32_to_cpu(ino->data_len); ui->flags = le32_to_cpu(ino->flags); ui->compr_type = le16_to_cpu(ino->compr_type); ui->creat_sqnum = le64_to_cpu(ino->creat_sqnum); ui->synced_i_size = ui->ui_size = inode->i_size; err = validate_inode(c, inode); if (err) goto out_invalid; if ((inode->i_mode & S_IFMT) == S_IFLNK) { if (ui->data_len <= 0 || ui->data_len > UBIFS_MAX_INO_DATA) { err = 12; goto out_invalid; } ui->data = kmalloc(ui->data_len + 1, GFP_NOFS); if (!ui->data) { err = -ENOMEM; goto out_ino; } memcpy(ui->data, ino->data, ui->data_len); ((char *)ui->data)[ui->data_len] = '\0'; } kfree(ino); inode->i_state &= ~(I_LOCK | I_NEW); return inode; out_invalid: ubifs_err("inode %lu validation failed, error %d", inode->i_ino, err); dbg_dump_node(c, ino); dbg_dump_inode(c, inode); err = -EINVAL; out_ino: kfree(ino); out: ubifs_err("failed to read inode %lu, error %d", inode->i_ino, err); return ERR_PTR(err); } /** * init_constants_early - initialize UBIFS constants. * @c: UBIFS file-system description object * * This function initialize UBIFS constants which do not need the superblock to * be read. It also checks that the UBI volume satisfies basic UBIFS * requirements. Returns zero in case of success and a negative error code in * case of failure. */ static int init_constants_early(struct ubifs_info *c) { if (c->vi.corrupted) { ubifs_warn("UBI volume is corrupted - read-only mode"); c->ro_media = 1; } if (c->di.ro_mode) { ubifs_msg("read-only UBI device"); c->ro_media = 1; } if (c->vi.vol_type == UBI_STATIC_VOLUME) { ubifs_msg("static UBI volume - read-only mode"); c->ro_media = 1; } c->leb_cnt = c->vi.size; c->leb_size = c->vi.usable_leb_size; c->half_leb_size = c->leb_size / 2; c->min_io_size = c->di.min_io_size; c->min_io_shift = fls(c->min_io_size) - 1; if (c->leb_size < UBIFS_MIN_LEB_SZ) { ubifs_err("too small LEBs (%d bytes), min. is %d bytes", c->leb_size, UBIFS_MIN_LEB_SZ); return -EINVAL; } if (c->leb_cnt < UBIFS_MIN_LEB_CNT) { ubifs_err("too few LEBs (%d), min. is %d", c->leb_cnt, UBIFS_MIN_LEB_CNT); return -EINVAL; } if (!is_power_of_2(c->min_io_size)) { ubifs_err("bad min. I/O size %d", c->min_io_size); return -EINVAL; } /* * UBIFS aligns all node to 8-byte boundary, so to make function in * io.c simpler, assume minimum I/O unit size to be 8 bytes if it is * less than 8. */ if (c->min_io_size < 8) { c->min_io_size = 8; c->min_io_shift = 3; } c->ref_node_alsz = ALIGN(UBIFS_REF_NODE_SZ, c->min_io_size); c->mst_node_alsz = ALIGN(UBIFS_MST_NODE_SZ, c->min_io_size); /* * Initialize node length ranges which are mostly needed for node * length validation. */ c->ranges[UBIFS_PAD_NODE].len = UBIFS_PAD_NODE_SZ; c->ranges[UBIFS_SB_NODE].len = UBIFS_SB_NODE_SZ; c->ranges[UBIFS_MST_NODE].len = UBIFS_MST_NODE_SZ; c->ranges[UBIFS_REF_NODE].len = UBIFS_REF_NODE_SZ; c->ranges[UBIFS_TRUN_NODE].len = UBIFS_TRUN_NODE_SZ; c->ranges[UBIFS_CS_NODE].len = UBIFS_CS_NODE_SZ; c->ranges[UBIFS_INO_NODE].min_len = UBIFS_INO_NODE_SZ; c->ranges[UBIFS_INO_NODE].max_len = UBIFS_MAX_INO_NODE_SZ; c->ranges[UBIFS_ORPH_NODE].min_len = UBIFS_ORPH_NODE_SZ + sizeof(__le64); c->ranges[UBIFS_ORPH_NODE].max_len = c->leb_size; c->ranges[UBIFS_DENT_NODE].min_len = UBIFS_DENT_NODE_SZ; c->ranges[UBIFS_DENT_NODE].max_len = UBIFS_MAX_DENT_NODE_SZ; c->ranges[UBIFS_XENT_NODE].min_len = UBIFS_XENT_NODE_SZ; c->ranges[UBIFS_XENT_NODE].max_len = UBIFS_MAX_XENT_NODE_SZ; c->ranges[UBIFS_DATA_NODE].min_len = UBIFS_DATA_NODE_SZ; c->ranges[UBIFS_DATA_NODE].max_len = UBIFS_MAX_DATA_NODE_SZ; /* * Minimum indexing node size is amended later when superblock is * read and the key length is known. */ c->ranges[UBIFS_IDX_NODE].min_len = UBIFS_IDX_NODE_SZ + UBIFS_BRANCH_SZ; /* * Maximum indexing node size is amended later when superblock is * read and the fanout is known. */ c->ranges[UBIFS_IDX_NODE].max_len = INT_MAX; /* * Initialize dead and dark LEB space watermarks. See gc.c for comments * about these values. */ c->dead_wm = ALIGN(MIN_WRITE_SZ, c->min_io_size); c->dark_wm = ALIGN(UBIFS_MAX_NODE_SZ, c->min_io_size); /* * Calculate how many bytes would be wasted at the end of LEB if it was * fully filled with data nodes of maximum size. This is used in * calculations when reporting free space. */ c->leb_overhead = c->leb_size % UBIFS_MAX_DATA_NODE_SZ; return 0; } /* * init_constants_sb - initialize UBIFS constants. * @c: UBIFS file-system description object * * This is a helper function which initializes various UBIFS constants after * the superblock has been read. It also checks various UBIFS parameters and * makes sure they are all right. Returns zero in case of success and a * negative error code in case of failure. */ static int init_constants_sb(struct ubifs_info *c) { int tmp, err; long long tmp64; c->main_bytes = (long long)c->main_lebs * c->leb_size; c->max_znode_sz = sizeof(struct ubifs_znode) + c->fanout * sizeof(struct ubifs_zbranch); tmp = ubifs_idx_node_sz(c, 1); c->ranges[UBIFS_IDX_NODE].min_len = tmp; c->min_idx_node_sz = ALIGN(tmp, 8); tmp = ubifs_idx_node_sz(c, c->fanout); c->ranges[UBIFS_IDX_NODE].max_len = tmp; c->max_idx_node_sz = ALIGN(tmp, 8); /* Make sure LEB size is large enough to fit full commit */ tmp = UBIFS_CS_NODE_SZ + UBIFS_REF_NODE_SZ * c->jhead_cnt; tmp = ALIGN(tmp, c->min_io_size); if (tmp > c->leb_size) { dbg_err("too small LEB size %d, at least %d needed", c->leb_size, tmp); return -EINVAL; } /* * Make sure that the log is large enough to fit reference nodes for * all buds plus one reserved LEB. */ tmp64 = c->max_bud_bytes + c->leb_size - 1; c->max_bud_cnt = div_u64(tmp64, c->leb_size); tmp = (c->ref_node_alsz * c->max_bud_cnt + c->leb_size - 1); tmp /= c->leb_size; tmp += 1; if (c->log_lebs < tmp) { dbg_err("too small log %d LEBs, required min. %d LEBs", c->log_lebs, tmp); return -EINVAL; } /* * When budgeting we assume worst-case scenarios when the pages are not * be compressed and direntries are of the maximum size. * * Note, data, which may be stored in inodes is budgeted separately, so * it is not included into 'c->inode_budget'. */ c->page_budget = UBIFS_MAX_DATA_NODE_SZ * UBIFS_BLOCKS_PER_PAGE; c->inode_budget = UBIFS_INO_NODE_SZ; c->dent_budget = UBIFS_MAX_DENT_NODE_SZ; /* * When the amount of flash space used by buds becomes * 'c->max_bud_bytes', UBIFS just blocks all writers and starts commit. * The writers are unblocked when the commit is finished. To avoid * writers to be blocked UBIFS initiates background commit in advance, * when number of bud bytes becomes above the limit defined below. */ c->bg_bud_bytes = (c->max_bud_bytes * 13) >> 4; /* * Ensure minimum journal size. All the bytes in the journal heads are * considered to be used, when calculating the current journal usage. * Consequently, if the journal is too small, UBIFS will treat it as * always full. */ tmp64 = (long long)(c->jhead_cnt + 1) * c->leb_size + 1; if (c->bg_bud_bytes < tmp64) c->bg_bud_bytes = tmp64; if (c->max_bud_bytes < tmp64 + c->leb_size) c->max_bud_bytes = tmp64 + c->leb_size; err = ubifs_calc_lpt_geom(c); if (err) return err; return 0; } /* * init_constants_master - initialize UBIFS constants. * @c: UBIFS file-system description object * * This is a helper function which initializes various UBIFS constants after * the master node has been read. It also checks various UBIFS parameters and * makes sure they are all right. */ static void init_constants_master(struct ubifs_info *c) { long long tmp64; c->min_idx_lebs = ubifs_calc_min_idx_lebs(c); /* * Calculate total amount of FS blocks. This number is not used * internally because it does not make much sense for UBIFS, but it is * necessary to report something for the 'statfs()' call. * * Subtract the LEB reserved for GC, the LEB which is reserved for * deletions, minimum LEBs for the index, and assume only one journal * head is available. */ tmp64 = c->main_lebs - 1 - 1 - MIN_INDEX_LEBS - c->jhead_cnt + 1; tmp64 *= (long long)c->leb_size - c->leb_overhead; tmp64 = ubifs_reported_space(c, tmp64); c->block_cnt = tmp64 >> UBIFS_BLOCK_SHIFT; } /** * free_orphans - free orphans. * @c: UBIFS file-system description object */ static void free_orphans(struct ubifs_info *c) { struct ubifs_orphan *orph; while (c->orph_dnext) { orph = c->orph_dnext; c->orph_dnext = orph->dnext; list_del(&orph->list); kfree(orph); } while (!list_empty(&c->orph_list)) { orph = list_entry(c->orph_list.next, struct ubifs_orphan, list); list_del(&orph->list); kfree(orph); dbg_err("orphan list not empty at unmount"); } vfree(c->orph_buf); c->orph_buf = NULL; } /** * check_volume_empty - check if the UBI volume is empty. * @c: UBIFS file-system description object * * This function checks if the UBIFS volume is empty by looking if its LEBs are * mapped or not. The result of checking is stored in the @c->empty variable. * Returns zero in case of success and a negative error code in case of * failure. */ static int check_volume_empty(struct ubifs_info *c) { int lnum, err; c->empty = 1; for (lnum = 0; lnum < c->leb_cnt; lnum++) { err = ubi_is_mapped(c->ubi, lnum); if (unlikely(err < 0)) return err; if (err == 1) { c->empty = 0; break; } cond_resched(); } return 0; } /** * mount_ubifs - mount UBIFS file-system. * @c: UBIFS file-system description object * * This function mounts UBIFS file system. Returns zero in case of success and * a negative error code in case of failure. * * Note, the function does not de-allocate resources it it fails half way * through, and the caller has to do this instead. */ static int mount_ubifs(struct ubifs_info *c) { struct super_block *sb = c->vfs_sb; int err, mounted_read_only = (sb->s_flags & MS_RDONLY); long long x; size_t sz; err = init_constants_early(c); if (err) return err; err = ubifs_debugging_init(c); if (err) return err; err = check_volume_empty(c); if (err) goto out_free; if (c->empty && (mounted_read_only || c->ro_media)) { /* * This UBI volume is empty, and read-only, or the file system * is mounted read-only - we cannot format it. */ ubifs_err("can't format empty UBI volume: read-only %s", c->ro_media ? "UBI volume" : "mount"); err = -EROFS; goto out_free; } if (c->ro_media && !mounted_read_only) { ubifs_err("cannot mount read-write - read-only media"); err = -EROFS; goto out_free; } /* * The requirement for the buffer is that it should fit indexing B-tree * height amount of integers. We assume the height if the TNC tree will * never exceed 64. */ err = -ENOMEM; c->bottom_up_buf = kmalloc(BOTTOM_UP_HEIGHT * sizeof(int), GFP_KERNEL); if (!c->bottom_up_buf) goto out_free; c->sbuf = vmalloc(c->leb_size); if (!c->sbuf) goto out_free; /* * We have to check all CRCs, even for data nodes, when we mount the FS * (specifically, when we are replaying). */ c->always_chk_crc = 1; err = ubifs_read_superblock(c); if (err) goto out_free; /* * Make sure the compressor which is set as default in the superblock * or overridden by mount options is actually compiled in. */ if (!ubifs_compr_present(c->default_compr)) { ubifs_err("'compressor \"%s\" is not compiled in", ubifs_compr_name(c->default_compr)); goto out_free; } dbg_failure_mode_registration(c); err = init_constants_sb(c); if (err) goto out_free; sz = ALIGN(c->max_idx_node_sz, c->min_io_size); sz = ALIGN(sz + c->max_idx_node_sz, c->min_io_size); c->cbuf = kmalloc(sz, GFP_NOFS); if (!c->cbuf) { err = -ENOMEM; goto out_free; } sprintf(c->bgt_name, BGT_NAME_PATTERN, c->vi.ubi_num, c->vi.vol_id); err = ubifs_read_master(c); if (err) goto out_master; init_constants_master(c); if ((c->mst_node->flags & cpu_to_le32(UBIFS_MST_DIRTY)) != 0) { ubifs_msg("recovery needed"); c->need_recovery = 1; } err = ubifs_lpt_init(c, 1, !mounted_read_only); if (err) goto out_lpt; err = dbg_check_idx_size(c, c->old_idx_sz); if (err) goto out_lpt; err = ubifs_replay_journal(c); if (err) goto out_journal; err = ubifs_mount_orphans(c, c->need_recovery, mounted_read_only); if (err) goto out_orphans; if (c->need_recovery) { err = ubifs_recover_size(c); if (err) goto out_orphans; } spin_lock(&ubifs_infos_lock); list_add_tail(&c->infos_list, &ubifs_infos); spin_unlock(&ubifs_infos_lock); if (c->need_recovery) { if (mounted_read_only) ubifs_msg("recovery deferred"); else { c->need_recovery = 0; ubifs_msg("recovery completed"); } } err = dbg_check_filesystem(c); if (err) goto out_infos; c->always_chk_crc = 0; ubifs_msg("mounted UBI device %d, volume %d, name \"%s\"", c->vi.ubi_num, c->vi.vol_id, c->vi.name); if (mounted_read_only) ubifs_msg("mounted read-only"); x = (long long)c->main_lebs * c->leb_size; ubifs_msg("file system size: %lld bytes (%lld KiB, %lld MiB, %d " "LEBs)", x, x >> 10, x >> 20, c->main_lebs); x = (long long)c->log_lebs * c->leb_size + c->max_bud_bytes; ubifs_msg("journal size: %lld bytes (%lld KiB, %lld MiB, %d " "LEBs)", x, x >> 10, x >> 20, c->log_lebs + c->max_bud_cnt); ubifs_msg("media format: w%d/r%d (latest is w%d/r%d)", c->fmt_version, c->ro_compat_version, UBIFS_FORMAT_VERSION, UBIFS_RO_COMPAT_VERSION); ubifs_msg("default compressor: %s", ubifs_compr_name(c->default_compr)); ubifs_msg("reserved for root: %llu bytes (%llu KiB)", c->report_rp_size, c->report_rp_size >> 10); dbg_msg("compiled on: " __DATE__ " at " __TIME__); dbg_msg("min. I/O unit size: %d bytes", c->min_io_size); dbg_msg("LEB size: %d bytes (%d KiB)", c->leb_size, c->leb_size >> 10); dbg_msg("data journal heads: %d", c->jhead_cnt - NONDATA_JHEADS_CNT); dbg_msg("UUID: %02X%02X%02X%02X-%02X%02X" "-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", c->uuid[0], c->uuid[1], c->uuid[2], c->uuid[3], c->uuid[4], c->uuid[5], c->uuid[6], c->uuid[7], c->uuid[8], c->uuid[9], c->uuid[10], c->uuid[11], c->uuid[12], c->uuid[13], c->uuid[14], c->uuid[15]); dbg_msg("big_lpt %d", c->big_lpt); dbg_msg("log LEBs: %d (%d - %d)", c->log_lebs, UBIFS_LOG_LNUM, c->log_last); dbg_msg("LPT area LEBs: %d (%d - %d)", c->lpt_lebs, c->lpt_first, c->lpt_last); dbg_msg("orphan area LEBs: %d (%d - %d)", c->orph_lebs, c->orph_first, c->orph_last); dbg_msg("main area LEBs: %d (%d - %d)", c->main_lebs, c->main_first, c->leb_cnt - 1); dbg_msg("index LEBs: %d", c->lst.idx_lebs); dbg_msg("total index bytes: %lld (%lld KiB, %lld MiB)", c->old_idx_sz, c->old_idx_sz >> 10, c->old_idx_sz >> 20); dbg_msg("key hash type: %d", c->key_hash_type); dbg_msg("tree fanout: %d", c->fanout); dbg_msg("reserved GC LEB: %d", c->gc_lnum); dbg_msg("first main LEB: %d", c->main_first); dbg_msg("max. znode size %d", c->max_znode_sz); dbg_msg("max. index node size %d", c->max_idx_node_sz); dbg_msg("node sizes: data %zu, inode %zu, dentry %zu", UBIFS_DATA_NODE_SZ, UBIFS_INO_NODE_SZ, UBIFS_DENT_NODE_SZ); dbg_msg("node sizes: trun %zu, sb %zu, master %zu", UBIFS_TRUN_NODE_SZ, UBIFS_SB_NODE_SZ, UBIFS_MST_NODE_SZ); dbg_msg("node sizes: ref %zu, cmt. start %zu, orph %zu", UBIFS_REF_NODE_SZ, UBIFS_CS_NODE_SZ, UBIFS_ORPH_NODE_SZ); dbg_msg("max. node sizes: data %zu, inode %zu dentry %zu", UBIFS_MAX_DATA_NODE_SZ, UBIFS_MAX_INO_NODE_SZ, UBIFS_MAX_DENT_NODE_SZ); dbg_msg("dead watermark: %d", c->dead_wm); dbg_msg("dark watermark: %d", c->dark_wm); dbg_msg("LEB overhead: %d", c->leb_overhead); x = (long long)c->main_lebs * c->dark_wm; dbg_msg("max. dark space: %lld (%lld KiB, %lld MiB)", x, x >> 10, x >> 20); dbg_msg("maximum bud bytes: %lld (%lld KiB, %lld MiB)", c->max_bud_bytes, c->max_bud_bytes >> 10, c->max_bud_bytes >> 20); dbg_msg("BG commit bud bytes: %lld (%lld KiB, %lld MiB)", c->bg_bud_bytes, c->bg_bud_bytes >> 10, c->bg_bud_bytes >> 20); dbg_msg("current bud bytes %lld (%lld KiB, %lld MiB)", c->bud_bytes, c->bud_bytes >> 10, c->bud_bytes >> 20); dbg_msg("max. seq. number: %llu", c->max_sqnum); dbg_msg("commit number: %llu", c->cmt_no); return 0; out_infos: spin_lock(&ubifs_infos_lock); list_del(&c->infos_list); spin_unlock(&ubifs_infos_lock); out_orphans: free_orphans(c); out_journal: out_lpt: ubifs_lpt_free(c, 0); out_master: kfree(c->mst_node); kfree(c->rcvrd_mst_node); if (c->bgt) kthread_stop(c->bgt); kfree(c->cbuf); out_free: vfree(c->ileb_buf); vfree(c->sbuf); kfree(c->bottom_up_buf); ubifs_debugging_exit(c); return err; } /** * ubifs_umount - un-mount UBIFS file-system. * @c: UBIFS file-system description object * * Note, this function is called to free allocated resourced when un-mounting, * as well as free resources when an error occurred while we were half way * through mounting (error path cleanup function). So it has to make sure the * resource was actually allocated before freeing it. */ void ubifs_umount(struct ubifs_info *c) { dbg_gen("un-mounting UBI device %d, volume %d", c->vi.ubi_num, c->vi.vol_id); spin_lock(&ubifs_infos_lock); list_del(&c->infos_list); spin_unlock(&ubifs_infos_lock); if (c->bgt) kthread_stop(c->bgt); free_orphans(c); ubifs_lpt_free(c, 0); kfree(c->cbuf); kfree(c->rcvrd_mst_node); kfree(c->mst_node); vfree(c->ileb_buf); vfree(c->sbuf); kfree(c->bottom_up_buf); ubifs_debugging_exit(c); /* Finally free U-Boot's global copy of superblock */ if (ubifs_sb != NULL) { free(ubifs_sb->s_fs_info); free(ubifs_sb); } } /** * open_ubi - parse UBI device name string and open the UBI device. * @name: UBI volume name * @mode: UBI volume open mode * * There are several ways to specify UBI volumes when mounting UBIFS: * o ubiX_Y - UBI device number X, volume Y; * o ubiY - UBI device number 0, volume Y; * o ubiX:NAME - mount UBI device X, volume with name NAME; * o ubi:NAME - mount UBI device 0, volume with name NAME. * * Alternative '!' separator may be used instead of ':' (because some shells * like busybox may interpret ':' as an NFS host name separator). This function * returns ubi volume object in case of success and a negative error code in * case of failure. */ static struct ubi_volume_desc *open_ubi(const char *name, int mode) { int dev, vol; char *endptr; if (name[0] != 'u' || name[1] != 'b' || name[2] != 'i') return ERR_PTR(-EINVAL); /* ubi:NAME method */ if ((name[3] == ':' || name[3] == '!') && name[4] != '\0') return ubi_open_volume_nm(0, name + 4, mode); if (!isdigit(name[3])) return ERR_PTR(-EINVAL); dev = simple_strtoul(name + 3, &endptr, 0); /* ubiY method */ if (*endptr == '\0') return ubi_open_volume(0, dev, mode); /* ubiX_Y method */ if (*endptr == '_' && isdigit(endptr[1])) { vol = simple_strtoul(endptr + 1, &endptr, 0); if (*endptr != '\0') return ERR_PTR(-EINVAL); return ubi_open_volume(dev, vol, mode); } /* ubiX:NAME method */ if ((*endptr == ':' || *endptr == '!') && endptr[1] != '\0') return ubi_open_volume_nm(dev, ++endptr, mode); return ERR_PTR(-EINVAL); } static int ubifs_fill_super(struct super_block *sb, void *data, int silent) { struct ubi_volume_desc *ubi = sb->s_fs_info; struct ubifs_info *c; struct inode *root; int err; c = kzalloc(sizeof(struct ubifs_info), GFP_KERNEL); if (!c) return -ENOMEM; spin_lock_init(&c->cnt_lock); spin_lock_init(&c->cs_lock); spin_lock_init(&c->buds_lock); spin_lock_init(&c->space_lock); spin_lock_init(&c->orphan_lock); init_rwsem(&c->commit_sem); mutex_init(&c->lp_mutex); mutex_init(&c->tnc_mutex); mutex_init(&c->log_mutex); mutex_init(&c->mst_mutex); mutex_init(&c->umount_mutex); init_waitqueue_head(&c->cmt_wq); c->buds = RB_ROOT; c->old_idx = RB_ROOT; c->size_tree = RB_ROOT; c->orph_tree = RB_ROOT; INIT_LIST_HEAD(&c->infos_list); INIT_LIST_HEAD(&c->idx_gc); INIT_LIST_HEAD(&c->replay_list); INIT_LIST_HEAD(&c->replay_buds); INIT_LIST_HEAD(&c->uncat_list); INIT_LIST_HEAD(&c->empty_list); INIT_LIST_HEAD(&c->freeable_list); INIT_LIST_HEAD(&c->frdi_idx_list); INIT_LIST_HEAD(&c->unclean_leb_list); INIT_LIST_HEAD(&c->old_buds); INIT_LIST_HEAD(&c->orph_list); INIT_LIST_HEAD(&c->orph_new); c->highest_inum = UBIFS_FIRST_INO; c->lhead_lnum = c->ltail_lnum = UBIFS_LOG_LNUM; ubi_get_volume_info(ubi, &c->vi); ubi_get_device_info(c->vi.ubi_num, &c->di); /* Re-open the UBI device in read-write mode */ c->ubi = ubi_open_volume(c->vi.ubi_num, c->vi.vol_id, UBI_READONLY); if (IS_ERR(c->ubi)) { err = PTR_ERR(c->ubi); goto out_free; } c->vfs_sb = sb; sb->s_fs_info = c; sb->s_magic = UBIFS_SUPER_MAGIC; sb->s_blocksize = UBIFS_BLOCK_SIZE; sb->s_blocksize_bits = UBIFS_BLOCK_SHIFT; sb->s_dev = c->vi.cdev; sb->s_maxbytes = c->max_inode_sz = key_max_inode_size(c); if (c->max_inode_sz > MAX_LFS_FILESIZE) sb->s_maxbytes = c->max_inode_sz = MAX_LFS_FILESIZE; if (c->rw_incompat) { ubifs_err("the file-system is not R/W-compatible"); ubifs_msg("on-flash format version is w%d/r%d, but software " "only supports up to version w%d/r%d", c->fmt_version, c->ro_compat_version, UBIFS_FORMAT_VERSION, UBIFS_RO_COMPAT_VERSION); return -EROFS; } mutex_lock(&c->umount_mutex); err = mount_ubifs(c); if (err) { ubifs_assert(err < 0); goto out_unlock; } /* Read the root inode */ root = ubifs_iget(sb, UBIFS_ROOT_INO); if (IS_ERR(root)) { err = PTR_ERR(root); goto out_umount; } sb->s_root = NULL; mutex_unlock(&c->umount_mutex); return 0; out_umount: ubifs_umount(c); out_unlock: mutex_unlock(&c->umount_mutex); ubi_close_volume(c->ubi); out_free: kfree(c); return err; } static int sb_test(struct super_block *sb, void *data) { dev_t *dev = data; return sb->s_dev == *dev; } static int ubifs_get_sb(struct file_system_type *fs_type, int flags, const char *name, void *data, struct vfsmount *mnt) { struct ubi_volume_desc *ubi; struct ubi_volume_info vi; struct super_block *sb; int err; dbg_gen("name %s, flags %#x", name, flags); /* * Get UBI device number and volume ID. Mount it read-only so far * because this might be a new mount point, and UBI allows only one * read-write user at a time. */ ubi = open_ubi(name, UBI_READONLY); if (IS_ERR(ubi)) { ubifs_err("cannot open \"%s\", error %d", name, (int)PTR_ERR(ubi)); return PTR_ERR(ubi); } ubi_get_volume_info(ubi, &vi); dbg_gen("opened ubi%d_%d", vi.ubi_num, vi.vol_id); sb = sget(fs_type, &sb_test, &sb_set, &vi.cdev); if (IS_ERR(sb)) { err = PTR_ERR(sb); goto out_close; } if (sb->s_root) { /* A new mount point for already mounted UBIFS */ dbg_gen("this ubi volume is already mounted"); if ((flags ^ sb->s_flags) & MS_RDONLY) { err = -EBUSY; goto out_deact; } } else { sb->s_flags = flags; /* * Pass 'ubi' to 'fill_super()' in sb->s_fs_info where it is * replaced by 'c'. */ sb->s_fs_info = ubi; err = ubifs_fill_super(sb, data, flags & MS_SILENT ? 1 : 0); if (err) goto out_deact; /* We do not support atime */ sb->s_flags |= MS_ACTIVE | MS_NOATIME; } /* 'fill_super()' opens ubi again so we must close it here */ ubi_close_volume(ubi); ubifs_sb = sb; return 0; out_deact: up_write(&sb->s_umount); out_close: ubi_close_volume(ubi); return err; } int __init ubifs_init(void) { int err; BUILD_BUG_ON(sizeof(struct ubifs_ch) != 24); /* Make sure node sizes are 8-byte aligned */ BUILD_BUG_ON(UBIFS_CH_SZ & 7); BUILD_BUG_ON(UBIFS_INO_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_DENT_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_XENT_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_DATA_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_TRUN_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_SB_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_MST_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_REF_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_CS_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_ORPH_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_MAX_DENT_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_MAX_XENT_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_MAX_DATA_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_MAX_INO_NODE_SZ & 7); BUILD_BUG_ON(UBIFS_MAX_NODE_SZ & 7); BUILD_BUG_ON(MIN_WRITE_SZ & 7); /* Check min. node size */ BUILD_BUG_ON(UBIFS_INO_NODE_SZ < MIN_WRITE_SZ); BUILD_BUG_ON(UBIFS_DENT_NODE_SZ < MIN_WRITE_SZ); BUILD_BUG_ON(UBIFS_XENT_NODE_SZ < MIN_WRITE_SZ); BUILD_BUG_ON(UBIFS_TRUN_NODE_SZ < MIN_WRITE_SZ); BUILD_BUG_ON(UBIFS_MAX_DENT_NODE_SZ > UBIFS_MAX_NODE_SZ); BUILD_BUG_ON(UBIFS_MAX_XENT_NODE_SZ > UBIFS_MAX_NODE_SZ); BUILD_BUG_ON(UBIFS_MAX_DATA_NODE_SZ > UBIFS_MAX_NODE_SZ); BUILD_BUG_ON(UBIFS_MAX_INO_NODE_SZ > UBIFS_MAX_NODE_SZ); /* Defined node sizes */ BUILD_BUG_ON(UBIFS_SB_NODE_SZ != 4096); BUILD_BUG_ON(UBIFS_MST_NODE_SZ != 512); BUILD_BUG_ON(UBIFS_INO_NODE_SZ != 160); BUILD_BUG_ON(UBIFS_REF_NODE_SZ != 64); /* * We use 2 bit wide bit-fields to store compression type, which should * be amended if more compressors are added. The bit-fields are: * @compr_type in 'struct ubifs_inode', @default_compr in * 'struct ubifs_info' and @compr_type in 'struct ubifs_mount_opts'. */ BUILD_BUG_ON(UBIFS_COMPR_TYPES_CNT > 4); /* * We require that PAGE_CACHE_SIZE is greater-than-or-equal-to * UBIFS_BLOCK_SIZE. It is assumed that both are powers of 2. */ if (PAGE_CACHE_SIZE < UBIFS_BLOCK_SIZE) { ubifs_err("VFS page cache size is %u bytes, but UBIFS requires" " at least 4096 bytes", (unsigned int)PAGE_CACHE_SIZE); return -EINVAL; } err = -ENOMEM; err = ubifs_compressors_init(); if (err) goto out_shrinker; return 0; out_shrinker: return err; } /* * ubifsmount... */ static struct file_system_type ubifs_fs_type = { .name = "ubifs", .owner = THIS_MODULE, .get_sb = ubifs_get_sb, }; int ubifs_mount(char *vol_name) { int flags; char name[80] = "ubi:"; void *data; struct vfsmount *mnt; int ret; struct ubifs_info *c; /* * First unmount if allready mounted */ if (ubifs_sb) ubifs_umount(ubifs_sb->s_fs_info); INIT_LIST_HEAD(&ubifs_infos); INIT_LIST_HEAD(&ubifs_fs_type.fs_supers); /* * Mount in read-only mode */ flags = MS_RDONLY; strcat(name, vol_name); data = NULL; mnt = NULL; ret = ubifs_get_sb(&ubifs_fs_type, flags, name, data, mnt); if (ret) { printf("Error reading superblock on volume '%s'!\n", name); return -1; } c = ubifs_sb->s_fs_info; ubi_close_volume(c->ubi); return 0; }
1001-study-uboot
fs/ubifs/super.c
C
gpl3
32,828
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter */ /* * This file is a part of UBIFS journal implementation and contains various * functions which manipulate the log. The log is a fixed area on the flash * which does not contain any data but refers to buds. The log is a part of the * journal. */ #include "ubifs.h" /** * ubifs_search_bud - search bud LEB. * @c: UBIFS file-system description object * @lnum: logical eraseblock number to search * * This function searches bud LEB @lnum. Returns bud description object in case * of success and %NULL if there is no bud with this LEB number. */ struct ubifs_bud *ubifs_search_bud(struct ubifs_info *c, int lnum) { struct rb_node *p; struct ubifs_bud *bud; spin_lock(&c->buds_lock); p = c->buds.rb_node; while (p) { bud = rb_entry(p, struct ubifs_bud, rb); if (lnum < bud->lnum) p = p->rb_left; else if (lnum > bud->lnum) p = p->rb_right; else { spin_unlock(&c->buds_lock); return bud; } } spin_unlock(&c->buds_lock); return NULL; } /** * ubifs_add_bud - add bud LEB to the tree of buds and its journal head list. * @c: UBIFS file-system description object * @bud: the bud to add */ void ubifs_add_bud(struct ubifs_info *c, struct ubifs_bud *bud) { struct rb_node **p, *parent = NULL; struct ubifs_bud *b; struct ubifs_jhead *jhead; spin_lock(&c->buds_lock); p = &c->buds.rb_node; while (*p) { parent = *p; b = rb_entry(parent, struct ubifs_bud, rb); ubifs_assert(bud->lnum != b->lnum); if (bud->lnum < b->lnum) p = &(*p)->rb_left; else p = &(*p)->rb_right; } rb_link_node(&bud->rb, parent, p); rb_insert_color(&bud->rb, &c->buds); if (c->jheads) { jhead = &c->jheads[bud->jhead]; list_add_tail(&bud->list, &jhead->buds_list); } else ubifs_assert(c->replaying && (c->vfs_sb->s_flags & MS_RDONLY)); /* * Note, although this is a new bud, we anyway account this space now, * before any data has been written to it, because this is about to * guarantee fixed mount time, and this bud will anyway be read and * scanned. */ c->bud_bytes += c->leb_size - bud->start; dbg_log("LEB %d:%d, jhead %d, bud_bytes %lld", bud->lnum, bud->start, bud->jhead, c->bud_bytes); spin_unlock(&c->buds_lock); }
1001-study-uboot
fs/ubifs/log.c
C
gpl3
3,013
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: Adrian Hunter */ #include "ubifs.h" /* * An orphan is an inode number whose inode node has been committed to the index * with a link count of zero. That happens when an open file is deleted * (unlinked) and then a commit is run. In the normal course of events the inode * would be deleted when the file is closed. However in the case of an unclean * unmount, orphans need to be accounted for. After an unclean unmount, the * orphans' inodes must be deleted which means either scanning the entire index * looking for them, or keeping a list on flash somewhere. This unit implements * the latter approach. * * The orphan area is a fixed number of LEBs situated between the LPT area and * the main area. The number of orphan area LEBs is specified when the file * system is created. The minimum number is 1. The size of the orphan area * should be so that it can hold the maximum number of orphans that are expected * to ever exist at one time. * * The number of orphans that can fit in a LEB is: * * (c->leb_size - UBIFS_ORPH_NODE_SZ) / sizeof(__le64) * * For example: a 15872 byte LEB can fit 1980 orphans so 1 LEB may be enough. * * Orphans are accumulated in a rb-tree. When an inode's link count drops to * zero, the inode number is added to the rb-tree. It is removed from the tree * when the inode is deleted. Any new orphans that are in the orphan tree when * the commit is run, are written to the orphan area in 1 or more orphan nodes. * If the orphan area is full, it is consolidated to make space. There is * always enough space because validation prevents the user from creating more * than the maximum number of orphans allowed. */ /** * tot_avail_orphs - calculate total space. * @c: UBIFS file-system description object * * This function returns the number of orphans that can be written in half * the total space. That leaves half the space for adding new orphans. */ static int tot_avail_orphs(struct ubifs_info *c) { int avail_lebs, avail; avail_lebs = c->orph_lebs; avail = avail_lebs * ((c->leb_size - UBIFS_ORPH_NODE_SZ) / sizeof(__le64)); return avail / 2; } /** * ubifs_clear_orphans - erase all LEBs used for orphans. * @c: UBIFS file-system description object * * If recovery is not required, then the orphans from the previous session * are not needed. This function locates the LEBs used to record * orphans, and un-maps them. */ int ubifs_clear_orphans(struct ubifs_info *c) { int lnum, err; for (lnum = c->orph_first; lnum <= c->orph_last; lnum++) { err = ubifs_leb_unmap(c, lnum); if (err) return err; } c->ohead_lnum = c->orph_first; c->ohead_offs = 0; return 0; } /** * insert_dead_orphan - insert an orphan. * @c: UBIFS file-system description object * @inum: orphan inode number * * This function is a helper to the 'do_kill_orphans()' function. The orphan * must be kept until the next commit, so it is added to the rb-tree and the * deletion list. */ static int insert_dead_orphan(struct ubifs_info *c, ino_t inum) { struct ubifs_orphan *orphan, *o; struct rb_node **p, *parent = NULL; orphan = kzalloc(sizeof(struct ubifs_orphan), GFP_KERNEL); if (!orphan) return -ENOMEM; orphan->inum = inum; p = &c->orph_tree.rb_node; while (*p) { parent = *p; o = rb_entry(parent, struct ubifs_orphan, rb); if (inum < o->inum) p = &(*p)->rb_left; else if (inum > o->inum) p = &(*p)->rb_right; else { /* Already added - no problem */ kfree(orphan); return 0; } } c->tot_orphans += 1; rb_link_node(&orphan->rb, parent, p); rb_insert_color(&orphan->rb, &c->orph_tree); list_add_tail(&orphan->list, &c->orph_list); orphan->dnext = c->orph_dnext; c->orph_dnext = orphan; dbg_mnt("ino %lu, new %d, tot %d", (unsigned long)inum, c->new_orphans, c->tot_orphans); return 0; } /** * do_kill_orphans - remove orphan inodes from the index. * @c: UBIFS file-system description object * @sleb: scanned LEB * @last_cmt_no: cmt_no of last orphan node read is passed and returned here * @outofdate: whether the LEB is out of date is returned here * @last_flagged: whether the end orphan node is encountered * * This function is a helper to the 'kill_orphans()' function. It goes through * every orphan node in a LEB and for every inode number recorded, removes * all keys for that inode from the TNC. */ static int do_kill_orphans(struct ubifs_info *c, struct ubifs_scan_leb *sleb, unsigned long long *last_cmt_no, int *outofdate, int *last_flagged) { struct ubifs_scan_node *snod; struct ubifs_orph_node *orph; unsigned long long cmt_no; ino_t inum; int i, n, err, first = 1; list_for_each_entry(snod, &sleb->nodes, list) { if (snod->type != UBIFS_ORPH_NODE) { ubifs_err("invalid node type %d in orphan area at " "%d:%d", snod->type, sleb->lnum, snod->offs); dbg_dump_node(c, snod->node); return -EINVAL; } orph = snod->node; /* Check commit number */ cmt_no = le64_to_cpu(orph->cmt_no) & LLONG_MAX; /* * The commit number on the master node may be less, because * of a failed commit. If there are several failed commits in a * row, the commit number written on orphan nodes will continue * to increase (because the commit number is adjusted here) even * though the commit number on the master node stays the same * because the master node has not been re-written. */ if (cmt_no > c->cmt_no) c->cmt_no = cmt_no; if (cmt_no < *last_cmt_no && *last_flagged) { /* * The last orphan node had a higher commit number and * was flagged as the last written for that commit * number. That makes this orphan node, out of date. */ if (!first) { ubifs_err("out of order commit number %llu in " "orphan node at %d:%d", cmt_no, sleb->lnum, snod->offs); dbg_dump_node(c, snod->node); return -EINVAL; } dbg_rcvry("out of date LEB %d", sleb->lnum); *outofdate = 1; return 0; } if (first) first = 0; n = (le32_to_cpu(orph->ch.len) - UBIFS_ORPH_NODE_SZ) >> 3; for (i = 0; i < n; i++) { inum = le64_to_cpu(orph->inos[i]); dbg_rcvry("deleting orphaned inode %lu", (unsigned long)inum); err = ubifs_tnc_remove_ino(c, inum); if (err) return err; err = insert_dead_orphan(c, inum); if (err) return err; } *last_cmt_no = cmt_no; if (le64_to_cpu(orph->cmt_no) & (1ULL << 63)) { dbg_rcvry("last orph node for commit %llu at %d:%d", cmt_no, sleb->lnum, snod->offs); *last_flagged = 1; } else *last_flagged = 0; } return 0; } /** * kill_orphans - remove all orphan inodes from the index. * @c: UBIFS file-system description object * * If recovery is required, then orphan inodes recorded during the previous * session (which ended with an unclean unmount) must be deleted from the index. * This is done by updating the TNC, but since the index is not updated until * the next commit, the LEBs where the orphan information is recorded are not * erased until the next commit. */ static int kill_orphans(struct ubifs_info *c) { unsigned long long last_cmt_no = 0; int lnum, err = 0, outofdate = 0, last_flagged = 0; c->ohead_lnum = c->orph_first; c->ohead_offs = 0; /* Check no-orphans flag and skip this if no orphans */ if (c->no_orphs) { dbg_rcvry("no orphans"); return 0; } /* * Orph nodes always start at c->orph_first and are written to each * successive LEB in turn. Generally unused LEBs will have been unmapped * but may contain out of date orphan nodes if the unmap didn't go * through. In addition, the last orphan node written for each commit is * marked (top bit of orph->cmt_no is set to 1). It is possible that * there are orphan nodes from the next commit (i.e. the commit did not * complete successfully). In that case, no orphans will have been lost * due to the way that orphans are written, and any orphans added will * be valid orphans anyway and so can be deleted. */ for (lnum = c->orph_first; lnum <= c->orph_last; lnum++) { struct ubifs_scan_leb *sleb; dbg_rcvry("LEB %d", lnum); sleb = ubifs_scan(c, lnum, 0, c->sbuf); if (IS_ERR(sleb)) { sleb = ubifs_recover_leb(c, lnum, 0, c->sbuf, 0); if (IS_ERR(sleb)) { err = PTR_ERR(sleb); break; } } err = do_kill_orphans(c, sleb, &last_cmt_no, &outofdate, &last_flagged); if (err || outofdate) { ubifs_scan_destroy(sleb); break; } if (sleb->endpt) { c->ohead_lnum = lnum; c->ohead_offs = sleb->endpt; } ubifs_scan_destroy(sleb); } return err; } /** * ubifs_mount_orphans - delete orphan inodes and erase LEBs that recorded them. * @c: UBIFS file-system description object * @unclean: indicates recovery from unclean unmount * @read_only: indicates read only mount * * This function is called when mounting to erase orphans from the previous * session. If UBIFS was not unmounted cleanly, then the inodes recorded as * orphans are deleted. */ int ubifs_mount_orphans(struct ubifs_info *c, int unclean, int read_only) { int err = 0; c->max_orphans = tot_avail_orphs(c); if (!read_only) { c->orph_buf = vmalloc(c->leb_size); if (!c->orph_buf) return -ENOMEM; } if (unclean) err = kill_orphans(c); else if (!read_only) err = ubifs_clear_orphans(c); return err; }
1001-study-uboot
fs/ubifs/orphan.c
C
gpl3
10,049
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Adrian Hunter * Artem Bityutskiy (Битюцкий Артём) */ /* * This file implements TNC (Tree Node Cache) which caches indexing nodes of * the UBIFS B-tree. * * At the moment the locking rules of the TNC tree are quite simple and * straightforward. We just have a mutex and lock it when we traverse the * tree. If a znode is not in memory, we read it from flash while still having * the mutex locked. */ #include "ubifs.h" /* * Returned codes of 'matches_name()' and 'fallible_matches_name()' functions. * @NAME_LESS: name corresponding to the first argument is less than second * @NAME_MATCHES: names match * @NAME_GREATER: name corresponding to the second argument is greater than * first * @NOT_ON_MEDIA: node referred by zbranch does not exist on the media * * These constants were introduce to improve readability. */ enum { NAME_LESS = 0, NAME_MATCHES = 1, NAME_GREATER = 2, NOT_ON_MEDIA = 3, }; /** * insert_old_idx - record an index node obsoleted since the last commit start. * @c: UBIFS file-system description object * @lnum: LEB number of obsoleted index node * @offs: offset of obsoleted index node * * Returns %0 on success, and a negative error code on failure. * * For recovery, there must always be a complete intact version of the index on * flash at all times. That is called the "old index". It is the index as at the * time of the last successful commit. Many of the index nodes in the old index * may be dirty, but they must not be erased until the next successful commit * (at which point that index becomes the old index). * * That means that the garbage collection and the in-the-gaps method of * committing must be able to determine if an index node is in the old index. * Most of the old index nodes can be found by looking up the TNC using the * 'lookup_znode()' function. However, some of the old index nodes may have * been deleted from the current index or may have been changed so much that * they cannot be easily found. In those cases, an entry is added to an RB-tree. * That is what this function does. The RB-tree is ordered by LEB number and * offset because they uniquely identify the old index node. */ static int insert_old_idx(struct ubifs_info *c, int lnum, int offs) { struct ubifs_old_idx *old_idx, *o; struct rb_node **p, *parent = NULL; old_idx = kmalloc(sizeof(struct ubifs_old_idx), GFP_NOFS); if (unlikely(!old_idx)) return -ENOMEM; old_idx->lnum = lnum; old_idx->offs = offs; p = &c->old_idx.rb_node; while (*p) { parent = *p; o = rb_entry(parent, struct ubifs_old_idx, rb); if (lnum < o->lnum) p = &(*p)->rb_left; else if (lnum > o->lnum) p = &(*p)->rb_right; else if (offs < o->offs) p = &(*p)->rb_left; else if (offs > o->offs) p = &(*p)->rb_right; else { ubifs_err("old idx added twice!"); kfree(old_idx); return 0; } } rb_link_node(&old_idx->rb, parent, p); rb_insert_color(&old_idx->rb, &c->old_idx); return 0; } /** * insert_old_idx_znode - record a znode obsoleted since last commit start. * @c: UBIFS file-system description object * @znode: znode of obsoleted index node * * Returns %0 on success, and a negative error code on failure. */ int insert_old_idx_znode(struct ubifs_info *c, struct ubifs_znode *znode) { if (znode->parent) { struct ubifs_zbranch *zbr; zbr = &znode->parent->zbranch[znode->iip]; if (zbr->len) return insert_old_idx(c, zbr->lnum, zbr->offs); } else if (c->zroot.len) return insert_old_idx(c, c->zroot.lnum, c->zroot.offs); return 0; } /** * ins_clr_old_idx_znode - record a znode obsoleted since last commit start. * @c: UBIFS file-system description object * @znode: znode of obsoleted index node * * Returns %0 on success, and a negative error code on failure. */ static int ins_clr_old_idx_znode(struct ubifs_info *c, struct ubifs_znode *znode) { int err; if (znode->parent) { struct ubifs_zbranch *zbr; zbr = &znode->parent->zbranch[znode->iip]; if (zbr->len) { err = insert_old_idx(c, zbr->lnum, zbr->offs); if (err) return err; zbr->lnum = 0; zbr->offs = 0; zbr->len = 0; } } else if (c->zroot.len) { err = insert_old_idx(c, c->zroot.lnum, c->zroot.offs); if (err) return err; c->zroot.lnum = 0; c->zroot.offs = 0; c->zroot.len = 0; } return 0; } /** * destroy_old_idx - destroy the old_idx RB-tree. * @c: UBIFS file-system description object * * During start commit, the old_idx RB-tree is used to avoid overwriting index * nodes that were in the index last commit but have since been deleted. This * is necessary for recovery i.e. the old index must be kept intact until the * new index is successfully written. The old-idx RB-tree is used for the * in-the-gaps method of writing index nodes and is destroyed every commit. */ void destroy_old_idx(struct ubifs_info *c) { struct rb_node *this = c->old_idx.rb_node; struct ubifs_old_idx *old_idx; while (this) { if (this->rb_left) { this = this->rb_left; continue; } else if (this->rb_right) { this = this->rb_right; continue; } old_idx = rb_entry(this, struct ubifs_old_idx, rb); this = rb_parent(this); if (this) { if (this->rb_left == &old_idx->rb) this->rb_left = NULL; else this->rb_right = NULL; } kfree(old_idx); } c->old_idx = RB_ROOT; } /** * copy_znode - copy a dirty znode. * @c: UBIFS file-system description object * @znode: znode to copy * * A dirty znode being committed may not be changed, so it is copied. */ static struct ubifs_znode *copy_znode(struct ubifs_info *c, struct ubifs_znode *znode) { struct ubifs_znode *zn; zn = kmalloc(c->max_znode_sz, GFP_NOFS); if (unlikely(!zn)) return ERR_PTR(-ENOMEM); memcpy(zn, znode, c->max_znode_sz); zn->cnext = NULL; __set_bit(DIRTY_ZNODE, &zn->flags); __clear_bit(COW_ZNODE, &zn->flags); ubifs_assert(!test_bit(OBSOLETE_ZNODE, &znode->flags)); __set_bit(OBSOLETE_ZNODE, &znode->flags); if (znode->level != 0) { int i; const int n = zn->child_cnt; /* The children now have new parent */ for (i = 0; i < n; i++) { struct ubifs_zbranch *zbr = &zn->zbranch[i]; if (zbr->znode) zbr->znode->parent = zn; } } atomic_long_inc(&c->dirty_zn_cnt); return zn; } /** * add_idx_dirt - add dirt due to a dirty znode. * @c: UBIFS file-system description object * @lnum: LEB number of index node * @dirt: size of index node * * This function updates lprops dirty space and the new size of the index. */ static int add_idx_dirt(struct ubifs_info *c, int lnum, int dirt) { c->calc_idx_sz -= ALIGN(dirt, 8); return ubifs_add_dirt(c, lnum, dirt); } /** * dirty_cow_znode - ensure a znode is not being committed. * @c: UBIFS file-system description object * @zbr: branch of znode to check * * Returns dirtied znode on success or negative error code on failure. */ static struct ubifs_znode *dirty_cow_znode(struct ubifs_info *c, struct ubifs_zbranch *zbr) { struct ubifs_znode *znode = zbr->znode; struct ubifs_znode *zn; int err; if (!test_bit(COW_ZNODE, &znode->flags)) { /* znode is not being committed */ if (!test_and_set_bit(DIRTY_ZNODE, &znode->flags)) { atomic_long_inc(&c->dirty_zn_cnt); atomic_long_dec(&c->clean_zn_cnt); atomic_long_dec(&ubifs_clean_zn_cnt); err = add_idx_dirt(c, zbr->lnum, zbr->len); if (unlikely(err)) return ERR_PTR(err); } return znode; } zn = copy_znode(c, znode); if (IS_ERR(zn)) return zn; if (zbr->len) { err = insert_old_idx(c, zbr->lnum, zbr->offs); if (unlikely(err)) return ERR_PTR(err); err = add_idx_dirt(c, zbr->lnum, zbr->len); } else err = 0; zbr->znode = zn; zbr->lnum = 0; zbr->offs = 0; zbr->len = 0; if (unlikely(err)) return ERR_PTR(err); return zn; } /** * lnc_add - add a leaf node to the leaf node cache. * @c: UBIFS file-system description object * @zbr: zbranch of leaf node * @node: leaf node * * Leaf nodes are non-index nodes directory entry nodes or data nodes. The * purpose of the leaf node cache is to save re-reading the same leaf node over * and over again. Most things are cached by VFS, however the file system must * cache directory entries for readdir and for resolving hash collisions. The * present implementation of the leaf node cache is extremely simple, and * allows for error returns that are not used but that may be needed if a more * complex implementation is created. * * Note, this function does not add the @node object to LNC directly, but * allocates a copy of the object and adds the copy to LNC. The reason for this * is that @node has been allocated outside of the TNC subsystem and will be * used with @c->tnc_mutex unlock upon return from the TNC subsystem. But LNC * may be changed at any time, e.g. freed by the shrinker. */ static int lnc_add(struct ubifs_info *c, struct ubifs_zbranch *zbr, const void *node) { int err; void *lnc_node; const struct ubifs_dent_node *dent = node; ubifs_assert(!zbr->leaf); ubifs_assert(zbr->len != 0); ubifs_assert(is_hash_key(c, &zbr->key)); err = ubifs_validate_entry(c, dent); if (err) { dbg_dump_stack(); dbg_dump_node(c, dent); return err; } lnc_node = kmalloc(zbr->len, GFP_NOFS); if (!lnc_node) /* We don't have to have the cache, so no error */ return 0; memcpy(lnc_node, node, zbr->len); zbr->leaf = lnc_node; return 0; } /** * lnc_add_directly - add a leaf node to the leaf-node-cache. * @c: UBIFS file-system description object * @zbr: zbranch of leaf node * @node: leaf node * * This function is similar to 'lnc_add()', but it does not create a copy of * @node but inserts @node to TNC directly. */ static int lnc_add_directly(struct ubifs_info *c, struct ubifs_zbranch *zbr, void *node) { int err; ubifs_assert(!zbr->leaf); ubifs_assert(zbr->len != 0); err = ubifs_validate_entry(c, node); if (err) { dbg_dump_stack(); dbg_dump_node(c, node); return err; } zbr->leaf = node; return 0; } /** * lnc_free - remove a leaf node from the leaf node cache. * @zbr: zbranch of leaf node * @node: leaf node */ static void lnc_free(struct ubifs_zbranch *zbr) { if (!zbr->leaf) return; kfree(zbr->leaf); zbr->leaf = NULL; } /** * tnc_read_node_nm - read a "hashed" leaf node. * @c: UBIFS file-system description object * @zbr: key and position of the node * @node: node is returned here * * This function reads a "hashed" node defined by @zbr from the leaf node cache * (in it is there) or from the hash media, in which case the node is also * added to LNC. Returns zero in case of success or a negative negative error * code in case of failure. */ static int tnc_read_node_nm(struct ubifs_info *c, struct ubifs_zbranch *zbr, void *node) { int err; ubifs_assert(is_hash_key(c, &zbr->key)); if (zbr->leaf) { /* Read from the leaf node cache */ ubifs_assert(zbr->len != 0); memcpy(node, zbr->leaf, zbr->len); return 0; } err = ubifs_tnc_read_node(c, zbr, node); if (err) return err; /* Add the node to the leaf node cache */ err = lnc_add(c, zbr, node); return err; } /** * try_read_node - read a node if it is a node. * @c: UBIFS file-system description object * @buf: buffer to read to * @type: node type * @len: node length (not aligned) * @lnum: LEB number of node to read * @offs: offset of node to read * * This function tries to read a node of known type and length, checks it and * stores it in @buf. This function returns %1 if a node is present and %0 if * a node is not present. A negative error code is returned for I/O errors. * This function performs that same function as ubifs_read_node except that * it does not require that there is actually a node present and instead * the return code indicates if a node was read. * * Note, this function does not check CRC of data nodes if @c->no_chk_data_crc * is true (it is controlled by corresponding mount option). However, if * @c->always_chk_crc is true, @c->no_chk_data_crc is ignored and CRC is always * checked. */ static int try_read_node(const struct ubifs_info *c, void *buf, int type, int len, int lnum, int offs) { int err, node_len; struct ubifs_ch *ch = buf; uint32_t crc, node_crc; dbg_io("LEB %d:%d, %s, length %d", lnum, offs, dbg_ntype(type), len); err = ubi_read(c->ubi, lnum, buf, offs, len); if (err) { ubifs_err("cannot read node type %d from LEB %d:%d, error %d", type, lnum, offs, err); return err; } if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC) return 0; if (ch->node_type != type) return 0; node_len = le32_to_cpu(ch->len); if (node_len != len) return 0; if (type == UBIFS_DATA_NODE && !c->always_chk_crc && c->no_chk_data_crc) return 1; crc = crc32(UBIFS_CRC32_INIT, buf + 8, node_len - 8); node_crc = le32_to_cpu(ch->crc); if (crc != node_crc) return 0; return 1; } /** * fallible_read_node - try to read a leaf node. * @c: UBIFS file-system description object * @key: key of node to read * @zbr: position of node * @node: node returned * * This function tries to read a node and returns %1 if the node is read, %0 * if the node is not present, and a negative error code in the case of error. */ static int fallible_read_node(struct ubifs_info *c, const union ubifs_key *key, struct ubifs_zbranch *zbr, void *node) { int ret; dbg_tnc("LEB %d:%d, key %s", zbr->lnum, zbr->offs, DBGKEY(key)); ret = try_read_node(c, node, key_type(c, key), zbr->len, zbr->lnum, zbr->offs); if (ret == 1) { union ubifs_key node_key; struct ubifs_dent_node *dent = node; /* All nodes have key in the same place */ key_read(c, &dent->key, &node_key); if (keys_cmp(c, key, &node_key) != 0) ret = 0; } if (ret == 0 && c->replaying) dbg_mnt("dangling branch LEB %d:%d len %d, key %s", zbr->lnum, zbr->offs, zbr->len, DBGKEY(key)); return ret; } /** * matches_name - determine if a direntry or xattr entry matches a given name. * @c: UBIFS file-system description object * @zbr: zbranch of dent * @nm: name to match * * This function checks if xentry/direntry referred by zbranch @zbr matches name * @nm. Returns %NAME_MATCHES if it does, %NAME_LESS if the name referred by * @zbr is less than @nm, and %NAME_GREATER if it is greater than @nm. In case * of failure, a negative error code is returned. */ static int matches_name(struct ubifs_info *c, struct ubifs_zbranch *zbr, const struct qstr *nm) { struct ubifs_dent_node *dent; int nlen, err; /* If possible, match against the dent in the leaf node cache */ if (!zbr->leaf) { dent = kmalloc(zbr->len, GFP_NOFS); if (!dent) return -ENOMEM; err = ubifs_tnc_read_node(c, zbr, dent); if (err) goto out_free; /* Add the node to the leaf node cache */ err = lnc_add_directly(c, zbr, dent); if (err) goto out_free; } else dent = zbr->leaf; nlen = le16_to_cpu(dent->nlen); err = memcmp(dent->name, nm->name, min_t(int, nlen, nm->len)); if (err == 0) { if (nlen == nm->len) return NAME_MATCHES; else if (nlen < nm->len) return NAME_LESS; else return NAME_GREATER; } else if (err < 0) return NAME_LESS; else return NAME_GREATER; out_free: kfree(dent); return err; } /** * get_znode - get a TNC znode that may not be loaded yet. * @c: UBIFS file-system description object * @znode: parent znode * @n: znode branch slot number * * This function returns the znode or a negative error code. */ static struct ubifs_znode *get_znode(struct ubifs_info *c, struct ubifs_znode *znode, int n) { struct ubifs_zbranch *zbr; zbr = &znode->zbranch[n]; if (zbr->znode) znode = zbr->znode; else znode = ubifs_load_znode(c, zbr, znode, n); return znode; } /** * tnc_next - find next TNC entry. * @c: UBIFS file-system description object * @zn: znode is passed and returned here * @n: znode branch slot number is passed and returned here * * This function returns %0 if the next TNC entry is found, %-ENOENT if there is * no next entry, or a negative error code otherwise. */ static int tnc_next(struct ubifs_info *c, struct ubifs_znode **zn, int *n) { struct ubifs_znode *znode = *zn; int nn = *n; nn += 1; if (nn < znode->child_cnt) { *n = nn; return 0; } while (1) { struct ubifs_znode *zp; zp = znode->parent; if (!zp) return -ENOENT; nn = znode->iip + 1; znode = zp; if (nn < znode->child_cnt) { znode = get_znode(c, znode, nn); if (IS_ERR(znode)) return PTR_ERR(znode); while (znode->level != 0) { znode = get_znode(c, znode, 0); if (IS_ERR(znode)) return PTR_ERR(znode); } nn = 0; break; } } *zn = znode; *n = nn; return 0; } /** * tnc_prev - find previous TNC entry. * @c: UBIFS file-system description object * @zn: znode is returned here * @n: znode branch slot number is passed and returned here * * This function returns %0 if the previous TNC entry is found, %-ENOENT if * there is no next entry, or a negative error code otherwise. */ static int tnc_prev(struct ubifs_info *c, struct ubifs_znode **zn, int *n) { struct ubifs_znode *znode = *zn; int nn = *n; if (nn > 0) { *n = nn - 1; return 0; } while (1) { struct ubifs_znode *zp; zp = znode->parent; if (!zp) return -ENOENT; nn = znode->iip - 1; znode = zp; if (nn >= 0) { znode = get_znode(c, znode, nn); if (IS_ERR(znode)) return PTR_ERR(znode); while (znode->level != 0) { nn = znode->child_cnt - 1; znode = get_znode(c, znode, nn); if (IS_ERR(znode)) return PTR_ERR(znode); } nn = znode->child_cnt - 1; break; } } *zn = znode; *n = nn; return 0; } /** * resolve_collision - resolve a collision. * @c: UBIFS file-system description object * @key: key of a directory or extended attribute entry * @zn: znode is returned here * @n: zbranch number is passed and returned here * @nm: name of the entry * * This function is called for "hashed" keys to make sure that the found key * really corresponds to the looked up node (directory or extended attribute * entry). It returns %1 and sets @zn and @n if the collision is resolved. * %0 is returned if @nm is not found and @zn and @n are set to the previous * entry, i.e. to the entry after which @nm could follow if it were in TNC. * This means that @n may be set to %-1 if the leftmost key in @zn is the * previous one. A negative error code is returned on failures. */ static int resolve_collision(struct ubifs_info *c, const union ubifs_key *key, struct ubifs_znode **zn, int *n, const struct qstr *nm) { int err; err = matches_name(c, &(*zn)->zbranch[*n], nm); if (unlikely(err < 0)) return err; if (err == NAME_MATCHES) return 1; if (err == NAME_GREATER) { /* Look left */ while (1) { err = tnc_prev(c, zn, n); if (err == -ENOENT) { ubifs_assert(*n == 0); *n = -1; return 0; } if (err < 0) return err; if (keys_cmp(c, &(*zn)->zbranch[*n].key, key)) { /* * We have found the branch after which we would * like to insert, but inserting in this znode * may still be wrong. Consider the following 3 * znodes, in the case where we are resolving a * collision with Key2. * * znode zp * ---------------------- * level 1 | Key0 | Key1 | * ----------------------- * | | * znode za | | znode zb * ------------ ------------ * level 0 | Key0 | | Key2 | * ------------ ------------ * * The lookup finds Key2 in znode zb. Lets say * there is no match and the name is greater so * we look left. When we find Key0, we end up * here. If we return now, we will insert into * znode za at slot n = 1. But that is invalid * according to the parent's keys. Key2 must * be inserted into znode zb. * * Note, this problem is not relevant for the * case when we go right, because * 'tnc_insert()' would correct the parent key. */ if (*n == (*zn)->child_cnt - 1) { err = tnc_next(c, zn, n); if (err) { /* Should be impossible */ ubifs_assert(0); if (err == -ENOENT) err = -EINVAL; return err; } ubifs_assert(*n == 0); *n = -1; } return 0; } err = matches_name(c, &(*zn)->zbranch[*n], nm); if (err < 0) return err; if (err == NAME_LESS) return 0; if (err == NAME_MATCHES) return 1; ubifs_assert(err == NAME_GREATER); } } else { int nn = *n; struct ubifs_znode *znode = *zn; /* Look right */ while (1) { err = tnc_next(c, &znode, &nn); if (err == -ENOENT) return 0; if (err < 0) return err; if (keys_cmp(c, &znode->zbranch[nn].key, key)) return 0; err = matches_name(c, &znode->zbranch[nn], nm); if (err < 0) return err; if (err == NAME_GREATER) return 0; *zn = znode; *n = nn; if (err == NAME_MATCHES) return 1; ubifs_assert(err == NAME_LESS); } } } /** * fallible_matches_name - determine if a dent matches a given name. * @c: UBIFS file-system description object * @zbr: zbranch of dent * @nm: name to match * * This is a "fallible" version of 'matches_name()' function which does not * panic if the direntry/xentry referred by @zbr does not exist on the media. * * This function checks if xentry/direntry referred by zbranch @zbr matches name * @nm. Returns %NAME_MATCHES it does, %NAME_LESS if the name referred by @zbr * is less than @nm, %NAME_GREATER if it is greater than @nm, and @NOT_ON_MEDIA * if xentry/direntry referred by @zbr does not exist on the media. A negative * error code is returned in case of failure. */ static int fallible_matches_name(struct ubifs_info *c, struct ubifs_zbranch *zbr, const struct qstr *nm) { struct ubifs_dent_node *dent; int nlen, err; /* If possible, match against the dent in the leaf node cache */ if (!zbr->leaf) { dent = kmalloc(zbr->len, GFP_NOFS); if (!dent) return -ENOMEM; err = fallible_read_node(c, &zbr->key, zbr, dent); if (err < 0) goto out_free; if (err == 0) { /* The node was not present */ err = NOT_ON_MEDIA; goto out_free; } ubifs_assert(err == 1); err = lnc_add_directly(c, zbr, dent); if (err) goto out_free; } else dent = zbr->leaf; nlen = le16_to_cpu(dent->nlen); err = memcmp(dent->name, nm->name, min_t(int, nlen, nm->len)); if (err == 0) { if (nlen == nm->len) return NAME_MATCHES; else if (nlen < nm->len) return NAME_LESS; else return NAME_GREATER; } else if (err < 0) return NAME_LESS; else return NAME_GREATER; out_free: kfree(dent); return err; } /** * fallible_resolve_collision - resolve a collision even if nodes are missing. * @c: UBIFS file-system description object * @key: key * @zn: znode is returned here * @n: branch number is passed and returned here * @nm: name of directory entry * @adding: indicates caller is adding a key to the TNC * * This is a "fallible" version of the 'resolve_collision()' function which * does not panic if one of the nodes referred to by TNC does not exist on the * media. This may happen when replaying the journal if a deleted node was * Garbage-collected and the commit was not done. A branch that refers to a node * that is not present is called a dangling branch. The following are the return * codes for this function: * o if @nm was found, %1 is returned and @zn and @n are set to the found * branch; * o if we are @adding and @nm was not found, %0 is returned; * o if we are not @adding and @nm was not found, but a dangling branch was * found, then %1 is returned and @zn and @n are set to the dangling branch; * o a negative error code is returned in case of failure. */ static int fallible_resolve_collision(struct ubifs_info *c, const union ubifs_key *key, struct ubifs_znode **zn, int *n, const struct qstr *nm, int adding) { struct ubifs_znode *o_znode = NULL, *znode = *zn; int uninitialized_var(o_n), err, cmp, unsure = 0, nn = *n; cmp = fallible_matches_name(c, &znode->zbranch[nn], nm); if (unlikely(cmp < 0)) return cmp; if (cmp == NAME_MATCHES) return 1; if (cmp == NOT_ON_MEDIA) { o_znode = znode; o_n = nn; /* * We are unlucky and hit a dangling branch straight away. * Now we do not really know where to go to find the needed * branch - to the left or to the right. Well, let's try left. */ unsure = 1; } else if (!adding) unsure = 1; /* Remove a dangling branch wherever it is */ if (cmp == NAME_GREATER || unsure) { /* Look left */ while (1) { err = tnc_prev(c, zn, n); if (err == -ENOENT) { ubifs_assert(*n == 0); *n = -1; break; } if (err < 0) return err; if (keys_cmp(c, &(*zn)->zbranch[*n].key, key)) { /* See comments in 'resolve_collision()' */ if (*n == (*zn)->child_cnt - 1) { err = tnc_next(c, zn, n); if (err) { /* Should be impossible */ ubifs_assert(0); if (err == -ENOENT) err = -EINVAL; return err; } ubifs_assert(*n == 0); *n = -1; } break; } err = fallible_matches_name(c, &(*zn)->zbranch[*n], nm); if (err < 0) return err; if (err == NAME_MATCHES) return 1; if (err == NOT_ON_MEDIA) { o_znode = *zn; o_n = *n; continue; } if (!adding) continue; if (err == NAME_LESS) break; else unsure = 0; } } if (cmp == NAME_LESS || unsure) { /* Look right */ *zn = znode; *n = nn; while (1) { err = tnc_next(c, &znode, &nn); if (err == -ENOENT) break; if (err < 0) return err; if (keys_cmp(c, &znode->zbranch[nn].key, key)) break; err = fallible_matches_name(c, &znode->zbranch[nn], nm); if (err < 0) return err; if (err == NAME_GREATER) break; *zn = znode; *n = nn; if (err == NAME_MATCHES) return 1; if (err == NOT_ON_MEDIA) { o_znode = znode; o_n = nn; } } } /* Never match a dangling branch when adding */ if (adding || !o_znode) return 0; dbg_mnt("dangling match LEB %d:%d len %d %s", o_znode->zbranch[o_n].lnum, o_znode->zbranch[o_n].offs, o_znode->zbranch[o_n].len, DBGKEY(key)); *zn = o_znode; *n = o_n; return 1; } /** * matches_position - determine if a zbranch matches a given position. * @zbr: zbranch of dent * @lnum: LEB number of dent to match * @offs: offset of dent to match * * This function returns %1 if @lnum:@offs matches, and %0 otherwise. */ static int matches_position(struct ubifs_zbranch *zbr, int lnum, int offs) { if (zbr->lnum == lnum && zbr->offs == offs) return 1; else return 0; } /** * resolve_collision_directly - resolve a collision directly. * @c: UBIFS file-system description object * @key: key of directory entry * @zn: znode is passed and returned here * @n: zbranch number is passed and returned here * @lnum: LEB number of dent node to match * @offs: offset of dent node to match * * This function is used for "hashed" keys to make sure the found directory or * extended attribute entry node is what was looked for. It is used when the * flash address of the right node is known (@lnum:@offs) which makes it much * easier to resolve collisions (no need to read entries and match full * names). This function returns %1 and sets @zn and @n if the collision is * resolved, %0 if @lnum:@offs is not found and @zn and @n are set to the * previous directory entry. Otherwise a negative error code is returned. */ static int resolve_collision_directly(struct ubifs_info *c, const union ubifs_key *key, struct ubifs_znode **zn, int *n, int lnum, int offs) { struct ubifs_znode *znode; int nn, err; znode = *zn; nn = *n; if (matches_position(&znode->zbranch[nn], lnum, offs)) return 1; /* Look left */ while (1) { err = tnc_prev(c, &znode, &nn); if (err == -ENOENT) break; if (err < 0) return err; if (keys_cmp(c, &znode->zbranch[nn].key, key)) break; if (matches_position(&znode->zbranch[nn], lnum, offs)) { *zn = znode; *n = nn; return 1; } } /* Look right */ znode = *zn; nn = *n; while (1) { err = tnc_next(c, &znode, &nn); if (err == -ENOENT) return 0; if (err < 0) return err; if (keys_cmp(c, &znode->zbranch[nn].key, key)) return 0; *zn = znode; *n = nn; if (matches_position(&znode->zbranch[nn], lnum, offs)) return 1; } } /** * dirty_cow_bottom_up - dirty a znode and its ancestors. * @c: UBIFS file-system description object * @znode: znode to dirty * * If we do not have a unique key that resides in a znode, then we cannot * dirty that znode from the top down (i.e. by using lookup_level0_dirty) * This function records the path back to the last dirty ancestor, and then * dirties the znodes on that path. */ static struct ubifs_znode *dirty_cow_bottom_up(struct ubifs_info *c, struct ubifs_znode *znode) { struct ubifs_znode *zp; int *path = c->bottom_up_buf, p = 0; ubifs_assert(c->zroot.znode); ubifs_assert(znode); if (c->zroot.znode->level > BOTTOM_UP_HEIGHT) { kfree(c->bottom_up_buf); c->bottom_up_buf = kmalloc(c->zroot.znode->level * sizeof(int), GFP_NOFS); if (!c->bottom_up_buf) return ERR_PTR(-ENOMEM); path = c->bottom_up_buf; } if (c->zroot.znode->level) { /* Go up until parent is dirty */ while (1) { int n; zp = znode->parent; if (!zp) break; n = znode->iip; ubifs_assert(p < c->zroot.znode->level); path[p++] = n; if (!zp->cnext && ubifs_zn_dirty(znode)) break; znode = zp; } } /* Come back down, dirtying as we go */ while (1) { struct ubifs_zbranch *zbr; zp = znode->parent; if (zp) { ubifs_assert(path[p - 1] >= 0); ubifs_assert(path[p - 1] < zp->child_cnt); zbr = &zp->zbranch[path[--p]]; znode = dirty_cow_znode(c, zbr); } else { ubifs_assert(znode == c->zroot.znode); znode = dirty_cow_znode(c, &c->zroot); } if (IS_ERR(znode) || !p) break; ubifs_assert(path[p - 1] >= 0); ubifs_assert(path[p - 1] < znode->child_cnt); znode = znode->zbranch[path[p - 1]].znode; } return znode; } /** * ubifs_lookup_level0 - search for zero-level znode. * @c: UBIFS file-system description object * @key: key to lookup * @zn: znode is returned here * @n: znode branch slot number is returned here * * This function looks up the TNC tree and search for zero-level znode which * refers key @key. The found zero-level znode is returned in @zn. There are 3 * cases: * o exact match, i.e. the found zero-level znode contains key @key, then %1 * is returned and slot number of the matched branch is stored in @n; * o not exact match, which means that zero-level znode does not contain * @key, then %0 is returned and slot number of the closed branch is stored * in @n; * o @key is so small that it is even less than the lowest key of the * leftmost zero-level node, then %0 is returned and %0 is stored in @n. * * Note, when the TNC tree is traversed, some znodes may be absent, then this * function reads corresponding indexing nodes and inserts them to TNC. In * case of failure, a negative error code is returned. */ int ubifs_lookup_level0(struct ubifs_info *c, const union ubifs_key *key, struct ubifs_znode **zn, int *n) { int err, exact; struct ubifs_znode *znode; unsigned long time = get_seconds(); dbg_tnc("search key %s", DBGKEY(key)); znode = c->zroot.znode; if (unlikely(!znode)) { znode = ubifs_load_znode(c, &c->zroot, NULL, 0); if (IS_ERR(znode)) return PTR_ERR(znode); } znode->time = time; while (1) { struct ubifs_zbranch *zbr; exact = ubifs_search_zbranch(c, znode, key, n); if (znode->level == 0) break; if (*n < 0) *n = 0; zbr = &znode->zbranch[*n]; if (zbr->znode) { znode->time = time; znode = zbr->znode; continue; } /* znode is not in TNC cache, load it from the media */ znode = ubifs_load_znode(c, zbr, znode, *n); if (IS_ERR(znode)) return PTR_ERR(znode); } *zn = znode; if (exact || !is_hash_key(c, key) || *n != -1) { dbg_tnc("found %d, lvl %d, n %d", exact, znode->level, *n); return exact; } /* * Here is a tricky place. We have not found the key and this is a * "hashed" key, which may collide. The rest of the code deals with * situations like this: * * | 3 | 5 | * / \ * | 3 | 5 | | 6 | 7 | (x) * * Or more a complex example: * * | 1 | 5 | * / \ * | 1 | 3 | | 5 | 8 | * \ / * | 5 | 5 | | 6 | 7 | (x) * * In the examples, if we are looking for key "5", we may reach nodes * marked with "(x)". In this case what we have do is to look at the * left and see if there is "5" key there. If there is, we have to * return it. * * Note, this whole situation is possible because we allow to have * elements which are equivalent to the next key in the parent in the * children of current znode. For example, this happens if we split a * znode like this: | 3 | 5 | 5 | 6 | 7 |, which results in something * like this: * | 3 | 5 | * / \ * | 3 | 5 | | 5 | 6 | 7 | * ^ * And this becomes what is at the first "picture" after key "5" marked * with "^" is removed. What could be done is we could prohibit * splitting in the middle of the colliding sequence. Also, when * removing the leftmost key, we would have to correct the key of the * parent node, which would introduce additional complications. Namely, * if we changed the the leftmost key of the parent znode, the garbage * collector would be unable to find it (GC is doing this when GC'ing * indexing LEBs). Although we already have an additional RB-tree where * we save such changed znodes (see 'ins_clr_old_idx_znode()') until * after the commit. But anyway, this does not look easy to implement * so we did not try this. */ err = tnc_prev(c, &znode, n); if (err == -ENOENT) { dbg_tnc("found 0, lvl %d, n -1", znode->level); *n = -1; return 0; } if (unlikely(err < 0)) return err; if (keys_cmp(c, key, &znode->zbranch[*n].key)) { dbg_tnc("found 0, lvl %d, n -1", znode->level); *n = -1; return 0; } dbg_tnc("found 1, lvl %d, n %d", znode->level, *n); *zn = znode; return 1; } /** * lookup_level0_dirty - search for zero-level znode dirtying. * @c: UBIFS file-system description object * @key: key to lookup * @zn: znode is returned here * @n: znode branch slot number is returned here * * This function looks up the TNC tree and search for zero-level znode which * refers key @key. The found zero-level znode is returned in @zn. There are 3 * cases: * o exact match, i.e. the found zero-level znode contains key @key, then %1 * is returned and slot number of the matched branch is stored in @n; * o not exact match, which means that zero-level znode does not contain @key * then %0 is returned and slot number of the closed branch is stored in * @n; * o @key is so small that it is even less than the lowest key of the * leftmost zero-level node, then %0 is returned and %-1 is stored in @n. * * Additionally all znodes in the path from the root to the located zero-level * znode are marked as dirty. * * Note, when the TNC tree is traversed, some znodes may be absent, then this * function reads corresponding indexing nodes and inserts them to TNC. In * case of failure, a negative error code is returned. */ static int lookup_level0_dirty(struct ubifs_info *c, const union ubifs_key *key, struct ubifs_znode **zn, int *n) { int err, exact; struct ubifs_znode *znode; unsigned long time = get_seconds(); dbg_tnc("search and dirty key %s", DBGKEY(key)); znode = c->zroot.znode; if (unlikely(!znode)) { znode = ubifs_load_znode(c, &c->zroot, NULL, 0); if (IS_ERR(znode)) return PTR_ERR(znode); } znode = dirty_cow_znode(c, &c->zroot); if (IS_ERR(znode)) return PTR_ERR(znode); znode->time = time; while (1) { struct ubifs_zbranch *zbr; exact = ubifs_search_zbranch(c, znode, key, n); if (znode->level == 0) break; if (*n < 0) *n = 0; zbr = &znode->zbranch[*n]; if (zbr->znode) { znode->time = time; znode = dirty_cow_znode(c, zbr); if (IS_ERR(znode)) return PTR_ERR(znode); continue; } /* znode is not in TNC cache, load it from the media */ znode = ubifs_load_znode(c, zbr, znode, *n); if (IS_ERR(znode)) return PTR_ERR(znode); znode = dirty_cow_znode(c, zbr); if (IS_ERR(znode)) return PTR_ERR(znode); } *zn = znode; if (exact || !is_hash_key(c, key) || *n != -1) { dbg_tnc("found %d, lvl %d, n %d", exact, znode->level, *n); return exact; } /* * See huge comment at 'lookup_level0_dirty()' what is the rest of the * code. */ err = tnc_prev(c, &znode, n); if (err == -ENOENT) { *n = -1; dbg_tnc("found 0, lvl %d, n -1", znode->level); return 0; } if (unlikely(err < 0)) return err; if (keys_cmp(c, key, &znode->zbranch[*n].key)) { *n = -1; dbg_tnc("found 0, lvl %d, n -1", znode->level); return 0; } if (znode->cnext || !ubifs_zn_dirty(znode)) { znode = dirty_cow_bottom_up(c, znode); if (IS_ERR(znode)) return PTR_ERR(znode); } dbg_tnc("found 1, lvl %d, n %d", znode->level, *n); *zn = znode; return 1; } /** * maybe_leb_gced - determine if a LEB may have been garbage collected. * @c: UBIFS file-system description object * @lnum: LEB number * @gc_seq1: garbage collection sequence number * * This function determines if @lnum may have been garbage collected since * sequence number @gc_seq1. If it may have been then %1 is returned, otherwise * %0 is returned. */ static int maybe_leb_gced(struct ubifs_info *c, int lnum, int gc_seq1) { /* * No garbage collection in the read-only U-Boot implementation */ return 0; } /** * ubifs_tnc_locate - look up a file-system node and return it and its location. * @c: UBIFS file-system description object * @key: node key to lookup * @node: the node is returned here * @lnum: LEB number is returned here * @offs: offset is returned here * * This function look up and reads node with key @key. The caller has to make * sure the @node buffer is large enough to fit the node. Returns zero in case * of success, %-ENOENT if the node was not found, and a negative error code in * case of failure. The node location can be returned in @lnum and @offs. */ int ubifs_tnc_locate(struct ubifs_info *c, const union ubifs_key *key, void *node, int *lnum, int *offs) { int found, n, err, safely = 0, gc_seq1; struct ubifs_znode *znode; struct ubifs_zbranch zbr, *zt; again: mutex_lock(&c->tnc_mutex); found = ubifs_lookup_level0(c, key, &znode, &n); if (!found) { err = -ENOENT; goto out; } else if (found < 0) { err = found; goto out; } zt = &znode->zbranch[n]; if (lnum) { *lnum = zt->lnum; *offs = zt->offs; } if (is_hash_key(c, key)) { /* * In this case the leaf node cache gets used, so we pass the * address of the zbranch and keep the mutex locked */ err = tnc_read_node_nm(c, zt, node); goto out; } if (safely) { err = ubifs_tnc_read_node(c, zt, node); goto out; } /* Drop the TNC mutex prematurely and race with garbage collection */ zbr = znode->zbranch[n]; gc_seq1 = c->gc_seq; mutex_unlock(&c->tnc_mutex); err = fallible_read_node(c, key, &zbr, node); if (err <= 0 || maybe_leb_gced(c, zbr.lnum, gc_seq1)) { /* * The node may have been GC'ed out from under us so try again * while keeping the TNC mutex locked. */ safely = 1; goto again; } return 0; out: mutex_unlock(&c->tnc_mutex); return err; } /** * ubifs_tnc_get_bu_keys - lookup keys for bulk-read. * @c: UBIFS file-system description object * @bu: bulk-read parameters and results * * Lookup consecutive data node keys for the same inode that reside * consecutively in the same LEB. This function returns zero in case of success * and a negative error code in case of failure. * * Note, if the bulk-read buffer length (@bu->buf_len) is known, this function * makes sure bulk-read nodes fit the buffer. Otherwise, this function prepares * maximum possible amount of nodes for bulk-read. */ int ubifs_tnc_get_bu_keys(struct ubifs_info *c, struct bu_info *bu) { int n, err = 0, lnum = -1, uninitialized_var(offs); int uninitialized_var(len); unsigned int block = key_block(c, &bu->key); struct ubifs_znode *znode; bu->cnt = 0; bu->blk_cnt = 0; bu->eof = 0; mutex_lock(&c->tnc_mutex); /* Find first key */ err = ubifs_lookup_level0(c, &bu->key, &znode, &n); if (err < 0) goto out; if (err) { /* Key found */ len = znode->zbranch[n].len; /* The buffer must be big enough for at least 1 node */ if (len > bu->buf_len) { err = -EINVAL; goto out; } /* Add this key */ bu->zbranch[bu->cnt++] = znode->zbranch[n]; bu->blk_cnt += 1; lnum = znode->zbranch[n].lnum; offs = ALIGN(znode->zbranch[n].offs + len, 8); } while (1) { struct ubifs_zbranch *zbr; union ubifs_key *key; unsigned int next_block; /* Find next key */ err = tnc_next(c, &znode, &n); if (err) goto out; zbr = &znode->zbranch[n]; key = &zbr->key; /* See if there is another data key for this file */ if (key_inum(c, key) != key_inum(c, &bu->key) || key_type(c, key) != UBIFS_DATA_KEY) { err = -ENOENT; goto out; } if (lnum < 0) { /* First key found */ lnum = zbr->lnum; offs = ALIGN(zbr->offs + zbr->len, 8); len = zbr->len; if (len > bu->buf_len) { err = -EINVAL; goto out; } } else { /* * The data nodes must be in consecutive positions in * the same LEB. */ if (zbr->lnum != lnum || zbr->offs != offs) goto out; offs += ALIGN(zbr->len, 8); len = ALIGN(len, 8) + zbr->len; /* Must not exceed buffer length */ if (len > bu->buf_len) goto out; } /* Allow for holes */ next_block = key_block(c, key); bu->blk_cnt += (next_block - block - 1); if (bu->blk_cnt >= UBIFS_MAX_BULK_READ) goto out; block = next_block; /* Add this key */ bu->zbranch[bu->cnt++] = *zbr; bu->blk_cnt += 1; /* See if we have room for more */ if (bu->cnt >= UBIFS_MAX_BULK_READ) goto out; if (bu->blk_cnt >= UBIFS_MAX_BULK_READ) goto out; } out: if (err == -ENOENT) { bu->eof = 1; err = 0; } bu->gc_seq = c->gc_seq; mutex_unlock(&c->tnc_mutex); if (err) return err; /* * An enormous hole could cause bulk-read to encompass too many * page cache pages, so limit the number here. */ if (bu->blk_cnt > UBIFS_MAX_BULK_READ) bu->blk_cnt = UBIFS_MAX_BULK_READ; /* * Ensure that bulk-read covers a whole number of page cache * pages. */ if (UBIFS_BLOCKS_PER_PAGE == 1 || !(bu->blk_cnt & (UBIFS_BLOCKS_PER_PAGE - 1))) return 0; if (bu->eof) { /* At the end of file we can round up */ bu->blk_cnt += UBIFS_BLOCKS_PER_PAGE - 1; return 0; } /* Exclude data nodes that do not make up a whole page cache page */ block = key_block(c, &bu->key) + bu->blk_cnt; block &= ~(UBIFS_BLOCKS_PER_PAGE - 1); while (bu->cnt) { if (key_block(c, &bu->zbranch[bu->cnt - 1].key) < block) break; bu->cnt -= 1; } return 0; } /** * validate_data_node - validate data nodes for bulk-read. * @c: UBIFS file-system description object * @buf: buffer containing data node to validate * @zbr: zbranch of data node to validate * * This functions returns %0 on success or a negative error code on failure. */ static int validate_data_node(struct ubifs_info *c, void *buf, struct ubifs_zbranch *zbr) { union ubifs_key key1; struct ubifs_ch *ch = buf; int err, len; if (ch->node_type != UBIFS_DATA_NODE) { ubifs_err("bad node type (%d but expected %d)", ch->node_type, UBIFS_DATA_NODE); goto out_err; } err = ubifs_check_node(c, buf, zbr->lnum, zbr->offs, 0, 0); if (err) { ubifs_err("expected node type %d", UBIFS_DATA_NODE); goto out; } len = le32_to_cpu(ch->len); if (len != zbr->len) { ubifs_err("bad node length %d, expected %d", len, zbr->len); goto out_err; } /* Make sure the key of the read node is correct */ key_read(c, buf + UBIFS_KEY_OFFSET, &key1); if (!keys_eq(c, &zbr->key, &key1)) { ubifs_err("bad key in node at LEB %d:%d", zbr->lnum, zbr->offs); dbg_tnc("looked for key %s found node's key %s", DBGKEY(&zbr->key), DBGKEY1(&key1)); goto out_err; } return 0; out_err: err = -EINVAL; out: ubifs_err("bad node at LEB %d:%d", zbr->lnum, zbr->offs); dbg_dump_node(c, buf); dbg_dump_stack(); return err; } /** * ubifs_tnc_bulk_read - read a number of data nodes in one go. * @c: UBIFS file-system description object * @bu: bulk-read parameters and results * * This functions reads and validates the data nodes that were identified by the * 'ubifs_tnc_get_bu_keys()' function. This functions returns %0 on success, * -EAGAIN to indicate a race with GC, or another negative error code on * failure. */ int ubifs_tnc_bulk_read(struct ubifs_info *c, struct bu_info *bu) { int lnum = bu->zbranch[0].lnum, offs = bu->zbranch[0].offs, len, err, i; void *buf; len = bu->zbranch[bu->cnt - 1].offs; len += bu->zbranch[bu->cnt - 1].len - offs; if (len > bu->buf_len) { ubifs_err("buffer too small %d vs %d", bu->buf_len, len); return -EINVAL; } /* Do the read */ err = ubi_read(c->ubi, lnum, bu->buf, offs, len); /* Check for a race with GC */ if (maybe_leb_gced(c, lnum, bu->gc_seq)) return -EAGAIN; if (err && err != -EBADMSG) { ubifs_err("failed to read from LEB %d:%d, error %d", lnum, offs, err); dbg_dump_stack(); dbg_tnc("key %s", DBGKEY(&bu->key)); return err; } /* Validate the nodes read */ buf = bu->buf; for (i = 0; i < bu->cnt; i++) { err = validate_data_node(c, buf, &bu->zbranch[i]); if (err) return err; buf = buf + ALIGN(bu->zbranch[i].len, 8); } return 0; } /** * do_lookup_nm- look up a "hashed" node. * @c: UBIFS file-system description object * @key: node key to lookup * @node: the node is returned here * @nm: node name * * This function look up and reads a node which contains name hash in the key. * Since the hash may have collisions, there may be many nodes with the same * key, so we have to sequentially look to all of them until the needed one is * found. This function returns zero in case of success, %-ENOENT if the node * was not found, and a negative error code in case of failure. */ static int do_lookup_nm(struct ubifs_info *c, const union ubifs_key *key, void *node, const struct qstr *nm) { int found, n, err; struct ubifs_znode *znode; dbg_tnc("name '%.*s' key %s", nm->len, nm->name, DBGKEY(key)); mutex_lock(&c->tnc_mutex); found = ubifs_lookup_level0(c, key, &znode, &n); if (!found) { err = -ENOENT; goto out_unlock; } else if (found < 0) { err = found; goto out_unlock; } ubifs_assert(n >= 0); err = resolve_collision(c, key, &znode, &n, nm); dbg_tnc("rc returned %d, znode %p, n %d", err, znode, n); if (unlikely(err < 0)) goto out_unlock; if (err == 0) { err = -ENOENT; goto out_unlock; } err = tnc_read_node_nm(c, &znode->zbranch[n], node); out_unlock: mutex_unlock(&c->tnc_mutex); return err; } /** * ubifs_tnc_lookup_nm - look up a "hashed" node. * @c: UBIFS file-system description object * @key: node key to lookup * @node: the node is returned here * @nm: node name * * This function look up and reads a node which contains name hash in the key. * Since the hash may have collisions, there may be many nodes with the same * key, so we have to sequentially look to all of them until the needed one is * found. This function returns zero in case of success, %-ENOENT if the node * was not found, and a negative error code in case of failure. */ int ubifs_tnc_lookup_nm(struct ubifs_info *c, const union ubifs_key *key, void *node, const struct qstr *nm) { int err, len; const struct ubifs_dent_node *dent = node; /* * We assume that in most of the cases there are no name collisions and * 'ubifs_tnc_lookup()' returns us the right direntry. */ err = ubifs_tnc_lookup(c, key, node); if (err) return err; len = le16_to_cpu(dent->nlen); if (nm->len == len && !memcmp(dent->name, nm->name, len)) return 0; /* * Unluckily, there are hash collisions and we have to iterate over * them look at each direntry with colliding name hash sequentially. */ return do_lookup_nm(c, key, node, nm); } /** * correct_parent_keys - correct parent znodes' keys. * @c: UBIFS file-system description object * @znode: znode to correct parent znodes for * * This is a helper function for 'tnc_insert()'. When the key of the leftmost * zbranch changes, keys of parent znodes have to be corrected. This helper * function is called in such situations and corrects the keys if needed. */ static void correct_parent_keys(const struct ubifs_info *c, struct ubifs_znode *znode) { union ubifs_key *key, *key1; ubifs_assert(znode->parent); ubifs_assert(znode->iip == 0); key = &znode->zbranch[0].key; key1 = &znode->parent->zbranch[0].key; while (keys_cmp(c, key, key1) < 0) { key_copy(c, key, key1); znode = znode->parent; znode->alt = 1; if (!znode->parent || znode->iip) break; key1 = &znode->parent->zbranch[0].key; } } /** * insert_zbranch - insert a zbranch into a znode. * @znode: znode into which to insert * @zbr: zbranch to insert * @n: slot number to insert to * * This is a helper function for 'tnc_insert()'. UBIFS does not allow "gaps" in * znode's array of zbranches and keeps zbranches consolidated, so when a new * zbranch has to be inserted to the @znode->zbranches[]' array at the @n-th * slot, zbranches starting from @n have to be moved right. */ static void insert_zbranch(struct ubifs_znode *znode, const struct ubifs_zbranch *zbr, int n) { int i; ubifs_assert(ubifs_zn_dirty(znode)); if (znode->level) { for (i = znode->child_cnt; i > n; i--) { znode->zbranch[i] = znode->zbranch[i - 1]; if (znode->zbranch[i].znode) znode->zbranch[i].znode->iip = i; } if (zbr->znode) zbr->znode->iip = n; } else for (i = znode->child_cnt; i > n; i--) znode->zbranch[i] = znode->zbranch[i - 1]; znode->zbranch[n] = *zbr; znode->child_cnt += 1; /* * After inserting at slot zero, the lower bound of the key range of * this znode may have changed. If this znode is subsequently split * then the upper bound of the key range may change, and furthermore * it could change to be lower than the original lower bound. If that * happens, then it will no longer be possible to find this znode in the * TNC using the key from the index node on flash. That is bad because * if it is not found, we will assume it is obsolete and may overwrite * it. Then if there is an unclean unmount, we will start using the * old index which will be broken. * * So we first mark znodes that have insertions at slot zero, and then * if they are split we add their lnum/offs to the old_idx tree. */ if (n == 0) znode->alt = 1; } /** * tnc_insert - insert a node into TNC. * @c: UBIFS file-system description object * @znode: znode to insert into * @zbr: branch to insert * @n: slot number to insert new zbranch to * * This function inserts a new node described by @zbr into znode @znode. If * znode does not have a free slot for new zbranch, it is split. Parent znodes * are splat as well if needed. Returns zero in case of success or a negative * error code in case of failure. */ static int tnc_insert(struct ubifs_info *c, struct ubifs_znode *znode, struct ubifs_zbranch *zbr, int n) { struct ubifs_znode *zn, *zi, *zp; int i, keep, move, appending = 0; union ubifs_key *key = &zbr->key, *key1; ubifs_assert(n >= 0 && n <= c->fanout); /* Implement naive insert for now */ again: zp = znode->parent; if (znode->child_cnt < c->fanout) { ubifs_assert(n != c->fanout); dbg_tnc("inserted at %d level %d, key %s", n, znode->level, DBGKEY(key)); insert_zbranch(znode, zbr, n); /* Ensure parent's key is correct */ if (n == 0 && zp && znode->iip == 0) correct_parent_keys(c, znode); return 0; } /* * Unfortunately, @znode does not have more empty slots and we have to * split it. */ dbg_tnc("splitting level %d, key %s", znode->level, DBGKEY(key)); if (znode->alt) /* * We can no longer be sure of finding this znode by key, so we * record it in the old_idx tree. */ ins_clr_old_idx_znode(c, znode); zn = kzalloc(c->max_znode_sz, GFP_NOFS); if (!zn) return -ENOMEM; zn->parent = zp; zn->level = znode->level; /* Decide where to split */ if (znode->level == 0 && key_type(c, key) == UBIFS_DATA_KEY) { /* Try not to split consecutive data keys */ if (n == c->fanout) { key1 = &znode->zbranch[n - 1].key; if (key_inum(c, key1) == key_inum(c, key) && key_type(c, key1) == UBIFS_DATA_KEY) appending = 1; } else goto check_split; } else if (appending && n != c->fanout) { /* Try not to split consecutive data keys */ appending = 0; check_split: if (n >= (c->fanout + 1) / 2) { key1 = &znode->zbranch[0].key; if (key_inum(c, key1) == key_inum(c, key) && key_type(c, key1) == UBIFS_DATA_KEY) { key1 = &znode->zbranch[n].key; if (key_inum(c, key1) != key_inum(c, key) || key_type(c, key1) != UBIFS_DATA_KEY) { keep = n; move = c->fanout - keep; zi = znode; goto do_split; } } } } if (appending) { keep = c->fanout; move = 0; } else { keep = (c->fanout + 1) / 2; move = c->fanout - keep; } /* * Although we don't at present, we could look at the neighbors and see * if we can move some zbranches there. */ if (n < keep) { /* Insert into existing znode */ zi = znode; move += 1; keep -= 1; } else { /* Insert into new znode */ zi = zn; n -= keep; /* Re-parent */ if (zn->level != 0) zbr->znode->parent = zn; } do_split: __set_bit(DIRTY_ZNODE, &zn->flags); atomic_long_inc(&c->dirty_zn_cnt); zn->child_cnt = move; znode->child_cnt = keep; dbg_tnc("moving %d, keeping %d", move, keep); /* Move zbranch */ for (i = 0; i < move; i++) { zn->zbranch[i] = znode->zbranch[keep + i]; /* Re-parent */ if (zn->level != 0) if (zn->zbranch[i].znode) { zn->zbranch[i].znode->parent = zn; zn->zbranch[i].znode->iip = i; } } /* Insert new key and branch */ dbg_tnc("inserting at %d level %d, key %s", n, zn->level, DBGKEY(key)); insert_zbranch(zi, zbr, n); /* Insert new znode (produced by spitting) into the parent */ if (zp) { if (n == 0 && zi == znode && znode->iip == 0) correct_parent_keys(c, znode); /* Locate insertion point */ n = znode->iip + 1; /* Tail recursion */ zbr->key = zn->zbranch[0].key; zbr->znode = zn; zbr->lnum = 0; zbr->offs = 0; zbr->len = 0; znode = zp; goto again; } /* We have to split root znode */ dbg_tnc("creating new zroot at level %d", znode->level + 1); zi = kzalloc(c->max_znode_sz, GFP_NOFS); if (!zi) return -ENOMEM; zi->child_cnt = 2; zi->level = znode->level + 1; __set_bit(DIRTY_ZNODE, &zi->flags); atomic_long_inc(&c->dirty_zn_cnt); zi->zbranch[0].key = znode->zbranch[0].key; zi->zbranch[0].znode = znode; zi->zbranch[0].lnum = c->zroot.lnum; zi->zbranch[0].offs = c->zroot.offs; zi->zbranch[0].len = c->zroot.len; zi->zbranch[1].key = zn->zbranch[0].key; zi->zbranch[1].znode = zn; c->zroot.lnum = 0; c->zroot.offs = 0; c->zroot.len = 0; c->zroot.znode = zi; zn->parent = zi; zn->iip = 1; znode->parent = zi; znode->iip = 0; return 0; } /** * ubifs_tnc_add - add a node to TNC. * @c: UBIFS file-system description object * @key: key to add * @lnum: LEB number of node * @offs: node offset * @len: node length * * This function adds a node with key @key to TNC. The node may be new or it may * obsolete some existing one. Returns %0 on success or negative error code on * failure. */ int ubifs_tnc_add(struct ubifs_info *c, const union ubifs_key *key, int lnum, int offs, int len) { int found, n, err = 0; struct ubifs_znode *znode; mutex_lock(&c->tnc_mutex); dbg_tnc("%d:%d, len %d, key %s", lnum, offs, len, DBGKEY(key)); found = lookup_level0_dirty(c, key, &znode, &n); if (!found) { struct ubifs_zbranch zbr; zbr.znode = NULL; zbr.lnum = lnum; zbr.offs = offs; zbr.len = len; key_copy(c, key, &zbr.key); err = tnc_insert(c, znode, &zbr, n + 1); } else if (found == 1) { struct ubifs_zbranch *zbr = &znode->zbranch[n]; lnc_free(zbr); err = ubifs_add_dirt(c, zbr->lnum, zbr->len); zbr->lnum = lnum; zbr->offs = offs; zbr->len = len; } else err = found; if (!err) err = dbg_check_tnc(c, 0); mutex_unlock(&c->tnc_mutex); return err; } /** * ubifs_tnc_replace - replace a node in the TNC only if the old node is found. * @c: UBIFS file-system description object * @key: key to add * @old_lnum: LEB number of old node * @old_offs: old node offset * @lnum: LEB number of node * @offs: node offset * @len: node length * * This function replaces a node with key @key in the TNC only if the old node * is found. This function is called by garbage collection when node are moved. * Returns %0 on success or negative error code on failure. */ int ubifs_tnc_replace(struct ubifs_info *c, const union ubifs_key *key, int old_lnum, int old_offs, int lnum, int offs, int len) { int found, n, err = 0; struct ubifs_znode *znode; mutex_lock(&c->tnc_mutex); dbg_tnc("old LEB %d:%d, new LEB %d:%d, len %d, key %s", old_lnum, old_offs, lnum, offs, len, DBGKEY(key)); found = lookup_level0_dirty(c, key, &znode, &n); if (found < 0) { err = found; goto out_unlock; } if (found == 1) { struct ubifs_zbranch *zbr = &znode->zbranch[n]; found = 0; if (zbr->lnum == old_lnum && zbr->offs == old_offs) { lnc_free(zbr); err = ubifs_add_dirt(c, zbr->lnum, zbr->len); if (err) goto out_unlock; zbr->lnum = lnum; zbr->offs = offs; zbr->len = len; found = 1; } else if (is_hash_key(c, key)) { found = resolve_collision_directly(c, key, &znode, &n, old_lnum, old_offs); dbg_tnc("rc returned %d, znode %p, n %d, LEB %d:%d", found, znode, n, old_lnum, old_offs); if (found < 0) { err = found; goto out_unlock; } if (found) { /* Ensure the znode is dirtied */ if (znode->cnext || !ubifs_zn_dirty(znode)) { znode = dirty_cow_bottom_up(c, znode); if (IS_ERR(znode)) { err = PTR_ERR(znode); goto out_unlock; } } zbr = &znode->zbranch[n]; lnc_free(zbr); err = ubifs_add_dirt(c, zbr->lnum, zbr->len); if (err) goto out_unlock; zbr->lnum = lnum; zbr->offs = offs; zbr->len = len; } } } if (!found) err = ubifs_add_dirt(c, lnum, len); if (!err) err = dbg_check_tnc(c, 0); out_unlock: mutex_unlock(&c->tnc_mutex); return err; } /** * ubifs_tnc_add_nm - add a "hashed" node to TNC. * @c: UBIFS file-system description object * @key: key to add * @lnum: LEB number of node * @offs: node offset * @len: node length * @nm: node name * * This is the same as 'ubifs_tnc_add()' but it should be used with keys which * may have collisions, like directory entry keys. */ int ubifs_tnc_add_nm(struct ubifs_info *c, const union ubifs_key *key, int lnum, int offs, int len, const struct qstr *nm) { int found, n, err = 0; struct ubifs_znode *znode; mutex_lock(&c->tnc_mutex); dbg_tnc("LEB %d:%d, name '%.*s', key %s", lnum, offs, nm->len, nm->name, DBGKEY(key)); found = lookup_level0_dirty(c, key, &znode, &n); if (found < 0) { err = found; goto out_unlock; } if (found == 1) { if (c->replaying) found = fallible_resolve_collision(c, key, &znode, &n, nm, 1); else found = resolve_collision(c, key, &znode, &n, nm); dbg_tnc("rc returned %d, znode %p, n %d", found, znode, n); if (found < 0) { err = found; goto out_unlock; } /* Ensure the znode is dirtied */ if (znode->cnext || !ubifs_zn_dirty(znode)) { znode = dirty_cow_bottom_up(c, znode); if (IS_ERR(znode)) { err = PTR_ERR(znode); goto out_unlock; } } if (found == 1) { struct ubifs_zbranch *zbr = &znode->zbranch[n]; lnc_free(zbr); err = ubifs_add_dirt(c, zbr->lnum, zbr->len); zbr->lnum = lnum; zbr->offs = offs; zbr->len = len; goto out_unlock; } } if (!found) { struct ubifs_zbranch zbr; zbr.znode = NULL; zbr.lnum = lnum; zbr.offs = offs; zbr.len = len; key_copy(c, key, &zbr.key); err = tnc_insert(c, znode, &zbr, n + 1); if (err) goto out_unlock; if (c->replaying) { /* * We did not find it in the index so there may be a * dangling branch still in the index. So we remove it * by passing 'ubifs_tnc_remove_nm()' the same key but * an unmatchable name. */ struct qstr noname = { .len = 0, .name = "" }; err = dbg_check_tnc(c, 0); mutex_unlock(&c->tnc_mutex); if (err) return err; return ubifs_tnc_remove_nm(c, key, &noname); } } out_unlock: if (!err) err = dbg_check_tnc(c, 0); mutex_unlock(&c->tnc_mutex); return err; } /** * tnc_delete - delete a znode form TNC. * @c: UBIFS file-system description object * @znode: znode to delete from * @n: zbranch slot number to delete * * This function deletes a leaf node from @n-th slot of @znode. Returns zero in * case of success and a negative error code in case of failure. */ static int tnc_delete(struct ubifs_info *c, struct ubifs_znode *znode, int n) { struct ubifs_zbranch *zbr; struct ubifs_znode *zp; int i, err; /* Delete without merge for now */ ubifs_assert(znode->level == 0); ubifs_assert(n >= 0 && n < c->fanout); dbg_tnc("deleting %s", DBGKEY(&znode->zbranch[n].key)); zbr = &znode->zbranch[n]; lnc_free(zbr); err = ubifs_add_dirt(c, zbr->lnum, zbr->len); if (err) { dbg_dump_znode(c, znode); return err; } /* We do not "gap" zbranch slots */ for (i = n; i < znode->child_cnt - 1; i++) znode->zbranch[i] = znode->zbranch[i + 1]; znode->child_cnt -= 1; if (znode->child_cnt > 0) return 0; /* * This was the last zbranch, we have to delete this znode from the * parent. */ do { ubifs_assert(!test_bit(OBSOLETE_ZNODE, &znode->flags)); ubifs_assert(ubifs_zn_dirty(znode)); zp = znode->parent; n = znode->iip; atomic_long_dec(&c->dirty_zn_cnt); err = insert_old_idx_znode(c, znode); if (err) return err; if (znode->cnext) { __set_bit(OBSOLETE_ZNODE, &znode->flags); atomic_long_inc(&c->clean_zn_cnt); atomic_long_inc(&ubifs_clean_zn_cnt); } else kfree(znode); znode = zp; } while (znode->child_cnt == 1); /* while removing last child */ /* Remove from znode, entry n - 1 */ znode->child_cnt -= 1; ubifs_assert(znode->level != 0); for (i = n; i < znode->child_cnt; i++) { znode->zbranch[i] = znode->zbranch[i + 1]; if (znode->zbranch[i].znode) znode->zbranch[i].znode->iip = i; } /* * If this is the root and it has only 1 child then * collapse the tree. */ if (!znode->parent) { while (znode->child_cnt == 1 && znode->level != 0) { zp = znode; zbr = &znode->zbranch[0]; znode = get_znode(c, znode, 0); if (IS_ERR(znode)) return PTR_ERR(znode); znode = dirty_cow_znode(c, zbr); if (IS_ERR(znode)) return PTR_ERR(znode); znode->parent = NULL; znode->iip = 0; if (c->zroot.len) { err = insert_old_idx(c, c->zroot.lnum, c->zroot.offs); if (err) return err; } c->zroot.lnum = zbr->lnum; c->zroot.offs = zbr->offs; c->zroot.len = zbr->len; c->zroot.znode = znode; ubifs_assert(!test_bit(OBSOLETE_ZNODE, &zp->flags)); ubifs_assert(test_bit(DIRTY_ZNODE, &zp->flags)); atomic_long_dec(&c->dirty_zn_cnt); if (zp->cnext) { __set_bit(OBSOLETE_ZNODE, &zp->flags); atomic_long_inc(&c->clean_zn_cnt); atomic_long_inc(&ubifs_clean_zn_cnt); } else kfree(zp); } } return 0; } /** * ubifs_tnc_remove - remove an index entry of a node. * @c: UBIFS file-system description object * @key: key of node * * Returns %0 on success or negative error code on failure. */ int ubifs_tnc_remove(struct ubifs_info *c, const union ubifs_key *key) { int found, n, err = 0; struct ubifs_znode *znode; mutex_lock(&c->tnc_mutex); dbg_tnc("key %s", DBGKEY(key)); found = lookup_level0_dirty(c, key, &znode, &n); if (found < 0) { err = found; goto out_unlock; } if (found == 1) err = tnc_delete(c, znode, n); if (!err) err = dbg_check_tnc(c, 0); out_unlock: mutex_unlock(&c->tnc_mutex); return err; } /** * ubifs_tnc_remove_nm - remove an index entry for a "hashed" node. * @c: UBIFS file-system description object * @key: key of node * @nm: directory entry name * * Returns %0 on success or negative error code on failure. */ int ubifs_tnc_remove_nm(struct ubifs_info *c, const union ubifs_key *key, const struct qstr *nm) { int n, err; struct ubifs_znode *znode; mutex_lock(&c->tnc_mutex); dbg_tnc("%.*s, key %s", nm->len, nm->name, DBGKEY(key)); err = lookup_level0_dirty(c, key, &znode, &n); if (err < 0) goto out_unlock; if (err) { if (c->replaying) err = fallible_resolve_collision(c, key, &znode, &n, nm, 0); else err = resolve_collision(c, key, &znode, &n, nm); dbg_tnc("rc returned %d, znode %p, n %d", err, znode, n); if (err < 0) goto out_unlock; if (err) { /* Ensure the znode is dirtied */ if (znode->cnext || !ubifs_zn_dirty(znode)) { znode = dirty_cow_bottom_up(c, znode); if (IS_ERR(znode)) { err = PTR_ERR(znode); goto out_unlock; } } err = tnc_delete(c, znode, n); } } out_unlock: if (!err) err = dbg_check_tnc(c, 0); mutex_unlock(&c->tnc_mutex); return err; } /** * key_in_range - determine if a key falls within a range of keys. * @c: UBIFS file-system description object * @key: key to check * @from_key: lowest key in range * @to_key: highest key in range * * This function returns %1 if the key is in range and %0 otherwise. */ static int key_in_range(struct ubifs_info *c, union ubifs_key *key, union ubifs_key *from_key, union ubifs_key *to_key) { if (keys_cmp(c, key, from_key) < 0) return 0; if (keys_cmp(c, key, to_key) > 0) return 0; return 1; } /** * ubifs_tnc_remove_range - remove index entries in range. * @c: UBIFS file-system description object * @from_key: lowest key to remove * @to_key: highest key to remove * * This function removes index entries starting at @from_key and ending at * @to_key. This function returns zero in case of success and a negative error * code in case of failure. */ int ubifs_tnc_remove_range(struct ubifs_info *c, union ubifs_key *from_key, union ubifs_key *to_key) { int i, n, k, err = 0; struct ubifs_znode *znode; union ubifs_key *key; mutex_lock(&c->tnc_mutex); while (1) { /* Find first level 0 znode that contains keys to remove */ err = ubifs_lookup_level0(c, from_key, &znode, &n); if (err < 0) goto out_unlock; if (err) key = from_key; else { err = tnc_next(c, &znode, &n); if (err == -ENOENT) { err = 0; goto out_unlock; } if (err < 0) goto out_unlock; key = &znode->zbranch[n].key; if (!key_in_range(c, key, from_key, to_key)) { err = 0; goto out_unlock; } } /* Ensure the znode is dirtied */ if (znode->cnext || !ubifs_zn_dirty(znode)) { znode = dirty_cow_bottom_up(c, znode); if (IS_ERR(znode)) { err = PTR_ERR(znode); goto out_unlock; } } /* Remove all keys in range except the first */ for (i = n + 1, k = 0; i < znode->child_cnt; i++, k++) { key = &znode->zbranch[i].key; if (!key_in_range(c, key, from_key, to_key)) break; lnc_free(&znode->zbranch[i]); err = ubifs_add_dirt(c, znode->zbranch[i].lnum, znode->zbranch[i].len); if (err) { dbg_dump_znode(c, znode); goto out_unlock; } dbg_tnc("removing %s", DBGKEY(key)); } if (k) { for (i = n + 1 + k; i < znode->child_cnt; i++) znode->zbranch[i - k] = znode->zbranch[i]; znode->child_cnt -= k; } /* Now delete the first */ err = tnc_delete(c, znode, n); if (err) goto out_unlock; } out_unlock: if (!err) err = dbg_check_tnc(c, 0); mutex_unlock(&c->tnc_mutex); return err; } /** * ubifs_tnc_remove_ino - remove an inode from TNC. * @c: UBIFS file-system description object * @inum: inode number to remove * * This function remove inode @inum and all the extended attributes associated * with the anode from TNC and returns zero in case of success or a negative * error code in case of failure. */ int ubifs_tnc_remove_ino(struct ubifs_info *c, ino_t inum) { union ubifs_key key1, key2; struct ubifs_dent_node *xent, *pxent = NULL; struct qstr nm = { .name = NULL }; dbg_tnc("ino %lu", (unsigned long)inum); /* * Walk all extended attribute entries and remove them together with * corresponding extended attribute inodes. */ lowest_xent_key(c, &key1, inum); while (1) { ino_t xattr_inum; int err; xent = ubifs_tnc_next_ent(c, &key1, &nm); if (IS_ERR(xent)) { err = PTR_ERR(xent); if (err == -ENOENT) break; return err; } xattr_inum = le64_to_cpu(xent->inum); dbg_tnc("xent '%s', ino %lu", xent->name, (unsigned long)xattr_inum); nm.name = (char *)xent->name; nm.len = le16_to_cpu(xent->nlen); err = ubifs_tnc_remove_nm(c, &key1, &nm); if (err) { kfree(xent); return err; } lowest_ino_key(c, &key1, xattr_inum); highest_ino_key(c, &key2, xattr_inum); err = ubifs_tnc_remove_range(c, &key1, &key2); if (err) { kfree(xent); return err; } kfree(pxent); pxent = xent; key_read(c, &xent->key, &key1); } kfree(pxent); lowest_ino_key(c, &key1, inum); highest_ino_key(c, &key2, inum); return ubifs_tnc_remove_range(c, &key1, &key2); } /** * ubifs_tnc_next_ent - walk directory or extended attribute entries. * @c: UBIFS file-system description object * @key: key of last entry * @nm: name of last entry found or %NULL * * This function finds and reads the next directory or extended attribute entry * after the given key (@key) if there is one. @nm is used to resolve * collisions. * * If the name of the current entry is not known and only the key is known, * @nm->name has to be %NULL. In this case the semantics of this function is a * little bit different and it returns the entry corresponding to this key, not * the next one. If the key was not found, the closest "right" entry is * returned. * * If the fist entry has to be found, @key has to contain the lowest possible * key value for this inode and @name has to be %NULL. * * This function returns the found directory or extended attribute entry node * in case of success, %-ENOENT is returned if no entry was found, and a * negative error code is returned in case of failure. */ struct ubifs_dent_node *ubifs_tnc_next_ent(struct ubifs_info *c, union ubifs_key *key, const struct qstr *nm) { int n, err, type = key_type(c, key); struct ubifs_znode *znode; struct ubifs_dent_node *dent; struct ubifs_zbranch *zbr; union ubifs_key *dkey; dbg_tnc("%s %s", nm->name ? (char *)nm->name : "(lowest)", DBGKEY(key)); ubifs_assert(is_hash_key(c, key)); mutex_lock(&c->tnc_mutex); err = ubifs_lookup_level0(c, key, &znode, &n); if (unlikely(err < 0)) goto out_unlock; if (nm->name) { if (err) { /* Handle collisions */ err = resolve_collision(c, key, &znode, &n, nm); dbg_tnc("rc returned %d, znode %p, n %d", err, znode, n); if (unlikely(err < 0)) goto out_unlock; } /* Now find next entry */ err = tnc_next(c, &znode, &n); if (unlikely(err)) goto out_unlock; } else { /* * The full name of the entry was not given, in which case the * behavior of this function is a little different and it * returns current entry, not the next one. */ if (!err) { /* * However, the given key does not exist in the TNC * tree and @znode/@n variables contain the closest * "preceding" element. Switch to the next one. */ err = tnc_next(c, &znode, &n); if (err) goto out_unlock; } } zbr = &znode->zbranch[n]; dent = kmalloc(zbr->len, GFP_NOFS); if (unlikely(!dent)) { err = -ENOMEM; goto out_unlock; } /* * The above 'tnc_next()' call could lead us to the next inode, check * this. */ dkey = &zbr->key; if (key_inum(c, dkey) != key_inum(c, key) || key_type(c, dkey) != type) { err = -ENOENT; goto out_free; } err = tnc_read_node_nm(c, zbr, dent); if (unlikely(err)) goto out_free; mutex_unlock(&c->tnc_mutex); return dent; out_free: kfree(dent); out_unlock: mutex_unlock(&c->tnc_mutex); return ERR_PTR(err); }
1001-study-uboot
fs/ubifs/tnc.c
C
gpl3
73,836
# # (C) Copyright 2006 # Wolfgang Denk, DENX Software Engineering, wd@denx.de. # # (C) Copyright 2003 # Pavel Bartusek, Sysgo Real-Time Solutions AG, pba@sysgo.de # # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk LIB = $(obj)libubifs.o COBJS-$(CONFIG_CMD_UBIFS) := ubifs.o io.o super.o sb.o master.o lpt.o COBJS-$(CONFIG_CMD_UBIFS) += lpt_commit.o scan.o lprops.o COBJS-$(CONFIG_CMD_UBIFS) += tnc.o tnc_misc.o debug.o crc16.o budget.o COBJS-$(CONFIG_CMD_UBIFS) += log.o orphan.o recovery.o replay.o SRCS := $(AOBJS:.o=.S) $(COBJS-y:.o=.c) OBJS := $(addprefix $(obj),$(AOBJS) $(COBJS-y)) all: $(LIB) $(AOBJS) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
fs/ubifs/Makefile
Makefile
gpl3
1,673
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter */ /* This file implements reading and writing the master node */ #include "ubifs.h" /** * scan_for_master - search the valid master node. * @c: UBIFS file-system description object * * This function scans the master node LEBs and search for the latest master * node. Returns zero in case of success and a negative error code in case of * failure. */ static int scan_for_master(struct ubifs_info *c) { struct ubifs_scan_leb *sleb; struct ubifs_scan_node *snod; int lnum, offs = 0, nodes_cnt; lnum = UBIFS_MST_LNUM; sleb = ubifs_scan(c, lnum, 0, c->sbuf); if (IS_ERR(sleb)) return PTR_ERR(sleb); nodes_cnt = sleb->nodes_cnt; if (nodes_cnt > 0) { snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node, list); if (snod->type != UBIFS_MST_NODE) goto out; memcpy(c->mst_node, snod->node, snod->len); offs = snod->offs; } ubifs_scan_destroy(sleb); lnum += 1; sleb = ubifs_scan(c, lnum, 0, c->sbuf); if (IS_ERR(sleb)) return PTR_ERR(sleb); if (sleb->nodes_cnt != nodes_cnt) goto out; if (!sleb->nodes_cnt) goto out; snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node, list); if (snod->type != UBIFS_MST_NODE) goto out; if (snod->offs != offs) goto out; if (memcmp((void *)c->mst_node + UBIFS_CH_SZ, (void *)snod->node + UBIFS_CH_SZ, UBIFS_MST_NODE_SZ - UBIFS_CH_SZ)) goto out; c->mst_offs = offs; ubifs_scan_destroy(sleb); return 0; out: ubifs_scan_destroy(sleb); return -EINVAL; } /** * validate_master - validate master node. * @c: UBIFS file-system description object * * This function validates data which was read from master node. Returns zero * if the data is all right and %-EINVAL if not. */ static int validate_master(const struct ubifs_info *c) { long long main_sz; int err; if (c->max_sqnum >= SQNUM_WATERMARK) { err = 1; goto out; } if (c->cmt_no >= c->max_sqnum) { err = 2; goto out; } if (c->highest_inum >= INUM_WATERMARK) { err = 3; goto out; } if (c->lhead_lnum < UBIFS_LOG_LNUM || c->lhead_lnum >= UBIFS_LOG_LNUM + c->log_lebs || c->lhead_offs < 0 || c->lhead_offs >= c->leb_size || c->lhead_offs & (c->min_io_size - 1)) { err = 4; goto out; } if (c->zroot.lnum >= c->leb_cnt || c->zroot.lnum < c->main_first || c->zroot.offs >= c->leb_size || c->zroot.offs & 7) { err = 5; goto out; } if (c->zroot.len < c->ranges[UBIFS_IDX_NODE].min_len || c->zroot.len > c->ranges[UBIFS_IDX_NODE].max_len) { err = 6; goto out; } if (c->gc_lnum >= c->leb_cnt || c->gc_lnum < c->main_first) { err = 7; goto out; } if (c->ihead_lnum >= c->leb_cnt || c->ihead_lnum < c->main_first || c->ihead_offs % c->min_io_size || c->ihead_offs < 0 || c->ihead_offs > c->leb_size || c->ihead_offs & 7) { err = 8; goto out; } main_sz = (long long)c->main_lebs * c->leb_size; if (c->old_idx_sz & 7 || c->old_idx_sz >= main_sz) { err = 9; goto out; } if (c->lpt_lnum < c->lpt_first || c->lpt_lnum > c->lpt_last || c->lpt_offs < 0 || c->lpt_offs + c->nnode_sz > c->leb_size) { err = 10; goto out; } if (c->nhead_lnum < c->lpt_first || c->nhead_lnum > c->lpt_last || c->nhead_offs < 0 || c->nhead_offs % c->min_io_size || c->nhead_offs > c->leb_size) { err = 11; goto out; } if (c->ltab_lnum < c->lpt_first || c->ltab_lnum > c->lpt_last || c->ltab_offs < 0 || c->ltab_offs + c->ltab_sz > c->leb_size) { err = 12; goto out; } if (c->big_lpt && (c->lsave_lnum < c->lpt_first || c->lsave_lnum > c->lpt_last || c->lsave_offs < 0 || c->lsave_offs + c->lsave_sz > c->leb_size)) { err = 13; goto out; } if (c->lscan_lnum < c->main_first || c->lscan_lnum >= c->leb_cnt) { err = 14; goto out; } if (c->lst.empty_lebs < 0 || c->lst.empty_lebs > c->main_lebs - 2) { err = 15; goto out; } if (c->lst.idx_lebs < 0 || c->lst.idx_lebs > c->main_lebs - 1) { err = 16; goto out; } if (c->lst.total_free < 0 || c->lst.total_free > main_sz || c->lst.total_free & 7) { err = 17; goto out; } if (c->lst.total_dirty < 0 || (c->lst.total_dirty & 7)) { err = 18; goto out; } if (c->lst.total_used < 0 || (c->lst.total_used & 7)) { err = 19; goto out; } if (c->lst.total_free + c->lst.total_dirty + c->lst.total_used > main_sz) { err = 20; goto out; } if (c->lst.total_dead + c->lst.total_dark + c->lst.total_used + c->old_idx_sz > main_sz) { err = 21; goto out; } if (c->lst.total_dead < 0 || c->lst.total_dead > c->lst.total_free + c->lst.total_dirty || c->lst.total_dead & 7) { err = 22; goto out; } if (c->lst.total_dark < 0 || c->lst.total_dark > c->lst.total_free + c->lst.total_dirty || c->lst.total_dark & 7) { err = 23; goto out; } return 0; out: ubifs_err("bad master node at offset %d error %d", c->mst_offs, err); dbg_dump_node(c, c->mst_node); return -EINVAL; } /** * ubifs_read_master - read master node. * @c: UBIFS file-system description object * * This function finds and reads the master node during file-system mount. If * the flash is empty, it creates default master node as well. Returns zero in * case of success and a negative error code in case of failure. */ int ubifs_read_master(struct ubifs_info *c) { int err, old_leb_cnt; c->mst_node = kzalloc(c->mst_node_alsz, GFP_KERNEL); if (!c->mst_node) return -ENOMEM; err = scan_for_master(c); if (err) { err = ubifs_recover_master_node(c); if (err) /* * Note, we do not free 'c->mst_node' here because the * unmount routine will take care of this. */ return err; } /* Make sure that the recovery flag is clear */ c->mst_node->flags &= cpu_to_le32(~UBIFS_MST_RCVRY); c->max_sqnum = le64_to_cpu(c->mst_node->ch.sqnum); c->highest_inum = le64_to_cpu(c->mst_node->highest_inum); c->cmt_no = le64_to_cpu(c->mst_node->cmt_no); c->zroot.lnum = le32_to_cpu(c->mst_node->root_lnum); c->zroot.offs = le32_to_cpu(c->mst_node->root_offs); c->zroot.len = le32_to_cpu(c->mst_node->root_len); c->lhead_lnum = le32_to_cpu(c->mst_node->log_lnum); c->gc_lnum = le32_to_cpu(c->mst_node->gc_lnum); c->ihead_lnum = le32_to_cpu(c->mst_node->ihead_lnum); c->ihead_offs = le32_to_cpu(c->mst_node->ihead_offs); c->old_idx_sz = le64_to_cpu(c->mst_node->index_size); c->lpt_lnum = le32_to_cpu(c->mst_node->lpt_lnum); c->lpt_offs = le32_to_cpu(c->mst_node->lpt_offs); c->nhead_lnum = le32_to_cpu(c->mst_node->nhead_lnum); c->nhead_offs = le32_to_cpu(c->mst_node->nhead_offs); c->ltab_lnum = le32_to_cpu(c->mst_node->ltab_lnum); c->ltab_offs = le32_to_cpu(c->mst_node->ltab_offs); c->lsave_lnum = le32_to_cpu(c->mst_node->lsave_lnum); c->lsave_offs = le32_to_cpu(c->mst_node->lsave_offs); c->lscan_lnum = le32_to_cpu(c->mst_node->lscan_lnum); c->lst.empty_lebs = le32_to_cpu(c->mst_node->empty_lebs); c->lst.idx_lebs = le32_to_cpu(c->mst_node->idx_lebs); old_leb_cnt = le32_to_cpu(c->mst_node->leb_cnt); c->lst.total_free = le64_to_cpu(c->mst_node->total_free); c->lst.total_dirty = le64_to_cpu(c->mst_node->total_dirty); c->lst.total_used = le64_to_cpu(c->mst_node->total_used); c->lst.total_dead = le64_to_cpu(c->mst_node->total_dead); c->lst.total_dark = le64_to_cpu(c->mst_node->total_dark); c->calc_idx_sz = c->old_idx_sz; if (c->mst_node->flags & cpu_to_le32(UBIFS_MST_NO_ORPHS)) c->no_orphs = 1; if (old_leb_cnt != c->leb_cnt) { /* The file system has been resized */ int growth = c->leb_cnt - old_leb_cnt; if (c->leb_cnt < old_leb_cnt || c->leb_cnt < UBIFS_MIN_LEB_CNT) { ubifs_err("bad leb_cnt on master node"); dbg_dump_node(c, c->mst_node); return -EINVAL; } dbg_mnt("Auto resizing (master) from %d LEBs to %d LEBs", old_leb_cnt, c->leb_cnt); c->lst.empty_lebs += growth; c->lst.total_free += growth * (long long)c->leb_size; c->lst.total_dark += growth * (long long)c->dark_wm; /* * Reflect changes back onto the master node. N.B. the master * node gets written immediately whenever mounting (or * remounting) in read-write mode, so we do not need to write it * here. */ c->mst_node->leb_cnt = cpu_to_le32(c->leb_cnt); c->mst_node->empty_lebs = cpu_to_le32(c->lst.empty_lebs); c->mst_node->total_free = cpu_to_le64(c->lst.total_free); c->mst_node->total_dark = cpu_to_le64(c->lst.total_dark); } err = validate_master(c); if (err) return err; err = dbg_old_index_check_init(c, &c->zroot); return err; }
1001-study-uboot
fs/ubifs/master.c
C
gpl3
9,387
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter */ #ifndef __UBIFS_DEBUG_H__ #define __UBIFS_DEBUG_H__ #ifdef CONFIG_UBIFS_FS_DEBUG /** * ubifs_debug_info - per-FS debugging information. * @buf: a buffer of LEB size, used for various purposes * @old_zroot: old index root - used by 'dbg_check_old_index()' * @old_zroot_level: old index root level - used by 'dbg_check_old_index()' * @old_zroot_sqnum: old index root sqnum - used by 'dbg_check_old_index()' * @failure_mode: failure mode for recovery testing * @fail_delay: 0=>don't delay, 1=>delay a time, 2=>delay a number of calls * @fail_timeout: time in jiffies when delay of failure mode expires * @fail_cnt: current number of calls to failure mode I/O functions * @fail_cnt_max: number of calls by which to delay failure mode * @chk_lpt_sz: used by LPT tree size checker * @chk_lpt_sz2: used by LPT tree size checker * @chk_lpt_wastage: used by LPT tree size checker * @chk_lpt_lebs: used by LPT tree size checker * @new_nhead_offs: used by LPT tree size checker * @new_ihead_lnum: used by debugging to check @c->ihead_lnum * @new_ihead_offs: used by debugging to check @c->ihead_offs * * @saved_lst: saved lprops statistics (used by 'dbg_save_space_info()') * @saved_free: saved free space (used by 'dbg_save_space_info()') * * dfs_dir_name: name of debugfs directory containing this file-system's files * dfs_dir: direntry object of the file-system debugfs directory * dfs_dump_lprops: "dump lprops" debugfs knob * dfs_dump_budg: "dump budgeting information" debugfs knob * dfs_dump_tnc: "dump TNC" debugfs knob */ struct ubifs_debug_info { void *buf; struct ubifs_zbranch old_zroot; int old_zroot_level; unsigned long long old_zroot_sqnum; int failure_mode; int fail_delay; unsigned long fail_timeout; unsigned int fail_cnt; unsigned int fail_cnt_max; long long chk_lpt_sz; long long chk_lpt_sz2; long long chk_lpt_wastage; int chk_lpt_lebs; int new_nhead_offs; int new_ihead_lnum; int new_ihead_offs; struct ubifs_lp_stats saved_lst; long long saved_free; char dfs_dir_name[100]; struct dentry *dfs_dir; struct dentry *dfs_dump_lprops; struct dentry *dfs_dump_budg; struct dentry *dfs_dump_tnc; }; #define UBIFS_DBG(op) op #define ubifs_assert(expr) do { \ if (unlikely(!(expr))) { \ printk(KERN_CRIT "UBIFS assert failed in %s at %u (pid %d)\n", \ __func__, __LINE__, 0); \ dbg_dump_stack(); \ } \ } while (0) #define ubifs_assert_cmt_locked(c) do { \ if (unlikely(down_write_trylock(&(c)->commit_sem))) { \ up_write(&(c)->commit_sem); \ printk(KERN_CRIT "commit lock is not locked!\n"); \ ubifs_assert(0); \ } \ } while (0) #define dbg_dump_stack() do { \ if (!dbg_failure_mode) \ dump_stack(); \ } while (0) /* Generic debugging messages */ #define dbg_msg(fmt, ...) do { \ spin_lock(&dbg_lock); \ printk(KERN_DEBUG "UBIFS DBG (pid %d): %s: " fmt "\n", 0, \ __func__, ##__VA_ARGS__); \ spin_unlock(&dbg_lock); \ } while (0) #define dbg_do_msg(typ, fmt, ...) do { \ if (ubifs_msg_flags & typ) \ dbg_msg(fmt, ##__VA_ARGS__); \ } while (0) #define dbg_err(fmt, ...) do { \ spin_lock(&dbg_lock); \ ubifs_err(fmt, ##__VA_ARGS__); \ spin_unlock(&dbg_lock); \ } while (0) const char *dbg_key_str0(const struct ubifs_info *c, const union ubifs_key *key); const char *dbg_key_str1(const struct ubifs_info *c, const union ubifs_key *key); /* * DBGKEY macros require @dbg_lock to be held, which it is in the dbg message * macros. */ #define DBGKEY(key) dbg_key_str0(c, (key)) #define DBGKEY1(key) dbg_key_str1(c, (key)) /* General messages */ #define dbg_gen(fmt, ...) dbg_do_msg(UBIFS_MSG_GEN, fmt, ##__VA_ARGS__) /* Additional journal messages */ #define dbg_jnl(fmt, ...) dbg_do_msg(UBIFS_MSG_JNL, fmt, ##__VA_ARGS__) /* Additional TNC messages */ #define dbg_tnc(fmt, ...) dbg_do_msg(UBIFS_MSG_TNC, fmt, ##__VA_ARGS__) /* Additional lprops messages */ #define dbg_lp(fmt, ...) dbg_do_msg(UBIFS_MSG_LP, fmt, ##__VA_ARGS__) /* Additional LEB find messages */ #define dbg_find(fmt, ...) dbg_do_msg(UBIFS_MSG_FIND, fmt, ##__VA_ARGS__) /* Additional mount messages */ #define dbg_mnt(fmt, ...) dbg_do_msg(UBIFS_MSG_MNT, fmt, ##__VA_ARGS__) /* Additional I/O messages */ #define dbg_io(fmt, ...) dbg_do_msg(UBIFS_MSG_IO, fmt, ##__VA_ARGS__) /* Additional commit messages */ #define dbg_cmt(fmt, ...) dbg_do_msg(UBIFS_MSG_CMT, fmt, ##__VA_ARGS__) /* Additional budgeting messages */ #define dbg_budg(fmt, ...) dbg_do_msg(UBIFS_MSG_BUDG, fmt, ##__VA_ARGS__) /* Additional log messages */ #define dbg_log(fmt, ...) dbg_do_msg(UBIFS_MSG_LOG, fmt, ##__VA_ARGS__) /* Additional gc messages */ #define dbg_gc(fmt, ...) dbg_do_msg(UBIFS_MSG_GC, fmt, ##__VA_ARGS__) /* Additional scan messages */ #define dbg_scan(fmt, ...) dbg_do_msg(UBIFS_MSG_SCAN, fmt, ##__VA_ARGS__) /* Additional recovery messages */ #define dbg_rcvry(fmt, ...) dbg_do_msg(UBIFS_MSG_RCVRY, fmt, ##__VA_ARGS__) /* * Debugging message type flags (must match msg_type_names in debug.c). * * UBIFS_MSG_GEN: general messages * UBIFS_MSG_JNL: journal messages * UBIFS_MSG_MNT: mount messages * UBIFS_MSG_CMT: commit messages * UBIFS_MSG_FIND: LEB find messages * UBIFS_MSG_BUDG: budgeting messages * UBIFS_MSG_GC: garbage collection messages * UBIFS_MSG_TNC: TNC messages * UBIFS_MSG_LP: lprops messages * UBIFS_MSG_IO: I/O messages * UBIFS_MSG_LOG: log messages * UBIFS_MSG_SCAN: scan messages * UBIFS_MSG_RCVRY: recovery messages */ enum { UBIFS_MSG_GEN = 0x1, UBIFS_MSG_JNL = 0x2, UBIFS_MSG_MNT = 0x4, UBIFS_MSG_CMT = 0x8, UBIFS_MSG_FIND = 0x10, UBIFS_MSG_BUDG = 0x20, UBIFS_MSG_GC = 0x40, UBIFS_MSG_TNC = 0x80, UBIFS_MSG_LP = 0x100, UBIFS_MSG_IO = 0x200, UBIFS_MSG_LOG = 0x400, UBIFS_MSG_SCAN = 0x800, UBIFS_MSG_RCVRY = 0x1000, }; /* Debugging message type flags for each default debug message level */ #define UBIFS_MSG_LVL_0 0 #define UBIFS_MSG_LVL_1 0x1 #define UBIFS_MSG_LVL_2 0x7f #define UBIFS_MSG_LVL_3 0xffff /* * Debugging check flags (must match chk_names in debug.c). * * UBIFS_CHK_GEN: general checks * UBIFS_CHK_TNC: check TNC * UBIFS_CHK_IDX_SZ: check index size * UBIFS_CHK_ORPH: check orphans * UBIFS_CHK_OLD_IDX: check the old index * UBIFS_CHK_LPROPS: check lprops * UBIFS_CHK_FS: check the file-system */ enum { UBIFS_CHK_GEN = 0x1, UBIFS_CHK_TNC = 0x2, UBIFS_CHK_IDX_SZ = 0x4, UBIFS_CHK_ORPH = 0x8, UBIFS_CHK_OLD_IDX = 0x10, UBIFS_CHK_LPROPS = 0x20, UBIFS_CHK_FS = 0x40, }; /* * Special testing flags (must match tst_names in debug.c). * * UBIFS_TST_FORCE_IN_THE_GAPS: force the use of in-the-gaps method * UBIFS_TST_RCVRY: failure mode for recovery testing */ enum { UBIFS_TST_FORCE_IN_THE_GAPS = 0x2, UBIFS_TST_RCVRY = 0x4, }; #if CONFIG_UBIFS_FS_DEBUG_MSG_LVL == 1 #define UBIFS_MSG_FLAGS_DEFAULT UBIFS_MSG_LVL_1 #elif CONFIG_UBIFS_FS_DEBUG_MSG_LVL == 2 #define UBIFS_MSG_FLAGS_DEFAULT UBIFS_MSG_LVL_2 #elif CONFIG_UBIFS_FS_DEBUG_MSG_LVL == 3 #define UBIFS_MSG_FLAGS_DEFAULT UBIFS_MSG_LVL_3 #else #define UBIFS_MSG_FLAGS_DEFAULT UBIFS_MSG_LVL_0 #endif #ifdef CONFIG_UBIFS_FS_DEBUG_CHKS #define UBIFS_CHK_FLAGS_DEFAULT 0xffffffff #else #define UBIFS_CHK_FLAGS_DEFAULT 0 #endif #define dbg_ntype(type) "" #define dbg_cstate(cmt_state) "" #define dbg_get_key_dump(c, key) ({}) #define dbg_dump_inode(c, inode) ({}) #define dbg_dump_node(c, node) ({}) #define dbg_dump_budget_req(req) ({}) #define dbg_dump_lstats(lst) ({}) #define dbg_dump_budg(c) ({}) #define dbg_dump_lprop(c, lp) ({}) #define dbg_dump_lprops(c) ({}) #define dbg_dump_lpt_info(c) ({}) #define dbg_dump_leb(c, lnum) ({}) #define dbg_dump_znode(c, znode) ({}) #define dbg_dump_heap(c, heap, cat) ({}) #define dbg_dump_pnode(c, pnode, parent, iip) ({}) #define dbg_dump_tnc(c) ({}) #define dbg_dump_index(c) ({}) #define dbg_walk_index(c, leaf_cb, znode_cb, priv) 0 #define dbg_old_index_check_init(c, zroot) 0 #define dbg_check_old_index(c, zroot) 0 #define dbg_check_cats(c) 0 #define dbg_check_ltab(c) 0 #define dbg_chk_lpt_free_spc(c) 0 #define dbg_chk_lpt_sz(c, action, len) 0 #define dbg_check_synced_i_size(inode) 0 #define dbg_check_dir_size(c, dir) 0 #define dbg_check_tnc(c, x) 0 #define dbg_check_idx_size(c, idx_size) 0 #define dbg_check_filesystem(c) 0 #define dbg_check_heap(c, heap, cat, add_pos) ({}) #define dbg_check_lprops(c) 0 #define dbg_check_lpt_nodes(c, cnode, row, col) 0 #define dbg_force_in_the_gaps_enabled 0 #define dbg_force_in_the_gaps() 0 #define dbg_failure_mode 0 #define dbg_failure_mode_registration(c) ({}) #define dbg_failure_mode_deregistration(c) ({}) int ubifs_debugging_init(struct ubifs_info *c); void ubifs_debugging_exit(struct ubifs_info *c); #else /* !CONFIG_UBIFS_FS_DEBUG */ #define UBIFS_DBG(op) /* Use "if (0)" to make compiler check arguments even if debugging is off */ #define ubifs_assert(expr) do { \ if (0 && (expr)) \ printk(KERN_CRIT "UBIFS assert failed in %s at %u (pid %d)\n", \ __func__, __LINE__, 0); \ } while (0) #define dbg_err(fmt, ...) do { \ if (0) \ ubifs_err(fmt, ##__VA_ARGS__); \ } while (0) #define dbg_msg(fmt, ...) do { \ if (0) \ printk(KERN_DEBUG "UBIFS DBG (pid %d): %s: " fmt "\n", \ 0, __func__, ##__VA_ARGS__); \ } while (0) #define dbg_dump_stack() #define ubifs_assert_cmt_locked(c) #define dbg_gen(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_jnl(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_tnc(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_lp(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_find(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_mnt(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_io(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_cmt(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_budg(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_log(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_gc(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_scan(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define dbg_rcvry(fmt, ...) dbg_msg(fmt, ##__VA_ARGS__) #define DBGKEY(key) ((char *)(key)) #define DBGKEY1(key) ((char *)(key)) #define ubifs_debugging_init(c) 0 #define ubifs_debugging_exit(c) ({}) #define dbg_ntype(type) "" #define dbg_cstate(cmt_state) "" #define dbg_get_key_dump(c, key) ({}) #define dbg_dump_inode(c, inode) ({}) #define dbg_dump_node(c, node) ({}) #define dbg_dump_budget_req(req) ({}) #define dbg_dump_lstats(lst) ({}) #define dbg_dump_budg(c) ({}) #define dbg_dump_lprop(c, lp) ({}) #define dbg_dump_lprops(c) ({}) #define dbg_dump_lpt_info(c) ({}) #define dbg_dump_leb(c, lnum) ({}) #define dbg_dump_znode(c, znode) ({}) #define dbg_dump_heap(c, heap, cat) ({}) #define dbg_dump_pnode(c, pnode, parent, iip) ({}) #define dbg_dump_tnc(c) ({}) #define dbg_dump_index(c) ({}) #define dbg_walk_index(c, leaf_cb, znode_cb, priv) 0 #define dbg_old_index_check_init(c, zroot) 0 #define dbg_check_old_index(c, zroot) 0 #define dbg_check_cats(c) 0 #define dbg_check_ltab(c) 0 #define dbg_chk_lpt_free_spc(c) 0 #define dbg_chk_lpt_sz(c, action, len) 0 #define dbg_check_synced_i_size(inode) 0 #define dbg_check_dir_size(c, dir) 0 #define dbg_check_tnc(c, x) 0 #define dbg_check_idx_size(c, idx_size) 0 #define dbg_check_filesystem(c) 0 #define dbg_check_heap(c, heap, cat, add_pos) ({}) #define dbg_check_lprops(c) 0 #define dbg_check_lpt_nodes(c, cnode, row, col) 0 #define dbg_force_in_the_gaps_enabled 0 #define dbg_force_in_the_gaps() 0 #define dbg_failure_mode 0 #define dbg_failure_mode_registration(c) ({}) #define dbg_failure_mode_deregistration(c) ({}) #endif /* !CONFIG_UBIFS_FS_DEBUG */ #endif /* !__UBIFS_DEBUG_H__ */
1001-study-uboot
fs/ubifs/debug.h
C
gpl3
15,086
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * Copyright (C) 2006, 2007 University of Szeged, Hungary * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter * Zoltan Sogor */ /* * This file implements UBIFS I/O subsystem which provides various I/O-related * helper functions (reading/writing/checking/validating nodes) and implements * write-buffering support. Write buffers help to save space which otherwise * would have been wasted for padding to the nearest minimal I/O unit boundary. * Instead, data first goes to the write-buffer and is flushed when the * buffer is full or when it is not used for some time (by timer). This is * similar to the mechanism is used by JFFS2. * * Write-buffers are defined by 'struct ubifs_wbuf' objects and protected by * mutexes defined inside these objects. Since sometimes upper-level code * has to lock the write-buffer (e.g. journal space reservation code), many * functions related to write-buffers have "nolock" suffix which means that the * caller has to lock the write-buffer before calling this function. * * UBIFS stores nodes at 64 bit-aligned addresses. If the node length is not * aligned, UBIFS starts the next node from the aligned address, and the padded * bytes may contain any rubbish. In other words, UBIFS does not put padding * bytes in those small gaps. Common headers of nodes store real node lengths, * not aligned lengths. Indexing nodes also store real lengths in branches. * * UBIFS uses padding when it pads to the next min. I/O unit. In this case it * uses padding nodes or padding bytes, if the padding node does not fit. * * All UBIFS nodes are protected by CRC checksums and UBIFS checks all nodes * every time they are read from the flash media. */ #include "ubifs.h" /** * ubifs_ro_mode - switch UBIFS to read read-only mode. * @c: UBIFS file-system description object * @err: error code which is the reason of switching to R/O mode */ void ubifs_ro_mode(struct ubifs_info *c, int err) { if (!c->ro_media) { c->ro_media = 1; c->no_chk_data_crc = 0; ubifs_warn("switched to read-only mode, error %d", err); dbg_dump_stack(); } } /** * ubifs_check_node - check node. * @c: UBIFS file-system description object * @buf: node to check * @lnum: logical eraseblock number * @offs: offset within the logical eraseblock * @quiet: print no messages * @must_chk_crc: indicates whether to always check the CRC * * This function checks node magic number and CRC checksum. This function also * validates node length to prevent UBIFS from becoming crazy when an attacker * feeds it a file-system image with incorrect nodes. For example, too large * node length in the common header could cause UBIFS to read memory outside of * allocated buffer when checking the CRC checksum. * * This function may skip data nodes CRC checking if @c->no_chk_data_crc is * true, which is controlled by corresponding UBIFS mount option. However, if * @must_chk_crc is true, then @c->no_chk_data_crc is ignored and CRC is * checked. Similarly, if @c->always_chk_crc is true, @c->no_chk_data_crc is * ignored and CRC is checked. * * This function returns zero in case of success and %-EUCLEAN in case of bad * CRC or magic. */ int ubifs_check_node(const struct ubifs_info *c, const void *buf, int lnum, int offs, int quiet, int must_chk_crc) { int err = -EINVAL, type, node_len; uint32_t crc, node_crc, magic; const struct ubifs_ch *ch = buf; ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0); ubifs_assert(!(offs & 7) && offs < c->leb_size); magic = le32_to_cpu(ch->magic); if (magic != UBIFS_NODE_MAGIC) { if (!quiet) ubifs_err("bad magic %#08x, expected %#08x", magic, UBIFS_NODE_MAGIC); err = -EUCLEAN; goto out; } type = ch->node_type; if (type < 0 || type >= UBIFS_NODE_TYPES_CNT) { if (!quiet) ubifs_err("bad node type %d", type); goto out; } node_len = le32_to_cpu(ch->len); if (node_len + offs > c->leb_size) goto out_len; if (c->ranges[type].max_len == 0) { if (node_len != c->ranges[type].len) goto out_len; } else if (node_len < c->ranges[type].min_len || node_len > c->ranges[type].max_len) goto out_len; if (!must_chk_crc && type == UBIFS_DATA_NODE && !c->always_chk_crc && c->no_chk_data_crc) return 0; crc = crc32(UBIFS_CRC32_INIT, buf + 8, node_len - 8); node_crc = le32_to_cpu(ch->crc); if (crc != node_crc) { if (!quiet) ubifs_err("bad CRC: calculated %#08x, read %#08x", crc, node_crc); err = -EUCLEAN; goto out; } return 0; out_len: if (!quiet) ubifs_err("bad node length %d", node_len); out: if (!quiet) { ubifs_err("bad node at LEB %d:%d", lnum, offs); dbg_dump_node(c, buf); dbg_dump_stack(); } return err; } /** * ubifs_pad - pad flash space. * @c: UBIFS file-system description object * @buf: buffer to put padding to * @pad: how many bytes to pad * * The flash media obliges us to write only in chunks of %c->min_io_size and * when we have to write less data we add padding node to the write-buffer and * pad it to the next minimal I/O unit's boundary. Padding nodes help when the * media is being scanned. If the amount of wasted space is not enough to fit a * padding node which takes %UBIFS_PAD_NODE_SZ bytes, we write padding bytes * pattern (%UBIFS_PADDING_BYTE). * * Padding nodes are also used to fill gaps when the "commit-in-gaps" method is * used. */ void ubifs_pad(const struct ubifs_info *c, void *buf, int pad) { uint32_t crc; ubifs_assert(pad >= 0 && !(pad & 7)); if (pad >= UBIFS_PAD_NODE_SZ) { struct ubifs_ch *ch = buf; struct ubifs_pad_node *pad_node = buf; ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC); ch->node_type = UBIFS_PAD_NODE; ch->group_type = UBIFS_NO_NODE_GROUP; ch->padding[0] = ch->padding[1] = 0; ch->sqnum = 0; ch->len = cpu_to_le32(UBIFS_PAD_NODE_SZ); pad -= UBIFS_PAD_NODE_SZ; pad_node->pad_len = cpu_to_le32(pad); crc = crc32(UBIFS_CRC32_INIT, buf + 8, UBIFS_PAD_NODE_SZ - 8); ch->crc = cpu_to_le32(crc); memset(buf + UBIFS_PAD_NODE_SZ, 0, pad); } else if (pad > 0) /* Too little space, padding node won't fit */ memset(buf, UBIFS_PADDING_BYTE, pad); } /** * next_sqnum - get next sequence number. * @c: UBIFS file-system description object */ static unsigned long long next_sqnum(struct ubifs_info *c) { unsigned long long sqnum; spin_lock(&c->cnt_lock); sqnum = ++c->max_sqnum; spin_unlock(&c->cnt_lock); if (unlikely(sqnum >= SQNUM_WARN_WATERMARK)) { if (sqnum >= SQNUM_WATERMARK) { ubifs_err("sequence number overflow %llu, end of life", sqnum); ubifs_ro_mode(c, -EINVAL); } ubifs_warn("running out of sequence numbers, end of life soon"); } return sqnum; } /** * ubifs_prepare_node - prepare node to be written to flash. * @c: UBIFS file-system description object * @node: the node to pad * @len: node length * @pad: if the buffer has to be padded * * This function prepares node at @node to be written to the media - it * calculates node CRC, fills the common header, and adds proper padding up to * the next minimum I/O unit if @pad is not zero. */ void ubifs_prepare_node(struct ubifs_info *c, void *node, int len, int pad) { uint32_t crc; struct ubifs_ch *ch = node; unsigned long long sqnum = next_sqnum(c); ubifs_assert(len >= UBIFS_CH_SZ); ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC); ch->len = cpu_to_le32(len); ch->group_type = UBIFS_NO_NODE_GROUP; ch->sqnum = cpu_to_le64(sqnum); ch->padding[0] = ch->padding[1] = 0; crc = crc32(UBIFS_CRC32_INIT, node + 8, len - 8); ch->crc = cpu_to_le32(crc); if (pad) { len = ALIGN(len, 8); pad = ALIGN(len, c->min_io_size) - len; ubifs_pad(c, node + len, pad); } } /** * ubifs_read_node - read node. * @c: UBIFS file-system description object * @buf: buffer to read to * @type: node type * @len: node length (not aligned) * @lnum: logical eraseblock number * @offs: offset within the logical eraseblock * * This function reads a node of known type and and length, checks it and * stores in @buf. Returns zero in case of success, %-EUCLEAN if CRC mismatched * and a negative error code in case of failure. */ int ubifs_read_node(const struct ubifs_info *c, void *buf, int type, int len, int lnum, int offs) { int err, l; struct ubifs_ch *ch = buf; dbg_io("LEB %d:%d, %s, length %d", lnum, offs, dbg_ntype(type), len); ubifs_assert(lnum >= 0 && lnum < c->leb_cnt && offs >= 0); ubifs_assert(len >= UBIFS_CH_SZ && offs + len <= c->leb_size); ubifs_assert(!(offs & 7) && offs < c->leb_size); ubifs_assert(type >= 0 && type < UBIFS_NODE_TYPES_CNT); err = ubi_read(c->ubi, lnum, buf, offs, len); if (err && err != -EBADMSG) { ubifs_err("cannot read node %d from LEB %d:%d, error %d", type, lnum, offs, err); return err; } if (type != ch->node_type) { ubifs_err("bad node type (%d but expected %d)", ch->node_type, type); goto out; } err = ubifs_check_node(c, buf, lnum, offs, 0, 0); if (err) { ubifs_err("expected node type %d", type); return err; } l = le32_to_cpu(ch->len); if (l != len) { ubifs_err("bad node length %d, expected %d", l, len); goto out; } return 0; out: ubifs_err("bad node at LEB %d:%d", lnum, offs); dbg_dump_node(c, buf); dbg_dump_stack(); return -EINVAL; }
1001-study-uboot
fs/ubifs/io.c
C
gpl3
10,030
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter */ /* * This file implements most of the debugging stuff which is compiled in only * when it is enabled. But some debugging check functions are implemented in * corresponding subsystem, just because they are closely related and utilize * various local functions of those subsystems. */ #define UBIFS_DBG_PRESERVE_UBI #include "ubifs.h" #ifdef CONFIG_UBIFS_FS_DEBUG DEFINE_SPINLOCK(dbg_lock); static char dbg_key_buf0[128]; static char dbg_key_buf1[128]; unsigned int ubifs_msg_flags = UBIFS_MSG_FLAGS_DEFAULT; unsigned int ubifs_chk_flags = UBIFS_CHK_FLAGS_DEFAULT; unsigned int ubifs_tst_flags; module_param_named(debug_msgs, ubifs_msg_flags, uint, S_IRUGO | S_IWUSR); module_param_named(debug_chks, ubifs_chk_flags, uint, S_IRUGO | S_IWUSR); module_param_named(debug_tsts, ubifs_tst_flags, uint, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_msgs, "Debug message type flags"); MODULE_PARM_DESC(debug_chks, "Debug check flags"); MODULE_PARM_DESC(debug_tsts, "Debug special test flags"); static const char *get_key_type(int type) { switch (type) { case UBIFS_INO_KEY: return "inode"; case UBIFS_DENT_KEY: return "direntry"; case UBIFS_XENT_KEY: return "xentry"; case UBIFS_DATA_KEY: return "data"; case UBIFS_TRUN_KEY: return "truncate"; default: return "unknown/invalid key"; } } static void sprintf_key(const struct ubifs_info *c, const union ubifs_key *key, char *buffer) { char *p = buffer; int type = key_type(c, key); if (c->key_fmt == UBIFS_SIMPLE_KEY_FMT) { switch (type) { case UBIFS_INO_KEY: sprintf(p, "(%lu, %s)", (unsigned long)key_inum(c, key), get_key_type(type)); break; case UBIFS_DENT_KEY: case UBIFS_XENT_KEY: sprintf(p, "(%lu, %s, %#08x)", (unsigned long)key_inum(c, key), get_key_type(type), key_hash(c, key)); break; case UBIFS_DATA_KEY: sprintf(p, "(%lu, %s, %u)", (unsigned long)key_inum(c, key), get_key_type(type), key_block(c, key)); break; case UBIFS_TRUN_KEY: sprintf(p, "(%lu, %s)", (unsigned long)key_inum(c, key), get_key_type(type)); break; default: sprintf(p, "(bad key type: %#08x, %#08x)", key->u32[0], key->u32[1]); } } else sprintf(p, "bad key format %d", c->key_fmt); } const char *dbg_key_str0(const struct ubifs_info *c, const union ubifs_key *key) { /* dbg_lock must be held */ sprintf_key(c, key, dbg_key_buf0); return dbg_key_buf0; } const char *dbg_key_str1(const struct ubifs_info *c, const union ubifs_key *key) { /* dbg_lock must be held */ sprintf_key(c, key, dbg_key_buf1); return dbg_key_buf1; } /** * ubifs_debugging_init - initialize UBIFS debugging. * @c: UBIFS file-system description object * * This function initializes debugging-related data for the file system. * Returns zero in case of success and a negative error code in case of * failure. */ int ubifs_debugging_init(struct ubifs_info *c) { c->dbg = kzalloc(sizeof(struct ubifs_debug_info), GFP_KERNEL); if (!c->dbg) return -ENOMEM; c->dbg->buf = vmalloc(c->leb_size); if (!c->dbg->buf) goto out; return 0; out: kfree(c->dbg); return -ENOMEM; } /** * ubifs_debugging_exit - free debugging data. * @c: UBIFS file-system description object */ void ubifs_debugging_exit(struct ubifs_info *c) { vfree(c->dbg->buf); kfree(c->dbg); } #endif /* CONFIG_UBIFS_FS_DEBUG */
1001-study-uboot
fs/ubifs/debug.c
C
gpl3
4,159